提取并接入 OpenAI Codex 的 Chrome 控制与 Computer Use 服务
直接调用浏览器底层调试端口往往会触发 DevToolsActivePort 的完全磁盘访问权限弹窗,走桌面截图又会消耗大量视觉推理开销。
OpenAI 在 ChatGPT.app 里自带了基于文本无障碍树的 Chrome 控制组件和 macOS 桌面控制服务,可以直接复用用户日常的 Chrome 会话。
这篇文章就是讲怎么把这两套内置运行时提取出来、绕过签名与策略校验,并封装成通用 MCP 服务与技能的。
内置目录与组件
我先梳理了 /Applications/ChatGPT.app/Contents/Resources 下的运行时布局,整套链路主要由三部分组成。
第一部分位于 cua_node/bin 目录,包含带苹果团队签名 2DC432GLL2 的 node 与 Rust rmcp 服务端 node_repl。
node_repl 通过 stdio 暴露 js、js_add_node_module_dir、js_reset 与 turn_ended 四个工具,提供带持久化绑定的 JS REPL 环境。
第二部分是 cua_node/lib/node_modules/@oai/sky 与 Codex Computer Use.app,核心后台进程为 Contents/MacOS/SkyComputerUseService。
该服务监听 ~/Library/Group Containers/2DC432GLL2.com.openai.sky.CUAService/IPC/computeruse.sock。
套接字采用 CodexComputerUseIPC-5 协议通信,帧格式为 4 字节小端长度前缀加上 JSON-RPC 2.0 载荷。
第三部分是浏览器控制插件。plugins/openai-bundled/plugins/chrome 目录存放了客户端脚本 scripts/browser-client.mjs 与技能定义。
同一目录还包含原生通信宿主 extension-host/macos/arm64/ChatGPT for Chrome。
原生通信宿主以 com.openai.codexextension 注册在 Chrome Native Messaging Hosts 中,启动后会监听 /tmp/codex-browser-use/<uuid>.sock。
在 ChatGPT.app 26.1123.101703 版本中,服务端脚本 browser-service.mjs 位于 plugins/openai-bundled/plugins/browser/scripts。
无障碍编译模块 browser-accessibility.wasm.br 也放在该目录下,而旧版客户端曾把这两个文件留在 plugins/chrome/scripts 中。
签名与策略校验
为什么在外部直接运行 node_repl 连不上这两个本地套接字?
反编译 SkyComputerUseService 与 browser-use-peer-authorization.node 可知,两边建立连接时都会读取 LOCAL_PEERTOKEN。
校验逻辑会回溯连接进程、父进程以及祖父进程三代审计令牌,要求这三级进程的苹果 Team ID 全部为 2DC432GLL2。
外部普通 Node 进程或终端壳的 Team ID 不符合要求,因此代理入口启动时必须借助 cua_node/bin/node 连续自我派生两次。
环境变量 CODEX_ANCESTRY_HOP 会从 0 递增到 2,从而让三代祖先进程全部带上 2DC432GLL2 签名。
当 ChatGPT.app 未启动时,为什么两个通道会同时报错?
阅读源码可知,SkyComputerUseService 内部的 CodexCLIExecutableLocator.launchConfiguration 会处理策略请求 ComputerUseIPCAppPolicyRequest。
执行策略校验时,它会先启动 codex app-server --listen stdio:// 查询 configRequirements/read。
查找可执行文件时,服务先检查 launchd 环境变量中的 CODEX_CLI_PATH,接着查找运行中的 ChatGPT.app,再找不到则回退到 /usr/bin/env codex。
浏览器服务端脚本 browser-service.mjs 在发现 Chrome 套接字时同样会调用 this.config.readRequirements 读取配置需求。
如果宿主未打开且 CODEX_CLI_PATH 缺失,@oai/sky 会返回 -10005: codex app-server exited before returning a response。
与此同时,browser-client.mjs 会过滤掉扩展通道并报错 Browser is not available: extension。
解决方法是把内置二进制 codex-cli/CodexCLI.app/Contents/MacOS/codex 的完整路径注入当前进程环境。
同时需要通过 launchctl setenv CODEX_CLI_PATH 写入用户会话环境,并终止缺少该变量的旧 SkyComputerUseService 进程,此后即可独立运行。
封装协议代理层
直接把 node_repl 接入外部 MCP 客户端会遇到几处协议与运行时差异,需要通过一段 Node 代理脚本做中间转发。
部分客户端在握手前会先发送 server/discover 探测请求,而 node_repl 要求首包必须是 initialize,因此代理直接拦截探测并返回 -32601 Method not found。
握手阶段,代理把 protocolVersion 规范化为 "2025-06-18",在客户端能力中声明 capabilities.elicitation = { form: {} },并过滤工具 turn_ended。
每次调用 tools/call 时,代理注入 _meta["x-codex-turn-metadata"] 中的 session_id 与 turn_id。
当子进程返回 withComputerUsePolicy 触发的 elicitation/create 询问时,代理自动回复 accept 放行。
代理还在用户代码前拼入 BOOTSTRAP_PREAMBLE,预先挂载 globalThis.sky、globalThis.setupBrowserRuntime 与常用 Node 全局对象。
为了兼容多轮 REPL 求值,脚本在送入代码前还会把顶层 const 转为 let,并把顶层 return 包进异步自执行块。
下面是完整的协议代理实现:
#!/usr/bin/env node
// codex-cua-mcp.mjs
import { spawn, execFileSync } from "node:child_process";
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const CHATGPT_APP = process.env.CHATGPT_APP_PATH || "/Applications/ChatGPT.app";
const CUA_DIR = `${CHATGPT_APP}/Contents/Resources/cua_node`;
const PLUGINS_DIR = `${CHATGPT_APP}/Contents/Resources/plugins/openai-bundled/plugins`;
const CODEX_CLI_DIR = `${CHATGPT_APP}/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS`;
const CODEX_CLI_BIN = `${CODEX_CLI_DIR}/codex`;
const CUA_NODE = `${CUA_DIR}/bin/node`;
// Ensure depth 0, depth 1, and depth 2 are all signed by 2DC432GLL2
const hop = Number(process.env.CODEX_ANCESTRY_HOP || "0");
if (hop < 2) {
const child = spawn(CUA_NODE, [process.argv[1], ...process.argv.slice(2)], {
env: { ...process.env, CODEX_ANCESTRY_HOP: String(hop + 1) },
stdio: ["pipe", "pipe", "pipe"],
});
process.stdin.pipe(child.stdin);
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
child.on("exit", (code) => process.exit(code ?? 0));
process.on("SIGTERM", () => child.kill("SIGTERM"));
process.on("SIGINT", () => child.kill("SIGINT"));
} else {
startProxy();
}
const BOOTSTRAP_PREAMBLE = `if (!globalThis.__agyCodexBootstrapped) {
let __req = (await import("node:module")).createRequire("file:///tmp/index.js");
globalThis.require ??= __req;
globalThis.process ??= __req("node:process");
globalThis.Buffer ??= __req("node:buffer").Buffer;
let rawSky = (await import("@oai/sky")).sky;
let decorateState = (res) => {
if (res && typeof res === "object" && typeof res.text === "string") {
Object.defineProperties(res, {
ax_tree: { get() { return res.text; }, configurable: true },
toString: { value() { return res.text; }, configurable: true },
split: { value(...a) { return res.text.split(...a); }, configurable: true },
slice: { value(...a) { return res.text.slice(...a); }, configurable: true },
includes: { value(...a) { return res.text.includes(...a); }, configurable: true },
indexOf: { value(...a) { return res.text.indexOf(...a); }, configurable: true },
match: { value(...a) { return res.text.match(...a); }, configurable: true },
});
}
return res;
};
let origGetAppState = rawSky.get_app_state.bind(rawSky);
let origClick = rawSky.click.bind(rawSky);
let origPressKey = rawSky.press_key.bind(rawSky);
let origScroll = rawSky.scroll.bind(rawSky);
let origSecondary = rawSky.perform_secondary_action.bind(rawSky);
globalThis.sky = Object.assign({}, rawSky, {
async get_app_state(opts) {
let norm = typeof opts === "string" ? { app: opts } : opts;
return decorateState(await origGetAppState(norm));
},
async click(opts) {
let norm = Object.assign({}, opts);
if (norm.point && norm.x === undefined) {
norm.x = Array.isArray(norm.point) ? norm.point[0] : norm.point.x;
norm.y = Array.isArray(norm.point) ? norm.point[1] : norm.point.y;
delete norm.point;
}
if (norm.button && norm.mouse_button === undefined) {
norm.mouse_button = norm.button;
delete norm.button;
}
await origClick(norm);
},
async press_key(opts) {
let norm = Object.assign({}, opts);
if (Array.isArray(norm.key)) norm.key = norm.key.join("+");
await origPressKey(norm);
},
async scroll(opts) {
let norm = Object.assign({}, opts);
if (norm.point && norm.x === undefined) {
norm.x = Array.isArray(norm.point) ? norm.point[0] : norm.point.x;
norm.y = Array.isArray(norm.point) ? norm.point[1] : norm.point.y;
delete norm.point;
}
if (!norm.direction && typeof norm.delta_y === "number") {
norm.direction = norm.delta_y >= 0 ? "down" : "up";
norm.pages ??= Math.max(1, Math.round(Math.abs(norm.delta_y) / 3));
delete norm.delta_y;
delete norm.delta_x;
}
await origScroll(norm);
},
type: rawSky.type_text.bind(rawSky),
async perform_Contextual_action(opts) {
let norm = Object.assign({}, opts);
if (norm.action_name && !norm.action) {
norm.action = norm.action_name;
delete norm.action_name;
}
await origSecondary(norm);
},
});
globalThis.setupBrowserRuntime ??= async (...args) => {
const mod = await import("${PLUGINS_DIR}/chrome/scripts/browser-client.mjs");
return mod.setupBrowserRuntime(...args);
};
globalThis.__agyCodexBootstrapped = true;
}\n`;
function ensureCodexCliAndSkyReady() {
try {
const localBinDir = path.join(os.homedir(), ".local", "bin");
if (fs.existsSync(localBinDir) && fs.existsSync(CODEX_CLI_BIN)) {
const linkPath = path.join(localBinDir, "codex");
let currentTarget = null;
try {
currentTarget = fs.readlinkSync(linkPath);
} catch {}
if (currentTarget !== CODEX_CLI_BIN && !fs.existsSync(linkPath)) {
fs.symlinkSync(CODEX_CLI_BIN, linkPath);
}
}
} catch {}
try {
execFileSync("launchctl", ["setenv", "CODEX_CLI_PATH", CODEX_CLI_BIN], {
stdio: "ignore",
timeout: 3000,
});
} catch {}
try {
const pids = execFileSync("pgrep", ["-x", "SkyComputerUseService"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
timeout: 3000,
})
.trim()
.split(/\s+/)
.filter(Boolean);
for (const pid of pids) {
const envOut = execFileSync("ps", ["eww", "-p", pid], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
timeout: 3000,
});
if (!envOut.includes("CODEX_CLI_PATH=")) {
process.kill(Number(pid), "SIGTERM");
}
}
} catch {}
}
function transformUserCode(code) {
if (typeof code !== "string") return code;
let normalized = code.replace(/^(\s*)const\s+/gm, "$1let ");
const hasTopLevelReturn = /(^|[\n;])\s*return\b/.test(normalized);
if (hasTopLevelReturn) {
normalized = `{\n let __agyRet = await (async () => {\n${normalized}\n })();\n if (__agyRet !== undefined) nodeRepl.write(__agyRet);\n}`;
}
return BOOTSTRAP_PREAMBLE + normalized;
}
function startProxy() {
ensureCodexCliAndSkyReady();
const sessionId = `agy-codex-${crypto.randomUUID()}`;
let turnCounter = 0;
let initializeId = null;
let toolsListId = null;
const basePath = process.env.PATH || "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
const defaultSkyApp = path.join(os.homedir(), ".codex/computer-use/Codex Computer Use.app");
const bundledSkyApp = `${CUA_DIR}/lib/node_modules/@oai/sky/Codex Computer Use.app`;
const env = {
...process.env,
TMPDIR: "/tmp",
PATH: `${CODEX_CLI_DIR}:${CUA_DIR}/bin:${basePath}`,
CODEX_CLI_PATH: CODEX_CLI_BIN,
NODE_REPL_NODE_PATH: CUA_NODE,
NODE_REPL_NODE_MODULE_DIRS: `${CUA_DIR}/lib/node_modules:${PLUGINS_DIR}/chrome/node_modules`,
NODE_REPL_TRUSTED_CODE_PATHS: `${os.homedir()}:${process.cwd()}:/tmp:${CHATGPT_APP}/Contents/Resources:${CUA_DIR}/lib/node_modules:${PLUGINS_DIR}`,
NODE_REPL_TRUSTED_SERVICES: JSON.stringify({
sky: "@oai/sky/service",
browser: `${PLUGINS_DIR}/chrome/scripts/browser-service.mjs`,
}),
BROWSER_USE_SECURITY_MODE: "disabled-for-local-testing",
BROWSER_USE_ENABLE_TINYSKY_ACCESSIBILITY: "1",
BROWSER_USE_TINYSKY_ENABLED: "1",
BROWSER_USE_FULL_CDP_ACCESS_ENABLED: "1",
SKY_CUA_SERVICE_PATH: fs.existsSync(defaultSkyApp) ? defaultSkyApp : bundledSkyApp,
};
delete env.CUA_REPL_ENABLED_SURFACES;
const child = spawn(`${CUA_DIR}/bin/node_repl`, ["--disable-sandbox"], {
env,
stdio: ["pipe", "pipe", "pipe"],
});
child.stderr.on("data", (chunk) => {
const text = chunk.toString("utf8");
const filtered = text
.split("\n")
.filter((line) => !line.includes("codex app-server auth fetch failed"))
.join("\n");
if (filtered.trim()) {
process.stderr.write(filtered);
}
});
let inBuf = "";
process.stdin.on("data", (chunk) => {
inBuf += chunk.toString("utf8");
let idx;
while ((idx = inBuf.indexOf("\n")) !== -1) {
const line = inBuf.slice(0, idx).trim();
inBuf = inBuf.slice(idx + 1);
if (!line) continue;
try {
const msg = JSON.parse(line);
if (msg.method === "server/discover") {
process.stdout.write(
JSON.stringify({
jsonrpc: "2.0",
id: msg.id ?? null,
error: { code: -32601, message: "Method not found" },
}) + "\n"
);
continue;
}
if (msg.method === "initialize") {
initializeId = msg.id;
msg.params ??= {};
if (
!msg.params.protocolVersion ||
!["2024-11-05", "2025-03-26", "2025-06-18"].includes(msg.params.protocolVersion)
) {
msg.params.protocolVersion = "2025-06-18";
}
msg.params.capabilities ??= {};
msg.params.capabilities.elicitation = { form: {} };
} else if (msg.method === "tools/list") {
toolsListId = msg.id;
} else if (msg.method === "tools/call") {
msg.params ??= {};
msg.params._meta ??= {};
msg.params._meta["x-codex-turn-metadata"] ??= {
session_id: sessionId,
turn_id: `turn-${++turnCounter}`,
};
if (msg.params.name === "js" && typeof msg.params.arguments?.code === "string") {
msg.params.arguments.code = transformUserCode(msg.params.arguments.code);
}
}
child.stdin.write(JSON.stringify(msg) + "\n");
} catch {
child.stdin.write(line + "\n");
}
}
});
let outBuf = "";
child.stdout.on("data", (chunk) => {
outBuf += chunk.toString("utf8");
let idx;
while ((idx = outBuf.indexOf("\n")) !== -1) {
const line = outBuf.slice(0, idx).trim();
outBuf = outBuf.slice(idx + 1);
if (!line) continue;
try {
const msg = JSON.parse(line);
if (msg.method === "elicitation/create" && msg.id !== undefined) {
child.stdin.write(
JSON.stringify({
jsonrpc: "2.0",
id: msg.id,
result: {
action: "accept",
content: {},
},
}) + "\n"
);
continue;
}
if (msg.id !== undefined && msg.id === initializeId && msg.result?.capabilities) {
delete msg.result.capabilities.experimental;
}
if (msg.id !== undefined && msg.id === toolsListId && Array.isArray(msg.result?.tools)) {
msg.result.tools = msg.result.tools.filter((t) => t.name !== "turn_ended");
}
process.stdout.write(JSON.stringify(msg) + "\n");
} catch {
process.stdout.write(line + "\n");
}
}
});
child.on("exit", (code) => process.exit(code ?? 0));
process.stdin.on("end", () => child.kill());
process.on("SIGTERM", () => child.kill("SIGTERM"));
process.on("SIGINT", () => child.kill("SIGINT"));
}
若宿主运行 ChatGPT.app 26.1123.101703 或更高版本,可把上述代理中 browser 服务的路径和模块目录从 plugins/chrome 改为 plugins/browser。
除了执行 JS 代码的 REPL 代理,原生的 SkyComputerUseClient mcp 子命令会请求 Mach 服务 2DC432GLL2.com.openai.sky.CUAService.xpc。
在 ChatGPT.app 外部直接运行该子命令会触发 bootstrapTimedOut 超时错误。
为此我单独补了一套直连脚本,在 cua_node/bin/node 下通过两跳签名派生的 globalThis.nodeRepl 环境导入 @oai/sky 的 client.js 与 create_client.js。
该代理跳过 XPC 直接读写 computeruse.sock,一共导出 30 个结构化工具。
工具覆盖桌面控件操作 list_apps、get_app_state、click、set_value,以及 computer_history_*、event_stream_*、日历和信息接口。
命令行直接验证
我使用自带签名的 cua_node/bin/node 启动代理脚本,向标准输入依次写入四条 JSON-RPC 消息来做验证。
消息顺序为 server/discover、initialize、notifications/initialized 与调用访达无障碍树的 tools/call。
/Applications/ChatGPT.app/Contents/Resources/cua_node/bin/node -e '
import { spawn } from "node:child_process";
const proc = spawn(
"/Applications/ChatGPT.app/Contents/Resources/cua_node/bin/node",
["/Users/<YOUR_USERNAME>/.gemini/config/codex-cua-mcp.mjs"],
{ stdio: ["pipe", "pipe", "pipe"] }
);
let out = "";
proc.stdout.on("data", (d) => { out += d.toString(); });
const msgs = [
{ jsonrpc: "2.0", id: 1, method: "server/discover" },
{
jsonrpc: "2.0",
id: 2,
method: "initialize",
params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "cli-test", version: "1.0" } }
},
{ jsonrpc: "2.0", method: "notifications/initialized" },
{
jsonrpc: "2.0",
id: 3,
method: "tools/call",
params: {
name: "js",
arguments: {
code: "const s = await sky.get_app_state(\"com.apple.finder\"); return s.text.split(\"\\n\").slice(0, 8).join(\"\\n\");"
}
}
}
];
for (const m of msgs) proc.stdin.write(JSON.stringify(m) + "\n");
setTimeout(() => { console.log(out); proc.kill(); process.exit(0); }, 5000);
' --input-type=module
实际执行后,标准输出依次返回了探测拒答、协议握手成功以及访达窗口的无障碍树文本。
{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"Method not found"}}
{"jsonrpc":"2.0","id":2,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{"listChanged":true}},"serverInfo":{"name":"rmcp","version":"3.5.1"},"instructions":"Use `js` for `node_repl` execution with persistent, redeclarable top-level bindings, `js_reset` to clear bindings, and `js_add_node_module_dir` to add package directories."}}
{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"Window: \"Desktop\", App: 访达.\n0 滚动区 (disabled) 桌面\n\t1 container 桌面\n\t\t2 图像 截屏2026-12-04 下午3.24.46, Secondary Actions: 打开\n\t\t3 图像 data, Secondary Actions: 打开\n\t\t4 图像 截屏2026-12-04 上午2.18.02, Secondary Actions: 打开\n\t\t5 图像 截屏2026-12-04 下午3.22.05, Secondary Actions: 打开\n\t\t6 图像 截屏2026-12-04 下午3.22.37, Secondary Actions: 打开"}],"isError":false,"_meta":{"codex/nodeReplExecutionDurationMs":2751,"codex/toolSurface":{"app":{"appId":"com.apple.finder","kind":"appId"},"kind":"computerUse"}}}}
当 Chrome 已加载扩展时,也可以在同一 js 工具调用中通过 setupBrowserRuntime 接管当前标签页并输出无障碍树。
const rt = await setupBrowserRuntime();
const chrome = await rt.browsers.get("extension");
const tabs = await chrome.user.openTabs();
const tab = await chrome.user.claimTab(tabs[0].id);
await tab.ax.write();
如果 Chrome 扩展未连接,上述调用会返回 Browser is not available: extension 错误,此时可先调用 rt.browsers.list 确认可用通道列表。
写入配置与技能
在客户端配置 mcp_config.json 中注册这两个服务端时,启动命令必须指向 ChatGPT.app 自带的 node,并显式设置 TMPDIR 为 /tmp。
{
"mcpServers": {
"codex-cua": {
"command": "/Applications/ChatGPT.app/Contents/Resources/cua_node/bin/node",
"args": [
"/Users/<YOUR_USERNAME>/.gemini/config/codex-cua-mcp.mjs"
],
"env": {
"TMPDIR": "/tmp"
}
},
"codex-sky": {
"command": "/Applications/ChatGPT.app/Contents/Resources/cua_node/bin/node",
"args": [
"/Users/<YOUR_USERNAME>/.gemini/config/codex-sky-mcp.mjs"
],
"env": {
"TMPDIR": "/tmp"
}
}
}
}
配置生效后,可以在技能目录创建 codex-computer-use/SKILL.md 与 codex-chrome-control/SKILL.md,把常用调用范式固化下来。
---
name: codex-computer-use
description: Control native macOS desktop apps via @oai/sky Accessibility tree.
---
# Codex Computer Use
```js
// 1. List running apps and inspect target app Accessibility tree
const apps = await sky.list_apps();
const state = await sky.get_app_state({ app: "com.apple.finder" });
nodeRepl.write(state.text);
// 2. Act by element_index (click / set_value return void; re-read state afterward)
await sky.click({ app: "com.google.Chrome", element_index: 9 });
await sky.set_value({ app: "com.google.Chrome", element_index: 9, value: "https://example.com" });
```
浏览器控制的技能模板同样优先读取编号无障碍树,避免直接截图。
---
name: codex-chrome-control
description: Control live Google Chrome tabs via control-chrome and TinySky tab.ax.
---
# Codex Chrome Control
```js
globalThis.chrome ??= await (await setupBrowserRuntime()).browsers.get("extension");
const tabs = await chrome.user.openTabs();
const tab = await chrome.user.claimTab(tabs[0].id);
await tab.ax.write();
await tab.ax.click(14);
await tab.ax.setValue(9, "search query");
// Playwright locators are also available on the claimed tab
await tab.playwright.getByRole("button", { name: "Submit" }).click();
```
已知问题
SkyComputerUseService 对宿主自身 com.openai.codex 硬编码了 decision: "forbidden" 策略。
调用 sky.get_app_state 访问该应用会报错 Computer Use is not allowed to use the app 'com.openai.codex' for safety reasons.。
浏览器扩展通道依赖 Chrome 中处于激活状态的 ChatGPT for Chrome 扩展,只有打开 /tmp/codex-browser-use/<uuid>.sock 时才能获取标签页。
日历与信息工具组依赖 macOS 系统隐私授权,需要在系统设置中为 Codex Computer Use.app 开启日历、通讯录与完全磁盘访问权限。