Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): recover MCP connections without replaying tool calls
Chrisa302862b33cd
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.mdindex 71eb395aef..7810d0984c 100644--- a/docs/dev-rules/pi-harness.md+++ b/docs/dev-rules/pi-harness.md@@ -74,6 +74,10 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 piMCP 请求接入 Pi 的取消信号;Bun fetch 的独立空闲计时关闭,由既有请求期限统一约束响应头与正文。取消只中止本次 HTTP 等待,不承诺撤销服务端已执行的动作。网络错误只附白名单错误码,仅 JSON-RPC `-32602` 明确参数错误附 schema,工具业务错误保留原反馈。+ 启动失败、传输断开、请求超时或已建立的 MCP session 返回 404 后,下一次定向发现/调用+ 按服务重新 initialize + tools/list,复用既有启动期限;并发等待共享一次握手,取消只退出+ 当前等待。恢复不自动重放 tools/call,不重启 Pi 或其它服务;新工具表替换旧表,定义改变+ 或删除时拒绝用旧定义继续调用。只恢复启动快照里的服务,不热加载配置变更。- **plan 模式**:自动挂载 Pi 分发包自带的 plan-mode 扩展,无需用户另装。UI 勾选是下一条消息的一次性意图,与原生运行态分开;`StartSessionOptions.planMode` 设置起始档,`SendOptions.planMode` 快照决定本轮,切档与 prompt 在同一 RPC 串行段执行。发送后消耗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 4885842ef5..fcd5a696cb 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@@ -195,6 +195,17 @@ function scriptedAnthropicTurn(requestBody: string): string {return call ? anthropicToolTurn(toolResultCount + 1, call.name, call.input): anthropicTextTurn(3, 'Result received');}+ if (requestBody.includes('recover MCP transport')) {+ const calls = [+ { name: 'cindy_mcp_list_tools', input: { server: 'recovery', tool: 'echo' } },+ { name: 'cindy_mcp_call_tool', input: { server: 'recovery', tool: 'echo', args: { text: 'write' } } },+ { name: 'cindy_mcp_list_tools', input: { server: 'recovery', tool: 'echo' } },+ { name: 'cindy_mcp_call_tool', input: { server: 'recovery', tool: 'echo', args: { text: 'inspect' } } },+ ];+ const call = calls[toolResultCount];+ return call ? anthropicToolTurn(toolResultCount + 1, call.name, call.input)+ : anthropicTextTurn(5, 'Recovery complete');+ }if (requestBody.includes('local host tool isolation')) {const calls = [{ name: 'cindy_mcp_list_tools', input: {} },@@ -419,6 +430,10 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pconst modelRequestBodies: string[] = [];const modelRequests: Array<Record<string, unknown>> = [];const opaqueTurnCaptures: Array<{ sessionId: string; provider: string; cwd: string }> = [];+ let recoveryMode: 'disconnect' | 'expired' = 'disconnect';+ let recoveryWrites = 0;+ const recoveryCalls: string[] = [];+ const recoveryHandshakes: Array<string | string[] | undefined> = [];beforeAll(async () => {agentHome = mkdtempSync(path.join(tmpdir(), 'pi-mcp-int-'));@@ -439,6 +454,33 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pmcpHttp = createServer(async (req: IncomingMessage, res: ServerResponse) => {seenMcpUrls.push(req.url ?? '');const auth = req.headers.authorization ?? '';+ if (req.url?.includes('/recovery')) {+ if (auth !== `Bearer ${MCP_TOKEN}`) { res.writeHead(401).end(); return; }+ const body = JSON.parse(await readBody(req));+ if (body.id === undefined) { res.writeHead(202).end(); return; }+ let result: unknown = {};+ if (body.method === 'initialize') {+ recoveryHandshakes.push(req.headers['mcp-session-id']);+ res.setHeader('mcp-session-id', 'session-' + recoveryHandshakes.length);+ result = { protocolVersion: '2025-03-26', capabilities: { tools: {} }, serverInfo: { name: 'recovery', version: '1' } };+ } else if (body.method === 'tools/list') {+ result = { tools: [{ name: 'echo', description: 'Recovery fixture', inputSchema: {+ type: 'object', properties: { text: { type: 'string' } }, required: ['text'],+ } }] };+ } else if (body.method === 'tools/call') {+ recoveryCalls.push(body.params.arguments.text);+ if (body.params.arguments.text === 'write') {+ if (recoveryMode === 'expired') { res.writeHead(404).end(); return; }+ recoveryWrites++;+ res.destroy();+ return;+ }+ result = { content: [{ type: 'text', text: 'writes=' + recoveryWrites }] };+ }+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ jsonrpc: '2.0', id: body.id, result }));+ return;+ }const apiKey = Array.isArray(req.headers['x-api-key'])? req.headers['x-api-key'][0]: req.headers['x-api-key'];@@ -790,7 +832,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pfunction buildDeps(bridgeMode:- | 'local' | 'orca' | 'local-multi' | 'bot-memory' | 'remote' | 'remote-sse' | 'remote-paginated' | 'remote-failures' = 'local',+ | 'local' | 'orca' | 'local-multi' | 'bot-memory' | 'remote' | 'remote-sse' | 'remote-paginated' | 'remote-failures' | 'recovery' = 'local',logger: Logger = noopLogger,): AgentDeps {return {@@ -824,6 +866,9 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p// `?session=` —— 既验 PiAgent.startSession 把 opts.sessionId 透传进 ctx,// 又让假 server 能观察到真 pi 是否原样转发该 query(见 seenMcpUrls 断言)。preparePiExtraSpawnConfig: async (_providers, ctx): Promise<PiExtraSpawnConfig> => {+ if (bridgeMode === 'recovery') {+ return { mcpBridge: { token: MCP_TOKEN, servers: [{ name: 'recovery', url: mcpUrl + '/recovery' }] } };+ }if (bridgeMode === 'remote') {return {mcpBridge: {@@ -991,7 +1036,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + ppermissionMode: 'ask' | 'bypassPermissions',resolver: (req: InteractionRequest) => Promise<InteractionDecision>,bridgeMode:- | 'local' | 'orca' | 'local-multi' | 'bot-memory' | 'remote' | 'remote-sse' | 'remote-paginated' = 'local',+ | 'local' | 'orca' | 'local-multi' | 'bot-memory' | 'remote' | 'remote-sse' | 'remote-paginated' | 'recovery' = 'local',prompt = 'call the echo tool',localHostOnly: boolean | 'native' = false,// 披露记录按 sessionId 落盘,所以要真正走到「首次未披露」必须给独立会话;@@ -1047,6 +1092,24 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p}}+ it.each(['disconnect', 'expired'] as const)('recovers MCP %s through real Pi without replaying a write', { timeout: 90_000 }, async (mode) => {+ recoveryMode = mode;+ recoveryWrites = 0;+ recoveryCalls.length = 0;+ recoveryHandshakes.length = 0;+ const approvals: string[] = [];+ const { requestBodies } = await runOneTurn('ask', async (req) => {+ if (req.kind === 'permission') approvals.push(req.toolName);+ return { kind: 'permission', behavior: 'allow' };+ }, 'recovery', 'recover MCP transport', false, 'recovery-' + mode);+ expect(recoveryCalls).toEqual(['write', 'inspect']);+ expect(recoveryHandshakes).toEqual([undefined, undefined]);+ expect(recoveryWrites).toBe(mode === 'disconnect' ? 1 : 0);+ expect(approvals.filter(name => name === 'mcp__recovery__echo')).toHaveLength(2);+ expect(requestBodies.at(-1)).toContain('not replayed');+ expect(requestBodies.at(-1)).toContain('writes=' + recoveryWrites);+ });+// PR2 integration: Pi has no private Worker schema. Exercise the real shared schema through// tools/list, schema disclosure, approval identity, tools/call, and the resulting model input.it('preserves new_worktree and spawn metadata through the dynamic Orca MCP gateway', {timeout: 90_000}, async () => {@@ -1173,11 +1236,24 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pconst toolResult = events.filter(event => event.type === 'tool_result_full').at(-1)!;expect((toolResult.data as { isError: boolean }).isError).toBe(scenario !== 'success');if (scenario === 'rich-failure') {- const blocks = result.content as Array<Record<string, unknown>>;- expect(blocks.map(block => block.type)).toEqual(['text', 'image', 'text', 'text']);- expect(blocks[0].text).toBe('Screenshot of the failing input');- expect(blocks[1].source).toMatchObject({ type: 'base64', media_type: 'image/png' });- expect(blocks[2].text).toBe('Correct the highlighted field');+ if (Array.isArray(result.content)) {+ const blocks = result.content as Array<Record<string, unknown>>;+ expect(blocks.map(block => block.type)).toEqual(['text', 'image', 'text', 'text']);+ expect(blocks[0].text).toBe('Screenshot of the failing input');+ expect(blocks[1].source).toMatchObject({ type: 'base64', media_type: 'image/png' });+ expect(blocks[2].text).toBe('Correct the highlighted field');+ } else {+ // Pi 1.4 moves images after tool results in the same user message.+ // Assert the actual image still reaches the model, not just a marker.+ expect(result.content).toContain('Screenshot of the failing input');+ expect(result.content).toContain('Correct the highlighted field');+ const containing = messages.find(message => message.content.includes(result))!;+ const images = containing.content.slice(containing.content.indexOf(result) + 1)+ .filter(block => block.type === 'image');+ expect(images).toHaveLength(1);+ expect(images[0].source).toMatchObject({ type: 'base64', media_type: 'image/png',+ data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aifoAAAAASUVORK5CYII=' });+ }}expect(JSON.stringify(requests)).not.toContain('MCP_CLIENT_ONLY_CANARY');},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.tsindex 7e988858f0..fa58883b38 100644--- 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.ts@@ -8,8 +8,8 @@ import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';// loads this standalone source, so importing a parallel client would miss bugs.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;',+ source.slice(source.indexOf('const CINDY_MCP_LIST_TOOLS'), source.indexOf('// Pi 内置 find 依赖 fd'))+ + '\nglobalThis.Client = McpHttpClient; globalThis.Gateway = CindyMcpGateway; globalThis.connect = connectServer;',{ compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 } },).outputText;@@ -39,12 +39,83 @@ function gatewayWithFetch(fetchImpl: typeof fetch) {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, gateway, client, resultHook: (event: unknown) => resultHooks[0]?.(event), list: (params: unknown = {}) => registered.find(t => t.name === 'cindy_mcp_list_tools').execute('list', params) };+ return { call, gateway, client,+ connect: () => context.connect({ name: 'cindy', url: 'https://example.test/mcp' }, 'fake-token'),+ resultHook: (event: unknown) => resultHooks[0]?.(event),+ list: (params: unknown = {}, signal?: AbortSignal) => registered.find(t => t.name === 'cindy_mcp_list_tools').execute('list', params, signal) };}afterEach(() => vi.useRealTimers());describe('Pi MCP request lifecycle', () => {+ // A transport failure can follow a successful write. Recover the connection+ // for a later explicit request, without replaying that ambiguous operation.+ it('recovers a lost response on the next call with one handshake and no replay', async () => {+ const methods: string[] = [];+ let calls = 0;+ const h = gatewayWithFetch(vi.fn(async (_url, options) => {+ const body = JSON.parse(String(options!.body));+ methods.push(body.method);+ if (body.method === 'tools/call' && ++calls === 1) throw { code: 'ECONNRESET' };+ return Response.json({ result: body.method === 'tools/list' ? { tools: [{ name: 'ghost_call', inputSchema: {+ type: 'object', properties: { ghost_id: { type: 'string' } }, required: ['ghost_id'],+ } }] } : { content: [{ type: 'text', text: 'ok' }] } });+ }));+ const connect = vi.fn(h.connect);+ h.gateway.registerReconnect('cindy', connect);+ await expect(h.call()).rejects.toThrow('not replayed');+ expect(methods).toEqual(['tools/call']);+ await Promise.all([h.call(), h.call()]);+ expect(connect).toHaveBeenCalledTimes(1);+ expect(methods).toEqual(['tools/call', 'initialize', 'notifications/initialized', 'tools/list', 'tools/call', 'tools/call']);+ });++ it('recovers an initially unavailable server through targeted discovery and cancels only one waiter', async () => {+ const h = gatewayWithFetch(vi.fn(async () => Response.json({ result: {+ content: [{ type: 'text', text: 'healthy server' }],+ } })));+ let finish!: (value: unknown) => void;+ const connect = vi.fn(() => new Promise(resolve => { finish = resolve; }));+ h.gateway.registerReconnect('catalog', connect);+ h.gateway.markUnavailable('catalog', 'HTTP 503');+ await h.list();+ expect(connect).not.toHaveBeenCalled();+ const controller = new AbortController();+ const cancelled = h.list({ server: 'catalog' }, controller.signal);+ const waiting = h.list({ server: 'catalog' });+ controller.abort();+ await expect(cancelled).rejects.toThrow('cancelled');+ finish({ client: h.client, tools: [{ name: 'ready' }] });+ expect((await waiting).details.tools[0].name).toBe('ready');+ expect(connect).toHaveBeenCalledTimes(1);+ await expect(h.call()).resolves.toMatchObject({ content: [{ text: 'healthy server' }] });+ });++ it.each(['changed', 'removed'])('does not dispatch an approved call when recovery returns a %s definition', async (mode) => {+ const fetchImpl = vi.fn(async () => { throw { code: 'ECONNRESET' }; });+ const h = gatewayWithFetch(fetchImpl);+ h.gateway.registerReconnect('cindy', async () => ({ client: h.client,+ tools: mode === 'removed' ? [] : [{ name: 'ghost_call', inputSchema: { type: 'object' } }],+ }));+ await expect(h.call()).rejects.toThrow('ECONNRESET');+ await expect(h.call()).rejects.toThrow('tool definition changed');+ expect(fetchImpl).toHaveBeenCalledTimes(1);+ });++ it('marks an expired session for recovery while leaving authentication failures alone', async () => {+ let status = 200;+ const h = gatewayWithFetch(vi.fn(async () => Response.json({ result: {} }, {+ status, headers: status === 200 ? { 'mcp-session-id': 'fixture-session' } : {},+ })));+ await h.client.initialize();+ status = 401;+ await expect(h.call()).rejects.toThrow('HTTP 401');+ expect(h.client.needsReconnect).toBe(false);+ status = 404;+ await expect(h.call()).rejects.toThrow('HTTP 404');+ expect(h.client.needsReconnect).toBe(true);+ });+it('bounds broad discovery, pages all tools, and inspects the full searchable description', async () => {const h = gatewayWithFetch(vi.fn());const description = 'Documentation '.repeat(200) + 'needle';diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex af79af9590..ccb5d25179 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -2801,6 +2801,7 @@ async function fetchDirectLoopbackMcp(url: string, headers: Headers, body: strinclass McpHttpClient {private nextId = 1;private sessionId: string | null = null;+ needsReconnect = false;private readonly requestUrl: string;private readonly directLoopback: boolean;private readonly requestTimeoutMs: number;@@ -2903,7 +2904,10 @@ class McpHttpClient {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 (controller.signal.aborted) {+ this.needsReconnect = true;+ throw new McpBridgeError('request timed out');+ }if (error instanceof McpBridgeError) throw error;if (error instanceof SyntaxError) throw new McpBridgeError('invalid JSON response');// Only known non-secret error codes may cross the bridge. Never include@@ -2913,6 +2917,9 @@ class McpHttpClient {'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));+ // A broken transport invalidates this connection, but never replays the+ // request: a tool may have completed before its response was lost.+ this.needsReconnect = true;throw new McpBridgeError('request failed' + (code ? ' (' + code + ')' : ''));} finally {clearTimeout(timeout);@@ -2978,6 +2985,7 @@ class McpHttpClient {private async readResponse(res: Response, id: number): Promise<any> {const contentType = res.headers.get('content-type') ?? '';if (!res.ok) {+ if (res.status === 404 && this.sessionId) this.needsReconnect = true;// 远端错误体可能回显 Authorization / API key,绝不拼进 Pi stderr。void res.body?.cancel().catch(() => {});throw new McpBridgeError('HTTP ' + res.status);@@ -3144,6 +3152,9 @@ class CindyMcpGateway {private readonly failedResults = new WeakMap<object, { content: object; details: unknown }>();private readonly tools = new Map<string, ConnectedMcpTool>();private readonly unavailableServers = new Map<string, string>();+ private readonly clients = new Map<string, McpHttpClient>();+ private readonly reconnectors = new Map<string, () => Promise<{ client: McpHttpClient; tools: any[] }>>();+ private readonly reconnecting = new Map<string, Promise<void>>();/** 已披露工具:键为 server + NUL + tool,值为该工具当前 schema 的指纹。 */private readonly disclosedSchemas = new Map<string, string>();/** 本次调用跳过了权限询问(hook 未披露即放行):按 toolCallId 记账,execute 见此标记一律回路标。 */@@ -3237,6 +3248,11 @@ class CindyMcpGateway {}add(serverName: string, client: McpHttpClient, tools: any[]): void {+ for (const [key, tool] of this.tools) {+ if (tool.serverName === serverName) this.tools.delete(key);+ }+ this.clients.set(serverName, client);+ this.unavailableServers.delete(serverName);for (const rawTool of tools) {if (!rawTool || typeof rawTool !== 'object' || typeof rawTool.name !== 'string' || !rawTool.name) {continue;@@ -3264,6 +3280,38 @@ class CindyMcpGateway {this.unavailableServers.set(serverName, reason);}+ registerReconnect(serverName: string, connect: () => Promise<{ client: McpHttpClient; tools: any[] }>): void {+ this.reconnectors.set(serverName, connect);+ }++ private needsRecovery(serverName: string): boolean {+ return this.reconnectors.has(serverName)+ && (this.unavailableServers.has(serverName) || this.clients.get(serverName)?.needsReconnect === true);+ }++ private async recover(serverName: string, signal?: AbortSignal): Promise<void> {+ if (signal?.aborted) throw new McpBridgeError('request cancelled');+ if (!this.needsRecovery(serverName)) return;+ let pending = this.reconnecting.get(serverName);+ if (!pending) {+ pending = this.reconnectors.get(serverName)!().then(({ client, tools }) => {+ this.add(serverName, client, tools);+ }).catch((error) => {+ this.markUnavailable(serverName, safeMcpFailure(error));+ throw new McpBridgeError('reconnect failed: ' + safeMcpFailure(error));+ }).finally(() => { this.reconnecting.delete(serverName); });+ this.reconnecting.set(serverName, pending);+ }+ // One handshake per server. Cancelling one waiter must not cancel another+ // caller's recovery; connectServer retains its bounded startup deadline.+ await new Promise<void>((resolve, reject) => {+ const cancel = () => reject(new McpBridgeError('request cancelled'));+ signal?.addEventListener('abort', cancel, { once: true });+ pending!.then(resolve, reject).finally(() => signal?.removeEventListener('abort', cancel));+ if (signal?.aborted) cancel();+ });+ }+resolveCall(input: unknown): ResolvedMcpGatewayCall | null {const record = recordInput(input);const serverName = typeof record.server === 'string' ? record.server : '';@@ -3604,6 +3652,14 @@ class CindyMcpGateway {}> {let result: any;try {+ if (this.needsRecovery(resolved.tool.serverName)) await this.recover(resolved.tool.serverName, signal);+ const current = this.tools.get(mcpGatewayKey(resolved.tool.serverName, resolved.tool.name));+ // Approval and disclosure happened against the original definition.+ // Never execute a replacement definition under that earlier approval.+ if (!current || (current !== resolved.tool && this.schemaFingerprint(current) !== this.schemaFingerprint(resolved.tool))) {+ throw new McpBridgeError('tool definition changed; inspect it with cindy_mcp_list_tools and call again');+ }+ resolved = { ...resolved, tool: current };result = await resolved.tool.client.request('tools/call', {name: resolved.tool.name,arguments: resolved.helperCommand@@ -3612,7 +3668,9 @@ class CindyMcpGateway {} catch (error) {throw new Error('MCP tool ' + resolved.tool.serverName + '/' + resolved.tool.name + ' failed: ' +- safeMcpFailure(error) + (error instanceof McpBridgeError && error.invalidParams+ safeMcpFailure(error) + (resolved.tool.client.needsReconnect+ ? '. The request was not replayed; check whether the operation completed before retrying.' : '')+ + (error instanceof McpBridgeError && error.invalidParams? '. Expected args schema: ' + schemaHint(resolved.tool.inputSchema) : ''),);}@@ -4034,7 +4092,16 @@ class CindyMcpGateway {},additionalProperties: false,},- execute: async (_toolCallId: string, params: unknown) => this.listResult(params),+ execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal) => {+ const server = recordInput(params).server;+ if (typeof server === 'string' && this.needsRecovery(server)) {+ try { await this.recover(server, signal); } catch (error) {+ if (signal?.aborted) throw error;+ // listResult reports the bounded, sanitized unavailable reason.+ }+ }+ return this.listResult(params);+ },});pi.registerTool({@@ -5462,6 +5529,7 @@ export default async function cindyBridge(piApi: any) {// 全部 server 并行启动:每个 remote 有独立短预算,多个黑洞 provider 也只占一份// startup window,不会串行叠加到 Pi RPC 的 30s ready 超时。await Promise.all(servers.map(async (server) => {+ mcpGateway.registerReconnect(server.name, () => connectServer(server, token));try {const connected = await connectServer(server, token);mcpGateway.add(server.name, connected.client, connected.tools);