Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: 修复 Cindy Browser 与 Codex 浏览器能力冲突 (#1706)
Dash7da2b61200fc
diff --git a/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts b/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.tsindex d62afb9d4f..72c567e73c 100644--- a/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts+++ b/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts@@ -62,6 +62,22 @@ describe('computer use plugin IPC invariants', () => {);});+ it('schedules a retry when the shared host is busy', async () => {+ const onDeferred = vi.fn();++ await expect(+ refreshCodexMcpEnvironment({+ restartCodex: vi.fn(async () => {+ throw new Error('codex busy');+ }),+ shutdownCodexEnvironment: vi.fn(async () => undefined),+ onDeferred,+ }),+ ).resolves.toEqual({ codexMcpRefreshed: false });++ expect(onDeferred).toHaveBeenCalledOnce();+ });+it('returns the non-blocking refresh result after global plugin persistence', () => {const registerSource = fs.readFileSync(path.resolve(__dirname, '../maker-ipc/register.ts'),@@ -86,6 +102,7 @@ describe('computer use plugin IPC invariants', () => {for (const body of [setEnabledBody, clearEnabledBody]) {expect(body).toContain('GLOBAL_PLUGIN_IDS.has(id)');+ expect(body).toContain("id !== 'browser'");expect(body).toContain('await getPluginRegistry()');expect(body).toContain('return { codexMcpRefreshed: true };');expect(body).toContain('return refreshCodexMcpEnvironment({');diff --git a/apps/desktop/src/main/maker-host/__tests__/capability-routing.test.ts b/apps/desktop/src/main/maker-host/__tests__/capability-routing.test.tsnew file mode 100644index 0000000000..a38996c97c--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/capability-routing.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from 'vitest';++import { buildDesktopCapabilityRoutingPolicy } from '../capability-routing.js';++function codexPluginRoutes(cindyBrowserEnabled: boolean, codexBrowserUseAvailable = true) {+ return buildDesktopCapabilityRoutingPolicy({+ cindyBrowserEnabled,+ codexBrowserUseAvailable,+ }).overrides.filter(+ (override) =>+ override.source.kind === 'harness-plugin'+ && override.source.harness === 'codex'+ && override.source.surface === 'plugin',+ );+}++describe('buildDesktopCapabilityRoutingPolicy', () => {+ it('disables both official Codex browser surfaces when Cindy Browser is enabled', () => {+ const routes = codexPluginRoutes(true);++ expect(routes.map((route) => route.source.id)).toEqual([+ 'computer-use@openai-bundled',+ 'browser@openai-bundled',+ 'chrome@openai-bundled',+ ]);+ expect(routes.slice(1)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ invocation: 'disabled',+ replacement: { kind: 'cindy-plugin', id: 'browser' },+ }),+ ]),+ );+ });++ it('leaves Chrome available while disabling the unsupported in-app Browser', () => {+ const routes = codexPluginRoutes(false, true);++ expect(routes.map((route) => route.source.id)).toEqual([+ 'computer-use@openai-bundled',+ 'browser@openai-bundled',+ ]);+ });++ it('also disables the privileged Browser MCP surface when Cindy Browser owns the capability', () => {+ const routes = buildDesktopCapabilityRoutingPolicy({+ cindyBrowserEnabled: true,+ codexBrowserUseAvailable: true,+ }).overrides;++ expect(routes).toContainEqual(expect.objectContaining({+ invocation: 'disabled',+ source: expect.objectContaining({ surface: 'mcp', id: 'node_repl' }),+ replacement: { kind: 'cindy-plugin', id: 'browser' },+ }));+ });++ it('fails closed without claiming a replacement when neither browser runtime is available', () => {+ const policy = buildDesktopCapabilityRoutingPolicy({+ cindyBrowserEnabled: false,+ codexBrowserUseAvailable: false,+ });+ const routes = policy.overrides.filter(+ (route) =>+ route.source.id !== 'computer-use@openai-bundled' && route.source.surface === 'plugin',+ );++ expect(routes.map((route) => route.source.id)).toEqual([+ 'browser@openai-bundled',+ 'chrome@openai-bundled',+ ]);+ expect(routes.every((route) => route.replacement === undefined)).toBe(true);+ const nodeReplRoute = policy.overrides.find(+ (route) => route.source.surface === 'mcp' && route.source.id === 'node_repl',+ );+ expect(nodeReplRoute).toMatchObject({+ invocation: 'disabled',+ source: expect.objectContaining({ surface: 'mcp', id: 'node_repl' }),+ });+ expect(nodeReplRoute?.replacement).toBeUndefined();+ });++ it('keeps remote Chrome available without claiming the local Cindy Browser replacement', () => {+ const policy = buildDesktopCapabilityRoutingPolicy({+ cindyComputerAvailable: false,+ cindyBrowserEnabled: true,+ codexBrowserUseAvailable: true,+ remoteHostId: 'remote-browser-host',+ });+ const browserRoutes = policy.overrides.filter(+ (route) => route.capabilityId === 'browser-use',+ );++ expect(browserRoutes).toEqual([+ expect.objectContaining({+ invocation: 'disabled',+ source: expect.objectContaining({+ surface: 'plugin',+ id: 'browser@openai-bundled',+ }),+ }),+ ]);+ expect(browserRoutes[0]?.replacement).toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/codex-browser-companion.test.ts b/apps/desktop/src/main/maker-host/__tests__/codex-browser-companion.test.tsnew file mode 100644index 0000000000..318e584c6a--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/codex-browser-companion.test.ts@@ -0,0 +1,517 @@+import os from 'node:os';+import path from 'node:path';+import { createHash } from 'node:crypto';+import { promises as fs } from 'node:fs';+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ buildOfficialMacBundleVerificationArgs,+ checkCodexBrowserCompanionConnection,+ hasOfficialMacTeamIdentifier,+ OFFICIAL_MAC_BUNDLE_REQUIREMENT,+ prepareCodexBrowserCompanion,+ resolveCodexBrowserCompanionSpawnConfig,+} from '../codex-browser-companion.js';++const tempDirs: string[] = [];++async function setup(overrides: {+ command?: string;+ pluginEnabled?: boolean;+ isolatedPluginEnabled?: boolean;+ nodeReplEnabled?: boolean;+ includeExtensionHost?: boolean;+ extraEnv?: string;+ nodeReplContent?: string;+} = {}) {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-browser-companion-'));+ tempDirs.push(root);+ const homeDir = path.join(root, 'home');+ const codexHome = path.join(root, 'cindy-codex-home');+ const appBundle = path.join(root, 'ChatGPT.app');+ const resources = path.join(appBundle, 'Contents', 'Resources');+ const nodeRepl = overrides.command+ ?? path.join(resources, 'cua_node', 'bin', 'node_repl');+ const nodePath = path.join(resources, 'cua_node', 'bin', 'node');+ const moduleDirs = path.join(resources, 'cua_node', 'lib', 'node_modules');+ const codexCli = path.join(resources, 'codex');+ const version = '26.727.51351';+ const pluginRoot = path.join(+ homeDir,+ '.codex',+ 'plugins',+ 'cache',+ 'openai-bundled',+ 'chrome',+ version,+ );+ const browserClient = path.join(pluginRoot, 'scripts', 'browser-client.mjs');+ const packageAsset = path.join(pluginRoot, 'skills', 'browser.md');+ const browserClientContent = 'export const browserClient = true;\n';+ const actualHash = createHash('sha256').update(browserClientContent).digest('hex');+ const extensionHost = path.join(+ pluginRoot,+ 'extension-host',+ 'macos',+ 'arm64',+ 'ChatGPT for Chrome',+ );+ const signedPluginRoot = path.join(+ resources,+ 'plugins',+ 'openai-bundled',+ 'plugins',+ 'chrome',+ );+ const signedBrowserClient = path.join(signedPluginRoot, 'scripts', 'browser-client.mjs');+ const signedPackageAsset = path.join(signedPluginRoot, 'skills', 'browser.md');+ const signedExtensionHost = path.join(+ signedPluginRoot,+ 'extension-host',+ 'macos',+ 'arm64',+ 'ChatGPT for Chrome',+ );+ const pluginManifest = path.join(pluginRoot, '.codex-plugin', 'plugin.json');+ const signedManifest = path.join(signedPluginRoot, '.codex-plugin', 'plugin.json');++ await Promise.all([+ fs.mkdir(path.dirname(nodeRepl), { recursive: true }),+ fs.mkdir(moduleDirs, { recursive: true }),+ fs.mkdir(path.dirname(browserClient), { recursive: true }),+ fs.mkdir(path.dirname(packageAsset), { recursive: true }),+ fs.mkdir(path.dirname(extensionHost), { recursive: true }),+ fs.mkdir(path.dirname(signedBrowserClient), { recursive: true }),+ fs.mkdir(path.dirname(signedPackageAsset), { recursive: true }),+ fs.mkdir(path.dirname(signedExtensionHost), { recursive: true }),+ fs.mkdir(path.dirname(pluginManifest), { recursive: true }),+ fs.mkdir(path.dirname(signedManifest), { recursive: true }),+ ]);+ await Promise.all([+ fs.writeFile(nodeRepl, overrides.nodeReplContent ?? 'node-repl'),+ fs.writeFile(nodePath, 'node'),+ fs.writeFile(codexCli, 'codex'),+ fs.writeFile(browserClient, browserClientContent),+ fs.writeFile(packageAsset, 'signed browser skill'),+ fs.writeFile(signedBrowserClient, browserClientContent),+ fs.writeFile(signedPackageAsset, 'signed browser skill'),+ fs.writeFile(signedExtensionHost, 'extension-host'),+ fs.writeFile(pluginManifest, JSON.stringify({ name: 'chrome', version })),+ fs.writeFile(signedManifest, JSON.stringify({ name: 'chrome', version })),+ ...(overrides.includeExtensionHost === false+ ? []+ : [fs.writeFile(extensionHost, 'extension-host')]),+ ]);+ await Promise.all([+ fs.chmod(nodeRepl, 0o755),+ fs.chmod(nodePath, 0o755),+ fs.chmod(codexCli, 0o755),+ fs.chmod(signedExtensionHost, 0o755),+ ...(overrides.includeExtensionHost === false ? [] : [fs.chmod(extensionHost, 0o755)]),+ ]);++ const sourceConfig = path.join(homeDir, '.codex', 'config.toml');+ await fs.mkdir(path.dirname(sourceConfig), { recursive: true });+ await fs.writeFile(+ sourceConfig,+ [+ '[plugins."chrome@openai-bundled"]',+ `enabled = ${overrides.pluginEnabled === false ? 'false' : 'true'}`,+ '',+ '[mcp_servers.node_repl]',+ ...(overrides.nodeReplEnabled === undefined+ ? []+ : [`enabled = ${overrides.nodeReplEnabled ? 'true' : 'false'}`]),+ `command = ${JSON.stringify(nodeRepl)}`,+ 'args = []',+ 'startup_timeout_sec = 120',+ '',+ '[mcp_servers.node_repl.env]',+ `NODE_REPL_NODE_MODULE_DIRS = ${JSON.stringify(moduleDirs)}`,+ `NODE_REPL_NODE_PATH = ${JSON.stringify(nodePath)}`,+ `CODEX_CLI_PATH = ${JSON.stringify(codexCli)}`,+ `BROWSER_USE_CODEX_APP_VERSION = ${JSON.stringify(version)}`,+ `NODE_REPL_TRUSTED_BROWSER_CLIENT_SHA256S = ${JSON.stringify(actualHash)}`,+ 'BROWSER_USE_AVAILABLE_BACKENDS = "chrome,iab"',+ 'NODE_REPL_TRUSTED_CODE_PATHS = "/outside/cindy"',+ overrides.extraEnv ?? '',+ '',+ ].join('\n'),+ 'utf8',+ );++ const isolatedMarketplace = path.join(+ codexHome,+ 'plugins',+ 'cache',+ 'openai-bundled',+ );+ await fs.mkdir(path.dirname(isolatedMarketplace), { recursive: true });+ await fs.symlink(+ path.join(homeDir, '.codex', 'plugins', 'cache', 'openai-bundled'),+ isolatedMarketplace,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ await fs.mkdir(codexHome, { recursive: true });+ await fs.writeFile(+ path.join(codexHome, 'config.toml'),+ [+ '[plugins."chrome@openai-bundled"]',+ `enabled = ${overrides.isolatedPluginEnabled === false ? 'false' : 'true'}`,+ '',+ '[mcp_servers.node_repl.env]',+ 'NODE_OPTIONS = "--require=/tmp/untrusted.cjs"',+ `NODE_REPL_TRUSTED_CODE_PATHS = ${JSON.stringify(codexHome)}`,+ '',+ ].join('\n'),+ 'utf8',+ );++ await fs.symlink(+ pluginRoot,+ path.join(path.dirname(pluginRoot), 'latest'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );++ return {+ appBundle,+ browserClient,+ codexHome,+ homeDir,+ nodeRepl,+ pluginRoot,+ signedPluginRoot,+ sourceConfig,+ };+}++afterEach(async () => {+ await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));+});++describe('prepareCodexBrowserCompanion', () => {+ it('anchors macOS verification to the signed OpenAI Codex identity', () => {+ const args = buildOfficialMacBundleVerificationArgs('/tmp/ChatGPT.app');++ expect(args).toEqual([+ '--verify',+ '--deep',+ '--strict',+ '--test-requirement',+ `=${OFFICIAL_MAC_BUNDLE_REQUIREMENT}`,+ '/tmp/ChatGPT.app',+ ]);+ expect(OFFICIAL_MAC_BUNDLE_REQUIREMENT).toContain('anchor apple generic');+ expect(OFFICIAL_MAC_BUNDLE_REQUIREMENT).toContain('identifier "com.openai.codex"');+ expect(OFFICIAL_MAC_BUNDLE_REQUIREMENT).toContain(+ 'certificate leaf[subject.OU] = "2DC432GLL2"',+ );+ expect(OFFICIAL_MAC_BUNDLE_REQUIREMENT).toContain(+ 'certificate 1[field.1.2.840.113635.100.6.2.6] exists',+ );+ expect(OFFICIAL_MAC_BUNDLE_REQUIREMENT).toContain(+ 'certificate leaf[field.1.2.840.113635.100.6.1.13] exists',+ );+ });++ it('parses TeamIdentifier as a complete codesign field', () => {+ expect(hasOfficialMacTeamIdentifier(+ 'Executable=/tmp/TeamIdentifier=2DC432GLL2/node_repl\nTeamIdentifier=OTHER',+ )).toBe(false);+ expect(hasOfficialMacTeamIdentifier(+ 'Executable=/tmp/node_repl\nTeamIdentifier=2DC432GLL2',+ )).toBe(true);+ });++ it('reports unsupported host platforms without claiming a verified companion', async () => {+ const companion = await prepareCodexBrowserCompanion({+ codexHome: '/tmp/cindy-codex-home',+ platform: 'win32',+ arch: 'x64',+ });++ expect(companion).toMatchObject({+ status: 'unavailable',+ reason: 'platform_unsupported',+ });+ expect(resolveCodexBrowserCompanionSpawnConfig(companion)).toEqual({+ codexBrowserUseAvailable: false,+ extraArgs: ['-c', 'mcp_servers.node_repl.enabled=false'],+ });+ });++ it('keeps the control-plane host neutral when no companion preflight applies', () => {+ expect(resolveCodexBrowserCompanionSpawnConfig(null)).toEqual({+ codexBrowserUseAvailable: false,+ extraArgs: [],+ });+ });++ it('injects an allowlisted Chrome-only companion config for the isolated Codex home', async () => {+ const { appBundle, codexHome, homeDir, nodeRepl, signedPluginRoot } = await setup({+ extraEnv: 'MALICIOUS_SECRET = "must-not-cross"',+ });++ const result = await prepareCodexBrowserCompanion({+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle: async (candidate) => candidate === appBundle,+ });++ expect(result.status).toBe('ready');+ if (result.status !== 'ready') return;+ expect(result.extraArgs).toContain('mcp_servers.node_repl.enabled=true');+ expect(result.extraArgs).toContain('mcp_servers.node_repl.command="/usr/bin/env"');+ const argsOverride = result.extraArgs.find((arg) => (+ arg.startsWith('mcp_servers.node_repl.args=')+ ));+ expect(argsOverride).toBeDefined();+ const cleanArgs = JSON.parse(+ argsOverride!.slice('mcp_servers.node_repl.args='.length),+ ) as string[];+ expect(cleanArgs[0]).toBe('-i');+ expect(cleanArgs.at(-1)).toBe(nodeRepl);+ expect(cleanArgs).toContain(`CODEX_HOME=${codexHome}`);+ expect(cleanArgs).toContain('BROWSER_USE_AVAILABLE_BACKENDS=chrome');+ expect(cleanArgs.some((arg) => arg.startsWith('NODE_REPL_TRUSTED_CODE_PATHS=')))+ .toBe(false);+ expect(cleanArgs.some((arg) => arg.startsWith('NODE_OPTIONS='))).toBe(false);+ expect(cleanArgs.some((arg) => arg.startsWith('MALICIOUS_SECRET='))).toBe(false);+ expect(result.startupTimeoutMs).toBe(120_000);+ expect(result.browserClientPath).toBe(+ path.join(signedPluginRoot, 'scripts', 'browser-client.mjs'),+ );+ expect(resolveCodexBrowserCompanionSpawnConfig(result)).toEqual({+ codexBrowserUseAvailable: true,+ extraArgs: result.extraArgs,+ });+ });++ it('rejects a latest selector that points at a different plugin version', async () => {+ const { codexHome, homeDir, pluginRoot } = await setup();+ const latest = path.join(path.dirname(pluginRoot), 'latest');+ const otherVersion = path.join(path.dirname(pluginRoot), 'other-version');+ await fs.unlink(latest);+ await fs.mkdir(otherVersion);+ await fs.symlink(+ otherVersion,+ latest,+ process.platform === 'win32' ? 'junction' : 'dir',+ );++ const result = await prepareCodexBrowserCompanion({+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle: async () => true,+ });++ expect(result).toMatchObject({ status: 'unavailable', reason: 'runtime_missing' });+ });++ it('rejects a Chrome plugin disabled in the isolated runtime even when the source is enabled', async () => {+ const { codexHome, homeDir } = await setup({ isolatedPluginEnabled: false });++ const result = await prepareCodexBrowserCompanion({+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle: async () => true,+ });++ expect(result).toMatchObject({ status: 'unavailable', reason: 'provider_not_installed' });+ });++ it('does not re-enable a node_repl descriptor disabled by the user', async () => {+ const { codexHome, homeDir } = await setup({ nodeReplEnabled: false });++ const result = await prepareCodexBrowserCompanion({+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle: async () => true,+ });++ expect(result).toMatchObject({+ status: 'unavailable',+ reason: 'provider_not_installed',+ });+ });++ it('revalidates the signed app bundle for each host provision', async () => {+ const { appBundle, codexHome, homeDir } = await setup();+ const verifyMacBundle = vi.fn(async (candidate: string) => candidate === appBundle);++ await prepareCodexBrowserCompanion({+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle,+ });+ await prepareCodexBrowserCompanion({+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle,+ });++ expect(verifyMacBundle).toHaveBeenCalledTimes(2);+ });++ it('rejects a node_repl command outside an official macOS app bundle layout', async () => {+ const { codexHome, homeDir, sourceConfig } = await setup();+ const sourceText = await fs.readFile(sourceConfig, 'utf8');+ await fs.writeFile(+ sourceConfig,+ sourceText.replace(+ /^command = .*$/m,+ `command = ${JSON.stringify(path.join(homeDir, 'untrusted', 'node_repl'))}`,+ ),+ 'utf8',+ );++ const result = await prepareCodexBrowserCompanion({+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle: async () => true,+ });++ expect(result).toMatchObject({ status: 'unavailable', reason: 'provider_untrusted' });+ });++ it('rejects a browser client whose exact plugin-version hash is not trusted', async () => {+ const { browserClient, codexHome, homeDir } = await setup();+ await fs.writeFile(browserClient, 'tampered browser client');++ const result = await prepareCodexBrowserCompanion({+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle: async () => true,+ });++ expect(result).toMatchObject({+ status: 'unavailable',+ reason: 'browser_client_untrusted',+ });+ });++ it('does not expose a half-installed companion without its extension host', async () => {+ const { codexHome, homeDir } = await setup({ includeExtensionHost: false });++ const result = await prepareCodexBrowserCompanion({+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle: async () => true,+ });++ expect(result).toMatchObject({+ status: 'unavailable',+ reason: 'extension_host_missing',+ });+ });++ it('rejects a tampered signed package asset beyond browser-client.mjs', async () => {+ const { codexHome, homeDir, pluginRoot } = await setup();+ await fs.writeFile(path.join(pluginRoot, 'skills', 'browser.md'), 'tampered browser skill');++ const result = await prepareCodexBrowserCompanion({+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle: async () => true,+ });++ expect(result).toMatchObject({+ status: 'unavailable',+ reason: 'plugin_package_untrusted',+ });+ });++ it('fails closed when the verified runtime has no connected Chrome browser', async () => {+ const { codexHome, homeDir } = await setup();++ const result = await checkCodexBrowserCompanionConnection(+ {+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle: async () => true,+ },+ async () => false,+ );++ expect(result).toMatchObject({+ status: 'unavailable',+ reason: 'browser_unavailable',+ });+ });++ it.skipIf(process.platform === 'win32')('probes Chrome through the clean node_repl transport at session time', async () => {+ const fakeNodeRepl = [+ `#!${process.execPath}`,+ "const readline = require('node:readline');",+ "const input = readline.createInterface({ input: process.stdin });",+ "input.on('line', (line) => {",+ " const request = JSON.parse(line);",+ " if (request.id == null) return;",+ " let result = {};",+ " if (request.method === 'initialize') {",+ " result = {",+ " protocolVersion: request.params.protocolVersion,",+ " capabilities: { tools: {} },",+ " serverInfo: { name: 'fake-node-repl', version: '0.0.0' },",+ " };",+ " } else if (request.method === 'tools/call') {",+ " const metadata = request.params._meta?.['x-codex-turn-metadata'];",+ " const code = request.params.arguments?.code ?? '';",+ " const valid = request.params.name === 'js'",+ " && typeof metadata?.session_id === 'string'",+ " && typeof metadata?.turn_id === 'string'",+ " && code.includes('setupBrowserRuntime')",+ " && code.includes('agent.browsers.list()')",+ " && code.includes('setTimeout(resolve, 2000)');",+ " result = { content: [{ type: 'text', text: String(valid) }], isError: false };",+ " }",+ " process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\\n');",+ "});",+ '',+ ].join('\n');+ const { codexHome, homeDir, nodeRepl, signedPluginRoot } = await setup({+ nodeReplContent: fakeNodeRepl,+ });+ const signedBrowserClient = path.join(signedPluginRoot, 'scripts', 'browser-client.mjs');+ await fs.writeFile(+ nodeRepl,+ fakeNodeRepl.replace(+ " && code.includes('agent.browsers.list()')",+ ` && code.includes(${JSON.stringify(signedBrowserClient)})\n && code.includes('agent.browsers.list()')`,+ ),+ 'utf8',+ );++ const result = await checkCodexBrowserCompanionConnection({+ codexHome,+ homeDir,+ platform: 'darwin',+ arch: 'arm64',+ verifyMacBundle: async () => true,+ });++ expect(result).toMatchObject({ status: 'ready', version: '26.727.51351' });+ });+});diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.tsindex fe6f336f92..236dcf3744 100644--- a/apps/desktop/src/main/maker-host/auth-adapters.ts+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts@@ -108,7 +108,7 @@ const log = createLogger('auth-adapters');export { CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY } from './claude-gateway-config.js';/** Codex CLI 的 HOME 目录, auth.json 放在根, sessions 子目录放会话 jsonl。 */-function getCodexHome(): string {+export function getCodexHome(): string {return path.join(app.getPath('userData'), 'codex-home');}diff --git a/apps/desktop/src/main/maker-host/capability-routing.ts b/apps/desktop/src/main/maker-host/capability-routing.tsindex 0c7be27fc7..1ee6373cd3 100644--- a/apps/desktop/src/main/maker-host/capability-routing.ts+++ b/apps/desktop/src/main/maker-host/capability-routing.ts@@ -133,22 +133,96 @@ export const DESKTOP_CAPABILITY_ROUTING_POLICY = {],} as const satisfies CapabilityRoutingPolicy;-/**- * Freeze the routing policy for one Codex session.- *- * Disabling the downstream plugin is replacement arbitration, so it only- * applies after the current Codex environment actually exposes cindy_computer.- * The base policy still hides the incompatible node_repl Skill when the Cindy- * replacement is unavailable, without changing the plugin-wide setting.- */+const CODEX_IN_APP_BROWSER_UNAVAILABLE_OVERRIDE = {+ capabilityId: 'browser-use',+ source: {+ kind: 'harness-plugin',+ harness: 'codex',+ surface: 'plugin',+ id: 'browser@openai-bundled',+ },+ invocation: 'disabled',+ reason: 'Cindy does not host the ChatGPT in-app browser runtime.',+} as const satisfies CapabilityRoutingPolicy['overrides'][number];++const CODEX_CHROME_USE_OVERRIDES = [+ {+ capabilityId: 'browser-use',+ source: {+ kind: 'harness-plugin',+ harness: 'codex',+ surface: 'plugin',+ id: 'chrome@openai-bundled',+ },+ invocation: 'disabled',+ replacement: {+ kind: 'cindy-plugin',+ id: 'browser',+ },+ reason: 'Cindy Browser owns browser automation while it is enabled for this workspace.',+ },+ {+ capabilityId: 'browser-use',+ source: {+ kind: 'harness-plugin',+ harness: 'codex',+ surface: 'mcp',+ id: 'node_repl',+ },+ invocation: 'disabled',+ replacement: {+ kind: 'cindy-plugin',+ id: 'browser',+ },+ reason: 'Cindy Browser owns browser automation while it is enabled for this workspace.',+ },+] as const satisfies CapabilityRoutingPolicy['overrides'];++const CODEX_CHROME_USE_UNAVAILABLE_OVERRIDES = CODEX_CHROME_USE_OVERRIDES.map(+ (override) => ({+ capabilityId: override.capabilityId,+ source: override.source,+ invocation: override.invocation,+ reason: 'The official Codex Browser companion is unavailable in this runtime.',+ }),+) satisfies CapabilityRoutingPolicy['overrides'];++/** Freeze workspace-scoped capability arbitration for one new runtime. */export function buildDesktopCapabilityRoutingPolicy(opts: {- cindyComputerAvailable: boolean;+ /** Whether the current Codex bridge exposes Cindy's Computer Use host. */+ cindyComputerAvailable?: boolean;+ /** Workspace-scoped Cindy Browser ownership snapshot. */+ cindyBrowserEnabled?: boolean;+ codexBrowserUseAvailable?: boolean;+ /** Remote Codex cannot invoke the local Cindy Browser plugin bridge. */+ remoteHostId?: string | null;}): CapabilityRoutingPolicy {- if (!opts.cindyComputerAvailable) return DESKTOP_CAPABILITY_ROUTING_POLICY;+ const cindyBrowserEnabled = opts.remoteHostId+ ? undefined+ : opts.cindyBrowserEnabled;+ const computerUseAvailable =+ opts.cindyComputerAvailable ?? cindyBrowserEnabled !== undefined;+ const computerOverrides = computerUseAvailable+ ? [CODEX_COMPUTER_USE_REPLACEMENT_ROUTE]+ : [];+ const chromeOverrides = cindyBrowserEnabled === undefined+ ? []+ : cindyBrowserEnabled+ ? CODEX_CHROME_USE_OVERRIDES+ : opts.codexBrowserUseAvailable === false+ ? CODEX_CHROME_USE_UNAVAILABLE_OVERRIDES+ : [];return {overrides: [...DESKTOP_CAPABILITY_ROUTING_POLICY.overrides,- CODEX_COMPUTER_USE_REPLACEMENT_ROUTE,+ ...computerOverrides,+ {+ ...CODEX_IN_APP_BROWSER_UNAVAILABLE_OVERRIDE,+ ...(cindyBrowserEnabled === true+ ? { replacement: { kind: 'cindy-plugin' as const, id: 'browser' } }+ : {}),+ },+ ...chromeOverrides,],};}diff --git a/apps/desktop/src/main/maker-host/codex-browser-companion.ts b/apps/desktop/src/main/maker-host/codex-browser-companion.tsnew file mode 100644index 0000000000..d2d8ae899c--- /dev/null+++ b/apps/desktop/src/main/maker-host/codex-browser-companion.ts@@ -0,0 +1,625 @@+import path from 'node:path';+import os from 'node:os';+import { constants as fsConstants, promises as fsp } from 'node:fs';+import { createHash, randomUUID } from 'node:crypto';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { parse as parseToml } from 'smol-toml';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';++const execFileAsync = promisify(execFile);+const OPENAI_TEAM_ID = '2DC432GLL2';+const SOURCE_PLUGIN_KEY = 'chrome@openai-bundled';++/**+ * Match the signed Codex app's designated requirement, not merely a valid+ * self-signed bundle that happens to report OpenAI's TeamIdentifier.+ */+export const OFFICIAL_MAC_BUNDLE_REQUIREMENT = [+ 'anchor apple generic',+ 'identifier "com.openai.codex"',+ 'certificate 1[field.1.2.840.113635.100.6.2.6] exists',+ 'certificate leaf[field.1.2.840.113635.100.6.1.13] exists',+ `certificate leaf[subject.OU] = "${OPENAI_TEAM_ID}"`,+].join(' and ');++export type CodexBrowserCompanionUnavailableReason =+ | 'provider_not_installed'+ | 'platform_unsupported'+ | 'descriptor_invalid'+ | 'provider_untrusted'+ | 'runtime_missing'+ | 'browser_client_untrusted'+ | 'plugin_package_untrusted'+ | 'extension_host_missing'+ | 'browser_unavailable';++export type CodexBrowserCompanionResult =+ | {+ status: 'ready';+ extraArgs: string[];+ version: string;+ startupTimeoutMs: number;+ browserClientPath: string;+ }+ | {+ status: 'unavailable';+ extraArgs: [];+ reason: CodexBrowserCompanionUnavailableReason;+ detail: string;+ };++export type CodexBrowserCompanionSpawnConfig = {+ codexBrowserUseAvailable: boolean;+ extraArgs: string[];+};++/**+ * Only a verified companion may enable Cindy's privileged node_repl bridge.+ * A null result belongs to the control-plane host and must remain neutral;+ * every concrete unavailable result fails closed for the local app-server.+ */+export function resolveCodexBrowserCompanionSpawnConfig(+ companion: CodexBrowserCompanionResult | null,+): CodexBrowserCompanionSpawnConfig {+ if (companion === null) {+ return { codexBrowserUseAvailable: false, extraArgs: [] };+ }+ if (companion.status === 'ready') {+ return { codexBrowserUseAvailable: true, extraArgs: companion.extraArgs };+ }+ return {+ codexBrowserUseAvailable: false,+ extraArgs: ['-c', 'mcp_servers.node_repl.enabled=false'],+ };+}++interface PrepareCodexBrowserCompanionOptions {+ codexHome: string;+ homeDir?: string;+ platform?: NodeJS.Platform;+ arch?: string;+ /** Tests can replace macOS signature verification without spawning codesign. */+ verifyMacBundle?: (appBundle: string) => Promise<boolean>;+}++function unavailable(+ reason: CodexBrowserCompanionUnavailableReason,+ detail: string,+): CodexBrowserCompanionResult {+ return { status: 'unavailable', extraArgs: [], reason, detail };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++async function exists(file: string, mode = fsConstants.F_OK): Promise<boolean> {+ try {+ await fsp.access(file, mode);+ return true;+ } catch {+ return false;+ }+}++async function runOfficialMacBundleVerification(appBundle: string): Promise<boolean> {+ try {+ await execFileAsync(+ '/usr/bin/codesign',+ buildOfficialMacBundleVerificationArgs(appBundle),+ );+ const { stderr } = await execFileAsync('/usr/bin/codesign', [+ '-dv',+ '--verbose=4',+ appBundle,+ ]);+ return hasOfficialMacTeamIdentifier(stderr);+ } catch {+ return false;+ }+}++/** Keep the privileged verifier's trust requirement visible and testable. */+export function buildOfficialMacBundleVerificationArgs(appBundle: string): string[] {+ return [+ '--verify',+ '--deep',+ '--strict',+ '--test-requirement',+ `=${OFFICIAL_MAC_BUNDLE_REQUIREMENT}`,+ appBundle,+ ];+}++/** Parse the codesign descriptor as fields, never as an arbitrary substring. */+export function hasOfficialMacTeamIdentifier(descriptor: string): boolean {+ return descriptor.split(/\r?\n/).some((line) => {+ const match = /^TeamIdentifier=([A-Za-z0-9]+)$/.exec(line.trim());+ return match?.[1] === OPENAI_TEAM_ID;+ });+}++function verifyOfficialMacBundle(appBundle: string): Promise<boolean> {+ // Do not cache by pathname: ChatGPT.app can be replaced in place by an+ // updater, and a stale positive verification would stop being a trust root.+ return runOfficialMacBundleVerification(appBundle);+}++function macBundleForNodeRepl(command: string): string | null {+ const suffix = path.join('Contents', 'Resources', 'cua_node', 'bin', 'node_repl');+ if (!path.isAbsolute(command) || !command.endsWith(suffix)) return null;+ const appBundle = command.slice(0, -suffix.length).replace(/[\\/]$/, '');+ return appBundle.endsWith('.app') ? appBundle : null;+}++function extensionHostPath(+ pluginRoot: string,+ platform: NodeJS.Platform,+ arch: string,+): string | null {+ if (arch !== 'arm64' && arch !== 'x64') return null;+ if (platform === 'darwin') {+ return path.join(pluginRoot, 'extension-host', 'macos', arch, 'ChatGPT for Chrome');+ }+ return null;+}++async function sha256(file: string): Promise<string> {+ return createHash('sha256').update(await fsp.readFile(file)).digest('hex');+}++async function collectPackageTree(+ root: string,+ relativeRoot = '',+): Promise<Map<string, string>> {+ const entries = await fsp.readdir(root, { withFileTypes: true });+ entries.sort((left, right) => left.name.localeCompare(right.name));+ const tree = new Map<string, string>();+ for (const entry of entries) {+ const absolutePath = path.join(root, entry.name);+ const relativePath = relativeRoot+ ? `${relativeRoot}/${entry.name}`+ : entry.name;+ if (entry.isDirectory()) {+ tree.set(`${relativePath}/`, 'directory');+ for (const [childPath, childHash] of await collectPackageTree(absolutePath, relativePath)) {+ tree.set(childPath, childHash);+ }+ continue;+ }+ if (entry.isFile()) {+ tree.set(relativePath, `file:${await sha256(absolutePath)}`);+ continue;+ }+ throw new Error(`unsupported package entry: ${relativePath}`);+ }+ return tree;+}++async function packageTreesMatch(activeRoot: string, signedRoot: string): Promise<boolean> {+ try {+ const [activeTree, signedTree] = await Promise.all([+ collectPackageTree(activeRoot),+ collectPackageTree(signedRoot),+ ]);+ if (activeTree.size !== signedTree.size) return false;+ for (const [relativePath, signedHash] of signedTree) {+ if (activeTree.get(relativePath) !== signedHash) return false;+ }+ return true;+ } catch {+ return false;+ }+}++function withTimeout<T>(task: Promise<T>, timeoutMs: number, label: string): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);+ timer.unref?.();+ void task.then(+ (value) => {+ clearTimeout(timer);+ resolve(value);+ },+ (error: unknown) => {+ clearTimeout(timer);+ reject(error);+ },+ );+ });+}++async function probeCodexChrome(+ companion: Extract<CodexBrowserCompanionResult, { status: 'ready' }>,+): Promise<boolean> {+ const encodedArgs = companion.extraArgs.find((arg) => (+ arg.startsWith('mcp_servers.node_repl.args=')+ ));+ if (!encodedArgs) return false;+ const parsedArgs: unknown = JSON.parse(+ encodedArgs.slice('mcp_servers.node_repl.args='.length),+ );+ if (+ !Array.isArray(parsedArgs)+ || parsedArgs.some((arg) => typeof arg !== 'string')+ ) return false;+ const args = parsedArgs as string[];++ const transport = new StdioClientTransport({+ command: '/usr/bin/env',+ args,+ stderr: 'pipe',+ });+ // The child emits diagnostics on stderr. Drain the pipe so a noisy failure+ // cannot block shutdown; the caller reports only the stable availability fact.+ transport.stderr?.on('data', () => undefined);+ const client = new Client({ name: 'cindy-browser-preflight', version: '0.0.0' });+ const probeTimeoutMs = Math.min(companion.startupTimeoutMs, 10_000);+ try {+ return await withTimeout((async () => {+ await client.connect(transport);+ // The wrapper passes the isolated CODEX_HOME to node_repl, but this host+ // process may use a different CODEX_HOME. Recover the verified path from+ // the clean child environment instead of relying on process.env.+ const codexHomeArg = args.find((arg) => arg.startsWith('CODEX_HOME='));+ if (!codexHomeArg) return false;+ const verifiedBrowserClient = companion.browserClientPath;+ const turnMetadata = {+ 'x-codex-turn-metadata': {+ session_id: `cindy-browser-preflight-${randomUUID()}`,+ turn_id: randomUUID(),+ },+ };+ const result = await client.callTool({+ name: 'js',+ arguments: {+ code: [+ 'if (globalThis.agent?.browsers == null) {',+ ` const { setupBrowserRuntime } = await import(${JSON.stringify(verifiedBrowserClient)});`,+ ' await setupBrowserRuntime({ globals: globalThis });',+ '}',+ 'var cindyChromeCandidates = await agent.browsers.list();',+ 'if (!cindyChromeCandidates.some((browser) => browser.type === "extension" && browser.family === "chrome")) {',+ ' await new Promise((resolve) => setTimeout(resolve, 2000));',+ ' cindyChromeCandidates = await agent.browsers.list();',+ '}',+ 'nodeRepl.write(cindyChromeCandidates.some((browser) => browser.type === "extension" && browser.family === "chrome"));',+ ].join('\n'),+ timeout_ms: probeTimeoutMs,+ },+ _meta: turnMetadata,+ });+ if (+ result.isError === true+ || !('content' in result)+ || !Array.isArray(result.content)+ ) return false;+ return result.content.some((item: unknown) => (+ isRecord(item)+ && item.type === 'text'+ && typeof item.text === 'string'+ && item.text.trim() === 'true'+ ));+ })(), probeTimeoutMs, 'Chrome browser connection probe');+ } catch {+ return false;+ } finally {+ try {+ await client.close();+ } catch {+ try {+ await transport.close();+ } catch {+ // Best-effort cleanup after a failed or timed-out preflight.+ }+ }+ }+}++/**+ * Build an ephemeral, allowlisted node_repl configuration for this app-server.+ * The user's Codex config is only a descriptor source; its arbitrary commands+ * and environment variables are never copied into Cindy's isolated runtime.+ */+async function inspectCodexBrowserCompanion(+ opts: PrepareCodexBrowserCompanionOptions,+): Promise<CodexBrowserCompanionResult> {+ const platform = opts.platform ?? process.platform;+ const arch = opts.arch ?? process.arch;+ const homeDir = opts.homeDir ?? os.homedir();+ if (platform !== 'darwin') {+ return unavailable(+ 'platform_unsupported',+ `official Codex Browser companion validation is not implemented for ${platform}`,+ );+ }++ const sourceHome = path.join(homeDir, '.codex');+ const sourceConfig = path.join(sourceHome, 'config.toml');+ let parsed: Record<string, unknown>;+ try {+ parsed = parseToml(await fsp.readFile(sourceConfig, 'utf8')) as Record<string, unknown>;+ } catch (error) {+ return unavailable(+ 'provider_not_installed',+ `cannot read the official Codex companion descriptor: ${error instanceof Error ? error.message : String(error)}`,+ );+ }++ const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};+ const sourcePlugin = plugins[SOURCE_PLUGIN_KEY];+ if (!isRecord(sourcePlugin) || sourcePlugin.enabled !== true) {+ return unavailable('provider_not_installed', `${SOURCE_PLUGIN_KEY} is not enabled`);+ }+ const mcpServers = isRecord(parsed.mcp_servers) ? parsed.mcp_servers : {};+ const nodeRepl = mcpServers.node_repl;+ if (!isRecord(nodeRepl)) {+ return unavailable('descriptor_invalid', 'the official node_repl descriptor is missing');+ }+ if (nodeRepl.enabled === false) {+ return unavailable('provider_not_installed', 'node_repl is disabled in the official Codex config');+ }+ if (typeof nodeRepl.command !== 'string') {+ return unavailable('descriptor_invalid', 'the official node_repl descriptor is missing');+ }+ if (+ nodeRepl.args !== undefined+ && (!Array.isArray(nodeRepl.args) || nodeRepl.args.length !== 0)+ ) {+ return unavailable('descriptor_invalid', 'node_repl arguments are not allowlisted');+ }+ const env = isRecord(nodeRepl.env) ? nodeRepl.env : null;+ const appBundle = macBundleForNodeRepl(nodeRepl.command);+ const verifyMacBundle = opts.verifyMacBundle ?? verifyOfficialMacBundle;+ if (!appBundle || !(await verifyMacBundle(appBundle))) {+ return unavailable('provider_untrusted', 'node_repl is not inside an OpenAI-signed app bundle');+ }++ const nodePath = env?.NODE_REPL_NODE_PATH;+ const moduleDirs = env?.NODE_REPL_NODE_MODULE_DIRS;+ const codexCliPath = env?.CODEX_CLI_PATH;+ const requiredExecutables = [nodeRepl.command, nodePath, codexCliPath];+ if (+ requiredExecutables.some((value) => typeof value !== 'string')+ || typeof moduleDirs !== 'string'+ ) {+ return unavailable('descriptor_invalid', 'required companion runtime paths are missing');+ }+ const resources = path.join(appBundle, 'Contents', 'Resources');+ const expectedRuntimePaths = {+ nodeRepl: path.join(resources, 'cua_node', 'bin', 'node_repl'),+ nodePath: path.join(resources, 'cua_node', 'bin', 'node'),+ moduleDirs: path.join(resources, 'cua_node', 'lib', 'node_modules'),+ codexCliPath: path.join(resources, 'codex'),+ };+ const requiredPaths = [+ // Tests may simulate a macOS target on a Windows runner. The production+ // macOS path is still checked against the real system executable.+ ...(platform === process.platform ? [['/usr/bin/env', fsConstants.X_OK] as const] : []),+ [nodeRepl.command, fsConstants.X_OK],+ [nodePath as string, fsConstants.X_OK],+ [codexCliPath as string, fsConstants.X_OK],+ [moduleDirs, fsConstants.F_OK],+ ] as const;+ for (const [file, mode] of requiredPaths) {+ if (!(await exists(file, mode))) {+ return unavailable('runtime_missing', `required companion runtime is missing: ${file}`);+ }+ }+ const [actualNodeRepl, actualNodePath, actualModuleDirs, actualCodexCli, expectedNodeRepl,+ expectedNodePath, expectedModuleDirs, expectedCodexCli] = await Promise.all([+ fsp.realpath(nodeRepl.command),+ fsp.realpath(nodePath as string),+ fsp.realpath(moduleDirs),+ fsp.realpath(codexCliPath as string),+ fsp.realpath(expectedRuntimePaths.nodeRepl),+ fsp.realpath(expectedRuntimePaths.nodePath),+ fsp.realpath(expectedRuntimePaths.moduleDirs),+ fsp.realpath(expectedRuntimePaths.codexCliPath),+ ]);+ if (+ actualNodeRepl !== expectedNodeRepl+ || actualNodePath !== expectedNodePath+ || actualModuleDirs !== expectedModuleDirs+ || actualCodexCli !== expectedCodexCli+ ) {+ return unavailable(+ 'provider_untrusted',+ 'the companion descriptor points outside its signed app bundle runtime',+ );+ }+ const signedPluginRoot = path.join(+ resources,+ 'plugins',+ 'openai-bundled',+ 'plugins',+ 'chrome',+ );+ let version: string;+ try {+ const manifest = JSON.parse(+ await fsp.readFile(path.join(signedPluginRoot, '.codex-plugin', 'plugin.json'), 'utf8'),+ ) as Record<string, unknown>;+ if (manifest.name !== 'chrome' || typeof manifest.version !== 'string') {+ throw new Error('invalid signed Chrome plugin manifest');+ }+ version = manifest.version;+ } catch (error) {+ return unavailable(+ 'runtime_missing',+ `signed Chrome plugin metadata is unavailable: ${error instanceof Error ? error.message : String(error)}`,+ );+ }++ let isolatedConfig: Record<string, unknown>;+ try {+ isolatedConfig = parseToml(+ await fsp.readFile(path.join(opts.codexHome, 'config.toml'), 'utf8'),+ ) as Record<string, unknown>;+ } catch (error) {+ return unavailable(+ 'provider_not_installed',+ `cannot read Cindy's isolated Codex plugin config: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ const isolatedPlugins = isRecord(isolatedConfig.plugins) ? isolatedConfig.plugins : {};+ const isolatedPlugin = isolatedPlugins[SOURCE_PLUGIN_KEY];+ if (!isRecord(isolatedPlugin) || isolatedPlugin.enabled !== true) {+ return unavailable(+ 'provider_not_installed',+ `${SOURCE_PLUGIN_KEY} is not enabled in Cindy's isolated Codex runtime`,+ );+ }++ const pluginRoot = path.join(+ opts.codexHome,+ 'plugins',+ 'cache',+ 'openai-bundled',+ 'chrome',+ version,+ );+ const selectedPluginRoot = path.join(path.dirname(pluginRoot), 'latest');+ try {+ const [selectedRoot, exactRoot] = await Promise.all([+ fsp.realpath(selectedPluginRoot),+ fsp.realpath(pluginRoot),+ ]);+ if (selectedRoot !== exactRoot) {+ return unavailable(+ 'runtime_missing',+ `the active Chrome plugin does not match the signed version ${version}`,+ );+ }+ } catch (error) {+ return unavailable(+ 'runtime_missing',+ `cannot resolve the active Chrome plugin version: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ const browserClient = path.join(pluginRoot, 'scripts', 'browser-client.mjs');+ if (!(await exists(browserClient))) {+ return unavailable('runtime_missing', `browser client is missing for plugin version ${version}`);+ }+ const actualHash = await sha256(browserClient);+ const signedBrowserClient = path.join(signedPluginRoot, 'scripts', 'browser-client.mjs');+ if (!(await exists(signedBrowserClient)) || actualHash !== await sha256(signedBrowserClient)) {+ return unavailable(+ 'browser_client_untrusted',+ `browser client does not match the signed plugin version ${version}`,+ );+ }+ const hostPath = extensionHostPath(pluginRoot, platform, arch);+ const signedHostPath = extensionHostPath(signedPluginRoot, platform, arch);+ if (+ !hostPath+ || !signedHostPath+ || !(await exists(hostPath, fsConstants.X_OK))+ || !(await exists(signedHostPath, fsConstants.X_OK))+ || await sha256(hostPath) !== await sha256(signedHostPath)+ ) {+ return unavailable(+ 'extension_host_missing',+ `Chrome extension host is missing for ${platform}/${arch}`,+ );+ }+ if (!(await packageTreesMatch(pluginRoot, signedPluginRoot))) {+ return unavailable(+ 'plugin_package_untrusted',+ `the active Chrome plugin package does not match the signed version ${version}`,+ );+ }++ const startupTimeout =+ typeof nodeRepl.startup_timeout_sec === 'number'+ && Number.isFinite(nodeRepl.startup_timeout_sec)+ && nodeRepl.startup_timeout_sec > 0+ ? Math.min(nodeRepl.startup_timeout_sec, 300)+ : 120;+ const injectedEnv: Record<string, string> = {+ CODEX_HOME: opts.codexHome,+ CODEX_CLI_PATH: codexCliPath as string,+ NODE_REPL_NATIVE_PIPE_CONNECT_TIMEOUT_MS: '1000',+ NODE_REPL_NODE_MODULE_DIRS: moduleDirs,+ NODE_REPL_NODE_PATH: nodePath as string,+ // The exact signed browser-client hash is enough to enter the privileged+ // context; its dependency graph inherits that context. Trusting the whole+ // CODEX_HOME would also trust arbitrary third-party plugin code.+ NODE_REPL_TRUSTED_BROWSER_CLIENT_SHA256S: actualHash,+ NODE_REPL_INSTRUCTIONS_USE_CASE_BROWSER:+ 'Control Chrome through the official Codex Browser plugin.',+ NODE_REPL_INSTRUCTIONS_USE_CASE_CHROME:+ 'Control Chrome through the official Codex Chrome plugin.',+ // Cindy has no ChatGPT in-app-browser host. Exposing it makes getDefault()+ // select an endpoint that can never connect; Chrome is the supported fallback.+ BROWSER_USE_AVAILABLE_BACKENDS: 'chrome',+ BROWSER_USE_CODEX_APP_BUILD_FLAVOR: 'prod',+ BROWSER_USE_CODEX_APP_VERSION: version,+ };+ const cleanEnvironment = {+ HOME: homeDir,+ PATH: '/usr/bin:/bin',+ TMPDIR: os.tmpdir(),+ ...injectedEnv,+ };+ const cleanEnvironmentArgs = [+ '-i',+ ...Object.entries(cleanEnvironment).map(([key, value]) => `${key}=${value}`),+ nodeRepl.command,+ ];++ const extraArgs = [+ '-c',+ 'mcp_servers.node_repl.command="/usr/bin/env"',+ '-c',+ // `-c` maps deep-merge with an existing config, so replacing `.env` alone+ // cannot delete stale keys. Launch through `env -i` instead: the signed+ // node_repl receives only this allowlist even if the config contains+ // NODE_OPTIONS, broad trusted paths, service paths, or arbitrary secrets.+ `mcp_servers.node_repl.args=${JSON.stringify(cleanEnvironmentArgs)}`,+ '-c',+ `mcp_servers.node_repl.startup_timeout_sec=${startupTimeout}`,+ '-c',+ 'mcp_servers.node_repl.enabled=true',+ ];+ return {+ status: 'ready',+ extraArgs,+ version,+ startupTimeoutMs: startupTimeout * 1_000,+ browserClientPath: signedBrowserClient,+ };+}++export async function prepareCodexBrowserCompanion(+ opts: PrepareCodexBrowserCompanionOptions,+): Promise<CodexBrowserCompanionResult> {+ try {+ return await inspectCodexBrowserCompanion(opts);+ } catch (error) {+ return unavailable(+ 'descriptor_invalid',+ `browser companion preflight failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+}++/**+ * Session-time health gate for the dynamic Chrome connection. Unlike static+ * provisioning, this result must not be frozen into the shared app-server:+ * Chrome can connect or disconnect while Cindy remains open.+ */+export async function checkCodexBrowserCompanionConnection(+ opts: PrepareCodexBrowserCompanionOptions,+ probeChrome: typeof probeCodexChrome = probeCodexChrome,+): Promise<CodexBrowserCompanionResult> {+ const companion = await prepareCodexBrowserCompanion(opts);+ if (companion.status !== 'ready') return companion;+ if (await probeChrome(companion)) return companion;+ return unavailable(+ 'browser_unavailable',+ 'the verified Chrome extension runtime did not publish a connected Chrome browser',+ );+}diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex f5e942ca18..d034ad7d4a 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -54,6 +54,7 @@ import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionSimport {desktopClaudeAuthAdapter,desktopCodexAuthAdapter,+ getCodexHome,readClaudeApiKey,} from './auth-adapters.js';import {@@ -165,7 +166,10 @@ import {invalidateRemoteCcQueriesForMcpGenerationChange,maybeDetachStaleRemoteCcQuery,} from './remote-codex-mcp-recovery.js';-import { CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY } from '../mcp-integrations/codexBuiltinToolPolicy.js';+import {+ CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY,+ readDisabledBuiltinPluginIds,+} from '../mcp-integrations/codexBuiltinToolPolicy.js';import { buildCodexProxySpawnArgs, CODEX_OPENAI_COMPACT_PROVIDER_ID } from './codex-gateway-config.js';import { buildCodexSubagentSpawnArgs } from './codex-subagent-config.js';import { readSubagentModelSettings } from './subagent-model-settings-store.js';@@ -190,6 +194,10 @@ import {buildDesktopCapabilityRoutingPolicy,DESKTOP_CAPABILITY_ROUTING_POLICY,} from './capability-routing.js';+import {+ prepareCodexBrowserCompanion,+ resolveCodexBrowserCompanionSpawnConfig,+} from './codex-browser-companion.js';export { withRehydrateCloseSuppressed };type RemoteCcQuery = Awaited<@@ -993,6 +1001,29 @@ export function getMaker(): Maker {getActiveCodexBridgeServerNames()?.includes('cindy_computer') === true,});},+ resolveCapabilityRouting: async ({+ workingDir,+ remoteHostId,+ vendorOptions,+ codexBrowserUseProvisioned,+ ensureCodexBrowserUseReady,+ }) => {+ const disabledPluginIds =+ readDisabledBuiltinPluginIds(vendorOptions)+ ?? getPluginRegistry().getDisabledRuntimePluginIds(workingDir);+ const cindyBrowserEnabled = !disabledPluginIds.includes('browser');+ let connectedCodexBrowserUse = codexBrowserUseProvisioned;+ if (!remoteHostId && !cindyBrowserEnabled && connectedCodexBrowserUse) {+ connectedCodexBrowserUse = await ensureCodexBrowserUseReady();+ }+ return buildDesktopCapabilityRoutingPolicy({+ cindyComputerAvailable:+ getActiveCodexBridgeServerNames()?.includes('cindy_computer') === true,+ cindyBrowserEnabled,+ codexBrowserUseAvailable: connectedCodexBrowserUse,+ remoteHostId,+ });+ },makerMemory: makerMemoryManager,// 通讯录 prompt 段有效状态(codex 版): 在 claude 的判定链之上再与「实际应用// 到 running app-server 的 spawn 快照」对齐 —— 开关切换后失效失败(busy,@@ -1051,7 +1082,15 @@ export function getMaker(): Maker {},prepareCodexExtraSpawnConfig: async (providers, ctx) => {if (ctx.remoteHostId) {- return { extraArgs: [], extraEnv: {}, codexProxyActive: false };+ // The remote daemon owns its own CODEX_HOME and Chrome companion.+ // Do not let the local Desktop platform or local companion probe+ // disable a remote runtime that is already configured there.+ return {+ extraArgs: [],+ extraEnv: {},+ codexProxyActive: false,+ codexBrowserUseAvailable: true,+ };}let mcpExtraArgs: string[] = [];let mcpExtraEnv: Record<string, string> = {};@@ -1063,7 +1102,9 @@ export function getMaker(): Maker {mcpProviders: providers,logger: desktopMakerLogger,});- mcpExtraArgs = cfg.extraArgs;+ // getCodexExtraSpawnConfig may return a cached array; per-host+ // Browser overrides must never mutate that shared snapshot.+ mcpExtraArgs = [...cfg.extraArgs];mcpExtraEnv = cfg.extraEnv;buildSessionMcpConfig = cfg.buildSessionMcpConfig;// 本次 spawn 配置实际应用的通讯录可用性快照 —— 从返回的 cfg 本体推导,@@ -1078,6 +1119,22 @@ export function getMaker(): Maker {// bridge 整体缺席 = cindy_contacts 必然不可达codexAppliedContactsEnabled = false;}+ const isControlPlane = ctx.hostPurpose === 'control-plane';+ const browserCompanion = isControlPlane+ ? null+ : await prepareCodexBrowserCompanion({ codexHome: getCodexHome() });+ const browserCompanionSpawnConfig =+ resolveCodexBrowserCompanionSpawnConfig(browserCompanion);+ mcpExtraArgs.push(...browserCompanionSpawnConfig.extraArgs);+ if (+ browserCompanion?.status === 'unavailable' &&+ browserCompanion.reason !== 'platform_unsupported'+ ) {+ desktopMakerLogger.warn('Codex Browser companion unavailable', {+ reason: browserCompanion.reason,+ detail: browserCompanion.detail,+ });+ }// API 模式: 追加 model_provider override, 让 codex app-server 走 AI Gateway// 而非 OAuth 订阅后端。每次 createHost 都现读 mode, 切模式后重建即生效。// 关掉 API 模式则不带这些 flag —— 天然可逆 (见 codex-gateway-config.ts)。@@ -1097,7 +1154,6 @@ export function getMaker(): Maker {? 'provider-oauth': 'env-key';const useOAuthBearer = authInjection === 'oauth-bearer';- const isControlPlane = ctx.hostPurpose === 'control-plane';if (!isControlPlane) {setCodexProxyAuthInjection(authInjection);await broadcastCodexRuntimeRoute();@@ -1140,6 +1196,13 @@ export function getMaker(): Maker {extraEnv: mcpExtraEnv,...(buildSessionMcpConfig ? { buildSessionMcpConfig } : {}),codexProxyActive: ready,+ codexBrowserUseAvailable: browserCompanionSpawnConfig.codexBrowserUseAvailable,+ ...(browserCompanion?.status === 'ready'+ ? {+ codexBrowserUseVersion: browserCompanion.version,+ codexBrowserUseStartupTimeoutMs: browserCompanion.startupTimeoutMs,+ }+ : {}),// oauth spawn 才定义 OpenAI 身份 provider(spawn args 同源);maker-core 只对// 「订阅直连路由」的 thread 用它开 OpenAI 远端压缩,其余 thread 保持本地压缩。...(useOAuthBearer && ready@@ -1151,7 +1214,9 @@ export function getMaker(): Maker {// Codex shares one app-server across sessions. Freeze the effective// ordinary-tool policy at thread creation so later Settings changes do// not mutate a runtime that is already running.- const disabledPluginIds = getPluginRegistry().getDisabledRuntimePluginIds(workingDir);+ const disabledPluginIds =+ readDisabledBuiltinPluginIds(vendorOptions)+ ?? getPluginRegistry().getDisabledRuntimePluginIds(workingDir);registerCodexMcpThreadContext(threadId, {agentKind: 'codex',sessionId,@@ -1387,6 +1452,15 @@ export function getMaker(): Maker {);}await preparePersistedOrcaSessionStart(sessionId, opts as MakerSessionCreateOpts);+ if (opts.agentKind === 'codex') {+ const disabledPluginIds = getPluginRegistry().getDisabledRuntimePluginIds(+ opts.workingDir,+ );+ opts.vendorOptions = {+ ...(opts.vendorOptions ?? {}),+ [CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY]: disabledPluginIds,+ };+ }},onBeforeStart: async ({ agentKind, workingDir, remoteHostId }) => {// 延迟记忆重启 pending 时,本地 Codex 新会话加入 shared host 前先尝试diff --git a/apps/desktop/src/main/maker-ipc/codexMcpRefresh.ts b/apps/desktop/src/main/maker-ipc/codexMcpRefresh.tsindex 00fafcf0f1..6fa3068ae9 100644--- a/apps/desktop/src/main/maker-ipc/codexMcpRefresh.ts+++ b/apps/desktop/src/main/maker-ipc/codexMcpRefresh.ts@@ -8,6 +8,8 @@export async function refreshCodexMcpEnvironment(deps: {restartCodex: () => Promise<void>;shutdownCodexEnvironment: () => Promise<void>;+ /** Schedule the same refresh for the next idle boundary when the host is busy. */+ onDeferred?: () => void;logger?: {warn: (message: string, meta?: Record<string, unknown>) => void;};@@ -18,6 +20,7 @@ export async function refreshCodexMcpEnvironment(deps: {deps.logger?.warn('Codex MCP refresh deferred because the shared host could not restart', {error: err instanceof Error ? err.message : String(err),});+ deps.onDeferred?.();return { codexMcpRefreshed: false };}@@ -27,6 +30,7 @@ export async function refreshCodexMcpEnvironment(deps: {deps.logger?.warn('Codex MCP refresh deferred because the old bridge could not shut down', {error: err instanceof Error ? err.message : String(err),});+ deps.onDeferred?.();return { codexMcpRefreshed: false };}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 7b2510e7c5..eb405d7f1c 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -11769,7 +11769,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// Ordinary plugins are user defaults: existing sessions keep their frozen// policy and only new sessions observe changes, so no shared environment// refresh is needed.- if (!GLOBAL_PLUGIN_IDS.has(id)) {+ if (!GLOBAL_PLUGIN_IDS.has(id) && id !== 'browser') {return { codexMcpRefreshed: true };}// Machine-wide tools keep their existing lifecycle. The preference is@@ -11779,6 +11779,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return refreshCodexMcpEnvironment({restartCodex: restartCodexAfterAuthModeChange,shutdownCodexEnvironment,+ onDeferred: () => deferredCodexRestartHolder?.schedule('Codex Browser capability routing changed'),logger: log,});});@@ -11791,12 +11792,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (!ok) {throwIpcError('PERMISSION_DENIED', `Cannot modify essential plugin: ${id}`);}- if (!GLOBAL_PLUGIN_IDS.has(id)) {+ if (!GLOBAL_PLUGIN_IDS.has(id) && id !== 'browser') {return { codexMcpRefreshed: true };}return refreshCodexMcpEnvironment({restartCodex: restartCodexAfterAuthModeChange,shutdownCodexEnvironment,+ onDeferred: () => deferredCodexRestartHolder?.schedule('Codex Browser capability routing changed'),logger: log,});});diff --git a/apps/desktop/src/main/mcp-integrations/codexBuiltinToolPolicy.ts b/apps/desktop/src/main/mcp-integrations/codexBuiltinToolPolicy.tsindex 2418993ba4..83c66e9632 100644--- a/apps/desktop/src/main/mcp-integrations/codexBuiltinToolPolicy.ts+++ b/apps/desktop/src/main/mcp-integrations/codexBuiltinToolPolicy.ts@@ -3,3 +3,14 @@* one Codex thread across maker-core and the desktop HTTP MCP bridge.*/export const CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY = '__cindyDisabledBuiltinPluginIds';++/** Read a valid frozen built-in policy without widening malformed input. */+export function readDisabledBuiltinPluginIds(+ vendorOptions: Readonly<Record<string, unknown>> | undefined,+): string[] | null {+ const raw = vendorOptions?.[CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY];+ if (!Array.isArray(raw) || !raw.every((value) => typeof value === 'string')) {+ return null;+ }+ return [...raw];+}diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 75f7945578..6f07097670 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -213,6 +213,12 @@ export interface PiExtraSpawnConfigContext {export interface CodexExtraSpawnConfig {extraArgs: string[];extraEnv: Record<string, string>;+ /** Whether this exact app-server spawn was provisioned with Codex Chrome. */+ codexBrowserUseAvailable?: boolean;+ /** Exact verified Chrome plugin version provisioned into this app-server. */+ codexBrowserUseVersion?: string;+ /** Maximum startup wait copied from the verified companion descriptor. */+ codexBrowserUseStartupTimeoutMs?: number;/*** Build per-thread config overrides that bind host-owned HTTP MCP URLs to one* in-memory Session instance. The app-server process is shared, so the spawn@@ -384,6 +390,23 @@ export interface AgentDeps {*/capabilityRouting?: CapabilityRoutingPolicy;+ /**+ * Resolve capability arbitration once for a new session. Use this for+ * workspace-scoped sources whose effective state is already frozen into+ * vendorOptions by the host. Static capabilityRouting remains the fallback.+ */+ resolveCapabilityRouting?: (ctx: {+ workingDir: string;+ remoteHostId?: string | null;+ vendorOptions: Readonly<Record<string, unknown>>;+ /** Frozen fact: the concrete app-server was provisioned with the companion. */+ codexBrowserUseProvisioned: boolean;+ /** Exact Chrome plugin version bound to that host, when provisioned. */+ codexBrowserUseVersion: string | null;+ /** Post-start readiness check, invoked only when this session needs the fallback. */+ ensureCodexBrowserUseReady: () => Promise<boolean>;+ }) => CapabilityRoutingPolicy | undefined | Promise<CapabilityRoutingPolicy | undefined>;+/*** 解析某条**具体路由**上该模型已核实的上下文窗口上限(host 注入);没有则返回 null。*diff --git a/packages/maker-core/src/agents/codex/app-server/host.test.ts b/packages/maker-core/src/agents/codex/app-server/host.test.tsindex ee12f69de3..be97be52d6 100644--- a/packages/maker-core/src/agents/codex/app-server/host.test.ts+++ b/packages/maker-core/src/agents/codex/app-server/host.test.ts@@ -74,6 +74,10 @@ class NotificationTransport implements Transport {private readonly closeHandlers = new Set<CloseHandler>();readonly lines: string[] = [];+ constructor(+ private readonly resultForMethod?: (method: string) => unknown,+ ) {}+async writeLine(line: string): Promise<void> {this.lines.push(line);const msg = JSON.parse(line) as { id?: unknown; method?: string };@@ -84,7 +88,7 @@ class NotificationTransport implements Transport {codexHome: '/tmp/codex-home',platformOs: 'linux',}- : {};+ : this.resultForMethod?.(msg.method ?? '') ?? {};this.emit({ id: msg.id, result });}@@ -112,6 +116,70 @@ class NotificationTransport implements Transport {}}+describe('AppServerHost MCP readiness', () => {+ it('retries a negative tool probe instead of permanently caching it', async () => {+ let available = false;+ const transport = new NotificationTransport((method) => (+ method === 'mcpServerStatus/list'+ ? {+ data: [{+ name: 'node_repl',+ tools: available ? { js: {} } : {},+ authStatus: 'notApplicable',+ }],+ nextCursor: null,+ }+ : {}+ ));+ const host = new AppServerHost({+ createTransport: () => transport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ codexBrowserUseStartupTimeoutMs: 10,+ });++ await expect(host.waitForMcpTool('node_repl', 'js')).resolves.toBe(false);+ available = true;+ await expect(host.waitForMcpTool('node_repl', 'js')).resolves.toBe(true);++ await host.shutdown();+ });++ it('re-probes MCP readiness after the app-server respawns', async () => {+ const firstTransport = new NotificationTransport((method) => (+ method === 'mcpServerStatus/list'+ ? {+ data: [{ name: 'node_repl', tools: { js: {} }, authStatus: 'notApplicable' }],+ nextCursor: null,+ }+ : {}+ ));+ const secondTransport = new NotificationTransport((method) => (+ method === 'mcpServerStatus/list'+ ? {+ data: [{ name: 'node_repl', tools: {}, authStatus: 'notApplicable' }],+ nextCursor: null,+ }+ : {}+ ));+ const transports = [firstTransport, secondTransport];+ const createTransport = vi.fn(() => transports.shift() ?? secondTransport);+ const host = new AppServerHost({+ createTransport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ codexBrowserUseStartupTimeoutMs: 10,+ });++ await expect(host.waitForMcpTool('node_repl', 'js')).resolves.toBe(true);+ await host.shutdown();+ await expect(host.waitForMcpTool('node_repl', 'js')).resolves.toBe(false);++ expect(createTransport).toHaveBeenCalledTimes(2);+ await host.shutdown();+ });+});+const logger: Logger = {trace: vi.fn(),debug: vi.fn(),@@ -482,6 +550,98 @@ describe('AppServerHost descendant thread routing', () => {await subscription.release();await host.shutdown();});++ it('briefly waits for descendant lineage before declining an MCP elicitation', async () => {+ const transport = new NotificationTransport();+ const host = new AppServerHost({+ createTransport: () => transport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ });+ await host.ensureStarted();++ const mcpServerElicitation = vi.fn(async () => ({+ action: 'accept' as const,+ content: { value: 'ok' },+ _meta: null,+ }));+ const subscription = host.subscribeThread('root-thread', { mcpServerElicitation });+ const initialLineCount = transport.lines.length;++ // The request is dispatched asynchronously. Emit the lineage notification+ // immediately afterwards to reproduce the observed cross-message race.+ transport.emit({+ id: 'early-elicitation',+ method: 'mcpServer/elicitation/request',+ params: {+ threadId: 'child-thread',+ turnId: 'turn-1',+ serverName: 'node_repl',+ mode: 'form',+ _meta: null,+ message: 'Confirm',+ requestedSchema: {},+ },+ });+ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'child-thread', parentThreadId: 'root-thread' } },+ });++ await vi.waitFor(() => {+ expect(transport.lines.length).toBe(initialLineCount + 1);+ });+ expect(JSON.parse(transport.lines.at(-1)!)).toEqual({+ id: 'early-elicitation',+ result: { action: 'accept', content: { value: 'ok' }, _meta: null },+ });+ expect(mcpServerElicitation).toHaveBeenCalledWith(+ expect.objectContaining({ threadId: 'child-thread', serverName: 'node_repl' }),+ );++ await subscription.release();+ await host.shutdown();+ });++ it('declines an MCP elicitation whose lineage stays unknown for the bounded window', async () => {+ const transport = new NotificationTransport();+ const host = new AppServerHost({+ createTransport: () => transport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ notificationBufferTtlMs: 20,+ });+ await host.ensureStarted();++ const mcpServerElicitation = vi.fn();+ const subscription = host.subscribeThread('root-thread', { mcpServerElicitation });+ const initialLineCount = transport.lines.length;+ transport.emit({+ id: 'unknown-elicitation',+ method: 'mcpServer/elicitation/request',+ params: {+ threadId: 'unknown-thread',+ turnId: 'turn-1',+ serverName: 'node_repl',+ mode: 'form',+ _meta: null,+ message: 'Confirm',+ requestedSchema: {},+ },+ });++ await vi.waitFor(() => {+ expect(transport.lines.length).toBe(initialLineCount + 1);+ });+ expect(JSON.parse(transport.lines.at(-1)!)).toEqual({+ id: 'unknown-elicitation',+ result: { action: 'decline', content: null, _meta: null },+ });+ expect(mcpServerElicitation).not.toHaveBeenCalled();++ await subscription.release();+ await host.shutdown();+ });});describe('AppServerHost descendant notification routing', () => {diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.tsindex 79bd4e456d..292da0fb60 100644--- a/packages/maker-core/src/agents/codex/app-server/host.ts+++ b/packages/maker-core/src/agents/codex/app-server/host.ts@@ -40,6 +40,7 @@ import {type FileChangeRequestApprovalResponse,type McpServerElicitationRequestParams,type McpServerElicitationRequestResponse,+ type CodexMcpServerStatusListResponse,type PermissionsRequestApprovalParams,type PermissionsRequestApprovalResponse,type ServerRequestResolvedNotification,@@ -239,6 +240,12 @@ export interface AppServerHostOptions {* 本机 codex proxy。session 级 prompt gate 只读这个值,不再 live 读取全局状态。*/codexProxyActive?: boolean;+ /** Host creation snapshot: this exact process received the Browser companion. */+ codexBrowserUseAvailable?: boolean;+ /** Exact verified Chrome plugin version provisioned into this process. */+ codexBrowserUseVersion?: string;+ /** Maximum wait for the provisioned Browser companion to publish its MCP tools. */+ codexBrowserUseStartupTimeoutMs?: number;/*** Host 创建时冻结的事实:spawn args 里定义的 OpenAI 身份 provider id(仅* oauth-bearer spawn 存在)。thread/start|resume 据此对订阅直连会话开远端压缩。@@ -267,6 +274,10 @@ export class AppServerHost {private readonly subscribers = new Map<string, ThreadEventHandlers>();/** root / descendant threadId → 当前拥有该子树订阅的 root threadId。 */private readonly lineageRoots = new Map<string, string>();+ /** Server request may race the child thread/started notification that establishes lineage. */+ private readonly threadHandlerWaiters = new Map<string, Set<() => void>>();+ /** One post-start MCP inventory probe per server/tool for this concrete process. */+ private readonly mcpToolAvailability = new Map<string, Promise<boolean>>();/** 找不到 subscriber 时按 threadId 暂存的 notification, drain on subscribe。 */private readonly buffered = new Map<string, BufferedNotification[]>();/** 血缘迭代重建的重入闸(routeDescendantThreadStarted 与重建互相调用)。 */@@ -294,6 +305,84 @@ export class AppServerHost {return this.opts.codexProxyActive === true;}+ isCodexBrowserUseAvailable(): boolean {+ return this.opts.codexBrowserUseAvailable === true;+ }++ getCodexBrowserUseVersion(): string | null {+ return this.opts.codexBrowserUseVersion ?? null;+ }++ /**+ * Verify that an MCP server connected and published a concrete tool. Static+ * spawn provisioning is not enough: this is the post-initialize gate that+ * prevents a Skill from being shown when its runtime tool never registered.+ */+ waitForMcpTool(+ serverName: string,+ toolName: string,+ opts: { timeoutMs?: number; pollIntervalMs?: number } = {},+ ): Promise<boolean> {+ const key = `${serverName}\0${toolName}`;+ const cached = this.mcpToolAvailability.get(key);+ if (cached) return cached;+ const probe = this.probeMcpTool(+ serverName,+ toolName,+ opts.timeoutMs ?? this.opts.codexBrowserUseStartupTimeoutMs ?? 10_000,+ opts.pollIntervalMs ?? 100,+ );+ this.mcpToolAvailability.set(key, probe);+ // A negative readiness probe is a point-in-time result, not a permanent+ // host capability fact. The MCP child may finish starting later, so the+ // next session must be allowed to retry. Successful probes stay cached.+ void probe.then((available) => {+ if (!available && this.mcpToolAvailability.get(key) === probe) {+ this.mcpToolAvailability.delete(key);+ }+ });+ return probe;+ }++ private async probeMcpTool(+ serverName: string,+ toolName: string,+ timeoutMs: number,+ pollIntervalMs: number,+ ): Promise<boolean> {+ const deadline = Date.now() + timeoutMs;+ try {+ while (!this.shuttingDown && Date.now() < deadline) {+ let cursor: string | null = null;+ do {+ const remaining = deadline - Date.now();+ if (remaining <= 0) return false;+ const response: CodexMcpServerStatusListResponse =+ await this.request<CodexMcpServerStatusListResponse>(+ Method.McpServerStatusList,+ { cursor, limit: 100, detail: 'toolsAndAuthOnly', threadId: null },+ { timeoutMs: remaining },+ );+ const server = response.data.find((entry) => entry.name === serverName);+ if (server && Object.hasOwn(server.tools, toolName)) return true;+ cursor = response.nextCursor;+ } while (cursor !== null);+ const remaining = deadline - Date.now();+ if (remaining <= 0) return false;+ await new Promise<void>((resolve) => {+ setTimeout(resolve, Math.min(pollIntervalMs, remaining));+ });+ }+ } catch (error) {+ this.logger.warn('MCP tool readiness probe failed', {+ serverName,+ toolName,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ return false;+ }+/** oauth spawn 定义的 OpenAI 身份 provider id;非 oauth spawn / 未下发 → null。 */getRemoteCompactionProviderId(): string | null {return this.opts.remoteCompactionProviderId ?? null;@@ -429,7 +518,11 @@ export class AppServerHost {client.setRequestHandler(Method.McpServerElicitationRequest, async (rawParams) => {const params = rawParams as McpServerElicitationRequestParams;- const handlers = this.handlersForThread(params.threadId);+ const handlers =+ this.handlersForThread(params.threadId)+ ?? (this.subscribers.size > 0+ ? await this.waitForThreadHandlers(params.threadId)+ : undefined);if (!handlers?.mcpServerElicitation) {this.logger.warn('MCP server elicitation without subscriber -> decline', {threadId: params.threadId,@@ -615,9 +708,16 @@ export class AppServerHost {async shutdown(reason = 'AppServerHost.shutdown()'): Promise<void> {if (this.shuttingDown) return;this.shuttingDown = true;+ // MCP readiness is scoped to the concrete app-server process. A normal+ // transport recovery reuses this host object, so never carry a positive+ // probe result into the replacement process.+ this.mcpToolAvailability.clear();this.subscribers.clear();this.lineageRoots.clear();this.buffered.clear();+ for (const threadId of this.threadHandlerWaiters.keys()) {+ this.notifyThreadHandlerWaiters(threadId);+ }const c = this.client;this.client = null;this.startPromise = null;@@ -680,6 +780,7 @@ export class AppServerHost {}this.subscribers.set(threadId, handlers);this.lineageRoots.set(threadId, threadId);+ this.notifyThreadHandlerWaiters(threadId);// 排空缓存 (thread/started 比 subscribe 早到的固有竞争)const buf = this.buffered.get(threadId);@@ -828,6 +929,43 @@ export class AppServerHost {return rootThreadId ? this.subscribers.get(rootThreadId) : undefined;}+ /**+ * Give an already-owned descendant a short window for its thread/started+ * notification to establish lineage. This closes an observed ordering race+ * for node_repl elicitation while preserving fail-closed routing: unknown+ * threads still decline after the bounded wait and can never fan out to an+ * arbitrary subscriber.+ */+ private waitForThreadHandlers(threadId: string): Promise<ThreadEventHandlers | undefined> {+ const current = this.handlersForThread(threadId);+ if (current) return Promise.resolve(current);+ return new Promise((resolve) => {+ let settled = false;+ const finish = (): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ const waiters = this.threadHandlerWaiters.get(threadId);+ waiters?.delete(finish);+ if (waiters?.size === 0) this.threadHandlerWaiters.delete(threadId);+ resolve(this.handlersForThread(threadId));+ };+ // Use the same bounded lineage window as early thread notifications.+ // Both races are caused by thread/started crossing the subscribe/request+ // boundary, so they should expire together instead of using a shorter+ // empirical timeout that can fail only under load.+ const timer = setTimeout(finish, this.bufferTtlMs);+ timer.unref?.();+ const waiters = this.threadHandlerWaiters.get(threadId) ?? new Set<() => void>();+ waiters.add(finish);+ this.threadHandlerWaiters.set(threadId, waiters);+ });+ }++ private notifyThreadHandlerWaiters(threadId: string): void {+ for (const finish of [...(this.threadHandlerWaiters.get(threadId) ?? [])]) finish();+ }+private routeDescendantThreadStarted(params: ThreadStartedNotification['params']): void {const childThreadId = params.thread.id;const parentThreadId = params.thread.parentThreadId;@@ -842,6 +980,7 @@ export class AppServerHost {if (!handlers) return;this.lineageRoots.set(childThreadId, rootThreadId);+ this.notifyThreadHandlerWaiters(childThreadId);if (handlers.descendantThreadStarted) {try {handlers.descendantThreadStarted(params);diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.tsindex 359f7accab..fc240b5a35 100644--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts@@ -139,6 +139,18 @@ export interface CodexModelListParams {includeHidden?: boolean | null;}+/** Minimal subset of `mcpServerStatus/list` used for post-start capability gates. */+export interface CodexMcpServerStatus {+ name: string;+ tools: Record<string, unknown>;+ [k: string]: unknown;+}++export interface CodexMcpServerStatusListResponse {+ data: CodexMcpServerStatus[];+ nextCursor: string | null;+}+export interface CodexModelListResponse {data: CodexModelListItem[];nextCursor: string | null;@@ -1164,6 +1176,7 @@ export type ServerNotification =export const Method = {Initialize: 'initialize',ModelList: 'model/list',+ McpServerStatusList: 'mcpServerStatus/list',SkillsList: 'skills/list',ThreadStart: 'thread/start',ThreadResume: 'thread/resume',diff --git a/packages/maker-core/src/agents/codex/capability-routing.test.ts b/packages/maker-core/src/agents/codex/capability-routing.test.tsindex e384f1cfb3..65a22d7ebb 100644--- a/packages/maker-core/src/agents/codex/capability-routing.test.ts+++ b/packages/maker-core/src/agents/codex/capability-routing.test.ts@@ -67,6 +67,25 @@ describe('buildCodexSessionCapabilityRoutingPolicy', () => {});describe('buildCodexCapabilityConfigOverrides', () => {+ it('can fail closed a host MCP server for one thread', () => {+ const policy = {+ overrides: [{+ capabilityId: 'browser-use',+ source: {+ kind: 'harness-plugin' as const,+ harness: 'codex',+ surface: 'mcp' as const,+ id: 'node_repl',+ },+ invocation: 'disabled' as const,+ }],+ };++ expect(buildCodexCapabilityConfigOverrides(policy)).toEqual({+ 'mcp_servers.node_repl.enabled': false,+ });+ });+it('disables the selected Codex plugin with a per-thread config override', () => {const policy = {overrides: [@@ -141,8 +160,8 @@ describe('buildCodexCapabilityConfigOverrides', () => {} as const satisfies CapabilityRoutingPolicy;expect(buildCodexCapabilityConfigOverrides(policy)).toEqual({- 'plugins."feishu-delegate@personal".mcp_servers."feishu-delegate".enabled': false,- 'plugins."feishu-delegate@personal".mcp_servers."cindy-routed-feishu-delegate".default_tools_approval_mode':+ 'plugins."feishu-delegate@personal".mcp_servers.feishu-delegate.enabled': false,+ 'plugins."feishu-delegate@personal".mcp_servers.cindy-routed-feishu-delegate.default_tools_approval_mode':'prompt',});});diff --git a/packages/maker-core/src/agents/codex/capability-routing.ts b/packages/maker-core/src/agents/codex/capability-routing.tsindex 6505c761a8..bd2a72b8bc 100644--- a/packages/maker-core/src/agents/codex/capability-routing.ts+++ b/packages/maker-core/src/agents/codex/capability-routing.ts@@ -47,6 +47,14 @@ function quoteTomlKeySegment(value: string): string {return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;}+function renderThreadConfigKeySegment(value: string): string {+ // app-server's thread config takes flattened paths, but unlike CLI `-c` it+ // does not parse quotes around a bare-safe segment. Quoting `node_repl`+ // therefore addresses a literal `"node_repl"` server and makes transport+ // resolution fail. Keep quoting only for names that TOML cannot render bare.+ return /^[A-Za-z0-9_-]+$/.test(value) ? value : quoteTomlKeySegment(value);+}+function isCodexHarnessPluginDirective(directive: CapabilityRouteOverride,): boolean {@@ -256,6 +264,15 @@ export function buildCodexCapabilityConfigOverrides(false;continue;}+ if (+ directive.source.surface === 'mcp' &&+ directive.invocation === 'disabled'+ ) {+ config[+ `mcp_servers.${renderThreadConfigKeySegment(directive.source.id)}.enabled`+ ] = false;+ continue;+ }if (directive.source.surface === 'mcp' &&directive.invocation === 'explicit-only' &&@@ -268,11 +285,11 @@ export function buildCodexCapabilityConfigOverrides(// same name. Disabling the original name also makes overlay failures// fail closed for the MCP surface.config[- `plugins.${quoteTomlKeySegment(directive.source.containerId)}.mcp_servers.${quoteTomlKeySegment(artifactId)}.enabled`+ `plugins.${quoteTomlKeySegment(directive.source.containerId)}.mcp_servers.${renderThreadConfigKeySegment(artifactId)}.enabled`] = false;}config[- `plugins.${quoteTomlKeySegment(directive.source.containerId)}.mcp_servers.${quoteTomlKeySegment(directive.source.id)}.default_tools_approval_mode`+ `plugins.${quoteTomlKeySegment(directive.source.containerId)}.mcp_servers.${renderThreadConfigKeySegment(directive.source.id)}.default_tools_approval_mode`] = 'prompt';}}diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 19ed64457e..0da154b120 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -146,6 +146,16 @@ const { MockCodexTransport, createdTransports } = vi.hoisted(() => {this.emitLine({ id: req.id, result: { data: [], nextCursor: null } });return;}+ if (req.method === 'mcpServerStatus/list') {+ this.emitLine({+ id: req.id,+ result: {+ data: [{ name: 'node_repl', tools: { js: { name: 'js' } } }],+ nextCursor: null,+ },+ });+ return;+ }if (req.method === 'config/read') {this.emitLine({id: req.id,@@ -321,6 +331,9 @@ function installFakeHost(requestImpl?: (method: string, params: unknown) => Promise<unknown> | unknown,opts: {codexProxyActive?: boolean;+ codexBrowserUseAvailable?: boolean;+ codexBrowserUseVersion?: string;+ codexBrowserMcpToolAvailable?: boolean;remoteCompactionProviderId?: string;userAgent?: string;codexHome?: string;@@ -377,6 +390,15 @@ function installFakeHost(});const unsubscribeThread = vi.fn(async () => {});const isCodexProxyActive = vi.fn(() => opts.codexProxyActive === true);+ const isCodexBrowserUseAvailable = vi.fn(+ () => opts.codexBrowserUseAvailable === true,+ );+ const getCodexBrowserUseVersion = vi.fn(+ () => opts.codexBrowserUseVersion ?? null,+ );+ const waitForMcpTool = vi.fn(async () => (+ opts.codexBrowserMcpToolAvailable ?? opts.codexBrowserUseAvailable === true+ ));const getRemoteCompactionProviderId = vi.fn(() => opts.remoteCompactionProviderId ?? null);const getSessionMcpConfig = vi.fn((sessionInstanceId?: string) =>opts.buildSessionMcpConfig?.(sessionInstanceId) ?? {},@@ -390,6 +412,9 @@ function installFakeHost(subscribeThread,unsubscribeThread,isCodexProxyActive,+ isCodexBrowserUseAvailable,+ getCodexBrowserUseVersion,+ waitForMcpTool,getRemoteCompactionProviderId,getSessionMcpConfig,getConnectionId: () => 'test-connection',@@ -589,6 +614,160 @@ describe('CodexAgent capability routing', () => {],} as const;+ it('resolves workspace routing once from the frozen session context', async () => {+ const resolveCapabilityRouting = vi.fn(() => ({+ overrides: [+ {+ capabilityId: 'browser-use',+ source: {+ kind: 'harness-plugin' as const,+ harness: 'codex',+ surface: 'plugin' as const,+ id: 'chrome@openai-bundled',+ },+ invocation: 'disabled' as const,+ },+ ],+ }));+ const agent = new CodexAgent(createDeps({}, { resolveCapabilityRouting }));+ const host = installFakeHost(agent, undefined, {+ userAgent: 'mock-codex/0.145.0',+ codexBrowserUseAvailable: true,+ codexBrowserUseVersion: '26.727.51351',+ });+ const handle = await agent.startSession({+ sessionId: 'session-scoped-capability-routing',+ model: 'gpt-5.4',+ workingDir: '/workspace/browser-off',+ vendorOptions: { frozenDisabledPluginIds: ['browser'] },+ });+ const params = host.request.mock.calls.find(+ ([method]) => method === Method.ThreadStart,+ )?.[1] as { config?: Record<string, unknown> };++ expect(resolveCapabilityRouting).toHaveBeenCalledOnce();+ expect(resolveCapabilityRouting).toHaveBeenCalledWith({+ workingDir: '/workspace/browser-off',+ remoteHostId: undefined,+ vendorOptions: { frozenDisabledPluginIds: ['browser'] },+ codexBrowserUseProvisioned: true,+ codexBrowserUseVersion: '26.727.51351',+ ensureCodexBrowserUseReady: expect.any(Function),+ });+ expect(params.config).toMatchObject({+ 'plugins."chrome@openai-bundled".enabled': false,+ });+ expect(host.waitForMcpTool).not.toHaveBeenCalled();++ await handle.close();+ });++ it('preserves the remote daemon Browser companion snapshot', async () => {+ const prepareCodexExtraSpawnConfig = vi.fn(async (_providers, ctx) => {+ expect(ctx?.remoteHostId).toBe('remote-browser-host');+ return {+ extraArgs: [],+ extraEnv: {},+ codexBrowserUseAvailable: true,+ codexBrowserUseVersion: '26.727.51351',+ codexBrowserUseStartupTimeoutMs: 120_000,+ };+ });+ const remoteTransport = new MockCodexTransport();+ const getRemoteCodexTransport = vi.fn(() => remoteTransport);+ const agent = new CodexAgent(createDeps({}, {+ prepareCodexExtraSpawnConfig,+ getRemoteCodexTransport,+ }));++ const handle = await agent.startSession({+ sessionId: 'session-remote-browser-companion',+ model: 'gpt-5.4',+ workingDir: '/remote/repo',+ remoteHostId: 'remote-browser-host',+ });+ const hosts = (agent as unknown as {+ hosts: Map<string, {+ isCodexBrowserUseAvailable(): boolean;+ getCodexBrowserUseVersion(): string | null;+ }>;+ }).hosts;++ expect(prepareCodexExtraSpawnConfig).toHaveBeenCalledWith([], {+ remoteHostId: 'remote-browser-host',+ credentialMode: undefined,+ });+ expect(getRemoteCodexTransport).toHaveBeenCalledWith('remote-browser-host');+ expect([...hosts.values()]).toHaveLength(1);+ expect([...hosts.values()][0]?.isCodexBrowserUseAvailable()).toBe(true);+ expect([...hosts.values()][0]?.getCodexBrowserUseVersion()).toBe('26.727.51351');++ await handle.close();+ await agent.dispose();+ });++ it('fails closed when a provisioned companion does not publish the js tool', async () => {+ let ready: boolean | undefined;+ const resolveCapabilityRouting = vi.fn(async (+ ctx: Parameters<NonNullable<AgentDeps['resolveCapabilityRouting']>>[0],+ ) => {+ ready = await ctx.ensureCodexBrowserUseReady();+ return { overrides: [] };+ });+ const agent = new CodexAgent(createDeps({}, { resolveCapabilityRouting }));+ const host = installFakeHost(agent, undefined, {+ userAgent: 'mock-codex/0.145.0',+ codexBrowserUseAvailable: true,+ codexBrowserMcpToolAvailable: false,+ });++ const handle = await agent.startSession({+ sessionId: 'session-browser-companion-missing-tool',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });++ expect(host.waitForMcpTool).toHaveBeenCalledWith('node_repl', 'js', {+ timeoutMs: 2_000,+ });+ expect(host.waitForMcpTool).toHaveBeenCalledTimes(2);+ expect(resolveCapabilityRouting).toHaveBeenCalledWith(expect.objectContaining({+ codexBrowserUseProvisioned: true,+ }));+ expect(ready).toBe(false);++ await handle.close();+ });++ it('retries a transient Browser companion readiness miss before freezing routing', async () => {+ let ready: boolean | undefined;+ const resolveCapabilityRouting = vi.fn(async (+ ctx: Parameters<NonNullable<AgentDeps['resolveCapabilityRouting']>>[0],+ ) => {+ ready = await ctx.ensureCodexBrowserUseReady();+ return { overrides: [] };+ });+ const agent = new CodexAgent(createDeps({}, { resolveCapabilityRouting }));+ const host = installFakeHost(agent, undefined, {+ userAgent: 'mock-codex/0.145.0',+ codexBrowserUseAvailable: true,+ });+ host.waitForMcpTool+ .mockResolvedValueOnce(false)+ .mockResolvedValueOnce(true);++ const handle = await agent.startSession({+ sessionId: 'session-browser-companion-transient-miss',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });++ expect(host.waitForMcpTool).toHaveBeenCalledTimes(2);+ expect(ready).toBe(true);++ await handle.close();+ });+it('applies host-owned plugin policy to new and resumed Codex 0.145 threads', async () => {const listComputerUseSkill = (method: string, params: unknown) => {if (method !== Method.SkillsList) return undefined;@@ -630,8 +809,8 @@ describe('CodexAgent capability routing', () => {)?.[1] as { config?: Record<string, unknown> };expect(startParams.config).toMatchObject({'plugins."computer-use@openai-bundled".enabled': false,- 'plugins."feishu-delegate@personal".mcp_servers."feishu-delegate".enabled': false,- 'plugins."feishu-delegate@personal".mcp_servers."cindy-routed-feishu-delegate".default_tools_approval_mode':+ 'plugins."feishu-delegate@personal".mcp_servers.feishu-delegate.enabled': false,+ 'plugins."feishu-delegate@personal".mcp_servers.cindy-routed-feishu-delegate.default_tools_approval_mode':'prompt','skills.config': [{@@ -665,8 +844,8 @@ describe('CodexAgent capability routing', () => {)?.[1] as { config?: Record<string, unknown> };expect(resumeParams.config).toMatchObject({'plugins."computer-use@openai-bundled".enabled': false,- 'plugins."feishu-delegate@personal".mcp_servers."feishu-delegate".enabled': false,- 'plugins."feishu-delegate@personal".mcp_servers."cindy-routed-feishu-delegate".default_tools_approval_mode':+ 'plugins."feishu-delegate@personal".mcp_servers.feishu-delegate.enabled': false,+ 'plugins."feishu-delegate@personal".mcp_servers.cindy-routed-feishu-delegate.default_tools_approval_mode':'prompt','skills.config': [{@@ -825,7 +1004,7 @@ describe('CodexAgent capability routing', () => {}],});expect(params.config).not.toHaveProperty(- 'plugins."feishu-delegate@personal".mcp_servers."cindy-routed-feishu-delegate".default_tools_approval_mode',+ 'plugins."feishu-delegate@personal".mcp_servers.cindy-routed-feishu-delegate.default_tools_approval_mode',);expect(params.config).not.toHaveProperty('plugins."computer-use@openai-bundled".enabled',@@ -3774,6 +3953,30 @@ describe('CodexAgent send', () => {});describe('CodexAgent MCP thread context hooks', () => {+ it('binds Browser companion availability to the concrete app-server host', async () => {+ const prepareCodexExtraSpawnConfig = vi.fn(async () => ({+ extraArgs: [],+ extraEnv: {},+ codexBrowserUseAvailable: true,+ }));+ const agent = new CodexAgent(createDeps({}, { prepareCodexExtraSpawnConfig }));++ const handle = await agent.startSession({+ sessionId: 'session-browser-companion-host-snapshot',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const hosts = (agent as unknown as {+ hosts: Map<string, { isCodexBrowserUseAvailable(): boolean }>;+ }).hosts;++ expect([...hosts.values()]).toHaveLength(1);+ expect([...hosts.values()][0]?.isCodexBrowserUseAvailable()).toBe(true);++ await handle.close();+ await agent.dispose();+ });+it('passes target context to Codex extra spawn config and reuses the shared local host', async () => {const prepareCodexExtraSpawnConfig = vi.fn(async () => ({extraArgs: ['-c', 'mcp_servers.cindy_test.url="http://127.0.0.1:1234/mcp/cindy_test"'],diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 8581d342e2..c049270020 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -822,6 +822,18 @@ const TIGHTEN_INTERRUPT_ACK_TIMEOUT_MS = 10_000;// ignore Stop.const PROFILE_LIFECYCLE_ACK_TIMEOUT_MS = 10_000;+// The Browser fallback route is resolved before thread/start, so the app-server+// can only answer its readiness query against the global MCP inventory. Keep+// that pre-thread probe bounded: a slow unrelated MCP server must not stretch+// Codex session creation to the companion's full startup timeout (which may be+// as high as 120 seconds). Once a concrete thread exists, callers can use the+// thread-scoped status API instead of this pre-thread path.+const CODEX_BROWSER_USE_READINESS_PROBE_TIMEOUT_MS = 2_000;+// A single short miss can race the MCP child process finishing its cold start.+// Retry once before freezing the thread's capability routing, while keeping a+// genuinely unavailable companion bounded to two short probes.+const CODEX_BROWSER_USE_READINESS_PROBE_ATTEMPTS = 2;+// thread/start / thread/resume / turn/start 的 RPC 上限。AppServerClient.request// 默认无超时 — 远端 daemon 失联 (SSH 隧道半开 / daemon 挂起但 socket 未断) 时// 裸 await 永久挂起, session 永远停在 generating (issue #677 同类断链面)。@@ -2020,6 +2032,9 @@ export class CodexAgent extends BaseAgent {let env: Record<string, string> = {};let extraArgs: string[] = [];let codexProxyActive = false;+ let codexBrowserUseAvailable = false;+ let codexBrowserUseVersion: string | undefined;+ let codexBrowserUseStartupTimeoutMs: number | undefined;let remoteCompactionProviderId: string | undefined;let buildSessionMcpConfig: CodexExtraSpawnConfig['buildSessionMcpConfig'];for (;;) {@@ -2041,6 +2056,9 @@ export class CodexAgent extends BaseAgent {extraArgs = [];codexProxyActive = false;+ codexBrowserUseAvailable = false;+ codexBrowserUseVersion = undefined;+ codexBrowserUseStartupTimeoutMs = undefined;remoteCompactionProviderId = undefined;buildSessionMcpConfig = undefined;if (this.deps.prepareCodexExtraSpawnConfig) {@@ -2058,6 +2076,12 @@ export class CodexAgent extends BaseAgent {extraArgs = cfg.extraArgs;buildSessionMcpConfig = cfg.buildSessionMcpConfig;codexProxyActive = cfg.codexProxyActive === true && !remoteHostId;+ // Remote daemons own their browser companion and its CODEX_HOME;+ // preserve the host-provided availability snapshot instead of+ // forcing every remote target into the local fail-closed state.+ codexBrowserUseAvailable = cfg.codexBrowserUseAvailable === true;+ codexBrowserUseVersion = cfg.codexBrowserUseVersion;+ codexBrowserUseStartupTimeoutMs = cfg.codexBrowserUseStartupTimeoutMs;// OpenAI 身份 provider 依赖 loopback proxy 路由订阅直连;proxy 不可用// (退化直连网关)时不得下发,否则远端压缩请求会打到不支持它的上游。if (codexProxyActive && cfg.codexRemoteCompactionProviderId) {@@ -2131,6 +2155,9 @@ export class CodexAgent extends BaseAgent {// (2026-07-17 随品牌翻转改 cindy;上游 gating 走 originator,与此无关)。clientInfo: { name: 'cindy', version: '0.0.0' },codexProxyActive,+ codexBrowserUseAvailable,+ codexBrowserUseVersion,+ codexBrowserUseStartupTimeoutMs,remoteCompactionProviderId,buildSessionMcpConfig,// app-server 对失败 RPC 返回 cloudRequirements + Auth/relogin 结构化错误时,当前 host@@ -3016,8 +3043,29 @@ export class CodexAgent extends BaseAgent {: credentialMode ?? this.hostEffectiveCredentialModes.get(currentHostKey);const approvalsReviewerProtocolSupported =supportsCodexApprovalsReviewerProtocol(initResp.userAgent);+ const codexBrowserUseProvisioned = host.isCodexBrowserUseAvailable();+ const hostCapabilityRoutingPolicy =+ await this.deps.resolveCapabilityRouting?.({+ workingDir: opts.workingDir,+ remoteHostId: opts.remoteHostId,+ vendorOptions: vo,+ codexBrowserUseProvisioned,+ codexBrowserUseVersion: host.getCodexBrowserUseVersion(),+ ensureCodexBrowserUseReady: async () => {+ if (!codexBrowserUseProvisioned) return false;+ for (let attempt = 0; attempt < CODEX_BROWSER_USE_READINESS_PROBE_ATTEMPTS; attempt++) {+ if (await host.waitForMcpTool('node_repl', 'js', {+ timeoutMs: CODEX_BROWSER_USE_READINESS_PROBE_TIMEOUT_MS,+ })) {+ return true;+ }+ }+ return false;+ },+ }) ?? this.deps.capabilityRouting;+ assertCurrentHost('capability routing resolution');const capabilityRoutingPolicy = buildCodexSessionCapabilityRoutingPolicy(- this.deps.capabilityRouting,+ hostCapabilityRoutingPolicy,{// Remote Codex does not receive the local Cindy MCP bridge. Keep// compatibility restrictions, but do not disable a remote capability