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。

feat(cindy-helper): 伙伴只获得五个项目工具 (#5034)

Dasha9898806f533
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts
index ca0ecbe3e6..2cf8ef4964 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts
@@ -198,20 +198,27 @@ describe('createProject', () => {
});
it.each(['source', 'link'])(
- 'rejects Bot %s callers before any project callback',
+ 'lets Bot %s callers manage account projects',
async (signal) => {
- h.query.mockResolvedValue([{ id: 'caller', source: signal === 'source' ? 'bot' : null }]);
+ h.query.mockResolvedValue([
+ { id: 'caller', remoteHostId: null, source: signal === 'source' ? 'bot' : null },
+ ]);
h.botLinks.mockResolvedValue(signal === 'link' ? [{ botId: 'bot' }] : []);
- for (const operation of [
- () => run(directory),
- () =>
- listProjects({ callerSessionId: 'caller', includeHidden: true, offset: 0, limit: 100 }),
- () => renameProject({ callerSessionId: 'caller', workingDir: directory, name: 'changed' }),
- () => removeProject({ callerSessionId: 'caller', workingDir: directory }),
- ])
- expect(await operation()).toMatchObject({ errorCode: 'UNSUPPORTED_CAPABILITY' });
- for (const effect of [h.upsert, h.restore, h.list, h.aliases, h.rename, h.visibility, h.send])
- expect(effect).not.toHaveBeenCalled();
+ expect(await run(directory)).toMatchObject({ ok: true });
+ expect(
+ await listProjects({ callerSessionId: 'caller', includeHidden: true, offset: 0, limit: 100 }),
+ ).toMatchObject({ ok: true });
+ expect(
+ await renameProject({ callerSessionId: 'caller', workingDir: directory, name: 'changed' }),
+ ).toMatchObject({ ok: true });
+ expect(await removeProject({ callerSessionId: 'caller', workingDir: directory })).toMatchObject({
+ ok: true,
+ removed: true,
+ });
+ expect(h.upsert).toHaveBeenCalled();
+ expect(h.list).toHaveBeenCalled();
+ expect(h.rename).toHaveBeenCalled();
+ expect(h.visibility).toHaveBeenCalled();
},
);
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/helperSurface.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/helperSurface.test.ts
new file mode 100644
index 0000000000..edb1019543
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/helperSurface.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+import { classifyHelperSurface } from '../helperSurface.js';
+
+describe('classifyHelperSurface', () => {
+ it.each([
+ ['bot', true],
+ ['bot', false],
+ [null, true],
+ ['user', true],
+ ] as const)('treats source=%s link=%s as a Bot', (source, hasBotLink) => {
+ expect(classifyHelperSurface(source, hasBotLink)).toBe('bot');
+ });
+
+ it('leaves ordinary tasks on the default surface', () => {
+ expect(classifyHelperSurface('user', false)).toBe('default');
+ expect(classifyHelperSurface(null, false)).toBe('default');
+ expect(classifyHelperSurface(undefined, false)).toBe('default');
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts
index daff4817f8..234b118834 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts
@@ -8,6 +8,7 @@ const h = vi.hoisted(() => ({
owner: { dataOwnerId: 'owner-a', ownerGeneration: 1 },
query: vi.fn(),
botLinks: [] as Array<{ botId: string }>,
+ botLinkSequence: null as null | Array<Array<{ botId: string }>>,
workers: [] as Array<{ sessionId: string }>,
running: new Set<string>(),
attached: false,
@@ -31,7 +32,12 @@ vi.mock('../../localDb/client/current.js', async () => {
drizzle: {
select: () => ({
from: (table: unknown) => ({
- where: () => ({ limit: table === botSessionLinks ? async () => h.botLinks : h.query }),
+ where: () => ({
+ limit:
+ table === botSessionLinks
+ ? async () => h.botLinkSequence?.shift() ?? h.botLinks
+ : h.query,
+ }),
innerJoin: () => ({ where: async () => h.workers }),
}),
}),
@@ -65,6 +71,7 @@ describe('moveSession host', () => {
h.running = new Set();
h.workers = [];
h.botLinks = [];
+ h.botLinkSequence = null;
h.attached = false;
h.enterLock.mockImplementation(() => undefined);
h.beforeCommit.mockImplementation(() => undefined);
@@ -155,13 +162,16 @@ describe('moveSession host', () => {
);
it.each(['source', 'link'])(
- 'rejects Bot %s callers before entering the target update',
+ 'lets Bot %s callers move ordinary tasks',
async (signal) => {
- h.query.mockResolvedValueOnce([{ id: 'caller', source: signal === 'source' ? 'bot' : null }]);
- h.botLinks = signal === 'link' ? [{ botId: 'bot' }] : [];
- expect(await run(directory)).toMatchObject({ errorCode: 'UNSUPPORTED_CAPABILITY' });
- expect(h.update).not.toHaveBeenCalled();
- expect(h.saved).not.toHaveBeenCalled();
+ h.query
+ .mockResolvedValueOnce([
+ { id: 'caller', remoteHostId: null, source: signal === 'source' ? 'bot' : null },
+ ])
+ .mockResolvedValue([{ id: 'target', status: 'active', remoteHostId: null, source: null }]);
+ if (signal === 'link') h.botLinkSequence = [[{ botId: 'bot' }], []];
+ expect(await run(directory)).toMatchObject({ ok: true });
+ expect(h.update).toHaveBeenCalled();
},
);
diff --git a/apps/desktop/src/main/mcp-integrations/createProject.ts b/apps/desktop/src/main/mcp-integrations/createProject.ts
index 7b2f364c60..53bc7ed7c4 100644
--- a/apps/desktop/src/main/mcp-integrations/createProject.ts
+++ b/apps/desktop/src/main/mcp-integrations/createProject.ts
@@ -48,7 +48,7 @@ export async function withLocalProjectContext<T extends object>(
};
try {
const [caller] = await client.drizzle
- .select({ id: sessions.id, remoteHostId: sessions.remoteHostId, source: sessions.source })
+ .select({ id: sessions.id, remoteHostId: sessions.remoteHostId })
.from(sessions)
.where(eq(sessions.id, callerSessionId))
.limit(1);
@@ -60,16 +60,16 @@ export async function withLocalProjectContext<T extends object>(
'UNSUPPORTED_CAPABILITY',
'Project registration only supports local Cindy tasks.',
);
- const [botLink] = await client.drizzle
+ // Account-generation checkpoint. Bot callers may manage projects; the
+ // helper surface names the five project tools and keeps the rest of
+ // control/history closed. This read must stay so an account switch during
+ // the lookup still fails closed.
+ await client.drizzle
.select({ botId: botSessionLinks.botId })
.from(botSessionLinks)
.where(eq(botSessionLinks.sessionId, callerSessionId))
.limit(1);
assertCurrent();
- // Legacy Bot tasks can have only one ownership signal. All five project
- // callbacks enforce this even when the helper surface classified them as default.
- if (caller.source === 'bot' || botLink)
- return fail('UNSUPPORTED_CAPABILITY', 'Bot tasks cannot manage account projects.');
const result = await run({ client, owner, assertCurrent });
assertCurrent();
return result;
diff --git a/apps/desktop/src/main/mcp-integrations/helperSurface.ts b/apps/desktop/src/main/mcp-integrations/helperSurface.ts
new file mode 100644
index 0000000000..dcdab1b7e3
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/helperSurface.ts
@@ -0,0 +1,11 @@
+/**
+ * Either legacy ownership signal is enough to keep a caller on the Bot surface.
+ * Requiring both lets a partial Bot record fall through to the full default
+ * surface, which includes Session control and history.
+ */
+export function classifyHelperSurface(
+ source: string | null | undefined,
+ hasBotLink: boolean,
+): 'bot' | 'default' {
+ return source === 'bot' || hasBotLink ? 'bot' : 'default';
+}
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 10bfcf6da1..426ef75424 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -1,5 +1,6 @@
import { executeTaskTags } from '../localDb/ipc/taskTags.js';
import { getPluginMarketService } from '../plugin-market/service.js';
+import { classifyHelperSurface } from './helperSurface.js';
import { createProject } from './createProject.js';
import { createMoveSession } from './moveSession.js';
import { listProjects, renameProject, removeProject } from './projectManagement.js';
@@ -503,18 +504,13 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
resolveSurface: async ({ sessionId }) => {
const dbClient = tryGetDbClient();
if (!dbClient) return 'restricted';
- const [owned] = await dbClient.drizzle
- .select({ role: botSessionLinks.role })
- .from(botSessionLinks)
- .innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))
- .where(
- and(
- eq(botSessionLinks.sessionId, sessionId),
- eq(sessions.source, 'bot'),
- ),
- )
+ const [row] = await dbClient.drizzle
+ .select({ source: sessions.source, botId: botSessionLinks.botId })
+ .from(sessions)
+ .leftJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id))
+ .where(eq(sessions.id, sessionId))
.limit(1);
- return owned ? 'bot' : 'default';
+ return classifyHelperSurface(row?.source, Boolean(row?.botId));
},
sessionQueue: {
listSessionQueue: wrap((service, sessionId: string) => service.listSessionQueue(sessionId)),
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 722c93d12c..1a2d4ca325 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -230,6 +230,9 @@ harness + provider + model + effort + fastMode
恢复后只生效一次,取消优先撤销暂存回答。恢复依据宿主实际应用回执清理等待状态,
已应用的回答不再通知发起伙伴;确实未答的交互仍重新通知。渠道卡片的回答状态不表示引擎已恢复。
这些模式都只作用于调用伙伴拥有的后台任务;通用 Session control 类不因此开放给伙伴。
+ 伙伴可以登记、列出、重命名和隐藏账号项目,也可以把已有的非伙伴任务移入或移出项目。
+ 移动任务必须已经持有该任务的 session id,不能按标题枚举其他任务。远程伙伴不获得这些工具。
+ 这不包含停止、插话、改运行时、改名、归档、标签或读取其他任务的历史与输入队列。
`check_session_task.control.last_stop_request` 保留最近一次优雅停止请求的时间、返回状态和轮次;
它是历史回执,实际是否停稳仍看 `stop_status`,重启不会重放停止请求或冻结下一轮。
diff --git a/packages/lizi-mcps/src/__tests__/createProject.test.ts b/packages/lizi-mcps/src/__tests__/createProject.test.ts
index 7b00f174a4..f41d8be828 100644
--- a/packages/lizi-mcps/src/__tests__/createProject.test.ts
+++ b/packages/lizi-mcps/src/__tests__/createProject.test.ts
@@ -72,7 +72,19 @@ describe("create_project MCP", () => {
errorCode: "NO_SESSION_CONTEXT",
});
sessionId = "caller";
- for (const restricted of ["bot", "restricted"] as const) {
+ // Bot surface now includes project management.
+ surface = "bot";
+ expect(
+ parse(
+ await client.callTool({ name: "list_tools", arguments: {} }),
+ ).categories ?? [],
+ ).toEqual(expect.arrayContaining([expect.objectContaining({ name: "control" })]));
+ expect(parse(await call({ working_dir: "/project" }))).toMatchObject({
+ ok: true,
+ working_dir: "/project",
+ });
+ expect(createProject).toHaveBeenCalledTimes(2);
+ for (const restricted of ["restricted"] as const) {
surface = restricted;
const categories = parse(
await client.callTool({ name: "list_tools", arguments: {} }),
@@ -84,7 +96,7 @@ describe("create_project MCP", () => {
);
expect((await call({ working_dir: "/project" })).isError).toBe(true);
}
- expect(createProject).toHaveBeenCalledTimes(1);
+ expect(createProject).toHaveBeenCalledTimes(2);
} finally {
await client.close();
await server.close();
diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
index e6a3a237f8..f0c156eb0c 100644
--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
@@ -624,8 +624,20 @@ describe("cindy_helper MCP server", () => {
}
});
- it("exposes product knowledge while keeping general history and control out of the Bot surface", async () => {
+ it("grants Bots only the named project tools, not the rest of control or history", async () => {
let surface: "bot" | "default" = "bot";
+ const createProject = vi.fn(async () => ({
+ ok: true as const,
+ workingDir: "/repo",
+ }));
+ const moveSession = vi.fn(async () => ({
+ ok: true as const,
+ sessionId: "task",
+ workingDir: "/repo",
+ workspaceKind: "project",
+ }));
+ const stopSessionTurn = vi.fn(async () => ({ ok: true as const, status: "requested" as const }));
+ const listSessionQueue = vi.fn(async () => ({ ok: true as const, messages: [] }));
const sendToSession = vi.fn(async () => ({
ok: true as const,
targetSessionId: TARGET_SESSION_ID,
@@ -645,6 +657,20 @@ describe("cindy_helper MCP server", () => {
{
resolveSurface: async () => surface,
sendToSession,
+ createProject,
+ moveSession,
+ sessionControl: {
+ updateQueuedMessage: vi.fn(),
+ cancelQueuedMessage: vi.fn(),
+ steerSession: vi.fn(),
+ stopSessionTurn,
+ getSessionRuntime: vi.fn(),
+ setSessionRuntime: vi.fn(),
+ },
+ sessionQueue: {
+ listSessionQueue,
+ listSessionQueuedCounts: vi.fn(),
+ },
botMessaging: { messageAgent },
},
{
@@ -661,7 +687,46 @@ describe("cindy_helper MCP server", () => {
const overview = parsePayload(
await client.callTool({ name: "list_tools", arguments: {} }),
);
- expect(overview.categories).toEqual([{ name: "cindy", tool_count: 2 }, { name: "bots", tool_count: 1 }]);
+ expect(overview.categories).toEqual([
+ { name: "cindy", tool_count: 2 },
+ { name: "control", tool_count: 2 },
+ { name: "bots", tool_count: 1 },
+ ]);
+
+ // Project/session management is now part of the Bot surface.
+ const projectRegistration = parsePayload(
+ await client.callTool({
+ name: "call_tool",
+ arguments: { name: "create_project", args: { working_dir: "/repo" } },
+ }),
+ );
+ expect(projectRegistration).toMatchObject({ ok: true, working_dir: "/repo" });
+ expect(createProject).toHaveBeenCalled();
+
+ const controlTools = parsePayload(
+ await client.callTool({ name: "list_tools", arguments: { category: "control" } }),
+ );
+ const controlNames = (controlTools.tools as Array<{ name: string; description: string }>);
+ expect(controlNames.map((tool) => tool.name)).toEqual(["create_project", "move_session"]);
+ expect(controlNames.find((tool) => tool.name === "create_project")?.description).toContain(
+ "start_session_task",
+ );
+ expect(controlNames.find((tool) => tool.name === "create_project")?.description).not.toContain(
+ "send_to_session",
+ );
+ expect(controlNames.find((tool) => tool.name === "move_session")?.description).not.toContain(
+ "list_sessions",
+ );
+ expect(controlNames.find((tool) => tool.name === "move_session")?.description).toContain(
+ "cannot look up another task by title",
+ );
+ for (const name of ["stop_session_turn", "list_session_queue"]) {
+ expect(
+ parsePayload(await client.callTool({ name: "call_tool", arguments: { name, args: {} } })),
+ ).toMatchObject({ ok: false, errorCode: "CAPABILITY_NOT_AVAILABLE" });
+ }
+ expect(stopSessionTurn).not.toHaveBeenCalled();
+ expect(listSessionQueue).not.toHaveBeenCalled();
const forbiddenCategory = parsePayload(
await client.callTool({ name: "list_tools", arguments: { category: "handoff" } }),
@@ -702,6 +767,36 @@ describe("cindy_helper MCP server", () => {
}
});
+ it("does not offer local project tools to a remote Bot", async () => {
+ const createProject = vi.fn(async () => ({ ok: true as const, workingDir: "/repo" }));
+ const server = createXdtHelperMcpServer(
+ { resolveSurface: async () => "bot", createProject },
+ {
+ agentKind: "codex",
+ workingDir: "/repo",
+ sessionId: "bot-remote",
+ remoteHostId: "ssh-host",
+ },
+ );
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: "remote-bot-projects", version: "0.0.0" });
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
+ try {
+ const overview = parsePayload(await client.callTool({ name: "list_tools", arguments: {} }));
+ expect(overview.categories).toEqual([{ name: "cindy", tool_count: 2 }]);
+ expect(
+ parsePayload(await client.callTool({
+ name: "call_tool",
+ arguments: { name: "create_project", args: { working_dir: "/repo" } },
+ })),
+ ).toMatchObject({ ok: false, errorCode: "CAPABILITY_NOT_AVAILABLE" });
+ expect(createProject).not.toHaveBeenCalled();
+ } finally {
+ await client.close();
+ await server.close();
+ }
+ });
+
it("fails closed when the host cannot classify the Session surface", async () => {
const sendToSession = vi.fn(async () => ({
ok: true as const,
diff --git a/packages/lizi-mcps/src/__tests__/moveSession.test.ts b/packages/lizi-mcps/src/__tests__/moveSession.test.ts
index 10ec23438e..cdde18c26a 100644
--- a/packages/lizi-mcps/src/__tests__/moveSession.test.ts
+++ b/packages/lizi-mcps/src/__tests__/moveSession.test.ts
@@ -95,12 +95,24 @@ describe("move_session MCP", () => {
await call({ session_id: "target", working_dir: null }),
).toMatchObject({ errorCode: "NO_SESSION_CONTEXT" });
sessionId = "caller";
- for (const denied of ["bot", "restricted"] as const) {
- surface = denied;
- expect(
- await call({ session_id: "target", working_dir: null }),
- ).toMatchObject({ ok: false });
- }
+ // Bot surface now includes project/session management.
+ surface = "bot";
+ expect(
+ await call({ session_id: "target", working_dir: null }),
+ ).toMatchObject({
+ ok: true,
+ workspace_kind: "dialogue",
+ });
+ expect(moveSession).toHaveBeenLastCalledWith({
+ callerSessionId: "caller",
+ sessionId: "target",
+ workingDir: null,
+ });
+ moveSession.mockClear();
+ surface = "restricted";
+ expect(
+ await call({ session_id: "target", working_dir: null }),
+ ).toMatchObject({ ok: false });
expect(moveSession).not.toHaveBeenCalled();
} finally {
await client.close();
diff --git a/packages/lizi-mcps/src/__tests__/projectManagement.test.ts b/packages/lizi-mcps/src/__tests__/projectManagement.test.ts
index c3176135df..23efc8c66d 100644
--- a/packages/lizi-mcps/src/__tests__/projectManagement.test.ts
+++ b/packages/lizi-mcps/src/__tests__/projectManagement.test.ts
@@ -146,21 +146,28 @@ describe("project management MCP", () => {
).ok,
).toBe(false);
remoteHostId = undefined;
- for (const nextSurface of ["bot", "restricted"] as const) {
- surface = nextSurface;
- for (const tool of [
- "list_projects",
- "rename_project",
- "remove_project",
- ]) {
- expect(await call(tool, {})).toMatchObject({
- errorCode: "CAPABILITY_NOT_AVAILABLE",
- });
- }
+ // Bot surface now includes project management.
+ surface = "bot";
+ expect(await call("list_projects", {})).toMatchObject({ ok: true });
+ expect(
+ await call("rename_project", { working_dir: "/repo", name: "Bot" }),
+ ).toMatchObject({ ok: true, alias: null });
+ expect(
+ await call("remove_project", { working_dir: "/repo" }),
+ ).toMatchObject({ ok: true, removed: true });
+ surface = "restricted";
+ for (const tool of [
+ "list_projects",
+ "rename_project",
+ "remove_project",
+ ]) {
+ expect(await call(tool, {})).toMatchObject({
+ errorCode: "CAPABILITY_NOT_AVAILABLE",
+ });
}
- expect(list).toHaveBeenCalledTimes(1);
- expect(rename).toHaveBeenCalledTimes(1);
- expect(remove).toHaveBeenCalledTimes(1);
+ expect(list).toHaveBeenCalledTimes(2);
+ expect(rename).toHaveBeenCalledTimes(2);
+ expect(remove).toHaveBeenCalledTimes(2);
} 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 bb25e764ae..c12109c5df 100644
--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
@@ -202,10 +202,51 @@ function cindyAvailableForSession(sessionCtx: XdtHelperMcpSessionCtx): boolean {
return !ctx.remoteHostId || ctx.agentKind === 'pi';
}
+/** Project tools a Bot may use without receiving the rest of `control` or `history`. */
+const BOT_PROJECT_TOOLS = new Set([
+ 'create_project',
+ 'list_projects',
+ 'rename_project',
+ 'remove_project',
+ 'move_session',
+]);
+
+interface HelperSurfaceAllow {
+ /** null means every registered category. An empty set means none. */
+ categories: ReadonlySet<string> | null;
+ /** Named tools visible even when their category stays closed. */
+ extraTools: ReadonlySet<string>;
+}
+
+function toolAllowed(
+ allow: HelperSurfaceAllow,
+ tool: { name: string; category: string },
+): boolean {
+ if (!allow.categories) return true;
+ return allow.categories.has(tool.category) || allow.extraTools.has(tool.name);
+}
+
+/** Bot project tools must not point at history/handoff tools that stay closed. */
+function describeBotProjectTool(tool: { name: string; description: string }): string {
+ if (tool.name === 'create_project') {
+ return tool.description.replace(
+ 'Pass the returned working_dir to send_to_session to start work there.',
+ 'Pass the returned working_dir to start_session_task to start work there.',
+ );
+ }
+ if (tool.name === 'move_session') {
+ return tool.description.replace(
+ 'Use list_sessions to find session_id and list_projects to find directories;',
+ 'Pass a session_id this Bot already has, such as one returned by start_session_task. This cannot look up another task by title. Use list_projects to find directories;',
+ );
+ }
+ return tool.description;
+}
+
function registerListToolsEntry(
server: McpServer,
registry: XdtHelperToolRegistry,
- allowedCategories: () => Promise<ReadonlySet<string> | null>,
+ allowedSurface: () => Promise<HelperSurfaceAllow>,
sessionCtx: XdtHelperMcpSessionCtx,
): void {
server.tool(
@@ -213,15 +254,17 @@ function registerListToolsEntry(
D_LIST_TOOLS,
LIST_TOOLS_INPUT,
async ({ category }) => {
- const allowed = await allowedCategories();
+ const allowed = await allowedSurface();
if (category) {
- if (allowed && !allowed.has(category)) {
- return errorPayload('CAPABILITY_NOT_AVAILABLE', '这个类目不属于当前任务的能力面。');
- }
const tools = withCindyGatedBotToolDescriptions(
- registry.list(category as (typeof CATEGORY_ENUM)[number]),
+ registry
+ .list(category as (typeof CATEGORY_ENUM)[number])
+ .filter((tool) => toolAllowed(allowed, tool)),
cindyAvailableForSession(sessionCtx),
);
+ if (tools.length === 0 && allowed.categories && !allowed.categories.has(category)) {
+ return errorPayload('CAPABILITY_NOT_AVAILABLE', '这个类目不属于当前任务的能力面。');
+ }
return {
content: [
{
@@ -231,7 +274,7 @@ function registerListToolsEntry(
category,
tools: tools.map((t) => ({
name: t.name,
- description: t.description,
+ description: allowed.extraTools.has(t.name) ? describeBotProjectTool(t) : t.description,
...(t.category === 'bots' || t.category === 'skills' ? {
inputSchema: z.toJSONSchema(z.strictObject(registry.get(t.name)!.inputShape)),
} : {}),
@@ -243,7 +286,7 @@ function registerListToolsEntry(
};
}
const counts: Record<string, number> = {};
- const visibleTools = registry.list().filter((tool) => !allowed || allowed.has(tool.category));
+ const visibleTools = registry.list().filter((tool) => toolAllowed(allowed, tool));
for (const t of visibleTools) {
counts[t.category] = (counts[t.category] ?? 0) + 1;
}
@@ -253,7 +296,7 @@ function registerListToolsEntry(
type: 'text' as const,
text: JSON.stringify({
ok: true,
- categories: registry.listCategories().filter((c) => !allowed || allowed.has(c)).map((c) => ({
+ categories: registry.listCategories().filter((c) => (counts[c] ?? 0) > 0).map((c) => ({
name: c,
tool_count: counts[c] ?? 0,
})),
@@ -273,16 +316,16 @@ function registerCallToolEntry(
logger?: LiziMcpLogger;
getSessionId: () => string | undefined;
},
- allowedCategories: () => Promise<ReadonlySet<string> | null>,
+ allowedSurface: () => Promise<HelperSurfaceAllow>,
): void {
server.tool(
'call_tool',
D_CALL_TOOL,
CALL_TOOL_INPUT,
async ({ name, args }) => {
- const allowed = await allowedCategories();
+ const allowed = await allowedSurface();
const definition = registry.get(name);
- if (allowed && definition && !allowed.has(definition.category)) {
+ if (definition && !toolAllowed(allowed, definition)) {
return errorPayload(
'CAPABILITY_NOT_AVAILABLE',
'这个工具不属于当前任务的能力面;请重新调用 list_tools。',
@@ -291,7 +334,7 @@ function registerCallToolEntry(
const result = definition
? await registry.call(name, args)
: errorPayload('UNKNOWN_TOOL', 'Unknown helper tool.', {
- available: registry.list().filter((tool) => !allowed || allowed.has(tool.category)).map((tool) => tool.name),
+ available: registry.list().filter((tool) => toolAllowed(allowed, tool)).map((tool) => tool.name),
});
// errorCode 遥测:UNKNOWN_TOOL / INVALID_ARGS / 业务 errorCode 返回给模型自纠
// 之前在这里落一条日志,否则 agent 犯错→自纠 的事件在日志里完全不存在。
@@ -758,20 +801,32 @@ export function createXdtHelperMcpServer(
});
const registry = new XdtHelperToolRegistry();
- const allowedCategories = async (): Promise<ReadonlySet<string> | null> => {
+ const none: HelperSurfaceAllow = { categories: new Set(), extraTools: new Set() };
+ const allowedSurface = async (): Promise<HelperSurfaceAllow> => {
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) return remoteBotOnly ? new Set() : defaultCategories;
- if (!deps.resolveSurface) return remoteBotOnly ? new Set(['auth']) : defaultCategories;
+ const allow = (categories: ReadonlySet<string>): HelperSurfaceAllow => ({
+ categories,
+ extraTools: new Set(),
+ });
+ if (!sessionId) return allow(remoteBotOnly ? new Set() : defaultCategories);
+ if (!deps.resolveSurface) return allow(remoteBotOnly ? new Set(['auth']) : 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', 'cindy', 'auth']);
- if (surface === 'restricted') return new Set();
- return remoteBotOnly ? new Set(['auth']) : defaultCategories;
+ // Bots keep bots/cindy/auth. Project tools are named exceptions so a Bot can
+ // register and organize projects without stop/steer/archive/history access.
+ // handoff/feedback/skills stay out of the Bot's discovery loop.
+ if (surface === 'bot') {
+ // Project tools run only on the local host. A remote Bot must keep its
+ // own tooling without being offered calls that always return unsupported.
+ return {
+ categories: new Set(['bots', 'cindy', 'auth']),
+ extraTools: context.remoteHostId ? new Set() : BOT_PROJECT_TOOLS,
+ };
+ }
+ if (surface === 'restricted') return none;
+ return allow(remoteBotOnly ? new Set(['auth']) : defaultCategories);
};
// 'cindy' 类: 自省 (无 host 依赖, 始终注册)。
@@ -913,13 +968,13 @@ export function createXdtHelperMcpServer(
callbacks: deps.botProfiles,
});
}
- registerListToolsEntry(server, registry, allowedCategories, sessionCtx);
+ registerListToolsEntry(server, registry, allowedSurface, sessionCtx);
registerCallToolEntry(server, registry, {
logger: deps.logger,
// per-call 解析:codex HTTP bridge 的 server factory 阶段 ctx 是空的,
// tool-call 阶段由 AsyncLocalStorage 恢复,所以 sessionId 必须调用时再取。
getSessionId: () => resolveLiziMcpSessionContext(sessionCtx).sessionId,
- }, allowedCategories);
+ }, allowedSurface);
// Pi already provides direct Bot tools through its native bridge. CC and Codex
// consume MCP tools/list instead; expose the same registered definitions there.
@@ -930,8 +985,8 @@ export function createXdtHelperMcpServer(
server.registerTool(definition.name, {
description: definition.description, inputSchema: z.strictObject(definition.inputShape),
}, async (args) => {
- const allowed = await allowedCategories();
- if (!allowed?.has('bots')) {
+ const allowed = await allowedSurface();
+ if (!allowed.categories?.has('bots')) {
return errorPayload('CAPABILITY_NOT_AVAILABLE', '这个工具不属于当前任务的能力面。');
}
const result = await registry.call(definition.name, args);
@@ -954,7 +1009,7 @@ export function createXdtHelperMcpServer(
// Codex/remote Claude share one helper factory; rewrite ghost guidance from
// the request-time session, not the empty factory ctx.
server.server.setRequestHandler(ListToolsRequestSchema, async () => ({
- tools: (await allowedCategories())?.has('bots')
+ tools: (await allowedSurface()).categories?.has('bots')
? [...entryTools, ...withCindyGatedBotToolDescriptions(botTools, cindyAvailableForSession(sessionCtx))]
: entryTools,
}));