Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): restore plugin cards and shared runtime controls (#4132)
Chris Zhang637f0a8eff43
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.tsindex 041d2d0810..93d1765fea 100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.ts@@ -13,6 +13,11 @@ const state = vi.hoisted(() => ({binaryPath: '',ripgrepPath: '',userDataPath: '',+ capToolchainThreads: true,+}));++vi.mock('../agent-resource-settings-store.js', () => ({+ readAgentResourceSettings: () => ({ capToolchainThreads: state.capToolchainThreads, processPriority: 'normal' }),}));vi.mock('electron', () => ({@@ -119,4 +124,25 @@ describe('Desktop Pi auto-compact wiring', () => {.deps.runtimeConfig;expect(runtimeConfig.autoCompactThresholdPct).toBeUndefined();});++ it('connects resource settings to Pi behavior flags and leaves remote machines alone', () => {+ const agent = buildPiAgent({ logger });+ const flags = (agent as unknown as { deps: { runtimeConfig: AgentRuntimeConfig } }).deps.runtimeConfig.behaviorFlags;+ expect(typeof flags).toBe('function');+ if (typeof flags !== 'function') throw new Error('behavior flags missing');+ vi.stubEnv('VITEST_MAX_THREADS', '7');+ vi.stubEnv('CARGO_BUILD_JOBS', undefined);+ try {+ state.capToolchainThreads = true;+ const local = flags({ spawnMode: 'local' });+ expect(Number(local.CARGO_BUILD_JOBS)).toBeGreaterThan(0);+ expect(local).not.toHaveProperty('VITEST_MAX_THREADS');+ expect(flags({ spawnMode: 'remote' })).toEqual({});+ state.capToolchainThreads = false;+ expect(flags({ spawnMode: 'local' })).toEqual({});+ } finally {+ state.capToolchainThreads = true;+ vi.unstubAllEnvs();+ }+ });});diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex 41c2926805..c115d1918d 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -24,6 +24,7 @@ import path from 'node:path';import { app } from 'electron';import { readModelContextLimit } from './model-context-limit-store.js';+import { toolchainThreadCapEnv } from './toolchain-thread-cap.js';import {PiAgent,@@ -907,6 +908,7 @@ export function composePiSystemPrompt(hostPrompt: string, agentPrompt: string):function buildDesktopPiRuntimeConfig(): AgentRuntimeConfig {const ripgrepPath = getRipgrepBinaryPath();const config: AgentRuntimeConfig = {+ behaviorFlags: (ctx) => ctx.spawnMode === 'remote' ? {} : toolchainThreadCapEnv(),// 保留 host 共用身份段,再追加 Pi 专属行为段;maker-core 会整体追加到 Pi 原生 prompt。systemPrompt: composePiSystemPrompt(hostSystemPrompt, piSystemPrompt),// Pi 的 grep 以及 Cindy 覆盖的 find 都固定复用随 Desktop 校验、打包的 rg。diff --git a/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.ts b/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.tsindex 3aacc9e081..b49f7b6fc9 100644--- a/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.ts+++ b/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.ts@@ -12,6 +12,7 @@import { describe, it, expect } from 'vitest';import { buildRenderItems, type RenderItem } from '../components/chat/MessageStream';import type { ChatMessage } from '@/lib/makerChatStore';+import { makerChatStore } from '@/lib/makerChatStore';import type { GhostCardSnapshot, GhostCardEntry, GhostLiveCard } from '@/cindy-brain/ghostCardStore';const GHOST_TOOL = 'mcp__cindy__ghost_call';@@ -143,6 +144,28 @@ describe('ghost_card · in-flight 锚定', () => {...over,});+ it('renders a Pi card before its tool returns and restores the settled card from old history', () => {+ const sessionId = 'pi-card-regression';+ const content = { toolUseId: 'tu-pi', toolName: 'cindy_mcp_call_tool', input: {+ server: 'cindy', tool: 'ghost_call', args: { ghost_id: 'cindy-art', tool: 'show_card' },+ } };+ try {+ makerChatStore.__applyStreamEventForTest(sessionId, { sessionId, type: 'tool_use', data: content });+ const messages = makerChatStore.getSnapshot(sessionId).messages;+ const snap = snapshot({ 'call-pi': readyEntry() }, [live('call-pi')]);+ expect(itemsOf(messages, snap).find(item => item.type === 'ghost_card')).toMatchObject({+ callId: 'call-pi', tool: 'show_card', settled: false,+ });+ const history = makerChatStore.__mapServerMessagesForTest([{+ id: 'persisted-pi', clientId: 'persisted-pi', sessionId, role: 'tool_use', content,+ toolUseId: null, agentMeta: null,+ createdAt: '2026-09-08T00:00:00.000Z',+ }]);+ expect(itemsOf([...history, mkResult('result-pi', 'tu-pi', { xdt_card_id: 'call-pi' })], snap)+ .find(item => item.type === 'ghost_card')).toMatchObject({ callId: 'call-pi', settled: true });+ } finally { makerChatStore.purgeSession(sessionId); }+ });+it('claude:活卡带 toolUseId 时精确锚到对应行', () => {const items = itemsOf([mkGhostCall('g1'), mkGhostCall('g2')],diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 60c304b37f..659a22d89e 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -22,6 +22,7 @@*/import type { CindyRegion } from '@cindy/maker-shared/brand-identity';+import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';import {getDataOwnerGeneration,isDataOwnerGenerationCurrent,@@ -5653,11 +5654,9 @@ export function handleStreamEvent(case 'tool_use': {dismissVisionBridgeToast(event.sessionId);- const { toolUseId, toolName, input } = event.data as {- toolUseId: string;- toolName: string;- input: unknown;- };+ const { toolUseId, toolName, input } = parseMessageToolUse({+ role: 'tool_use', content: event.data,+ });// F1-a: 在飞 assistant 文本 + tool_use 的落库都已收口 main(messagePersistBroadcaster// 在 tool_use 边界先 flushAssistantBlock 再落 tool_use),renderer 这里只做 UI:@@ -16556,13 +16555,9 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {const mapped = ordered.map((m) => {if (m.role === 'tool_use' && m.content && typeof m.content === 'object') {const c = m.content as Record<string, unknown>;- const toolName = typeof c.toolName === 'string' ? c.toolName : '';- const toolInput = c.input ?? null;+ const { toolName, input: toolInput, toolUseId } = parseMessageToolUse(m);const agentTaskStatus = normalizeAgentTaskTerminalStatus(m.agentMeta?.agentTaskStatus);// toolUseId 来源:DB 列(新数据) → fallback 旧数据存在 content.toolUseId 里- const toolUseId =- (typeof m.toolUseId === 'string' && m.toolUseId.length > 0 ? m.toolUseId : undefined) ??- (typeof c.toolUseId === 'string' && c.toolUseId.length > 0 ? c.toolUseId : undefined);return {clientId: m.clientId,role: m.role,diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.mdindex 21ee07e34b..3ec5a3d70d 100644--- a/docs/dev-rules/pi-harness.md+++ b/docs/dev-rules/pi-harness.md@@ -50,6 +50,11 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi`mcp__<server>__<tool>` identity 和真实参数,不能退化成对网关包装器授权。Claude Code 与Codex 保持各自的直接 MCP 注册方式,不经过此 Pi 专属网关。配置新增、修改、禁用或删除对下一新建/重启会话生效;旧活动会话保留启动时 generation 快照至 close。+ 展示层通过共享 `parseMessageToolUse` 将网关调用还原为既有 MCP 工具名与参数;实时事件、+ Pi 分支历史和旧持久化消息共用此解析,保留 toolUseId,不改变 Pi 原生 transcript 或授权路径。+ MCP 请求接入 Pi 的取消信号;Bun fetch 的独立空闲计时关闭,由既有请求期限统一约束响应头与+ 正文。取消只中止本次 HTTP 等待,不承诺撤销服务端已执行的动作。网络错误只附白名单错误码,+ 仅 JSON-RPC `-32602` 明确参数错误附 schema,工具业务错误保留原反馈。- **plan 模式**:挂 pi 自带 plan-mode 扩展,`/plan` toggle 驱动;Cindy 维护镜像态并在 resume时从 `get_entries` 校正。@@ -71,6 +76,11 @@ provider/model/contextWindow,因为 Pi 会用进程初始 CLI route 重建外部 MCP 专用动态 env、`PI_OFFLINE=1`(关启动期联网)、`NO_PROXY` 兜底 loopback(防全局代理打穿本地 proxy 与 MCP bridge)。+Pi 同样消费 `AgentRuntimeConfig.behaviorFlags`(静态对象或按来源、凭证形态、执行位置求值)。+Desktop 复用既有工具链并行度设置,向本机 Pi 注入 `VITEST_MAX_FORKS`、`VITEST_MAX_THREADS`、+`CARGO_BUILD_JOBS` 与非 Windows 的 `MAKEFLAGS`;用户已有 env 优先,关闭设置后新进程不注入,+SSH 不套用本机限核值。沿用现有默认值与 override 存储,不新增 PI 专属开关。+放任 pi 默认(未写 settings.json):`httpIdleTimeoutMs=300000`、`websocketConnectTimeoutMs`、`compaction.keepRecentTokens`、`defaultProjectTrust`。Cindy 会在每次 startSession 覆写`transport`、`retry.maxRetries=6`(provider 级保持 0)与 `compaction.reserveTokens`;diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex fce171be74..e505a3de42 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -581,6 +581,26 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {expect(captured.env.no_proxy).toBeUndefined();});+ it.each(['local', 'remote'] as const)('passes route context to behavior flags on %s spawn', async (mode) => {+ const deps = buildDeps();+ const remoteTransport = deps.getRemotePiTransport!;+ deps.getRemotePiTransport = async (host, options) => {+ captured.env = options.env;+ return remoteTransport(host, options);+ };+ const behaviorFlags = vi.fn(({ spawnMode }: { spawnMode?: string }): Record<string, string> =>+ spawnMode === 'remote' ? { CINDY_TEST_ROUTE: 'remote' } : { VITEST_MAX_THREADS: '2' });+ deps.runtimeConfig.behaviorFlags = behaviorFlags;+ const agent = new PiAgent(deps);+ const handle = await agent.startSession({ sessionId: 'flags', workingDir: cwd, model: 'm',+ ...(mode === 'remote' ? { remoteHostId: 'remote-1' } : {}),+ });+ expect(behaviorFlags).toHaveBeenCalledWith(expect.objectContaining({ spawnMode: mode }));+ expect(captured.env[mode === 'remote' ? 'CINDY_TEST_ROUTE' : 'VITEST_MAX_THREADS'])+ .toBe(mode === 'remote' ? 'remote' : '2');+ await handle.close();+ });+it('lets Pi discover user-installed packages natively instead of gating them on Cindy metadata', async () => {const packageRoot = path.join(agentHome, 'future-pi-package-shape');mkdirSync(packageRoot, { recursive: true });diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.tsindex 0a8efaa3eb..c5691f59cd 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts@@ -1259,7 +1259,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p);it(- 'invalid MCP args expose the selected schema and let Pi correct the call without losing the capability',+ 'invalid MCP args preserve validation feedback and the inspected schema so Pi can correct the call',{ timeout: 90_000 },async () => {echoCalls.length = 0;@@ -1272,9 +1272,13 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pexpect(permissionAsked).toBe(false);expect(echoCalls).toEqual([{ text: 'hello-pi' }]);- expect(requestBodies.some((body) =>- body.includes('Expected args schema') && body.includes('"required"') && body.includes('"text"')- )).toBe(true);+ expect(requestBodies.some((body) => body.includes('"required"') && body.includes('"text"'))).toBe(true);+ const errorResult = events.filter(event => event.type === 'tool_result_full')+ .map(event => event.data as { isError?: boolean; fullText: string })+ .find(result => result.isError);+ expect(errorResult?.fullText).toMatch(/validation|invalid/i);+ expect(errorResult?.fullText).toContain('text');+ expect(errorResult?.fullText).not.toContain('Expected args schema');const finalText = events.filter((event) => event.type === 'text').map((event) => event.data as { text: string; isFinal?: boolean })diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-client.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-client.test.tsnew file mode 100644index 0000000000..600759015a--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-client.test.ts@@ -0,0 +1,100 @@+import { runInNewContext } from 'node:vm';+import ts from 'typescript';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';++// Execute the generated extension's actual client and registered gateway. Pi+// loads this standalone source, so importing a parallel client would miss bugs.+function gatewayWithFetch(fetchImpl: typeof fetch) {+ const source = CINDY_BRIDGE_EXTENSION_SOURCE;+ const compiled = ts.transpileModule(+ source.slice(source.indexOf('const CINDY_MCP_LIST_TOOLS'), source.indexOf('async function connectServer'))+ + '\nglobalThis.Client = McpHttpClient; globalThis.Gateway = CindyMcpGateway;',+ { compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 } },+ ).outputText;+ const context: Record<string, any> = {+ fetch: fetchImpl, URL, Headers, AbortController, TextDecoder, process: { env: {} },+ setTimeout, clearTimeout,+ };+ runInNewContext(compiled, context);+ const client = new context.Client({ name: 'cindy', url: 'http://127.0.0.1/mcp' }, 'fake-token');+ client.finishStartup();+ const gateway = new context.Gateway();+ gateway.add('cindy', client, [{ name: 'ghost_call', inputSchema: {+ type: 'object', properties: { ghost_id: { type: 'string' } }, required: ['ghost_id'],+ } }]);+ const registered: any[] = [];+ gateway.register({ registerTool: (tool: unknown) => registered.push(tool) });+ registered.find(t => t.name === 'cindy_mcp_list_tools').execute('list', { server: 'cindy', tool: 'ghost_call' });+ const call = (signal?: AbortSignal) => registered.find(t => t.name === 'cindy_mcp_call_tool')+ .execute('call', { server: 'cindy', tool: 'ghost_call', args: { ghost_id: 'demo' } }, signal);+ return { call };+}++afterEach(() => vi.useRealTimers());++describe('Pi MCP request lifecycle', () => {+ it('waits for card interaction beyond five minutes with one explicit deadline', async () => {+ vi.useFakeTimers();+ let complete!: (response: Response) => void;+ const fetchImpl = vi.fn((_url, options) => {+ expect(options.timeout).toBe(false);+ return new Promise<Response>(resolve => { complete = resolve; });+ });+ const { call } = gatewayWithFetch(fetchImpl);+ const result = call();+ await vi.advanceTimersByTimeAsync(301_000);+ expect(fetchImpl.mock.calls[0][1].signal.aborted).toBe(false);+ complete(Response.json({ result: { content: [{ type: 'text', text: 'clicked' }] } }));+ await expect(result).resolves.toMatchObject({ content: [{ text: 'clicked' }] });+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each(['cancel', 'timeout'] as const)('aborts an in-flight response on %s without blaming its arguments', async (action) => {+ vi.useFakeTimers();+ const controller = new AbortController();+ let bodyStarted!: () => void;+ const bodyReady = new Promise<void>(resolve => { bodyStarted = resolve; });+ const { call } = gatewayWithFetch(vi.fn(async (_url, options) => {+ // Response headers arrived; body is still waiting for the tool.+ return { headers: new Headers(), ok: true, json: () => new Promise((_resolve, reject) => {+ options!.signal!.addEventListener('abort', () => reject(new Error('secret URL')), { once: true });+ bodyStarted();+ }) } as Response;+ }));+ const result = call(controller.signal);+ const assertion = expect(result).rejects.toThrow(action === 'cancel' ? 'request cancelled' : 'request timed out');+ await bodyReady;+ if (action === 'cancel') controller.abort();+ else await vi.advanceTimersByTimeAsync(600_000);+ await assertion;+ await result.catch((error: Error) => {+ expect(error.message).not.toContain('schema');+ expect(error.message).not.toContain('secret');+ });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('retains only allowlisted transport codes, not messages or arbitrary causes', async () => {+ const { call } = gatewayWithFetch(vi.fn(async () => {+ throw Object.assign(new Error('https://[email protected]'), {+ cause: { code: 'ECONNRESET', message: 'Authorization: secret' },+ });+ }));+ await expect(call()).rejects.toThrow('request failed (ECONNRESET)');+ await call().catch((error: Error) => {+ expect(error.message).not.toMatch(/secret|schema|example/);+ });+ });++ it('adds schema help only for the MCP invalid-parameters error code', async () => {+ const { call } = gatewayWithFetch(vi.fn(async () => Response.json({+ error: { code: -32602, message: 'untrusted upstream text' },+ })));+ await expect(call()).rejects.toThrow('Expected args schema:');+ const business = gatewayWithFetch(vi.fn(async () => Response.json({ result: {+ isError: true, content: [{ type: 'text', text: 'Plugin unavailable' }],+ } })));+ await expect(business.call()).rejects.toThrow(/^Plugin unavailable$/);+ });+});diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.tsindex 589dd2de13..cf62ae2186 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts@@ -41,6 +41,25 @@ function makeQueue(): { queue: AsyncQueue<AgentEvent>; events: AgentEvent[] } {const ev = (e: Record<string, unknown>): PiRpcEvent => e as unknown as PiRpcEvent;describe('pi translator', () => {+ it('projects MCP gateway calls into ordinary tools while keeping result pairing intact', () => {+ const ctx = createPiTranslateContext(noopLogger);+ const { queue, events } = makeQueue();+ const input = { ghost_id: 'demo', tool: 'show_card' };+ translatePiEvent(ev({ type: 'tool_execution_start', toolCallId: 'card-1',+ toolName: 'cindy_mcp_call_tool', args: { server: 'cindy', tool: 'ghost_call', args: input },+ }), queue, ctx);+ const fullText = JSON.stringify({ xdt_card_id: 'plugin-call' });+ translatePiEvent(ev({ type: 'tool_execution_end', toolCallId: 'card-1',+ toolName: 'cindy_mcp_call_tool', result: { content: [{ type: 'text', text: fullText }] },+ }), queue, ctx);+ expect(events.find(e => e.type === 'tool_use')?.data).toEqual({+ toolUseId: 'card-1', toolName: 'mcp:cindy:ghost_call', input,+ });+ expect(events.find(e => e.type === 'tool_result_full')?.data).toMatchObject({+ toolUseId: 'card-1', fullText,+ });+ disposePiTranslateContext(ctx);+ });it('marks only the Cindy subagent tool as a durable lifecycle', () => {const ctx = createPiTranslateContext(noopLogger);const { queue, events } = makeQueue();diff --git a/packages/maker-core/src/agents/pi/__tests__/session-tree.test.ts b/packages/maker-core/src/agents/pi/__tests__/session-tree.test.tsindex 61b1527590..a43b193783 100644--- a/packages/maker-core/src/agents/pi/__tests__/session-tree.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/session-tree.test.ts@@ -56,6 +56,17 @@ const treeData = {};describe('pi session tree adapter', () => {+ it('restores gateway calls using the same tool contract as live events', () => {+ const data = structuredClone(treeData);+ const block = data.tree[0].children[0].entry.message.content[2];+ Object.assign(block, { name: 'cindy_mcp_call_tool', arguments: {+ server: 'cindy', tool: 'ghost_call', args: { ghost_id: 'demo', tool: 'show' },+ } });+ const history = activePiHistoryFromTree(data, normalizePiSessionTree(data));+ expect(history.find(m => m.role === 'tool_use')?.content).toEqual({+ toolUseId: 'call-1', toolName: 'mcp:cindy:ghost_call', input: { ghost_id: 'demo', tool: 'show' },+ });+ });it('normalizes branches and derives the active root-to-leaf path', () => {const snapshot = normalizePiSessionTree(treeData);expect(snapshot.leafId).toBe('tool-result');diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex a3b7445365..6ab8c45665 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -2489,7 +2489,9 @@ interface ResolvedMcpGatewayCall {tool: ConnectedMcpTool;}-class McpBridgeError extends Error {}+class McpBridgeError extends Error {+ constructor(message: string, readonly invalidParams = false) { super(message); }+}function safeMcpFailure(error: unknown): string {return error instanceof McpBridgeError ? error.message : 'unexpected error';@@ -2587,9 +2589,12 @@ class McpHttpClient {return h;}- private async post<T>(body: unknown, consume: (response: Response) => Promise<T>): Promise<T> {+ private async post<T>(body: unknown, consume: (response: Response) => Promise<T>, signal?: AbortSignal): Promise<T> {const requestTimeoutMs = this.nextRequestTimeoutMs();const controller = new AbortController();+ const cancel = () => controller.abort();+ signal?.addEventListener('abort', cancel, { once: true });+ if (signal?.aborted) controller.abort();const timeout = setTimeout(() => controller.abort(), requestTimeoutMs);try {const res = await fetch(this.requestUrl, {@@ -2598,6 +2603,9 @@ class McpHttpClient {body: JSON.stringify(body),redirect: 'error',signal: controller.signal,+ // Bun's idle timer must not preempt the explicit request deadline while+ // a local MCP tool is waiting for a user's card interaction.+ timeout: false,});const sid = res.headers.get('mcp-session-id');if (sid) this.sessionId = sid;@@ -2605,12 +2613,21 @@ class McpHttpClient {// body 也会按 requestTimeoutMs 中止,不会无限阻塞后续 server 注册。return await consume(res);} catch (error) {+ if (signal?.aborted) throw new McpBridgeError('request cancelled');if (controller.signal.aborted) throw new McpBridgeError('request timed out');if (error instanceof McpBridgeError) throw error;if (error instanceof SyntaxError) throw new McpBridgeError('invalid JSON response');- throw new McpBridgeError('request failed');+ // Only known non-secret error codes may cross the bridge. Never include+ // arbitrary messages/causes, which may contain URLs or authentication.+ const codes = new Set(['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN',+ 'ETIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT',+ 'UND_ERR_BODY_TIMEOUT', 'CERT_HAS_EXPIRED', 'DEPTH_ZERO_SELF_SIGNED_CERT']);+ const err = error as { code?: unknown; cause?: { code?: unknown } } | null;+ const code = [err?.code, err?.cause?.code].find((value) => typeof value === 'string' && codes.has(value));+ throw new McpBridgeError('request failed' + (code ? ' (' + code + ')' : ''));} finally {clearTimeout(timeout);+ signal?.removeEventListener('abort', cancel);}}@@ -2682,14 +2699,16 @@ class McpHttpClient {return res.json();}- async request(method: string, params?: unknown): Promise<any> {+ async request(method: string, params?: unknown, signal?: AbortSignal): Promise<any> {const id = this.nextId++;const msg = await this.post({ jsonrpc: '2.0', id, method, ...(params !== undefined ? { params } : {}) },(res) => this.readResponse(res, id),+ signal,);if (msg.error) {- throw new McpBridgeError('MCP ' + method + ' returned an error');+ const invalidParams = msg.error.code === -32602;+ throw new McpBridgeError('MCP ' + method + (invalidParams ? ' rejected invalid parameters' : ' returned an error'), invalidParams);}return msg.result;}@@ -3014,7 +3033,7 @@ class CindyMcpGateway {JSON.stringify(this.unavailable()).slice(0, 4_000);}- private async executeResolvedCall(resolved: ResolvedMcpGatewayCall): Promise<{+ private async executeResolvedCall(resolved: ResolvedMcpGatewayCall, signal?: AbortSignal): Promise<{content: Array<Record<string, unknown>>;details: unknown;}> {@@ -3024,11 +3043,12 @@ class CindyMcpGateway {name: resolved.tool.name,arguments: resolved.helperCommand? { name: resolved.helperCommand, args: resolved.args } : resolved.args,- });+ }, signal);} catch (error) {throw new Error('MCP tool ' + resolved.tool.serverName + '/' + resolved.tool.name + ' failed: ' +- safeMcpFailure(error) + '. Expected args schema: ' + schemaHint(resolved.tool.inputSchema),+ safeMcpFailure(error) + (error instanceof McpBridgeError && error.invalidParams+ ? '. Expected args schema: ' + schemaHint(resolved.tool.inputSchema) : ''),);}const content = mcpContentToPi(result?.content);@@ -3038,14 +3058,13 @@ class CindyMcpGateway {.join('\n').trim();throw new Error(- (message.length > 0 ? message : 'MCP tool returned an error') +- '. Expected args schema: ' + schemaHint(resolved.tool.inputSchema),+ message.length > 0 ? message : 'MCP tool returned an error',);}return { content, details: result?.structuredContent ?? {} };}- private async executeCall(params: unknown): Promise<{+ private async executeCall(params: unknown, signal?: AbortSignal): Promise<{content: Array<Record<string, unknown>>;details: unknown;}> {@@ -3057,35 +3076,35 @@ class CindyMcpGateway {JSON.stringify({ server: resolved.tool.serverName, tool: resolved.tool.name }) + '.',);}- return this.executeResolvedCall(resolved);+ return this.executeResolvedCall(resolved, signal);}- private async executeDirectHelperTool(name: string, params: unknown): Promise<{+ private async executeDirectHelperTool(name: string, params: unknown, signal?: AbortSignal): Promise<{content: Array<Record<string, unknown>>;details: unknown;}> {const resolved = this.resolveDirectHelperTool(name, params);if (!resolved) throw new Error('Cindy tool ' + name + ' is unavailable in this task.');- return this.executeResolvedCall(resolved);+ return this.executeResolvedCall(resolved, signal);}- private async executeStartSessionTask(params: unknown): Promise<{+ private async executeStartSessionTask(params: unknown, signal?: AbortSignal): Promise<{content: Array<Record<string, unknown>>;details: unknown;}> {- return this.executeDirectHelperTool(CINDY_START_SESSION_TASK_TOOL, params);+ return this.executeDirectHelperTool(CINDY_START_SESSION_TASK_TOOL, params, signal);}- private async executeCreateTeammate(params: unknown): Promise<{+ private async executeCreateTeammate(params: unknown, signal?: AbortSignal): Promise<{content: Array<Record<string, unknown>>;details: unknown;}> {const resolved = this.resolveCreateTeammate(params);if (!resolved) throw new Error('Cindy teammate creation is unavailable in this task.');- return this.executeResolvedCall(resolved);+ return this.executeResolvedCall(resolved, signal);}- private async executeBotMemory(params: unknown): Promise<{+ private async executeBotMemory(params: unknown, signal?: AbortSignal): Promise<{content: Array<Record<string, unknown>>;details: unknown;}> {@@ -3095,7 +3114,7 @@ class CindyMcpGateway {'Invalid Bot Memory request. Choose list, read, search, write, delete, review, or consolidate and provide the fields required by that action.',);}- return this.executeResolvedCall(resolved);+ return this.executeResolvedCall(resolved, signal);}register(pi: any, options: { botMemoryFacade?: boolean } = {}): void {@@ -3133,7 +3152,7 @@ class CindyMcpGateway {required: ['action'],additionalProperties: false,},- execute: async (_toolCallId: string, params: unknown) => this.executeBotMemory(params),+ execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal) => this.executeBotMemory(params, signal),});}@@ -3155,8 +3174,8 @@ class CindyMcpGateway {required: ['instruction'],additionalProperties: false,},- execute: async (_toolCallId: string, params: unknown) =>- this.executeStartSessionTask(params),+ execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal) =>+ this.executeStartSessionTask(params, signal),});}@@ -3175,8 +3194,8 @@ class CindyMcpGateway {required: ['target_id', 'message'],additionalProperties: false,},- execute: async (_toolCallId: string, params: unknown) =>- this.executeDirectHelperTool(CINDY_SEND_TO_AGENT_TOOL, params),+ execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal) =>+ this.executeDirectHelperTool(CINDY_SEND_TO_AGENT_TOOL, params, signal),});}@@ -3190,8 +3209,8 @@ class CindyMcpGateway {required: ['task_id'],additionalProperties: false,},- execute: async (_toolCallId: string, params: unknown) =>- this.executeDirectHelperTool(CINDY_CHECK_SESSION_TASK_TOOL, params),+ execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal) =>+ this.executeDirectHelperTool(CINDY_CHECK_SESSION_TASK_TOOL, params, signal),});}@@ -3213,8 +3232,8 @@ class CindyMcpGateway {required: ['task_id'],additionalProperties: false,},- execute: async (_toolCallId: string, params: unknown) =>- this.executeDirectHelperTool(CINDY_MESSAGE_SESSION_TASK_TOOL, params),+ execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal) =>+ this.executeDirectHelperTool(CINDY_MESSAGE_SESSION_TASK_TOOL, params, signal),});}@@ -3229,8 +3248,8 @@ class CindyMcpGateway {required: ['task_id'],additionalProperties: false,},- execute: async (_toolCallId: string, params: unknown) =>- this.executeDirectHelperTool(CINDY_STOP_SESSION_TASK_TOOL, params),+ execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal) =>+ this.executeDirectHelperTool(CINDY_STOP_SESSION_TASK_TOOL, params, signal),});}@@ -3251,7 +3270,7 @@ class CindyMcpGateway {required: ['name', 'description', 'identity_source', 'welcome_message'],additionalProperties: false,},- execute: async (_toolCallId: string, params: unknown) => this.executeCreateTeammate(params),+ execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal) => this.executeCreateTeammate(params, signal),});}@@ -3299,7 +3318,7 @@ class CindyMcpGateway {required: ['server', 'tool', 'args'],additionalProperties: false,},- execute: async (_toolCallId: string, params: unknown) => this.executeCall(params),+ execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal) => this.executeCall(params, signal),});}}diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex dceb8267e6..82142869e1 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -4449,6 +4449,13 @@ export class PiAgent extends BaseAgent {const proxyEnv = remote && this.deps.getRemotePiAgentProxyEnv ? await this.deps.getRemotePiAgentProxyEnv(opts.remoteHostId!) : null;const spawnEnv: NodeJS.ProcessEnv = {...(remote ? {} : process.env),+ ...(typeof this.deps.runtimeConfig.behaviorFlags === 'function'+ ? this.deps.runtimeConfig.behaviorFlags({+ credentialMode,+ sessionProviderId: authProviderId,+ spawnMode: remote ? 'remote' : 'local',+ })+ : this.deps.runtimeConfig.behaviorFlags),...authEnv,...(proxyEnv ?? {}),// BYOM 原生 provider 的 api keys(键名对应 spec.apiKeyEnvVar,models.json 用 $ENV 引用)。diff --git a/packages/maker-core/src/agents/pi/session-tree.ts b/packages/maker-core/src/agents/pi/session-tree.tsindex 6b83a4175b..986cf99655 100644--- a/packages/maker-core/src/agents/pi/session-tree.ts+++ b/packages/maker-core/src/agents/pi/session-tree.ts@@ -1,3 +1,4 @@+import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';import type {SessionTreeEntryKind,SessionTreeHistoryMessage,@@ -263,7 +264,11 @@ export function activePiHistoryFromTree(clientId: `pi-tree-${entryId}-tool-${index}`,role: 'tool_use',toolUseId: block.id,- content: { toolUseId: block.id, toolName, input: safeToolArguments(block.arguments) },+ content: parseMessageToolUse({+ role: 'tool_use',+ toolUseId: block.id,+ content: { toolName, input: safeToolArguments(block.arguments) },+ }),agentMeta: meta,}, baseTs + index);}diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.tsindex 8745276cf2..e4e727d729 100644--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@ -16,6 +16,7 @@*/import { randomUUID } from 'node:crypto';+import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';import type { Logger } from '../../interfaces/logger.js';import { PI_SUBAGENT_TOOL_NAME, subagentSpawnResultIndicatesRunning } from '@cindy/maker-shared/agent-task';import {@@ -773,8 +774,11 @@ export function translatePiEvent(type: 'tool_use',data: {toolUseId,- toolName,- input: toolArgs,+ ...parseMessageToolUse({+ role: 'tool_use',+ content: { toolName, input: toolArgs },+ toolUseId,+ }),},source: 'pi',});diff --git a/packages/maker-shared/src/__tests__/messageNormalize.test.ts b/packages/maker-shared/src/__tests__/messageNormalize.test.tsindex 191a8cfe93..ff027a6d1f 100644--- a/packages/maker-shared/src/__tests__/messageNormalize.test.ts+++ b/packages/maker-shared/src/__tests__/messageNormalize.test.ts@@ -26,6 +26,28 @@ function message(patch: Partial<FixtureMessage> & Pick<FixtureMessage, 'id' | 'r}describe('message normalize shared model', () => {+ it('unwraps Pi MCP calls without changing their identity or nested arguments', () => {+ const input = { ghost_id: 'demo', tool: 'show', args: { value: 1 } };+ const raw = message({ id: 'pi', role: 'tool_use', toolUseId: 'call-pi', content: {+ toolName: 'cindy_mcp_call_tool', input: { server: 'cindy', tool: 'ghost_call', args: input },+ } });+ const tool = parseMessageToolUse(raw);+ expect(tool).toEqual({ toolUseId: 'call-pi', toolName: 'mcp:cindy:ghost_call', input });+ expect(tool.input).toBe(input);+ expect(parseMessageToolUse({ ...raw, content: tool })).toEqual(tool);+ expect((raw.content as { toolName: string }).toolName).toBe('cindy_mcp_call_tool');+ expect(parseMessageToolUse({ role: 'tool_use', content: {+ toolName: 'cindy_mcp_call_tool', input: { server: 'custom', tool: 'status' },+ } })).toMatchObject({ toolName: 'mcp:custom:status', input: {} });+ });++ it.each([null, [], {}, { server: 'cindy' }, { server: 'cindy', tool: 'ghost_call', args: [] }])(+ 'preserves malformed gateway inputs for diagnostics: %j', (input) => {+ expect(parseMessageToolUse({ role: 'tool_use', content: { toolName: 'cindy_mcp_call_tool', input } }))+ .toMatchObject({ toolName: 'cindy_mcp_call_tool', input });+ },+ );+it('builds text previews from desktop content shapes', () => {expect(messageContentToPreview('plain')).toBe('plain');expect(messageContentToPreview([diff --git a/packages/maker-shared/src/__tests__/toolUseDescriptor.test.ts b/packages/maker-shared/src/__tests__/toolUseDescriptor.test.tsindex 182bfd6d81..3102878768 100644--- a/packages/maker-shared/src/__tests__/toolUseDescriptor.test.ts+++ b/packages/maker-shared/src/__tests__/toolUseDescriptor.test.ts@@ -1,4 +1,5 @@import { describe, expect, it } from 'vitest';+import { parseMessageToolUse } from '../messageNormalize.js';import {createdPathsFromDescriptor,describeToolUse,@@ -10,6 +11,26 @@ import {} from '../toolUseDescriptor';describe('parseToolName', () => {+ it('describes persisted Pi MCP wrappers with the same descriptor as direct calls', () => {+ const args = { query: 'card' };+ expect(describeToolUse('cindy_mcp_call_tool', { server: 'custom', tool: 'search', args }))+ .toEqual(describeToolUse('mcp:custom:search', args));+ });+ it.each(['start_team', 'part__tool'])('preserves Pi server boundaries for %s in raw and normalized messages', (tool) => {+ const server = 'cindy_orca__evil';+ const input = { value: 1 };+ const gateway = { server, tool, args: input };+ const normalized = parseMessageToolUse({ role: 'tool_use', toolUseId: 'pi-id', content: {+ toolName: 'cindy_mcp_call_tool', input: gateway,+ } });+ expect(normalized.toolUseId).toBe('pi-id');+ expect(parseToolName(normalized.toolName)).toEqual({ kind: 'mcp', server, tool });+ const expected = describeToolUse(`mcp:${server}:${tool}`, input);+ expect(describeToolUse('cindy_mcp_call_tool', gateway)).toEqual(expected);+ expect(describeToolUse(normalized.toolName, normalized.input)).toEqual(expected);+ expect(parseMessageToolUse({ role: 'tool_use', content: normalized })).toEqual(normalized);+ });+it('parses Claude Code mcp__server__tool names', () => {expect(parseToolName('mcp__feishu__read_by_url')).toEqual({kind: 'mcp',diff --git a/packages/maker-shared/src/messageNormalize.ts b/packages/maker-shared/src/messageNormalize.tsindex e7de7edcb7..b761ea4c46 100644--- a/packages/maker-shared/src/messageNormalize.ts+++ b/packages/maker-shared/src/messageNormalize.ts@@ -69,11 +69,25 @@ export function messageNormalizeKey(message: MessageNormalizeSourceMessageLike):export function parseMessageToolUse(message: MessageNormalizeSourceMessageLike): MessageNormalizeToolUse {const content = readRecord(message.content);const toolUseId = readNonEmptyString(message.toolUseId) ?? readNonEmptyString(content?.toolUseId);- const toolName = readNonEmptyString(content?.toolName) ?? '';+ let toolName = readNonEmptyString(content?.toolName) ?? '';+ let input = content?.input ?? null;+ // Pi wraps all MCP calls. Normalize live events and persisted history through+ // the existing descriptor contract; this is not an authorization decision.+ if (toolName === 'cindy_mcp_call_tool') {+ const gateway = readRecord(input);+ const server = readNonEmptyString(gateway?.server);+ const tool = readNonEmptyString(gateway?.tool);+ const args = gateway?.args;+ if (server && tool && (args === undefined || readRecord(args))) {+ // Reuse the Codex display format: valid server IDs can contain "__".+ toolName = `mcp:${server}:${tool}`;+ input = args ?? {};+ }+ }return {toolUseId: toolUseId ?? undefined,toolName,- input: content?.input ?? null,+ input,};}diff --git a/packages/maker-shared/src/toolUseDescriptor.ts b/packages/maker-shared/src/toolUseDescriptor.tsindex 93db4dcb1e..1695b91f1e 100644--- a/packages/maker-shared/src/toolUseDescriptor.ts+++ b/packages/maker-shared/src/toolUseDescriptor.ts@@ -1,4 +1,5 @@import { basenameRemotePath } from './filePreview.js';+import { parseMessageToolUse } from './messageNormalize.js';import { normalizeDisplayCommand } from './commandDisplay.js';import {commandIntentFromActions,@@ -21,7 +22,7 @@ import {* `dynamic:ns:tool` / `collab:tool` / `web_search`。* - pi:内置工具名全小写(bash/read/edit/write/grep/find/ls),文件参数字段为* `path`(fileDescriptor 已双认 file_path/path);bash 无 description 字段,- * 桥接 MCP 复用 Claude Code 的 `mcp__server__tool` 形态。+ * 桥接 MCP 复用 Codex 的 `mcp:server:tool` 形态,保留 server 中的双下划线。*/// ── 工具名拆解 ───────────────────────────────────────────────────────────────@@ -251,6 +252,7 @@ const DETAIL_MAX_CHARS = 80;* generic(文件/搜索/Web 类)或空串回退(command 类)。*/export function describeToolUse(toolName: string, input: unknown): ToolUseDescriptor {+ ({ toolName, input } = parseMessageToolUse({ role: 'tool_use', content: { toolName, input } }));const inp = readRecord(input);const parsed = parseToolName(toolName);