Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(codex): preserve remote tool isolation when forking threads

MagicLizia328b8566bd2
diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.md
index 6824e9a085..2830d503f5 100644
--- a/docs/product-rules/provider-sharing.md
+++ b/docs/product-rules/provider-sharing.md
@@ -426,6 +426,12 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):
实现:Claude Code 用 SDK `tools` 白名单,Codex 按功能清单关闭白名单之外的功能,Pi 只放行 Cindy
扩展注册的工具(`packages/maker-core/src/agents/{shared/device-hosted,codex/device-hosted-guest,pi/cindy-bridge-source}.ts`);
受邀者电脑上的 WebFetch 见 `apps/desktop/src/main/remote-agent/executor/webFetch.ts`。
+ **重建同样保持隔离**(2026-10-27):Codex 原生 `thread/fork` 会重新加载进程默认配置,不能
+ 假定它继承源线程的覆盖项。回退/编辑重发必须和正常启动、恢复一样带上任务的执行环境、远程 MCP
+ 路由与完整能力隔离配置。受邀者复制历史的一次性 fork 不接入任何本机 MCP 或连接器,不能检查
+ 功能清单时拒绝创建子线程,用后关闭独立进程;子线程正式恢复时再接入受邀者工具。
+ 回归:`packages/maker-core/src/agents/codex/__tests__/device-hosted-guest{,.native}.test.ts`,
+ 覆盖回退后续发、历史复制与功能检查失败;真实 Codex 0.159.2 验证本机默认能力不会重新进入受邀者线程。
6. **受邀者隐私**:申请前明确告知对话与文件内容会经过分享者的电脑,并保存在实际运行任务的那台电脑上
(有供应商组时可能是分享者安排的其他电脑)。运行中疑似工具循环时,与分享者自己的任务一样,由运行任务
那台电脑的辅助模型复核:用户目标与最新要求、主模型已有的公开行动说明,以及最近十余次工具调用的
diff --git a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts
index 97243e586f..9adddeaee9 100644
--- a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts
+++ b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts
@@ -140,8 +140,9 @@ describe.skipIf(!binaryPath)('Codex device-hosted guest with a real app-server',
'-c', `model_providers.fixture={ name = "Fixture", base_url = "${endpoint}", wire_api = "responses", requires_openai_auth = false, request_max_retries = 0, supports_websockets = false }`,
'-c', 'check_for_update_on_startup=false',
'-c', 'analytics.enabled=false',
- // A private Cindy MCP must never enter an external client's model request.
- ...(localClient ? ['-c', `mcp_servers.private_canary={url="${endpoint}/mcp",enabled=true}`] : []),
+ // Provider defaults must stay excluded after native rewind/fork too.
+ ...(localClient || guest ? ['-c', `mcp_servers.private_canary={url="${endpoint}/mcp",enabled=true}`] : []),
+ ...(guest ? ['-c', 'features.apps=true'] : []),
// 本机用户开了智能子代理调配时 host 会带上的配置;受邀者的 app-server 不接受。
'-c', 'features.multi_agent_v2.expose_spawn_agent_model_overrides=true',
],
@@ -280,8 +281,43 @@ describe.skipIf(!binaryPath)('Codex device-hosted guest with a real app-server',
await other.close();await handle.close();return;
}
expect(['shell_tool', 'unified_exec', 'shell_snapshot', 'view_image', 'multi_agent'].filter((name) => !enabled.has(name))).toEqual([]);
+
+ // Regression: native fork reloads process defaults. Exercise the production
+ // rewind entry and a subsequent turn, then inspect the new native runtime.
+ // Existing startup-only assertions missed restored apps and provider MCP.
+ const previousThreadId = handle.id;
+ const turns = await threadHost.request('thread/turns/list', { threadId: previousThreadId, limit: 10 }) as { data: Array<{ id: string }> };
+ expect(turns.data).toHaveLength(1);
+ const rewound = await handle.commitRewindFiles!('', '', { tailTurnsToDrop: 1, lastTurnId: turns.data[0]!.id });
+ expect(rewound?.sdkSessionId).not.toBe(previousThreadId);
+ const rewindDone = (async () => {
+ for await (const event of handle.events()) {
+ if (event.type === 'error') throw new Error(JSON.stringify(event));
+ if (event.type === 'done') return;
+ }
+ })();
+ await handle.send({ type: 'user', content: 'continue after rewind' }, { throwOnStartFailure: true });
+ await rewindDone;
+ if (guest) {
+ const afterRewindFeatures = await listCodexFeatures(cursor => threadHost.request(
+ 'experimentalFeature/list', { threadId: rewound!.sdkSessionId, limit: 200, ...(cursor ? { cursor } : {}) },
+ ));
+ expect(afterRewindFeatures.filter(feature => feature.enabled && feature.stage !== 'removed'
+ && !CODEX_DEVICE_HOSTED_GUEST_KEPT_FEATURES.has(feature.name)).map(feature => feature.name)).toEqual([]);
+ expect(bodies.join('')).not.toContain('private_canary');
+ }
await handle.close();
+ if (guest) {
+ const requestCount = bodies.length;
+ const forked = await agent.forkSdkSession({
+ sourceSdkSessionId: rewound!.sdkSessionId!, upToMessageId: undefined,
+ lastTurnId: turns.data[0]!.id, workingDir, hostedGuestHome: guestHome, providerId: 'xd', model: 'gpt-5.5',
+ });
+ expect(forked.newSdkSessionId).not.toBe(rewound!.sdkSessionId);
+ expect(bodies).toHaveLength(requestCount);
+ }
+
expect(bodies.length).toBeGreaterThan(0);
const sent = bodies.join('\n');
// 本机用户的全局说明只在同账号会话里;本机影子目录及其上级的说明文件两者都不读(项目说明经执行环境
diff --git a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.ts b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.ts
index ea1c857298..b710608c4d 100644
--- a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.ts
+++ b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.ts
@@ -256,6 +256,8 @@ async function startHosted(fixture: Fixture) {
};
case Method.ThreadResume:
return { thread: { id: 'resume-thread-id' }, model: 'gpt-5.5', modelProvider: 'openai', cwd: workingDir };
+ case Method.ThreadFork:
+ return { thread: { id: 'fork-thread-id' }, model: 'gpt-5.5', modelProvider: 'openai' };
case Method.TurnStart:
return { turn: { id: 'turn-1' } };
default:
@@ -327,7 +329,7 @@ async function startHosted(fixture: Fixture) {
return {
started, request, getHost, getGhostRosterPrompt, getContactsPromptState, getDisabledSkillPaths,
prepareCodexSkills, prepareCodexResumeSession, resolveCodexThreadStorage, recordCodexThreadLocation,
- hostSkill, systemSkill, pluginSkill, guestSkill, guestHome, codexHome,
+ hostSkill, systemSkill, pluginSkill, guestSkill, guestHome, codexHome, agent, workingDir,
};
}
@@ -349,6 +351,90 @@ afterEach(async () => {
});
describe('Codex device-hosted guest sessions', () => {
+ // Provider sharing §9.5: even a history-only native fork initializes MCP and
+ // connectors. Existing fork tests covered proxy/history ownership only.
+ // Minimal input: one guest source and a native turn anchor; tier: unit.
+ it.each([false, true])('isolates history-only guest forks before allocating a child (feature inspection fails: %s)', async (inspectionFails) => {
+ const fixture = await startHosted({ guest: true });
+ const handle = await fixture.started;
+ await handle.close();
+ fixture.request.mockClear();
+ if (inspectionFails) {
+ const baseRequest = fixture.request.getMockImplementation()!;
+ fixture.request.mockImplementation(async (method, params) => {
+ if (method === Method.ExperimentalFeatureList) throw new Error('feature inspection failed');
+ return baseRequest(method, params);
+ });
+ }
+ const forked = fixture.agent.forkSdkSession({
+ sourceSdkSessionId: 'guest-source', upToMessageId: undefined,
+ lastTurnId: 'kept-turn', workingDir: fixture.workingDir,
+ hostedGuestHome: fixture.guestHome, providerId: SHARED_PROVIDER.providerId,
+ });
+ if (inspectionFails) {
+ await expect(forked).rejects.toThrow('feature inspection failed');
+ expect(fixture.request.mock.calls.some(([method]) => method === Method.ThreadFork)).toBe(false);
+ } else {
+ await expect(forked).resolves.toMatchObject({ newSdkSessionId: 'fork-thread-id' });
+ expect(threadParams(fixture.request, Method.ThreadFork)).toMatchObject({
+ config: {
+ 'mcp_servers.local_docs.enabled': false,
+ 'mcp_servers.cindy_contacts.enabled': false,
+ 'plugins."configured@personal".enabled': false,
+ 'features.apps': false,
+ 'features.hooks': false,
+ 'features.future_local_tool': false,
+ 'memories.use_memories': false,
+ },
+ });
+ }
+ expect(fixture.request.mock.calls.some(([method]) => method === Method.TurnStart)).toBe(false);
+ expect(fixture.getHost).toHaveBeenLastCalledWith(undefined, expect.anything(), expect.objectContaining({
+ nativeStorageOnly: true,
+ }));
+ });
+
+ // Provider sharing §9.5: rewind must retain the consumer's MCP transport and
+ // guest isolation. Startup-only coverage missed that native fork reloads host
+ // defaults. Minimal input: a hosted session rewound at a persisted turn anchor;
+ // tier: unit, through startSession -> commitRewindFiles -> send.
+ it.each([false, true])('keeps the task tool route and capability scope after rewind (guest: %s)', async (guest) => {
+ const fixture = await startHosted({ guest });
+ const handle = await fixture.started;
+ const initial = threadParams(fixture.request, Method.ThreadStart);
+
+ await expect(handle.commitRewindFiles?.('', '', { tailTurnsToDrop: 1, lastTurnId: 'kept-turn' }))
+ .resolves.toEqual({ sdkSessionId: 'fork-thread-id' });
+
+ const fork = threadParams(fixture.request, Method.ThreadFork);
+ expect(fork).toMatchObject({
+ threadId: 'start-thread-id',
+ lastTurnId: 'kept-turn',
+ approvalPolicy: initial.approvalPolicy,
+ sandbox: initial.sandbox,
+ environments: initial.environments,
+ config: {
+ 'mcp_servers.local_docs.enabled': false,
+ 'mcp_servers.cindy_contacts.enabled': true,
+ 'mcp_servers.cindy_contacts.url': 'http://127.0.0.1:4000/t/tok/mcp/cindy_contacts',
+ },
+ });
+ expect(fork.config).toEqual(initial.config);
+ if (guest) expect(fork.config).toMatchObject({
+ 'features.apps': false,
+ 'features.hooks': false,
+ 'features.plugins': false,
+ 'features.future_local_tool': false,
+ 'memories.use_memories': false,
+ });
+
+ await handle.send({ type: 'user', content: 'continue after rewind' });
+ expect(threadParams(fixture.request, Method.TurnStart)).toMatchObject({
+ threadId: 'fork-thread-id', environments: initial.environments,
+ });
+ await handle.close();
+ });
+
it.each([false, true])('isolates this computer\'s capabilities from a shared user (resume: %s)', async (resume) => {
const fixture = await startHosted({ guest: true, resume });
const handle = await fixture.started;
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 642b285d3c..115f48d9d1 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -24636,9 +24636,16 @@ describe('CodexAgent.forkSdkSession', () => {
}
return { extraArgs: [], extraEnv: {}, onHostRetired };
});
- MockCodexTransport.onCreate = transport => transport.setMockResponse('account/login/start', {
- result: { type: 'chatgptAuthTokens' },
- });
+ MockCodexTransport.onCreate = transport => {
+ transport.setMockResponse('account/login/start', { result: { type: 'chatgptAuthTokens' } });
+ transport.setMockResponse('experimentalFeature/list', { result: {
+ data: [{ name: 'apps', stage: 'stable', enabled: true }], nextCursor: null,
+ } });
+ transport.setMockResponse('config/read', { result: { config: {
+ cli_auth_credentials_store: 'ephemeral',
+ mcp_servers: { node_repl: { command: 'synthetic-node-repl' } },
+ } } });
+ };
const agent = new CodexAgent(createDeps({}, {
prepareCodexExtraSpawnConfig: prepare,
createCodexAuthTokenReader: () => async () => ({ accessToken: 'test-guest-token', chatgptAccountId: 'shared-account' }),
@@ -24670,7 +24677,11 @@ describe('CodexAgent.forkSdkSession', () => {
const agent = new CodexAgent(createDeps({}, { resolveCodexThreadStorage, prepareCodexResumeSession }));
const home = path.join(os.tmpdir(), 'guest-fork-fixture');
const codexHome = path.join(home, 'codex');
- const host = installFakeHost(agent, undefined, { userAgent: 'mock-codex/0.153.4', codexHome });
+ const host = installFakeHost(agent, method => {
+ if (method === Method.ExperimentalFeatureList) return {
+ data: [{ name: 'apps', stage: 'stable', enabled: true }], nextCursor: null,
+ };
+ }, { userAgent: 'mock-codex/0.153.4', codexHome });
await expect(agent.forkSdkSession({ sourceSdkSessionId: 'guest-source', upToMessageId: undefined,
lastTurnId: 'guest-turn', hostedGuestHome: home, providerId: 'xd' }))
.resolves.toMatchObject({ newSdkSessionId: 'fork-thread-id' });
@@ -25463,12 +25474,12 @@ describe('CodexAgent rewind', () => {
threadId: 'start-thread-id',
numTurns: 1,
});
- expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, {
+ expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({
threadId: 'start-thread-id',
lastTurnId: 'boundary-turn',
excludeTurns: true,
cwd: '/repo',
- });
+ }), expect.objectContaining({ timeoutMs: 60_000 }));
expect(commitResult).toEqual({ sdkSessionId: 'fork-thread-id' });
expect(host.subscribeThread).toHaveBeenCalledTimes(2);
expect(host.subscribeThread).toHaveBeenLastCalledWith('fork-thread-id', expect.any(Object));
@@ -25498,7 +25509,7 @@ describe('CodexAgent rewind', () => {
expect(host.request).not.toHaveBeenCalledWith(Method.ThreadTurnsList, expect.anything());
expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({
threadId: 'start-thread-id', lastTurnId: 'persisted-boundary',
- }));
+ }), expect.objectContaining({ timeoutMs: 60_000 }));
await handle.close();
});
@@ -25573,12 +25584,12 @@ describe('CodexAgent rewind', () => {
const commitResult = await commitRewindFiles('', '', { tailTurnsToDrop: 1, forkAtTimestampMs: 150_500 });
expect(host.request).not.toHaveBeenCalledWith(Method.ThreadRollback, expect.anything());
- expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, {
+ expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({
threadId: 'start-thread-id',
lastTurnId: 'boundary-turn',
excludeTurns: true,
cwd: '/repo',
- });
+ }), expect.objectContaining({ timeoutMs: 60_000 }));
expect(commitResult).toEqual({ sdkSessionId: 'fork-thread-id' });
expect(host.subscribeThread).toHaveBeenLastCalledWith('fork-thread-id', expect.any(Object));
expect(await nextEvent(iterator)).toMatchObject({
@@ -25614,7 +25625,7 @@ describe('CodexAgent rewind', () => {
});
expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({
threadId: 'start-thread-id', lastTurnId: 'persisted-boundary',
- }));
+ }), expect.objectContaining({ timeoutMs: 60_000 }));
expect(host.subscribeThread).toHaveBeenLastCalledWith('fork-thread-id', expect.any(Object));
await handle.close();
});
@@ -25638,12 +25649,12 @@ describe('CodexAgent rewind', () => {
await expect(commitRewindFiles('', '', { tailTurnsToDrop: 1, lastTurnId: 'persisted-boundary' }))
.resolves.toEqual({ sdkSessionId: 'fork-thread-id' });
- expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, {
+ expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({
threadId: 'start-thread-id',
lastTurnId: 'persisted-boundary',
excludeTurns: true,
cwd: '/repo',
- });
+ }), expect.objectContaining({ timeoutMs: 60_000 }));
await handle.close();
});
@@ -25668,7 +25679,7 @@ describe('CodexAgent rewind', () => {
await expect(commitRewindFiles('', '', { tailTurnsToDrop: 1, forkAtTimestampMs: 150_500 }))
.resolves.toEqual({ sdkSessionId: 'fork-thread-id' });
expect(host.request).toHaveBeenCalledWith(Method.ThreadTurnsList, expect.objectContaining({ threadId: 'start-thread-id' }));
- expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({ lastTurnId: 'boundary-turn' }));
+ expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({ lastTurnId: 'boundary-turn' }), expect.objectContaining({ timeoutMs: 60_000 }));
await handle.close();
});
@@ -25734,7 +25745,9 @@ describe('CodexAgent rewind', () => {
await handle.close();
});
- it('holds MCP discovery identity around the fresh rewind thread/start (#4994)', async () => {
+ // Rewind forks must discover tools under the same task identity as fresh
+ // threads; the original test covered only first-turn replacement.
+ it.each([false, true])('holds MCP discovery identity during rewind (native fork: %s)', async (nativeFork) => {
const order: string[] = [];
const deps = createDeps();
deps.withCodexMcpDiscoveryContext = async (ctx, run) => {
@@ -25752,7 +25765,7 @@ describe('CodexAgent rewind', () => {
}, { userAgent: 'mock-codex/0.156.0' });
const original = host.request.getMockImplementation()!;
host.request.mockImplementation(async (...args) => {
- if (args[0] === Method.ThreadStart) {
+ if (args[0] === Method.ThreadStart || args[0] === Method.ThreadFork) {
expect(order.at(-1)).toBe('discovery');
order.push('native');
}
@@ -25769,8 +25782,10 @@ describe('CodexAgent rewind', () => {
const commitRewindFiles = handle.commitRewindFiles;
if (!commitRewindFiles) throw new Error('expected commitRewindFiles');
- await expect(commitRewindFiles('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true }))
- .resolves.toEqual({ sdkSessionId: 'fresh-thread-id' });
+ await expect(commitRewindFiles('', '', {
+ tailTurnsToDrop: 1,
+ ...(nativeFork ? { lastTurnId: 'persisted-boundary' } : { rewindsToNativeThreadStart: true }),
+ })).resolves.toEqual({ sdkSessionId: nativeFork ? 'fork-thread-id' : 'fresh-thread-id' });
expect(order).toEqual(['discovery', 'native', 'released']);
await handle.close();
});
@@ -25876,7 +25891,7 @@ describe('CodexAgent rewind', () => {
lastTurnId: 'persisted-boundary',
rewindsToNativeThreadStart: true,
})).resolves.toEqual({ sdkSessionId: 'fork-thread-id' });
- expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({ lastTurnId: 'persisted-boundary' }));
+ expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({ lastTurnId: 'persisted-boundary' }), expect.objectContaining({ timeoutMs: 60_000 }));
expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadStart)).toHaveLength(1);
await handle.close();
});
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index f879abf74e..66f4faf91c 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -2176,6 +2176,120 @@ export class CodexAgent extends BaseAgent {
host => this.listSkillsForHost(host, workingDir, forceReload));
}
+ /**
+ * 本机的 Skill、插件与 MCP 逐项关闭(线程级覆盖)。不传 keep 时全部关闭(Review);受邀者的
+ * 托管会话用 keep 保留它自己的 Skill、Codex 自带 Skill 与经隧道的 MCP。
+ */
+ private async buildLocalCapabilityIsolationConfig(
+ host: AppServerHost,
+ workingDir: string,
+ keep?: {
+ skill: (skillPath: string, scope?: SkillMetadata['scope']) => boolean;
+ mcpServer: (serverName: string) => boolean;
+ plugin?: (pluginId: string) => boolean;
+ allSkills?: true;
+ },
+ ): Promise<Record<string, unknown>> {
+ const { skills, errors } = keep?.allSkills ? { skills: [], errors: [] } : await this.listSkillsForHost(
+ host,
+ workingDir,
+ false,
+ CRITICAL_THREAD_RPC_TIMEOUT_MS,
+ );
+ const unscopedSkillError = errors.find((error) => !error.path);
+ if (unscopedSkillError && !keep?.skill('')) throw new Error(unscopedSkillError.message);
+
+ const configResponse = await host.request<{ config?: Record<string, unknown> }>(
+ Method.ConfigRead,
+ { includeLayers: false },
+ { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS },
+ );
+ const effectiveConfig = asRecord(configResponse.config);
+ const configuredMcp = asRecord(effectiveConfig.mcp_servers);
+ const configuredPlugins = asRecord(effectiveConfig.plugins);
+ const configuredMcpServerNames = new Set(
+ Object.entries(configuredMcp)
+ .filter(([, serverConfig]) => hasCodexMcpTransport(serverConfig))
+ .map(([serverName]) => serverName),
+ );
+ const transportConfiguredMcpServerNames = new Set(configuredMcpServerNames);
+ for (const pluginConfig of Object.values(configuredPlugins)) {
+ const pluginMcp = asRecord(asRecord(pluginConfig).mcp_servers);
+ for (const [serverName, serverConfig] of Object.entries(pluginMcp)) {
+ if (!hasCodexMcpTransport(serverConfig)) continue;
+ transportConfiguredMcpServerNames.add(serverName);
+ }
+ }
+ const unconfiguredRuntimeMcpServerNames = new Set<string>();
+ let cursor: string | null = null;
+ do {
+ const status: CodexMcpServerStatusListResponse =
+ await host.request<CodexMcpServerStatusListResponse>(
+ Method.McpServerStatusList,
+ { cursor, limit: 100, detail: 'toolsAndAuthOnly', threadId: null },
+ { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS },
+ );
+ for (const server of status.data) {
+ if (
+ !transportConfiguredMcpServerNames.has(server.name) &&
+ server.name !== CODEX_APPS_MCP_SERVER_NAME
+ ) {
+ unconfiguredRuntimeMcpServerNames.add(server.name);
+ }
+ }
+ cursor = status.nextCursor;
+ } while (cursor !== null);
+ if (unconfiguredRuntimeMcpServerNames.size > 0) {
+ throw new Error(
+ `Codex reported runtime MCP servers without transport-bearing config: ${[
+ ...unconfiguredRuntimeMcpServerNames,
+ ].sort().join(', ')}`,
+ );
+ }
+
+ const skillPaths = new Set([
+ ...skills.filter((skill) => !keep?.skill(skill.path, skill.scope)).map((skill) => skill.path),
+ ...errors.flatMap((error) => (error.path && !keep?.skill(error.path) ? [error.path] : [])),
+ ]);
+ const pluginIds = new Set(Object.keys(configuredPlugins));
+ for (const skillPath of skillPaths) {
+ const pluginId = pluginIdFromCodexSkillPath(skillPath);
+ if (pluginId) pluginIds.add(pluginId);
+ }
+
+ const isolationConfig: Record<string, unknown> = {};
+ if (skillPaths.size > 0) {
+ isolationConfig['skills.config'] = [...skillPaths]
+ .sort()
+ .map((skillPath) => ({ path: skillPath, enabled: false }));
+ }
+ // Only configured MCP entries have a command/url transport that can
+ // accept a per-thread `.enabled=false` merge. `codex_apps` is an
+ // app-server builtin surfaced by mcpServerStatus/list but absent from
+ // config/read; synthesizing an override for it makes Codex 0.145.0
+ // reject thread/start with "invalid transport". Apps are isolated by
+ // `features.apps=false` instead.
+ for (const serverName of configuredMcpServerNames) {
+ if (keep?.mcpServer(serverName)) continue;
+ isolationConfig[
+ `mcp_servers.${renderReviewConfigSegment(serverName)}.enabled`
+ ] = false;
+ }
+ for (const pluginId of pluginIds) {
+ if (!keep?.plugin?.(pluginId)) {
+ isolationConfig[`plugins.${quoteReviewConfigSegment(pluginId)}.enabled`] = false;
+ }
+ const pluginMcp = asRecord(asRecord(configuredPlugins[pluginId]).mcp_servers);
+ for (const [serverName, serverConfig] of Object.entries(pluginMcp)) {
+ if (!hasCodexMcpTransport(serverConfig)) continue;
+ isolationConfig[
+ `plugins.${quoteReviewConfigSegment(pluginId)}.mcp_servers.${renderReviewConfigSegment(serverName)}.enabled`
+ ] = false;
+ }
+ }
+ return isolationConfig;
+ }
+
private async listSkillsForHost(
host: AppServerHost,
workingDir: string,
@@ -5510,122 +5624,13 @@ assertRouteCurrent();
);
}
}
- /**
- * 本机的 Skill、插件与 MCP 逐项关闭(线程级覆盖)。不传 keep 时全部关闭(Review);受邀者的
- * 托管会话用 keep 保留它自己的 Skill、Codex 自带 Skill 与经隧道的 MCP。
- */
- const buildLocalCapabilityIsolationConfig = async (keep?: {
- skill: (skillPath: string, scope?: SkillMetadata['scope']) => boolean;
- mcpServer: (serverName: string) => boolean;
- plugin?: (pluginId: string) => boolean;
- allSkills?: true;
- }): Promise<Record<string, unknown>> => {
- const { skills, errors } = keep?.allSkills ? { skills: [], errors: [] } : await this.listSkillsForHost(
- host,
- opts.workingDir,
- false,
- CRITICAL_THREAD_RPC_TIMEOUT_MS,
- );
- const unscopedSkillError = errors.find((error) => !error.path);
- if (unscopedSkillError && !keep?.skill('')) throw new Error(unscopedSkillError.message);
-
- const configResponse = await host.request<{ config?: Record<string, unknown> }>(
- Method.ConfigRead,
- { includeLayers: false },
- { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS },
- );
- const effectiveConfig = asRecord(configResponse.config);
- const configuredMcp = asRecord(effectiveConfig.mcp_servers);
- const configuredPlugins = asRecord(effectiveConfig.plugins);
- const configuredMcpServerNames = new Set(
- Object.entries(configuredMcp)
- .filter(([, serverConfig]) => hasCodexMcpTransport(serverConfig))
- .map(([serverName]) => serverName),
- );
- const transportConfiguredMcpServerNames = new Set(configuredMcpServerNames);
- for (const pluginConfig of Object.values(configuredPlugins)) {
- const pluginMcp = asRecord(asRecord(pluginConfig).mcp_servers);
- for (const [serverName, serverConfig] of Object.entries(pluginMcp)) {
- if (!hasCodexMcpTransport(serverConfig)) continue;
- transportConfiguredMcpServerNames.add(serverName);
- }
- }
- const unconfiguredRuntimeMcpServerNames = new Set<string>();
- let cursor: string | null = null;
- do {
- const status: CodexMcpServerStatusListResponse =
- await host.request<CodexMcpServerStatusListResponse>(
- Method.McpServerStatusList,
- { cursor, limit: 100, detail: 'toolsAndAuthOnly', threadId: null },
- { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS },
- );
- for (const server of status.data) {
- if (
- !transportConfiguredMcpServerNames.has(server.name) &&
- server.name !== CODEX_APPS_MCP_SERVER_NAME
- ) {
- unconfiguredRuntimeMcpServerNames.add(server.name);
- }
- }
- cursor = status.nextCursor;
- } while (cursor !== null);
- if (unconfiguredRuntimeMcpServerNames.size > 0) {
- throw new Error(
- `Codex reported runtime MCP servers without transport-bearing config: ${[
- ...unconfiguredRuntimeMcpServerNames,
- ].sort().join(', ')}`,
- );
- }
-
- const skillPaths = new Set([
- ...skills.filter((skill) => !keep?.skill(skill.path, skill.scope)).map((skill) => skill.path),
- ...errors.flatMap((error) => (error.path && !keep?.skill(error.path) ? [error.path] : [])),
- ]);
- const pluginIds = new Set(Object.keys(configuredPlugins));
- for (const skillPath of skillPaths) {
- const pluginId = pluginIdFromCodexSkillPath(skillPath);
- if (pluginId) pluginIds.add(pluginId);
- }
-
- const isolationConfig: Record<string, unknown> = {};
- if (skillPaths.size > 0) {
- isolationConfig['skills.config'] = [...skillPaths]
- .sort()
- .map((skillPath) => ({ path: skillPath, enabled: false }));
- }
- // Only configured MCP entries have a command/url transport that can
- // accept a per-thread `.enabled=false` merge. `codex_apps` is an
- // app-server builtin surfaced by mcpServerStatus/list but absent from
- // config/read; synthesizing an override for it makes Codex 0.145.0
- // reject thread/start with "invalid transport". Apps are isolated by
- // `features.apps=false` instead.
- for (const serverName of configuredMcpServerNames) {
- if (keep?.mcpServer(serverName)) continue;
- isolationConfig[
- `mcp_servers.${renderReviewConfigSegment(serverName)}.enabled`
- ] = false;
- }
- for (const pluginId of pluginIds) {
- if (!keep?.plugin?.(pluginId)) {
- isolationConfig[`plugins.${quoteReviewConfigSegment(pluginId)}.enabled`] = false;
- }
- const pluginMcp = asRecord(asRecord(configuredPlugins[pluginId]).mcp_servers);
- for (const [serverName, serverConfig] of Object.entries(pluginMcp)) {
- if (!hasCodexMcpTransport(serverConfig)) continue;
- isolationConfig[
- `plugins.${quoteReviewConfigSegment(pluginId)}.mcp_servers.${renderReviewConfigSegment(serverName)}.enabled`
- ] = false;
- }
- }
- return isolationConfig;
- };
if (reviewMode || opts[LOCAL_AGENT_CLIENT]) {
try {
assertCurrentHost('local capability isolation');
// Native execution retains its project Skills and installed native plugins.
// Only the automatically inherited credential-bearing MCP connections are excluded.
const nativeClient = opts[LOCAL_AGENT_CLIENT] && !opts[LOCAL_AGENT_CLIENT]!.hostToolsOnly;
- const reviewCapabilityConfig = await buildLocalCapabilityIsolationConfig(nativeClient
+ const reviewCapabilityConfig = await this.buildLocalCapabilityIsolationConfig(host, opts.workingDir, nativeClient
? { skill: () => true, plugin: () => true, mcpServer: () => false, allSkills: true }
: undefined);
capabilityRoutingConfig = {
@@ -5648,7 +5653,7 @@ assertRouteCurrent();
assertCurrentHost('Shared-user capability isolation');
// 受邀者目录里没有本机用户的全局说明;没有受邀者目录(旧接线)时仍按 fail-closed 检查。
await assertNoCodexUserInstructions(sessionCodexHome);
- const guestCapabilityConfig = await buildLocalCapabilityIsolationConfig({
+ const guestCapabilityConfig = await this.buildLocalCapabilityIsolationConfig(host, opts.workingDir, {
skill: (skillPath, scope) => guestSkillAllowed!(skillPath, scope),
mcpServer: (serverName) => hosted.mcpServers.includes(serverName),
});
@@ -14962,8 +14967,18 @@ assertRouteCurrent();
lastTurnId,
...(rollbackMethodRemoved || supportsCodexForkExcludeTurns(initResp.userAgent) ? { excludeTurns: true } : {}),
...(opts.workingDir ? { cwd: opts.workingDir } : {}),
+ // Native fork reloads the host defaults rather than inheriting the
+ // source thread's overrides. Reapply the task's execution environment,
+ // MCP routes and capability isolation before the new runtime starts.
+ ...currentThreadWorkspaceConfig(),
+ ...(threadModelProvider ? { modelProvider: threadModelProvider } : {}),
+ ...(mutableModel && mutableModel !== 'gpt-5' ? { model: mutableModel } : {}),
+ ...(serviceTierState.value !== undefined ? { serviceTier: serviceTierState.value } : {}),
+ ...(developerInstructions && !useProxyChannel ? { developerInstructions } : {}),
};
- const forkResp = await host.request<ThreadForkResponse>(Method.ThreadFork, forkParams);
+ const forkResp = await withMcpDiscoveryContext(() => host.request<ThreadForkResponse>(
+ Method.ThreadFork, forkParams, criticalThreadRpcOptions(),
+ ));
replacementThread = forkResp.thread;
}
const nextThreadId = replacementThread.id || previousThreadId;
@@ -15306,6 +15321,7 @@ assertRouteCurrent();
deviceHostedGuestProviderId: opts.providerId,
deviceHostedGuestSessionId: forkBaseHostKey,
deviceHostedGuestModelIds: opts.model ? [opts.model] : [],
+ nativeStorageOnly: true,
} : {}),
routeIsCurrent: selection.isCurrent,
routeSignal: forkRouteSignal,
@@ -15353,6 +15369,22 @@ assertRouteCurrent();
const usedNativeForkAnchor = Boolean(
lastTurnId && !opts.stripEncryptedReasoning && supportsCodexNativeTurnFork(initResp.userAgent),
);
+ let guestForkConfig: Record<string, unknown> | undefined;
+ if (guestCodexHome) {
+ // Fork starts a native runtime even without a turn. It must not
+ // initialize the provider's MCP or connectors while copying history;
+ // the child receives its consumer routes when startSession resumes it.
+ await assertNoCodexUserInstructions(forkCodexHome);
+ const features = await listCodexFeatures(cursor => host.request(
+ Method.ExperimentalFeatureList, { cursor, limit: 100 },
+ { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS },
+ ));
+ guestForkConfig = {
+ ...await this.buildLocalCapabilityIsolationConfig(host, opts.workingDir ?? guestCodexHome),
+ ...CODEX_DEVICE_HOSTED_GUEST_THREAD_CONFIG,
+ ...codexGuestFeatureOverrides(features),
+ };
+ }
const params: ThreadForkParams = {
threadId: opts.sourceSdkSessionId,
...(preparedSourcePath ? { path: preparedSourcePath } : {}),
@@ -15363,6 +15395,7 @@ assertRouteCurrent();
// 一次性 host 的隔离仍兜住故障半径。
...(supportsCodexForkExcludeTurns(initResp.userAgent) ? { excludeTurns: true } : {}),
...(opts.workingDir ? { cwd: opts.workingDir } : {}),
+ ...(guestForkConfig ? { config: guestForkConfig } : {}),
};
// Once dispatched, a lost response may still mean a child was allocated.
stage = 'thread-fork';