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(bots): connect remote harness task tools

Chris9605e0e2c97e
diff --cc apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
index b430b50cb6,b430b50cb6..cbebdd1f88
--- a/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
@@@ -60,6 -60,6 +60,24 @@@ describe('buildCcRemoteHttpMcpServers'
vi.clearAllMocks();
});
++ it.each([true, false])('injects the helper only for an identified Bot (bot=%s)', async (botSession) => {
++ const { bridge, registered } = fakeBridge();
++ const { servers, cleanup } = await buildCcRemoteHttpMcpServers({
++ host: HOST, sessionId: 'bot-session', sessionInstanceId: 'bot-instance', workingDir: '/remote/bot', botSession,
++ vendorOptions: { [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: ['xdt_helper'] },
++ }, {
++ ensureBridgeStarted: async () => ({ port: 38080, serverNames: ['cindy_helper', 'cindy_orca'], bridge }),
++ ensureForward: async () => 47921, getBridgeToken: () => 'remote-test-token', isCollabEnabled: () => false,
++ });
++ expect(Object.keys(servers)).toEqual(botSession ? ['cindy_helper'] : []);
++ if (botSession) {
++ expect(servers.cindy_helper).toEqual({ type: 'http', url: 'http://127.0.0.1:47921/mcp/cindy_helper?session=bot-session&instance=bot-instance', headers: { Authorization: 'Bearer remote-test-token' } });
++ expect(registered.get('bot-session')).toMatchObject({ sessionInstanceId: 'bot-instance', remoteHostId: 'host-1' });
++ }
++ cleanup();
++ expect(registered.size).toBe(0);
++ });
++
it('returns empty when the bridge is unavailable', async () => {
const { servers, cleanup } = await buildCcRemoteHttpMcpServers(
{ host: HOST, sessionId: 's1', workingDir: '/remote/repo' },
diff --cc apps/desktop/src/main/maker-host/cc-remote-mcp.ts
index fb9294a1a9,fb9294a1a9..b904433817
--- a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
+++ b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
@@@ -108,6 -108,6 +108,8 @@@ export async function buildCcRemoteHttp
/** 当前 Maker Session 实例代号;作为 opaque bridge route identity 下发。 */
sessionInstanceId?: string;
workingDir: string;
++ /** Host-owned Bot classification; helper also rechecks the live surface. */
++ botSession?: boolean;
/** session 自己的 vendorOptions (maker-core startSession 透传); 优先于 DB 合成。 */
vendorOptions?: Record<string, unknown>;
/**
@@@ -184,6 -184,6 +186,8 @@@
collabEnabled:
(deps.isCollabEnabled?.() ?? true) && isFrozenBuiltinPluginAllowed(vendorOptions, 'collab'),
memoryEnabled: args.makerMemoryEnabled === true,
++ botHelperEnabled: args.botSession === true && !!args.sessionInstanceId
++ && isFrozenBuiltinPluginAllowed(vendorOptions, 'xdt_helper'),
});
if (names.length === 0) {
// 无注入也是一代 (collab 禁用 / 白名单空):指纹常量 'disabled',
diff --cc apps/desktop/src/main/maker-host/index.ts
index 22009638e6,1a627dc88d..ed354d84f7
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@@ -246,6 -246,6 +247,7 @@@ import { setRemoteMcpBridgeTokenRotated
import { isBotToolsetAvailableOnTarget } from '../../shared/botRemoteCapabilities.js';
import {
ensureRemoteMcpForward,
++ buildRemoteCodexSessionMcpConfig,
setRemoteMcpForwardRearmedHook,
stripRemoteCodexMcpConfig,
} from '../remote-ssh/codex-remote-mcp.js';
@@@ -1101,6 -1106,6 +1108,7 @@@ export function getMaker(): Maker
onOAuthRefresh,
makerMemoryEnabled,
makerMemoryScopeKey,
++ botSession,
}) => {
const host = getRemoteSshPool().get(remoteHostId);
if (host?.getStatus() !== 'ready') {
@@@ -1135,6 -1140,6 +1143,7 @@@
vendorOptions,
// per-session Maker Memory 开关 (maker-core 归一后透传)。
makerMemoryEnabled,
++ botSession,
// 同源的 scope key: Bot 会话恒为 `bot:<botId>`, 缺失时远端工具
// 会回落 workdir 键, 与本地 prompt 注入的伙伴记忆分家。
...(makerMemoryScopeKey ? { makerMemoryScopeKey } : {}),
@@@ -1445,6 -1450,6 +1454,8 @@@
extraEnv: {},
codexProxyActive: false,
codexBrowserUseAvailable: true,
++ buildSessionMcpConfig: (instance: string) =>
++ buildRemoteCodexSessionMcpConfig(ctx.remoteHostId!, instance),
};
}
const isControlPlane = ctx.hostPurpose === 'control-plane';
diff --cc apps/desktop/src/main/maker-ipc/register.ts
index 8b9f1f37a6,c9b5c94c17..a254508237
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@@ -148,7 -147,7 +148,7 @@@ import
shutdownCodexEnvironment,
} from '../mcp-integrations/codexEnvironment.js';
import { invalidatePiEnvironment } from '../mcp-integrations/piEnvironment.js';
--import { REMOTE_MEMORY_SERVER_NAME } from '../mcp-integrations/codexHttpBridge.js';
++import { REMOTE_MEMORY_SERVER_NAME, REMOTE_BOT_HELPER_SERVER_NAME } from '../mcp-integrations/codexHttpBridge.js';
import { getRemoteMcpBridgeToken } from '../mcp-integrations/remoteMcpBridgeToken.js';
import {
checkComputerDriverUpdate,
@@@ -6784,6 -6787,6 +6788,7 @@@ export function registerMakerIpc(maker
// 不能只看 manager 现值 — 否则旧 bridge 缺 cindy_memory 时 drift 永不
// 收敛, 每次 live send 白跑完整 ensure。
makerMemoryEnabled: remoteMakerMemoryEnabledForBridge(),
++ botHelperAvailable: getActiveCodexBridgeServerNames()?.includes(REMOTE_BOT_HELPER_SERVER_NAME) ?? false,
token: getRemoteMcpBridgeToken(),
bridgeInstanceId: getActiveCodexBridgeInstanceId(),
};
diff --cc apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
index 4c48c24d72,130c218949..83ef6bbc92
--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
@@@ -1,7 -1,6 +1,7 @@@
--import { afterEach, describe, expect, it } from 'vitest';
++import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
--import { getLiziMcpSessionContext } from '@cindy/mcps';
++import { createXdtHelperMcpServer, getLiziMcpSessionContext } from '@cindy/mcps';
import type { Logger } from '@cindy/maker-core';
import {
@@@ -156,56 -155,6 +156,134 @@@ describe('codexHttpBridge', () =>
bridge = null;
});
+ it('scopes startup tools/list before thread registration without authorizing execution', async () => {
+ bridge = await startCodexHttpBridge({
+ serverFactories: { cindy_helper: () => {
+ const server = createTestServer();
+ server.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [{
+ name: getLiziMcpSessionContext()?.sessionId ?? 'unbound',
+ inputSchema: { type: 'object', properties: {} },
+ }] }));
+ return server;
+ } },
+ pluginIdByServerName: { cindy_helper: 'cindy_helper' },
+ logger: noopLogger(),
+ });
+ const current = bridge;
+ const url = withMcpRouteIdentity(current.url('cindy_helper'), { sessionInstanceId: 'starting-instance' });
+ const headers: Record<string, string> = {
+ authorization: `Bearer ${current.token}`, accept: 'application/json, text/event-stream',
+ 'content-type': 'application/json',
+ };
+ const initialized = await fetch(url, { method: 'POST', headers, body: JSON.stringify({
+ jsonrpc: '2.0', id: 1, method: 'initialize', params: {
+ protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'startup-test', version: '1' },
+ },
+ }) });
+ headers['mcp-session-id'] = initialized.headers.get('mcp-session-id')!;
+ await initialized.text();
+ let id = 2;
+ const request = (method: string, params: unknown = {}) => fetch(url, {
+ method: 'POST', headers, body: JSON.stringify({ jsonrpc: '2.0', id: id++, method, params }),
+ });
+ const list = async () => await readRpcResponse(await request('tools/list')) as { result: { tools: Array<{ name: string }> } };
+ expect((await list()).result.tools[0].name).toBe('unbound');
+ const context = { agentKind: 'codex' as const, sessionId: 'bot-parent', sessionInstanceId: 'starting-instance', workingDir: '/bot' };
+ await expect(current.withDiscoveryContext(context, async () => {
+ expect((await list()).result.tools[0].name).toBe('bot-parent');
+ const execution = await request('tools/call', { name: 'current_session', arguments: {} });
+ expect(execution.status).toBe(401);
+ await execution.text();
+ const stale = await readRpcResponse(await request('tools/list', { _meta: { threadId: 'unregistered-thread' } })) as { result: { tools: Array<{ name: string }> } };
+ expect(stale.result.tools[0].name).toBe('unbound');
+ throw new Error('native startup failed');
+ })).rejects.toThrow('native startup failed');
+ expect((await list()).result.tools[0].name).toBe('unbound');
+ current.registerThreadContext('real-thread', context);
+ expect((await list()).result.tools[0].name).toBe('bot-parent');
+ const execution = await request('tools/call', { name: 'current_session', arguments: {}, _meta: { threadId: 'real-thread' } });
+ expect(execution.status).toBe(200);
+ expect(await readRpcResponse(execution)).toMatchObject({ result: { content: [{ text: 'bot-parent' }] } });
+ });
+
++ it.each(['codex', 'claude-code'] as const)('serves only live Bot tasks over the %s remote helper route', async (agentKind) => {
++ let surface: 'bot' | 'default' = 'bot';
++ const start = vi.fn(async () => ({ ok: true as const, delegationId: 'remote-task', childSessionId: 'child-session', status: 'running', deadlineAt: 1000 }));
++ const unavailable = vi.fn(async () => ({ ok: false as const, errorCode: 'UNEXPECTED', message: 'unused' }));
++ bridge = await startCodexHttpBridge({
++ serverFactories: { cindy_helper: () => createXdtHelperMcpServer({
++ resolveSurface: async () => surface,
++ sessionTasks: { startSessionTask: start, getSessionTask: unavailable, messageSessionTask: unavailable, stopSessionTask: unavailable },
++ }, { agentKind, workingDir: '', getSessionContext: getLiziMcpSessionContext }) },
++ pluginIdByServerName: { cindy_helper: 'xdt_helper' },
++ additionalBearerTokens: () => ['remote-test-token'],
++ logger: noopLogger(),
++ });
++ const current = bridge;
++ const ctx = { agentKind, sessionId: 'remote-bot', sessionInstanceId: 'remote-instance', remoteHostId: 'ssh-host', workingDir: '/bot' };
++ if (agentKind === 'claude-code') current.registerSessionCtx(ctx.sessionId, ctx);
++ const url = withMcpRouteIdentity(current.url('cindy_helper'), {
++ sessionInstanceId: ctx.sessionInstanceId,
++ ...(agentKind === 'claude-code' ? { sessionId: ctx.sessionId } : {}),
++ });
++ const headers: Record<string, string> = {
++ authorization: 'Bearer remote-test-token', accept: 'application/json, text/event-stream', 'content-type': 'application/json',
++ };
++ const init = await fetch(url, { method: 'POST', headers, body: JSON.stringify({
++ jsonrpc: '2.0', id: 1, method: 'initialize', params: {
++ protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'remote-bot-test', version: '1' },
++ },
++ }) });
++ expect(init.status).toBe(200);
++ headers['mcp-session-id'] = init.headers.get('mcp-session-id')!;
++ await init.text();
++ let id = 2;
++ const request = (method: string, params: unknown = {}, target = url) => fetch(target, {
++ method: 'POST', headers, body: JSON.stringify({ jsonrpc: '2.0', id: id++, method, params }),
++ });
++ const list = async () => readRpcResponse(await request('tools/list')) as Promise<{ result: { tools: Array<{ name: string }> } }>;
++ await current.withDiscoveryContext(ctx, async () => {
++ expect((await list()).result.tools.map(t => t.name)).toEqual(expect.arrayContaining([
++ 'start_session_task', 'check_session_task', 'message_session_task', 'stop_session_task',
++ ]));
++ if (agentKind === 'codex') {
++ const denied = await request('tools/call', { name: 'start_session_task', arguments: { instruction: 'too early' } });
++ expect(denied.status).toBe(401);
++ await denied.text();
++ }
++ });
++ if (agentKind === 'codex') current.registerThreadContext('remote-thread', ctx);
++ const firstList = await list();
++ expect((await list()).result).toEqual(firstList.result);
++ const result = await readRpcResponse(await request('tools/call', {
++ name: 'start_session_task', arguments: { instruction: 'Build the report' },
++ ...(agentKind === 'codex' ? { _meta: { threadId: 'remote-thread' } } : {}),
++ }));
++ expect(result).toMatchObject({ result: { content: [{ type: 'text', text: expect.stringContaining('remote-task') }] } });
++ expect(start).toHaveBeenCalledWith(expect.objectContaining({ callerSessionId: 'remote-bot', objective: 'Build the report' }));
++ // The bridge is shared: a live surface change must not reveal ordinary helper controls.
++ surface = 'default';
++ expect((await list()).result.tools.map(t => t.name).sort()).toEqual(['call_tool', 'list_tools']);
++ const categories = await readRpcResponse(await request('tools/call', { name: 'list_tools', arguments: {} }));
++ expect(categories).toMatchObject({ result: { content: [{ text: expect.stringContaining('"categories":[]') }] } });
++ await request('tools/call', { name: 'start_session_task', arguments: { instruction: 'denied' } }).then(readRpcResponse);
++ expect(start).toHaveBeenCalledTimes(1);
++ if (agentKind === 'codex') {
++ // A remote token cannot borrow a local or Pi context to get the broad helper surface.
++ for (const invalid of [{ ...ctx, remoteHostId: undefined }, { ...ctx, agentKind: 'pi' as const }]) {
++ current.registerThreadContext('remote-thread', invalid);
++ const denied = await request('tools/list');
++ expect(denied.status).toBe(401);
++ await denied.text();
++ }
++ }
++ if (agentKind === 'codex') current.unregisterThreadContext('remote-thread', ctx.sessionInstanceId);
++ else current.unregisterSessionCtx(ctx.sessionId, ctx);
++ const stale = await request('tools/list');
++ expect(stale.status).toBe(401);
++ await stale.text();
++ });
++
it('accepts an additional bearer token (remote daemon) and rejects unknown tokens', async () => {
bridge = await startCodexHttpBridge({
serverFactories: {
diff --cc apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
index 5392444fde,bf0660ef38..3b9a4043db
--- a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
+++ b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
@@@ -48,10 -48,10 +48,12 @@@ export const REMOTE_COLLAB_SERVER_NAMES
* 本机 store (per hostId+远端路径 分区, 见 maker-core buildMemoryScopeKey)。
*/
export const REMOTE_MEMORY_SERVER_NAME = 'cindy_memory';
++/** Remote helper is enabled only for Bot Sessions and rechecks their live surface. */
++export const REMOTE_BOT_HELPER_SERVER_NAME = 'cindy_helper';
/**
* 远端 (SSH remote-forward) 允许暴露的 server 全集 — additionalBearerTokens
* (persistent token) 认证的请求只能访问这些 server, 鉴权层按它 scope。
-- * 只放协同 (cindy_orca / orca_worker_bridge) 与 Maker Memory (cindy_memory,
++ * 放行协同、按 Session 限定的伙伴 helper 与 Maker Memory (cindy_memory,
* 2026-07 放行: 工具面固定、只触达本机 maker-memory 目录, 与协同同威胁模型);
* 拿到 persistent token 的远端进程仍不得经 bridge 初始化 cindy_ssh 等其余
* 本机 server。
@@@ -59,6 -59,6 +61,7 @@@
export const REMOTE_ALLOWED_SERVER_NAMES: ReadonlySet<string> = new Set([
...REMOTE_COLLAB_SERVER_NAMES,
REMOTE_MEMORY_SERVER_NAME,
++ REMOTE_BOT_HELPER_SERVER_NAME,
]);
/**
@@@ -71,10 -71,10 +74,13 @@@
*/
export function selectRemoteInjectableServerNames(
available: readonly string[],
-- gates: { collabEnabled: boolean; memoryEnabled: boolean },
++ gates: { collabEnabled: boolean; memoryEnabled: boolean; botHelperEnabled?: boolean },
): string[] {
return [
...(gates.collabEnabled ? available.filter((n) => REMOTE_COLLAB_SERVER_NAMES.has(n)) : []),
++ ...(gates.botHelperEnabled && available.includes(REMOTE_BOT_HELPER_SERVER_NAME)
++ ? [REMOTE_BOT_HELPER_SERVER_NAME]
++ : []),
...(gates.memoryEnabled && available.includes(REMOTE_MEMORY_SERVER_NAME)
? [REMOTE_MEMORY_SERVER_NAME]
: []),
@@@ -245,7 -242,7 +251,7 @@@ export async function startCodexHttpBri
// (persistent, 远端常驻 codex daemon 与远端 cc 共用) / per-session token
// (pi 会话, 按 ?session= 隔离, 见 interface 注释)。主 token 与 pi
// per-session token 全通;额外 token 只允许访问 REMOTE_ALLOWED_SERVER_NAMES
-- // 白名单 (协同 + cindy_memory; 远端进程拿到 token 也不得初始化其余本机 server)。
++ // 白名单 (协同、记忆、伙伴 helper;helper 另有 Session 实例与能力面校验)。
// URL 解析提前:per-session token 匹配需要 session query,纯解析无副作用。
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
const sessionQuery = url.searchParams.get('session');
@@@ -339,7 -336,7 +345,7 @@@
res.end();
return;
}
-- // scoped (persistent) token 仅限远端白名单 server (协同 + cindy_memory):
++ // scoped (persistent) token 仅限远端白名单 server:
// 同一 remote-forward 能摸到完整 /mcp/<name> 路由, 不得经它初始化
// cindy_ssh 等其余本机 server — codex-connector P1。
if (isScopedRemoteToken && !REMOTE_ALLOWED_SERVER_NAMES.has(serverName)) {
@@@ -369,6 -365,6 +375,7 @@@
pluginId: opts.pluginIdByServerName?.[serverName],
sessionTokenCtx,
threadInstanceQuery: sessionQuery === null ? instanceQuery : null,
++ remoteBotHelper: isScopedRemoteToken && serverName === REMOTE_BOT_HELPER_SERVER_NAME,
});
} catch (err) {
log.error('request handler threw', {
@@@ -565,7 -552,6 +572,8 @@@ interface DispatchOpts
serverName: string;
log: Logger;
threadContextStore: ReturnType<typeof createCodexMcpThreadContextStore>;
+ discoveryContexts: ReadonlyMap<string, LiziMcpSessionContext>;
++ remoteBotHelper?: boolean;
pluginId?: string;
/** per-session token 命中时解析出的 ctx;存在即优先于 _meta.threadId 路由。 */
sessionTokenCtx?: LiziMcpSessionContext;
@@@ -600,6 -585,6 +608,7 @@@ async function dispatchToTransport(opts
pluginId,
sessionTokenCtx,
threadInstanceQuery,
++ remoteBotHelper,
} = opts;
const sessionIdHeader = req.headers['mcp-session-id'];
@@@ -664,6 -641,6 +673,16 @@@
});
}
}
++ // The remote token must never open the ordinary local helper surface.
++ // Startup discovery may list tools, but calls still need the registered thread.
++ if (remoteBotHelper && (hasToolCall(parsedBody) ||
++ (parsedBody as { method?: unknown } | undefined)?.method === 'tools/list') &&
++ (!activeContext?.remoteHostId || !activeContext.sessionInstanceId ||
++ (activeContext.agentKind !== 'codex' && activeContext.agentKind !== 'claude-code'))) {
++ res.statusCode = 401;
++ res.end('Remote helper requires a bound Session instance');
++ return;
++ }
if (
!sessionTokenCtx &&
threadInstanceQuery !== null &&
diff --cc apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
index 5758026145,5758026145..bd6b422cf9
--- a/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
+++ b/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
@@@ -13,6 -13,6 +13,7 @@@ import type { RemoteHost } from '@cindy
import {
renderManagedMcpBlock,
++ buildRemoteCodexSessionMcpConfig,
mergeManagedMcpBlock,
ensureRemoteCodexMcpBridge,
stripRemoteCodexMcpConfig,
@@@ -1350,3 -1350,3 +1351,28 @@@ describe('codex-connector R27 regressio
expect(execCmds.join('\n')).not.toContain('bootstrap');
});
});
++
++
++describe('remote Bot helper transport', () => {
++ it('keeps the shared helper disabled and binds per-thread URLs with collab and memory off', async () => {
++ const { host, inputs } = fakeHost('host-helper-only', '');
++ const ensured = await ensureRemoteCodexMcpBridge(host, {
++ ensureBridgeStarted: async () => ({ port: 38991, serverNames: ['cindy_helper'], bridgeInstanceId: 'helper-bridge' }),
++ isCollabEnabled: () => false, isMakerMemoryEnabled: () => false,
++ });
++ expect(ensured.ok).toBe(true);
++ expect(decodeWrittenConfig(inputs)).toContain('[mcp_servers.cindy_helper]');
++ expect(decodeWrittenConfig(inputs)).toContain('enabled = false');
++ const config = buildRemoteCodexSessionMcpConfig(host.id, 'bot-instance');
++ expect(config).toMatchObject({
++ 'mcp_servers.cindy_helper.url': 'http://127.0.0.1:47921/mcp/cindy_helper?instance=bot-instance',
++ 'mcp_servers.cindy_helper.bearer_token_env_var': 'LIZI_MCP_TOKEN',
++ 'mcp_servers.cindy_helper.enabled': false,
++ });
++ expect(buildRemoteCodexSessionMcpConfig('missing-host', 'bot-instance')).toEqual({});
++ expect(hasPendingRemoteMcpDrift(host.id, {
++ collabEnabled: false, makerMemoryEnabled: false, botHelperAvailable: true,
++ token: 'test-persistent-token', bridgeInstanceId: 'helper-bridge',
++ })).toBe(false);
++ });
++});
diff --cc apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
index 7abf8fc91c,7abf8fc91c..baf835b147
--- a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
+++ b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
@@@ -36,6 -36,6 +36,8 @@@ import { createLogger } from '../logger
import {
REMOTE_ALLOWED_SERVER_NAMES,
REMOTE_COLLAB_SERVER_NAMES,
++ REMOTE_BOT_HELPER_SERVER_NAME,
++ withMcpRouteIdentity,
computeRemoteMcpFingerprint,
selectRemoteInjectableServerNames,
} from '../mcp-integrations/codexHttpBridge.js';
@@@ -199,6 -199,6 +201,26 @@@ export function invalidateRemoteCodexMc
});
}
++/** Bind the remote daemon's disabled helper transport to one concrete Session.
++ * Read the port at use time: SSH forwarding is established after host construction.
++ * Only Bot MCP policy enables this transport; ordinary remote threads keep it disabled.
++ */
++export function buildRemoteCodexSessionMcpConfig(
++ hostId: string,
++ sessionInstanceId: string,
++): Record<string, unknown> {
++ const prefs = readPortPrefs()[hostId];
++ if (!prefs?.appliedFingerprint || !sessionInstanceId) return {};
++ return {
++ [`mcp_servers.${REMOTE_BOT_HELPER_SERVER_NAME}.url`]: withMcpRouteIdentity(
++ `http://127.0.0.1:${prefs.remotePort}/mcp/${REMOTE_BOT_HELPER_SERVER_NAME}`,
++ { sessionInstanceId },
++ ),
++ [`mcp_servers.${REMOTE_BOT_HELPER_SERVER_NAME}.bearer_token_env_var`]: TOKEN_ENV,
++ [`mcp_servers.${REMOTE_BOT_HELPER_SERVER_NAME}.enabled`]: false,
++ };
++}
++
// ── 远端 config.toml 管理段 (纯函数, 便于单测) ──────────────────────────────
/** 生成我们管理的 mcp_servers 配置块 (带 begin/end 标记)。 */
@@@ -218,6 -218,6 +240,7 @@@ export function renderManagedMcpBlock(o
`[mcp_servers.${name}]`,
`url = "http://127.0.0.1:${opts.remotePort}/mcp/${name}"`,
`bearer_token_env_var = "${TOKEN_ENV}"`,
++ ...(name === REMOTE_BOT_HELPER_SERVER_NAME ? ['enabled = false'] : []),
'startup_timeout_sec = 600',
'tool_timeout_sec = 600',
'',
@@@ -672,12 -672,12 +695,13 @@@ export function hasPendingRemoteMcpDrif
* 含 cindy_memory — 与 ensure 内的注入集合同源, 开关翻转构成漂移。
*/
makerMemoryEnabled: boolean;
++ botHelperAvailable?: boolean;
token: string | null;
bridgeInstanceId: string | null;
},
): boolean {
const applied = readPortPrefs()[hostId]?.appliedFingerprint ?? null;
-- if ((!opts.collabEnabled && !opts.makerMemoryEnabled) || !opts.token) {
++ if ((!opts.collabEnabled && !opts.makerMemoryEnabled && !opts.botHelperAvailable) || !opts.token) {
// 清理语义:applied 存在 = 待清理 (strip / 清理路径未跑过)。
return applied !== null;
}
@@@ -695,6 -695,6 +719,7 @@@
serverNames: selectRemoteInjectableServerNames([...REMOTE_ALLOWED_SERVER_NAMES], {
collabEnabled: opts.collabEnabled,
memoryEnabled: opts.makerMemoryEnabled,
++ botHelperEnabled: opts.botHelperAvailable,
}),
});
return desired !== applied;
@@@ -794,6 -794,6 +819,8 @@@ async function doEnsureRemoteCodexMcpBr
let serverNames = selectRemoteInjectableServerNames(bridge.serverNames, {
collabEnabled,
memoryEnabled: deps.isMakerMemoryEnabled?.() ?? false,
++ // Shared transport stays disabled; the Bot policy enables it per thread.
++ botHelperEnabled: true,
});
if (
!collabEnabled &&
diff --cc packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
index 3f11018015,8285474f72..2cfa2005f1
--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
@@@ -579,6 -578,6 +580,7 @@@ export interface XdtHelperMcpDeps
export interface XdtHelperMcpSessionCtx {
agentKind: 'claude-code' | 'codex' | 'pi';
workingDir: string;
++ remoteHostId?: string;
getSessionContext?: () => import('./types.js').LiziMcpSessionContext | undefined;
sessionId?: string;
vendorOptions?: Record<string, unknown>;
@@@ -595,15 -594,15 +597,17 @@@ export function createXdtHelperMcpServe
const registry = new XdtHelperToolRegistry();
const allowedCategories = async (): Promise<ReadonlySet<string> | null> => {
-- const sessionId = resolveLiziMcpSessionContext(sessionCtx).sessionId;
++ const context = resolveLiziMcpSessionContext(sessionCtx);
++ const sessionId = context.sessionId;
++ const remoteBotOnly = !!context.remoteHostId && context.agentKind !== 'pi';
const defaultCategories = new Set(CATEGORY_ENUM.filter((category) => category !== 'bots'));
-- if (!sessionId || !deps.resolveSurface) return defaultCategories;
++ if (!sessionId || !deps.resolveSurface) return remoteBotOnly ? new Set() : defaultCategories;
const surface = await deps.resolveSurface({ sessionId }).catch(() => 'restricted' as const);
// Bot-specific memory, Skills, messaging, delegation and durable notes all
// live in this single category. Cindy-wide history/control/feedback/handoff
// stay out of the Bot's discovery loop.
if (surface === 'bot') return new Set(['bots']);
-- return surface === 'restricted' ? new Set() : defaultCategories;
++ return remoteBotOnly || surface === 'restricted' ? new Set() : defaultCategories;
};
// 'cindy' 类: 自省 (无 host 依赖, 始终注册)。
diff --cc packages/maker-core/src/agents/base-agent.ts
index d6a09798ab,90e87ce84c..eac4f419d9
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@@ -960,11 -960,6 +960,11 @@@ export interface AgentDeps
*/
reviewAutoPermissionAction?: AutoReviewDelegate;
+ /** Scope tools/list during native startup, before a real thread id exists. Never authorizes tools/call. */
+ withCodexMcpDiscoveryContext?: <T>(
- args: Pick<CodexMcpThreadContextArgs, 'sessionId' | 'sessionInstanceId' | 'workingDir' | 'vendorOptions'>,
++ args: Pick<CodexMcpThreadContextArgs, 'sessionId' | 'sessionInstanceId' | 'workingDir' | 'vendorOptions' | 'remoteHostId'>,
+ run: () => Promise<T>,
+ ) => Promise<T>;
/**
* Codex-only: bind app-server thread ids back to xdt-maker session context
* for host-owned HTTP MCP bridges. Missing hooks keep the old no-session
@@@ -1293,6 -1288,6 +1293,8 @@@
*/
remoteCcQueryFactory?: (opts: {
remoteHostId: string;
++ /** Inject the narrow helper transport for a Bot runtime. */
++ botSession?: boolean;
sessionId: string;
/** 当前 Maker Session 实例代号;只在宿主 MCP 身份上下文中流转。 */
sessionInstanceId?: string;
diff --cc packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts
index 258bc8821a,c40b15de21..35791980e7
--- a/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts
@@@ -104,15 -102,7 +104,16 @@@ async function startBotSession(input:
const workingDir = await makeTempDir();
sdkMock.query.mockReturnValue(createFakeQuery());
- const agent = new ClaudeCodeAgent(createDeps());
+ const deps = createDeps();
+ let remoteOptions: unknown;
+ if (input.remote) {
- deps.remoteCcQueryFactory = async ({ startParams }) => {
++ deps.remoteCcQueryFactory = async ({ startParams, botSession }) => {
++ expect(botSession).toBe(!input.reviewMode && !input.ordinary);
+ remoteOptions = startParams.extraOptions;
+ return createFakeQuery() as never;
+ };
+ }
+ const agent = new ClaudeCodeAgent(deps);
await agent.startSession({
sessionId: 'session-bot-skills',
model: 'claude-opus-4-6',
diff --cc packages/maker-core/src/agents/claude-code/index.ts
index ba1b843c6a,6ab7656236..bb58fa01fe
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@@ -3254,6 -3252,6 +3254,7 @@@ export class ClaudeCodeAgent extends Ba
const remoteQuery = await this.deps.remoteCcQueryFactory({
remoteHostId: opts.remoteHostId,
++ botSession: !reviewMode && !!opts.botRuntimeProfile,
sessionId: opts.sessionId,
...(opts.sessionInstanceId ? { sessionInstanceId: opts.sessionInstanceId } : {}),
startParams,
diff --cc packages/maker-core/src/agents/codex/index.test.ts
index d9fc5962a9,d7c9896382..094e4ac6ac
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@@ -8479,32 -8480,6 +8488,62 @@@ describe('CodexAgent MCP thread contex
);
});
- it.each([false, true])('registers discovery identity around native startup (resume=%s)', async (resume) => {
++ it.each([{ resume: false, remote: false }, { resume: true, remote: false }, { resume: false, remote: true }, { resume: true, remote: true }])('registers discovery identity around native startup ($resume, $remote)', async ({ resume, remote }) => {
+ const order: string[] = [];
+ const deps = createDeps();
+ deps.withCodexMcpDiscoveryContext = async (ctx, run) => {
+ expect(ctx).toMatchObject({ sessionId: 'bot-parent', sessionInstanceId: 'bot-instance' });
++ expect(ctx.remoteHostId).toBe(remote ? 'remote-bot-host' : undefined);
+ order.push('discovery');
+ try { return await run(); } finally { order.push('released'); }
+ };
+ const agent = new CodexAgent(deps);
+ const host = installFakeHost(agent);
+ const original = host.request.getMockImplementation()!;
+ host.request.mockImplementation(async (...args) => {
+ if (args[0] === Method.ThreadStart || args[0] === Method.ThreadResume) {
+ expect(order).toEqual(['discovery']);
+ order.push('native');
+ }
+ return original(...args);
+ });
+ const handle = await agent.startSession({
+ sessionId: 'bot-parent', sessionInstanceId: 'bot-instance', workingDir: '/bot', model: 'gpt-5.4',
++ ...(remote ? { remoteHostId: 'remote-bot-host' } : {}),
+ ...(resume ? { resumeSessionId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' } : {}),
+ });
+ expect(order).toEqual(['discovery', 'native', 'released']);
+ await handle.close();
+ });
+
++ it.each([{ bot: true, resume: false }, { bot: true, resume: true }, { bot: false, resume: false }])(
++ 'enables the remote helper transport only for a Bot (bot=$bot, resume=$resume)', async ({ bot, resume }) => {
++ const agent = new CodexAgent(createDeps());
++ const host = installFakeHost(agent, undefined, {
++ userAgent: 'mock-codex/0.145.0',
++ buildSessionMcpConfig: (instance) => ({
++ 'mcp_servers.cindy_helper.url': `http://127.0.0.1:47921/mcp/cindy_helper?instance=${instance}`,
++ 'mcp_servers.cindy_helper.bearer_token_env_var': 'LIZI_MCP_TOKEN',
++ 'mcp_servers.cindy_helper.enabled': false,
++ }),
++ });
++ const handle = await agent.startSession({
++ sessionId: 'remote-bot', sessionInstanceId: 'remote-instance', remoteHostId: 'ssh-host', workingDir: '/bot', model: 'gpt-5.4',
++ ...(resume ? { resumeSessionId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' } : {}),
++ ...(bot ? { botRuntimeProfile: {
++ botId: 'bot-1', profileVersion: 1,
++ skillPolicy: { mode: 'allowlist' as const, configured: [], catalog: [] },
++ mcpPolicy: { mode: 'allowlist' as const, configured: [], catalog: [] },
++ toolsetPolicy: { mode: 'allowlist' as const, configured: [], catalog: [] },
++ } } : {}),
++ });
++ const params = host.request.mock.calls.find(([method]) => method === (resume ? Method.ThreadResume : Method.ThreadStart))?.[1] as { config: Record<string, unknown> };
++ expect(params.config['mcp_servers.cindy_helper.enabled']).toBe(bot);
++ expect(params.config['mcp_servers.cindy_helper.url']).toBe('http://127.0.0.1:47921/mcp/cindy_helper?instance=remote-instance');
++ await handle.close();
++ },
++ );
++
it('applies instance-bound MCP URLs to both thread/start and thread/resume', async () => {
const buildConfig = (sessionInstanceId?: string) => ({
'mcp_servers.cindy_ghosts.url': `http://127.0.0.1:47100/mcp/cindy_ghosts?instance=${sessionInstanceId}`,
diff --cc packages/maker-core/src/agents/codex/index.ts
index e00cb7eebe,890c47fc49..8bdabda3b8
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@@ -4807,6 -4807,6 +4807,10 @@@ export class CodexAgent extends BaseAge
if (match && typeof value === 'string' && value.trim()) transports.add(match[1]);
}
botMcpConfig = buildCodexBotMcpConfigOverrides(opts.botRuntimeProfile.mcpPolicy, transports);
++ // Remote daemons keep this shared transport disabled for ordinary tasks.
++ if (opts.remoteHostId && transports.has('cindy_helper')) {
++ botMcpConfig['mcp_servers.cindy_helper.enabled'] = true;
++ }
if (!makerMemoryEnabled && transports.has('cindy_memory')) {
botMcpConfig['mcp_servers.cindy_memory.enabled'] = false;
}
@@@ -5585,17 -5585,8 +5589,19 @@@
const { approvalPolicy, approvalsReviewer, sandbox } = currentApprovalConfig();
const threadContextWindow = effectiveThreadContextWindow(contextLimit);
const config = {
++ // Apply transport defaults before the per-session Bot capability policy.
++ ...(reviewMode ? {} : host.getSessionMcpConfig(opts.sessionInstanceId)),
...capabilityRoutingConfig,
...customProviderThreadConfig,
+ // Bot memory and delegation belong to its Cindy Profile and Session
+ // tasks, not the shared native home or hidden harness child threads.
+ ...(opts.botRuntimeProfile ? {
+ 'features.multi_agent': false,
+ 'features.multi_agent_v2': false,
+ 'agents.enabled': false,
+ 'memories.generate_memories': false,
+ 'memories.use_memories': false,
+ } : {}),
...(readonlyReferenceDirsSupported ? readonlyReferencesConfig() : {}),
...(reviewMode ? reviewPermissionsConfig : {}),
...(reviewMode
@@@ -5608,7 -5599,7 +5614,6 @@@
'features.remote_plugin': false,
}
: {}),
-- ...(reviewMode ? {} : host.getSessionMcpConfig(opts.sessionInstanceId)),
...(!makerMemoryEnabled && !opts.botRuntimeProfile
? { 'mcp_servers.cindy_memory.enabled': false }
: {}),
@@@ -5956,14 -5947,6 +5961,15 @@@
let codexThreadModelProviderId: string | undefined;
let codexProductPromptDelivery: AgentSessionHandle['codexProductPromptDelivery'];
+ const withMcpDiscoveryContext = <T>(run: () => Promise<T>): Promise<T> => {
+ if (reviewMode || !sid || !opts.sessionInstanceId || !this.deps.withCodexMcpDiscoveryContext) return run();
+ return this.deps.withCodexMcpDiscoveryContext({
+ sessionId: sid, sessionInstanceId: opts.sessionInstanceId,
+ workingDir: opts.workingDir, vendorOptions: vo,
++ ...(opts.remoteHostId ? { remoteHostId: opts.remoteHostId } : {}),
+ }, run);
+ };
+
/**
* Start a replacement thread after the exact provider proof that the
* persisted thread has no rollout. This is intentionally narrower than a