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): restore model sync and harness task capabilities

Chris7e2e242659d3
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index 0f8f1c48d4..59c3fc305f 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -289,20 +289,15 @@ describe('session runtime control wiring', () => {
'const handleSetModel = async (',
'const recoverRemoteRuntimeAxisPersistence',
);
- const guard = setModel.indexOf(
- "if (internalOptions.source === 'user' && !internalOptions.sessionLockHeld && !isDeviceLinkInvoke()) {",
- );
- expect(guard).toBeGreaterThan(-1);
- expect(setModel.indexOf('assertTrustedAppRendererEvent(')).toBeGreaterThan(
- guard,
- );
- expect(setModel.indexOf('assertTrustedAppRendererEvent(')).toBeLessThan(
- setModel.indexOf("typeof sessionId !== 'string'"),
- );
+ const ingress = setModel.indexOf('registerSessionSetModelHandler(makerSessionRegistry, {');
+ expect(ingress).toBeGreaterThan(-1);
+ expect(setModel.slice(0, ingress)).not.toContain('assertTrustedAppRendererEvent(');
+ expect(setModel.slice(ingress)).toContain('assertTrustedSender: (event) => assertTrustedAppRendererEvent(');
+ expect(setModel.slice(ingress)).toContain('isDeviceLinkInvoke,');
expect(setModel).toContain('!isSupportedRuntimeEffort(selectionEffort)');
expect(setModel).toContain("internalOptions.source !== 'user'");
expect(registerSource).toMatch(
- /handleSetModel\(\s*undefined,\s*sessionId,\s*model,\s*providerId,\s*undefined,\s*selection,\s*options,?\s*\)/,
+ /handleSetModel\(\s*sessionId,\s*model,\s*providerId,\s*undefined,\s*selection,\s*options,?\s*\)/,
);
expect(setModel).toMatch(/\{\s*source:\s*'user',?\s*\}/);
expect(setModel).not.toContain('ipcMain.handle(MAKER_INVOKE.SET_MODEL, handleSetModel)');
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 90c87343bb..22009638e6 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -234,6 +234,7 @@ import {
import { cleanupComputerDriverSession } from '../mcp-integrations/computer.js';
import { createPluginRegistry, resetPluginRegistry } from './plugins/index.js';
import {
+ withCodexMcpDiscoveryContext,
getActiveCodexBridgeServerNames,
getCodexExtraSpawnConfig,
registerCodexMcpThreadContext,
@@ -1698,6 +1699,8 @@ export function getMaker(): Maker {
: {}),
};
},
+ withCodexMcpDiscoveryContext: (ctx, run) =>
+ withCodexMcpDiscoveryContext({ ...ctx, agentKind: 'codex' }, run),
registerCodexMcpThreadContext: ({
threadId,
sessionId,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionSetModelHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionSetModelHandler.test.ts
new file mode 100644
index 0000000000..2ef04deb48
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionSetModelHandler.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it, vi } from 'vitest';
+import { MAKER_INVOKE } from '../channels';
+import { registerSessionSetModelHandler } from '../sessionSetModelHandler';
+import { IpcHarness } from './helpers/ipcHarness';
+
+describe('SET_MODEL ingress', () => {
+ it('checks the actual local sender before passing the complete selection to the transaction', async () => {
+ const harness = new IpcHarness();
+ const order: string[] = [];
+ const assertTrustedSender = vi.fn(() => { order.push('trust'); });
+ const apply = vi.fn(() => { order.push('apply'); return { applied: true }; });
+ registerSessionSetModelHandler(harness, { isDeviceLinkInvoke: () => false, assertTrustedSender, apply });
+ const selection = { effort: 'high', fastMode: false };
+ await expect(harness.invokeFrom(42, MAKER_INVOKE.SET_MODEL, 'bot-session', 'model', null, 2, selection))
+ .resolves.toEqual({ applied: true });
+ expect(assertTrustedSender).toHaveBeenCalledWith(expect.objectContaining({ sender: expect.objectContaining({ id: 42 }) }));
+ expect(apply).toHaveBeenCalledWith('bot-session', 'model', null, 2, selection);
+ expect(order).toEqual(['trust', 'apply']);
+ });
+
+ it('rejects untrusted local callers before changing a model', async () => {
+ const harness = new IpcHarness();
+ const apply = vi.fn();
+ registerSessionSetModelHandler(harness, {
+ isDeviceLinkInvoke: () => false,
+ assertTrustedSender: () => { throw new Error('untrusted sender'); }, apply,
+ });
+ await expect(harness.invoke(MAKER_INVOKE.SET_MODEL, 'bot-session', 'model')).rejects.toThrow('untrusted sender');
+ expect(apply).not.toHaveBeenCalled();
+ });
+
+ it('lets authenticated device-link ingress use the transaction without an Electron frame', async () => {
+ const harness = new IpcHarness();
+ const assertTrustedSender = vi.fn(() => { throw new Error('no Electron frame'); });
+ const apply = vi.fn(() => 'applied');
+ registerSessionSetModelHandler(harness, { isDeviceLinkInvoke: () => true, assertTrustedSender, apply });
+ await expect(harness.invoke(MAKER_INVOKE.SET_MODEL, 'bot-session', 'model')).resolves.toBe('applied');
+ expect(assertTrustedSender).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index c65fa4b24f..8b9f1f37a6 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1,3 +1,4 @@
+import { registerSessionSetModelHandler } from './sessionSetModelHandler.js';
import { projectRemoteBotDelegations } from './remoteBotDelegations.js';
/**
* registerMakerIpc — 把 Maker Core 的能力暴露为 maker:* IPC channel。
@@ -14776,7 +14777,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 可以乐观调用 (UI 更新先行, IPC 失败也不会回滚 UI, 老 agentManager 同语义)。
const handleSetModel = async (
- event: Electron.IpcMainInvokeEvent | undefined,
sessionId: unknown,
model: unknown,
providerId: unknown,
@@ -14784,9 +14784,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
selection: unknown,
internalOptions: InternalRuntimeSelectionOptions,
) => {
- if (internalOptions.source === 'user' && !internalOptions.sessionLockHeld && !isDeviceLinkInvoke()) {
- assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);
- }
if (typeof sessionId !== 'string' || typeof model !== 'string') {
throwIpcError('INVALID_PARAMS', 'sessionId + model required');
}
@@ -15983,14 +15980,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return internalOptions.sessionLockHeld ? applyLocked() : withSendToSessionLock(sessionId, applyLocked);
};
applySessionRuntimeSelection = (sessionId, model, providerId, selection, options) =>
- handleSetModel(undefined, sessionId, model, providerId, undefined, selection, options);
- ipcMain.handle(
- MAKER_INVOKE.SET_MODEL,
- (event, sessionId, model, providerId, expectedAgentSwitchRevision, selection) =>
- handleSetModel(event, sessionId, model, providerId, expectedAgentSwitchRevision, selection, {
- source: 'user',
- }),
- );
+ handleSetModel(sessionId, model, providerId, undefined, selection, options);
+ registerSessionSetModelHandler(makerSessionRegistry, {
+ isDeviceLinkInvoke,
+ assertTrustedSender: (event) => assertTrustedAppRendererEvent(
+ event as Parameters<typeof assertTrustedAppRendererEvent>[0],
+ ),
+ apply: (sessionId, model, providerId, revision, selection) =>
+ handleSetModel(sessionId, model, providerId, revision, selection, { source: 'user' }),
+ });
const recoverRemoteRuntimeAxisPersistence = async (
sessionId: string,
diff --git a/apps/desktop/src/main/maker-ipc/sessionSetModelHandler.ts b/apps/desktop/src/main/maker-ipc/sessionSetModelHandler.ts
new file mode 100644
index 0000000000..ac6dbb30b1
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sessionSetModelHandler.ts
@@ -0,0 +1,18 @@
+import { MAKER_INVOKE } from './channels.js';
+import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';
+
+/** Window trust belongs to IPC ingress, not the model transaction also used by Bots. */
+export function registerSessionSetModelHandler(
+ registry: IpcHandlerRegistry,
+ deps: {
+ isDeviceLinkInvoke(): boolean;
+ assertTrustedSender(event: unknown): void;
+ apply(sessionId: unknown, model: unknown, providerId: unknown, revision: unknown, selection: unknown): unknown;
+ },
+): void {
+ registry.handle(MAKER_INVOKE.SET_MODEL, (event, sessionId, model, providerId, revision, selection) => {
+ // Remote callers have already passed device-link authentication and control checks.
+ if (!deps.isDeviceLinkInvoke()) deps.assertTrustedSender(event);
+ return deps.apply(sessionId, model, providerId, revision, selection);
+ });
+}
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
index 130c218949..4c48c24d72 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
@@ -1,4 +1,5 @@
import { afterEach, describe, expect, it } from 'vitest';
+import { ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { getLiziMcpSessionContext } from '@cindy/mcps';
@@ -155,6 +156,56 @@ 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('accepts an additional bearer token (remote daemon) and rejects unknown tokens', async () => {
bridge = await startCodexHttpBridge({
serverFactories: {
diff --git a/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts b/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
index 3a80c90f8f..d2e11ad5ae 100644
--- a/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
+++ b/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
@@ -426,3 +426,11 @@ async function doStart(
: {}),
};
}
+
+/** Native startup discovery is earlier than the thread registration callback. */
+export function withCodexMcpDiscoveryContext<T>(
+ ctx: LiziMcpSessionContext,
+ run: () => Promise<T>,
+): Promise<T> {
+ return activeBridge ? activeBridge.withDiscoveryContext(ctx, run) : run();
+}
diff --git a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
index bf0660ef38..5392444fde 100644
--- a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
+++ b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
@@ -138,6 +138,8 @@ export interface CodexHttpBridge {
instanceId: string;
/** 拼出 codex 端 config 用的 URL,例如 http://127.0.0.1:54321/mcp/lizi_feishu */
url(serverName: string): string;
+ /** Temporary startup identity, usable only by tools/list before thread registration. */
+ withDiscoveryContext<T>(ctx: LiziMcpSessionContext, run: () => Promise<T>): Promise<T>;
registerThreadContext(threadId: string, ctx: LiziMcpSessionContext): void;
unregisterThreadContext(threadId: string, expectedSessionInstanceId?: string): void;
/**
@@ -213,6 +215,7 @@ export async function startCodexHttpBridge(
transportsByServer.set(name, new Map());
}
const threadContextStore = createCodexMcpThreadContextStore();
+ const discoveryContexts = new Map<string, LiziMcpSessionContext>();
// sessionId → ctx (远端 cc 的身份通道, 经 ?session= query 路由, 见 interface 注释)。
const sessionCtxById = new Map<string, LiziMcpSessionContext>();
// sessionId → per-session bearer token 注册代次(pi 会话, 见 interface 注释)。
@@ -362,6 +365,7 @@ export async function startCodexHttpBridge(
serverName,
log,
threadContextStore,
+ discoveryContexts,
pluginId: opts.pluginIdByServerName?.[serverName],
sessionTokenCtx,
threadInstanceQuery: sessionQuery === null ? instanceQuery : null,
@@ -487,6 +491,15 @@ export async function startCodexHttpBridge(
token,
instanceId: randomBytes(8).toString('hex'),
url: (serverName) => `http://127.0.0.1:${port}${MCP_PATH_PREFIX}${encodeURIComponent(serverName)}`,
+ withDiscoveryContext: async (ctx, run) => {
+ const instance = ctx.sessionInstanceId;
+ if (!instance) return run();
+ // Each lease owns its exact object, so late completion cannot delete a replacement.
+ const lease = { ...ctx };
+ discoveryContexts.set(instance, lease);
+ try { return await run(); }
+ finally { if (discoveryContexts.get(instance) === lease) discoveryContexts.delete(instance); }
+ },
registerThreadContext: threadContextStore.registerThreadContext,
unregisterThreadContext: threadContextStore.unregisterThreadContext,
registerSessionCtx: (sessionId, ctx) => {
@@ -552,6 +565,7 @@ interface DispatchOpts {
serverName: string;
log: Logger;
threadContextStore: ReturnType<typeof createCodexMcpThreadContextStore>;
+ discoveryContexts: ReadonlyMap<string, LiziMcpSessionContext>;
pluginId?: string;
/** per-session token 命中时解析出的 ctx;存在即优先于 _meta.threadId 路由。 */
sessionTokenCtx?: LiziMcpSessionContext;
@@ -582,6 +596,7 @@ async function dispatchToTransport(opts: DispatchOpts): Promise<void> {
serverName,
log,
threadContextStore,
+ discoveryContexts,
pluginId,
sessionTokenCtx,
threadInstanceQuery,
@@ -620,6 +635,14 @@ async function dispatchToTransport(opts: DispatchOpts): Promise<void> {
threadContextStore,
threadInstanceQuery,
);
+ // Native Codex lists tools before thread/start returns. Only that exact
+ // request may use the startup lease; batches, calls and claimed thread ids
+ // still require the real registered execution context.
+ if (!activeContext && !threadId && threadInstanceQuery !== null
+ && parsedBody && !Array.isArray(parsedBody)
+ && (parsedBody as { method?: unknown }).method === 'tools/list') {
+ activeContext = discoveryContexts.get(threadInstanceQuery);
+ }
let decision:
| 'no_thread_id'
| 'thread_unregistered'
diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
index f2ee9cc362..d93ee4525f 100644
--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
@@ -500,6 +500,8 @@ describe("cindy_helper MCP server", () => {
const result = parsePayload(await client.callTool({ name: "call_tool", arguments: { name, args: {} } }));
expect(result).toMatchObject({ ok: false, errorCode: "CAPABILITY_NOT_AVAILABLE" });
}
+ const direct = await client.callTool({ name: "start_session_task", arguments: { instruction: "do work" } });
+ expect(parsePayload(direct)).toMatchObject({ ok: false, errorCode: "CAPABILITY_NOT_AVAILABLE" });
expect(callback).not.toHaveBeenCalled();
} finally {
await client.close();
@@ -629,3 +631,48 @@ describe("cindy_helper MCP server", () => {
}
});
});
+
+describe("direct Bot MCP tools", () => {
+ it.each(["claude-code", "codex"] as const)("exposes and executes tasks on %s without discovery", async (agentKind) => {
+ let sessionId: string | undefined = "bot-parent";
+ const start = vi.fn(async () => ({ ok: true as const, taskId: "task-1" }));
+ const unavailable = vi.fn(async () => ({ ok: false as const, errorCode: "UNEXPECTED", message: "must not run" }));
+ const server = createXdtHelperMcpServer({
+ resolveSurface: async ({ sessionId }) => sessionId === "bot-parent" ? "bot" : "default",
+ sessionTasks: { startSessionTask: start, getSessionTask: unavailable, messageSessionTask: unavailable, stopSessionTask: unavailable },
+ }, {
+ agentKind, workingDir: "",
+ getSessionContext: () => sessionId ? { agentKind, workingDir: "/bot", sessionId } : undefined,
+ });
+ const [ct, st] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: "direct-bot-test", version: "0.0.0" });
+ await Promise.all([server.connect(st), client.connect(ct)]);
+ try {
+ const first = await client.listTools();
+ const task = first.tools.find(t => t.name === "start_session_task");
+ expect(task?.inputSchema.required).toContain("instruction");
+ expect(first.tools.map(t => t.name)).toEqual(expect.arrayContaining([
+ "start_session_task", "check_session_task", "message_session_task", "stop_session_task",
+ ]));
+ expect(await client.listTools()).toEqual(first);
+ const result = await client.callTool({ name: "start_session_task", arguments: {
+ instruction: "Fix the project", working_dir: "/repo", title: "Fix",
+ } });
+ expect(parsePayload(result)).toMatchObject({ ok: true });
+ expect(start).toHaveBeenCalledWith(expect.objectContaining({
+ callerSessionId: "bot-parent", objective: "Fix the project", workingDir: "/repo", title: "Fix",
+ }));
+ // A shared Codex bridge must re-check the caller for both listing and execution.
+ for (const next of ["ordinary-task", undefined]) {
+ sessionId = next;
+ expect((await client.listTools()).tools.map(t => t.name).sort()).toEqual(["call_tool", "list_tools"]);
+ expect(parsePayload(await client.callTool({ name: "start_session_task", arguments: { instruction: "denied" } })))
+ .toMatchObject({ ok: false, errorCode: "CAPABILITY_NOT_AVAILABLE" });
+ }
+ expect(start).toHaveBeenCalledTimes(1);
+ } finally {
+ await client.close();
+ await server.close();
+ }
+ });
+});
diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
index 981893e9a3..3f11018015 100644
--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
@@ -27,6 +27,7 @@
import { BRAND_NAME } from '@cindy/maker-shared/branding';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { ListToolsRequestSchema, type Tool } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
import { jsonObjectArg } from './json-object-arg.js';
@@ -91,6 +92,14 @@ const D_LIST_TOOLS =
const D_CALL_TOOL =
'调用 list_tools 为当前任务返回的一个具体工具。不要猜工具名,也不要把它当成通用命令入口。';
+const LIST_TOOLS_INPUT = {
+ category: z.string().optional().describe('list_tools 上一步返回的类目;不传则先取类目概览。'),
+};
+const CALL_TOOL_INPUT = {
+ name: z.string().describe('工具名,从 list_tools 获取(如 get_capabilities)'),
+ args: jsonObjectArg('工具参数(JSON 对象)。不确定 schema 时可先传 {} 触发错误反馈。'),
+};
+
// list_tools 入口类目: cindy(自省) / control(会话控制面) / history(聊天历史) / feedback(官方反馈提交) / handoff(session 间 handoff)。
// 协同 team 工具已拆到独立 cindy_orca server(插件开关 gate)。
const CATEGORY_ENUM = ['cindy', 'control', 'history', 'feedback', 'handoff', 'bots'] as const;
@@ -155,9 +164,7 @@ function registerListToolsEntry(
server.tool(
'list_tools',
D_LIST_TOOLS,
- {
- category: z.string().optional().describe('list_tools 上一步返回的类目;不传则先取类目概览。'),
- },
+ LIST_TOOLS_INPUT,
async ({ category }) => {
const allowed = await allowedCategories();
if (category) {
@@ -221,12 +228,7 @@ function registerCallToolEntry(
server.tool(
'call_tool',
D_CALL_TOOL,
- {
- name: z
- .string()
- .describe('工具名,从 list_tools 获取(如 get_capabilities)'),
- args: jsonObjectArg('工具参数(JSON 对象)。不确定 schema 时可先传 {} 触发错误反馈。'),
- },
+ CALL_TOOL_INPUT,
async ({ name, args }) => {
const allowed = await allowedCategories();
const definition = registry.get(name);
@@ -701,5 +703,39 @@ export function createXdtHelperMcpServer(
getSessionId: () => resolveLiziMcpSessionContext(sessionCtx).sessionId,
}, allowedCategories);
+ // Pi already provides direct Bot tools through its native bridge. CC and Codex
+ // consume MCP tools/list instead; expose the same registered definitions there.
+ // Resolve identity per request: Codex's HTTP server is shared across sessions.
+ if (sessionCtx.agentKind !== 'pi') {
+ const directTools = registry.list('bots').map((summary) => registry.get(summary.name)!);
+ for (const definition of directTools) {
+ server.registerTool(definition.name, {
+ description: definition.description, inputSchema: z.strictObject(definition.inputShape),
+ }, async (args) => {
+ const allowed = await allowedCategories();
+ if (!allowed?.has('bots')) {
+ return errorPayload('CAPABILITY_NOT_AVAILABLE', '这个工具不属于当前任务的能力面。');
+ }
+ const result = await registry.call(definition.name, args);
+ logToolResultErrorCode({
+ logger: deps.logger, server: 'cindy_helper', tool: definition.name, result,
+ sessionId: resolveLiziMcpSessionContext(sessionCtx).sessionId,
+ });
+ return result;
+ });
+ }
+ const schema = (shape: z.ZodRawShape): Tool['inputSchema'] =>
+ z.toJSONSchema(z.strictObject(shape)) as Tool['inputSchema'];
+ const entryTools: Tool[] = [
+ { name: 'list_tools', description: D_LIST_TOOLS, inputSchema: schema(LIST_TOOLS_INPUT) },
+ { name: 'call_tool', description: D_CALL_TOOL, inputSchema: schema(CALL_TOOL_INPUT) },
+ ];
+ const botTools: Tool[] = directTools.map((definition) => ({
+ name: definition.name, description: definition.description, inputSchema: schema(definition.inputShape),
+ }));
+ server.server.setRequestHandler(ListToolsRequestSchema, async () => ({
+ tools: (await allowedCategories())?.has('bots') ? [...entryTools, ...botTools] : entryTools,
+ }));
+ }
return server;
}
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 90e87ce84c..d6a09798ab 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -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'>,
+ 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
diff --git 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
index c40b15de21..258bc8821a 100644
--- 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
@@ -96,23 +96,34 @@ const OWN_SKILL_ROOT = '/userdata/bot-skills/bot-1';
async function startBotSession(input: {
ownSkillPluginRoots?: string[];
reviewMode?: boolean;
+ remote?: boolean;
+ ordinary?: boolean;
}) {
const configDir = await makeTempDir();
process.env.CLAUDE_CONFIG_DIR = configDir;
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 }) => {
+ remoteOptions = startParams.extraOptions;
+ return createFakeQuery() as never;
+ };
+ }
+ const agent = new ClaudeCodeAgent(deps);
await agent.startSession({
sessionId: 'session-bot-skills',
model: 'claude-opus-4-6',
workingDir,
+ ...(input.remote ? { remoteHostId: 'remote-bot-host' } : {}),
permissionMode: 'acceptEdits',
botProfilePrompt: 'BOT SOUL',
botProfileContextPrompt: 'BOT HOME CONTEXT',
userPrompt: 'GLOBAL USER PROMPT',
...(input.reviewMode ? { reviewMode: true as const } : {}),
- botRuntimeProfile: {
+ botRuntimeProfile: input.ordinary ? undefined : {
botId: 'bot-1',
profileVersion: 1,
skillPolicy: {
@@ -131,10 +142,13 @@ async function startBotSession(input: {
},
});
- const options = sdkMock.query.mock.calls.at(-1)?.[0]?.options as
+ const options = (input.remote ? remoteOptions : sdkMock.query.mock.calls.at(-1)?.[0]?.options) as
| {
plugins?: Array<{ type: string; path: string }>;
settingSources?: string[];
+ disallowedTools?: string[];
+ strictMcpConfig?: boolean;
+ settings?: { autoMemoryEnabled?: boolean; autoDreamEnabled?: boolean };
systemPrompt?: { append?: string };
}
| undefined;
@@ -158,6 +172,23 @@ describe('Claude Code mounts the Bot\'s own learned Skills', () => {
const options = await startBotSession({ ownSkillPluginRoots: [OWN_SKILL_ROOT] });
expect(options.plugins).toEqual([{ type: 'local', path: OWN_SKILL_ROOT }]);
expect(options.settingSources).toEqual([]);
+ expect(options.disallowedTools).toEqual(['Task', 'Agent']);
+ expect(options.strictMcpConfig).toBe(true);
+ expect(options.settings).toMatchObject({ autoMemoryEnabled: false, autoDreamEnabled: false });
+ });
+
+ it('keeps remote Bot tools and memory in the same scope as local Bots', async () => {
+ const options = await startBotSession({ remote: true });
+ expect(options.disallowedTools).toEqual(['Task', 'Agent']);
+ expect(options.strictMcpConfig).toBe(true);
+ expect(options.settings).toMatchObject({ autoMemoryEnabled: false, autoDreamEnabled: false });
+ });
+
+ it('preserves ordinary session native delegation and MCP settings', async () => {
+ const options = await startBotSession({ ordinary: true });
+ expect(options.disallowedTools).toBeUndefined();
+ expect(options.strictMcpConfig).toBeUndefined();
+ expect(options.settingSources).toEqual(['user', 'project', 'local']);
});
it('omits the field entirely when the Bot has not learned anything', async () => {
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 6ab7656236..ba1b843c6a 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -2370,12 +2370,13 @@ export class ClaudeCodeAgent extends BaseAgent {
const settings = buildClaudeFlagSettings({
showThinkingSummaries,
availableModels: currentAvailableSdkModels(mutableModel),
- // Do not carry the local manager's native-memory suppression across the
+ // Bots keep memory in their own Cindy scope, including remote sessions.
+ // For ordinary sessions, do not carry native-memory suppression across the
// SSH boundary: the remote host retains its own Claude memory
// configuration. Maker Memory on remote sessions is injected via the
// host bridge (prompt + http MCP), which coexists with — but does not
// rewrite — the remote machine's native memory settings.
- memoryOverride: reviewMode ? false : opts.remoteHostId ? undefined : this.memoryOverride,
+ memoryOverride: reviewMode || opts.botRuntimeProfile ? false : opts.remoteHostId ? undefined : this.memoryOverride,
// Fast 模式:进 flag settings 层(= --settings),解锁 cc 二进制在 Agent SDK 通道下的
// fast(否则二进制按 "Agent SDK 不可用" 拒绝)。是否 Opus/官方/firstParty 由二进制把关,
// agent 层不重复硬判(规则 9:确定性逻辑就近,但 fast 的最终门槛是二进制 + 配置门控)。
@@ -3235,6 +3236,7 @@ export class ClaudeCodeAgent extends BaseAgent {
// options (cc-mgr.ts:106), 所以 extraOptions 是任意 SDK 字段的统一透传出口。
extraOptions: {
includePartialMessages: true,
+ ...(opts.botRuntimeProfile ? { disallowedTools: ['Task', 'Agent'], strictMcpConfig: true } : {}),
...thinkingOpts,
...(currentSdkEffort ? { effort: currentSdkEffort } : {}),
// settings 对象跟本地分支同源 — 不透传则远端 SDK 拿不到
@@ -3779,6 +3781,8 @@ export class ClaudeCodeAgent extends BaseAgent {
// permissionMode=auto 时再调用远程安全分类器。动态聚合入口不在列表中。
...(claudeAllowedTools ? { allowedTools: [...claudeAllowedTools] } : {}),
canUseTool,
+ // Bot work is delegated through tracked Cindy Session tasks.
+ ...(opts.botRuntimeProfile ? { disallowedTools: ['Task', 'Agent'], strictMcpConfig: true } : {}),
settingSources: reviewMode || !!opts.botRuntimeProfile
? []
: ['user', 'project', 'local'],
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 7e08666522..d9fc5962a9 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -5360,7 +5360,15 @@ describe('CodexAgent.startSession developerInstructions', () => {
const params = host.request.mock.calls.find(([method]) => method === Method.ThreadStart)?.[1] as {
developerInstructions?: string;
+ config?: Record<string, unknown>;
};
+ expect(params.config).toMatchObject({
+ 'features.multi_agent': false,
+ 'features.multi_agent_v2': false,
+ 'agents.enabled': false,
+ 'memories.generate_memories': false,
+ 'memories.use_memories': false,
+ });
expect(params.developerInstructions).toContain('BOT SOUL');
expect(params.developerInstructions).toContain('BOT HOME CONTEXT');
expect(params.developerInstructions).not.toContain('GLOBAL CINDY HOST PROMPT');
@@ -8471,6 +8479,32 @@ describe('CodexAgent MCP thread context hooks', () => {
);
});
+ it.each([false, true])('registers discovery identity around native startup (resume=%s)', async (resume) => {
+ const order: string[] = [];
+ const deps = createDeps();
+ deps.withCodexMcpDiscoveryContext = async (ctx, run) => {
+ expect(ctx).toMatchObject({ sessionId: 'bot-parent', sessionInstanceId: 'bot-instance' });
+ 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',
+ ...(resume ? { resumeSessionId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' } : {}),
+ });
+ expect(order).toEqual(['discovery', 'native', 'released']);
+ 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 --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index d1b570946b..e00cb7eebe 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -5587,6 +5587,15 @@ export class CodexAgent extends BaseAgent {
const config = {
...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
@@ -5947,6 +5956,14 @@ export class CodexAgent extends BaseAgent {
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,
+ }, run);
+ };
+
/**
* Start a replacement thread after the exact provider proof that the
* persisted thread has no rollout. This is intentionally narrower than a
@@ -5965,9 +5982,9 @@ export class CodexAgent extends BaseAgent {
};
acquireHostBindingLeaseIfNeeded();
assertCurrentHost('thread/start');
- const resp = await host.request<ThreadStartResponse>(Method.ThreadStart, params, {
+ const resp = await withMcpDiscoveryContext(() => host.request<ThreadStartResponse>(Method.ThreadStart, params, {
timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,
- });
+ }));
assertCurrentHost('thread/start');
if (Object.hasOwn(resp, 'serviceTier')) {
mutableServiceTier = normalizeServiceTier(resp.serviceTier) ?? null;
@@ -6079,9 +6096,9 @@ export class CodexAgent extends BaseAgent {
try {
acquireHostBindingLeaseIfNeeded();
assertCurrentHost('thread/resume');
- const resp = await host.request<ThreadResumeResponse>(Method.ThreadResume, params, {
+ const resp = await withMcpDiscoveryContext(() => host.request<ThreadResumeResponse>(Method.ThreadResume, params, {
timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,
- });
+ }));
assertCurrentHost('thread/resume');
if (Object.hasOwn(resp, 'serviceTier')) {
mutableServiceTier = normalizeServiceTier(resp.serviceTier) ?? null;