Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): close review and integration gaps
Chrisb4c1a1db5f1b
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.tsindex 19b011bd39..d07c74d5c4 100644--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts@@ -249,7 +249,7 @@ describe('sendToSession ordering', () => {);const liveBranch = extractBetween(block,- 'const live = maker.getSession(targetSessionId);',+ 'live = maker.getSession(targetSessionId);','try {\n const createOpts = buildCreateOptsWithStderr({',);const resumedBranch = extractBetween(@@ -360,12 +360,12 @@ describe('sendToSession ordering', () => {const anySessionInTurnBlock = extractBetween(source,'export function anySessionInTurn',- '/**\n * 把 desktop 版的 interaction listener',+ 'let goalClearObserver:',);const handlerBlock = extractBetween(source,'ipcMain.handle(MAKER_INVOKE.ANY_SESSION_IN_TURN',- 'ipcMain.handle(MAKER_INVOKE.GET_CAPABILITIES',+ 'ipcMain.handle(MAKER_INVOKE.SESSION_IN_TURN',);expect(anySessionInTurnBlock).toContain('maker?.listActiveSessions()');@@ -446,7 +446,7 @@ describe('sendToSession ordering', () => {expectOrder(block, 'await createDbMessage(targetSessionId, {', 'await runAcceptedCallback(onAccepted, targetSessionId, clientId);');const liveBranch = extractBetween(block,- 'const live = maker.getSession(targetSessionId);',+ 'live = maker.getSession(targetSessionId);','try {\n const createOpts = buildCreateOptsWithStderr({',);diff --git a/apps/desktop/src/main/hook-control/__tests__/defaults.test.ts b/apps/desktop/src/main/hook-control/__tests__/defaults.test.tsindex 2717c590d1..5aa1f38880 100644--- a/apps/desktop/src/main/hook-control/__tests__/defaults.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/defaults.test.ts@@ -77,6 +77,24 @@ describe('resolveHookSessionConfig', () => {});});+ it('accepts Pi as an explicit hook agent override', () => {+ const r = resolveHookSessionConfig(+ deps({+ getModels: (agentKind) => agentKind === 'pi'+ ? [{ id: 'claude-sonnet-5', efforts: ['high'], defaultEffort: 'high' }]+ : [],+ }),+ over({ agentKind: 'pi', model: 'claude-sonnet-5', effort: 'high', permissionMode: 'auto' }),+ );+ expect(r).toEqual({+ agentKind: 'pi',+ model: 'claude-sonnet-5',+ effort: 'high',+ permissionMode: 'auto',+ providerId: null,+ });+ });+it('override 模型不在实时目录: 记录告警并降级到可用桌面默认', () => {const warns: string[] = [];const r = resolveHookSessionConfig(diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.tsindex fb84a21f13..0e065e1125 100644--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts@@ -1739,6 +1739,26 @@ describe('watchContinuation: 观察桌面端续跑并回流', () => {expect(ends[0]?.finalText).toBe('先回一句。\n\n这是终答。');});+ it('Pi message_end 全文替换流式尾部,不重复拼接多文本块', async () => {+ fakeMaker.getSession.mockReturnValueOnce(makeManualSession('sess-live'));+ const runner = createMakerHookSessionRunner({ log });+ const { req, ends } = watchReq();+ runner.watchContinuation!(req as never);++ const cb = h.eventCbs.get('sess-live')!;+ cb({ type: 'text', source: 'pi', data: { text: '第一段', isFinal: false } });+ cb({ type: 'text', source: 'pi', data: { text: '第二段', isFinal: false } });+ cb({+ type: 'text',+ source: 'pi',+ data: { text: '第一段\n\n第二段', isFinal: true },+ });+ cb({ type: 'done', data: null });+ await flush();++ expect(ends[0]?.finalText).toBe('第一段\n\n第二段');+ });+it('续跑轮自己失败 -> onEnd(error) 带错误信息', async () => {fakeMaker.getSession.mockReturnValueOnce(makeManualSession('sess-live'));const runner = createMakerHookSessionRunner({ log });diff --git a/apps/desktop/src/main/hook-control/defaults.ts b/apps/desktop/src/main/hook-control/defaults.tsindex f514676fad..bfd56275d0 100644--- a/apps/desktop/src/main/hook-control/defaults.ts+++ b/apps/desktop/src/main/hook-control/defaults.ts@@ -64,7 +64,7 @@ export interface ResolvedHookSessionConfig {providerId: string | null;}-const AGENT_KINDS = new Set(['claude-code', 'codex']);+const AGENT_KINDS = new Set(['claude-code', 'codex', 'pi']);/*** 合成新 hook 会话的 agent/model/effort。diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.tsindex df8dd5328a..95b24d580b 100644--- a/apps/desktop/src/main/hook-control/ipc.ts+++ b/apps/desktop/src/main/hook-control/ipc.ts@@ -402,7 +402,9 @@ function ensureInstances(): { store: SlackHookStore; manager: HookControlManagerdeviceId: authManager.getDeviceId(),deviceName: os.hostname(),}),- agents: ['claude-code', 'codex'],+ // Only advertise runtimes that are actually registered on this build.+ // Pi is optional on unsupported/unprepared platforms.+ agents: getMaker().listAvailableAgents(),notifyStatus: broadcastStatus,onSlackToolProviderEnabledChanged: requestCodexMcpRefreshForSlackAvailability,notifyPrefs: broadcastPrefs,@@ -419,7 +421,7 @@ function ensureInstances(): { store: SlackHookStore; manager: HookControlManager// 侧据此渲染权限档下拉(选中值经 dispatch options.permissionMode 回流)listAgentModels: async () => {const providers = await getDesktopProviderService().listProviders({ allowSideEffects: true });- return (['claude-code', 'codex'] as const).map((agentKind) => {+ return getMaker().listAvailableAgents().map((agentKind) => {const models = visibleModelUnion(providers, agentKind, (providerId, m) =>isModelVisible(getModelVisibilityOverride(agentKind, providerId, m.id),diff --git a/apps/desktop/src/main/hook-control/turnObserver.ts b/apps/desktop/src/main/hook-control/turnObserver.tsindex 80a9e0c3cb..5c7b87fb77 100644--- a/apps/desktop/src/main/hook-control/turnObserver.ts+++ b/apps/desktop/src/main/hook-control/turnObserver.ts@@ -236,14 +236,14 @@ export function observeHookTurn(// (renderer 同款 raw concat), 不同消息之间空行分隔。// ② claude result 兜底 fallbackTail(刻意不带 agentMeta):// 只含 UI 缺的尾段, 与已流增量原样接上。- // ③ codex item.completed: 该条全文, 覆盖已流增量。+ // ③ codex item.completed / pi message_end:该条全文,覆盖已流增量。// ④ 未知 source: 保守用前缀启发式。const src = (ev as { source?: string }).source;const meta = (ev as { agentMeta?: { uuid?: unknown } }).agentMeta;const claudeTail = src === 'claude-code' && meta === undefined;const segment = claudeTail? streamTail + data.text- : src === 'claude-code' || src === 'codex'+ : src === 'claude-code' || src === 'codex' || src === 'pi'? data.text: data.text.startsWith(streamTail)? data.textdiff --git a/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts b/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.tsindex fc067fbc9c..5b97ddb223 100644--- a/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts+++ b/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts@@ -102,6 +102,21 @@ describe('im default settings store', () => {expect(persisted.agents).toBeDefined();});+ it('persists a Pi-specific default instead of dropping it from sparse overrides', () => {+ writeImDefaultSettingsPatch({+ agents: {+ pi: { providerId: 'openai', model: 'chatgpt/gpt-5.6', effort: 'high' },+ },+ });++ const persisted = JSON.parse(fs.readFileSync(settingsFile(), 'utf-8'));+ expect(persisted.global.agents.pi).toEqual({+ providerId: 'openai',+ model: 'chatgpt/gpt-5.6',+ effort: 'high',+ });+ });+it('preserves existing agent overrides when another agent is updated', () => {writeImDefaultSettingsPatch({agents: {diff --git a/apps/desktop/src/main/im/defaultSettingsStore.ts b/apps/desktop/src/main/im/defaultSettingsStore.tsindex 623c4e8037..6384c7decc 100644--- a/apps/desktop/src/main/im/defaultSettingsStore.ts+++ b/apps/desktop/src/main/im/defaultSettingsStore.ts@@ -319,7 +319,7 @@ function settingsOverrides(overrides.permissionMode = value.permissionMode;}const agents: Partial<Record<ImDefaultAgentKind, ImDefaultAgentSettings>> = {};- for (const agentKind of ['claude-code', 'codex'] as const) {+ for (const agentKind of ['claude-code', 'codex', 'pi'] as const) {if (!agentSettingsEqual(value.agents[agentKind], defaults.agents[agentKind])) {agents[agentKind] = value.agents[agentKind];}@@ -332,7 +332,7 @@ function settingsCustomizedKeys(value: ImDefaultSettings, defaults: ImDefaultSetconst keys: string[] = [];if (value.agentKind !== defaults.agentKind) keys.push('agentKind');if (value.permissionMode !== defaults.permissionMode) keys.push('permissionMode');- for (const agentKind of ['claude-code', 'codex'] as const) {+ for (const agentKind of ['claude-code', 'codex', 'pi'] as const) {if (!agentSettingsEqual(value.agents[agentKind], defaults.agents[agentKind])) {keys.push(`agents.${agentKind}`);}diff --git a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.tsindex 9fd3ad2a47..7f765817ee 100644--- a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts@@ -104,6 +104,18 @@ describe('orcaTeamStore', () => {});});+ it('preserves Pi worker identity in Orca projections', async () => {+ const { listWorkersByLead } = await import('../orcaTeamStore.js');+ const client = createTestDbClient();+ setCurrentDbClient(client, 'test-user');++ await seedOrcaWorkers(client);+ const workers = await listWorkersByLead('lead-session-1');++ expect(workers.find((worker) => worker.sessionId === 'worker-session-2')?.session.agentKind)+ .toBe('pi');+ });+it('executes worker status CAS updates and only rolls back idle acknowledgements', async () => {const { markWorkerIdleIfStatus, restoreWorkerDoneIfIdle } = await import('../orcaTeamStore.js');const client = createTestDbClient();@@ -232,7 +244,7 @@ async function seedOrcaWorkers(client: DbClient): Promise<void> {);await client.exec('INSERT INTO sessions (id, title, agent_kind, orca_role, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)',- ['worker-session-2', 'Worker 2', 'codex', 'worker', now, now],+ ['worker-session-2', 'Worker 2', 'pi', 'worker', now, now],);await client.exec('INSERT INTO orca_teams (id, lead_session_id, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',diff --git a/apps/desktop/src/main/localDb/orcaTeamStore.ts b/apps/desktop/src/main/localDb/orcaTeamStore.tsindex d86edccfd2..58f957472d 100644--- a/apps/desktop/src/main/localDb/orcaTeamStore.ts+++ b/apps/desktop/src/main/localDb/orcaTeamStore.ts@@ -13,7 +13,7 @@ const log = createLogger('orca-team-store');export type OrcaRole = 'lead' | 'worker';export type OrcaTeamStatus = 'active' | 'completed' | 'cancelled' | 'failed';-export type MakerAgentKind = 'claude-code' | 'codex';+export type MakerAgentKind = 'claude-code' | 'codex' | 'pi';// Worker 状态枚举与 "占用槽位" 判定下沉到 renderer-safe 模块,// 让 main (本文件) 与 renderer (useWorkers) 共享同一份算法, 避免 F6 那种@@ -597,7 +597,7 @@ function workerToRecord(}function fromDbAgentKind(agentKind: string): MakerAgentKind {- return agentKind === 'codex' ? 'codex' : 'claude-code';+ return agentKind === 'codex' || agentKind === 'pi' ? agentKind : 'claude-code';}function msToIso(ms: number | null | undefined): string | null {diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.tsindex 5a7f9da45a..634adcfb42 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts@@ -54,6 +54,10 @@ import {resetClaudeSessionRouteRegistryForTest,} from '../claude-session-route-registry';import { setProviderOAuthTokenReader } from '../provider-route';+import {+ registerPiProxySession,+ resetPiProxySessionsForTest,+} from '../pi-proxy-session-auth';const SESSION_HEADER = { 'x-claude-code-session-id': 'sdk-grok' };@@ -155,6 +159,7 @@ describe('pi routingTransform — xdt session header selects the Pi provider rouafterEach(() => {clearSessionProvider('sess-pi');setProviderOAuthTokenReader(() => null);+ resetPiProxySessionsForTest();});it('routes an Anthropic Pi request with host-managed OAuth and strips Pi placeholder auth', async () => {@@ -163,10 +168,12 @@ describe('pi routingTransform — xdt session header selects the Pi provider rousetProviderOAuthTokenReader((providerId, agent) =>providerId === 'anthropic' && agent === 'pi' ? Promise.resolve('pi-claude-token') : null,);+ registerPiProxySession('sess-pi', 'session-secret');const decision = createModelRoutingTransform()({ model: 'claude-opus-5' },ctxWith({'x-cindy-pi-session-id': 'sess-pi',+ 'x-cindy-pi-session-token': 'session-secret','x-api-key': 'cindy-pi-provider-auth-placeholder',}),);@@ -177,7 +184,45 @@ describe('pi routingTransform — xdt session header selects the Pi provider rou'anthropic-beta': 'oauth-2025-04-20',authorization: 'Bearer pi-claude-token',},- headerDelete: ['x-api-key'],+ headerDelete: [+ 'x-api-key',+ 'x-cindy-pi-session-id',+ 'x-cindy-pi-session-token',+ ],+ });+ });++ it('rejects a forged session id before provider credentials can be selected', async () => {+ setSessionProvider('sess-pi', 'anthropic');+ registerPiProxySession('sess-pi', 'real-secret');+ const decision = await createModelRoutingTransform()(+ { model: 'claude-opus-5' },+ ctxWith({+ 'x-cindy-pi-session-id': 'sess-pi',+ 'x-cindy-pi-session-token': 'wrong-secret',+ }),+ );+ expect(decision).toEqual({ localHandler: expect.any(Function) });++ const response = {+ status: 0,+ body: '',+ writeHead(status: number) { this.status = status; },+ end(body: string) { this.body = body; },+ };+ await decision?.localHandler?.({ res: response } as never);+ expect(response.status).toBe(401);+ expect(response.body).toContain('invalid_pi_session_token');+ });++ it('never forwards an orphaned internal Pi token header', async () => {+ const decision = createModelRoutingTransform()(+ { model: 'claude-opus-5' },+ ctxWith({ 'x-cindy-pi-session-token': 'orphaned-secret' }),+ );+ expect(decision).toMatchObject({+ headerDelete: ['x-cindy-pi-session-id', 'x-cindy-pi-session-token'],});+ expect(decision?.headerOverride).not.toHaveProperty('x-cindy-pi-session-token');});});diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.tsindex 3bb146259a..4a02e3e736 100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts@@ -101,21 +101,29 @@ describe('buildPiNativeProvidersFromConfigs', () => {expect(skips).toContain('oauthp');});- it('ignores configs without a pi runtime; passes headers + models through', () => {- const { providers } = buildPiNativeProvidersFromConfigs(+ it('ignores configs without a pi runtime; keeps custom header values out of models.json specs', () => {+ const { providers, env } = buildPiNativeProvidersFromConfigs([{ id: 'codexonly', name: 'C', runtimes: {} },{id: 'withhdr',name: 'H',auth: { method: 'none' },- runtimes: { pi: piRuntime({ headers: { 'x-org': 'acme' }, models: [{ id: 'm1', name: 'M1', contextWindow: 8000 }] }) },+ runtimes: {+ pi: piRuntime({+ headers: { 'x-org': 'acme', authorization: 'Bearer header-secret' },+ models: [{ id: 'm1', name: 'M1', contextWindow: 8000 }],+ }),+ },},],() => null,);expect(providers.map((p) => p.id)).toEqual(['withhdr']);- expect(providers[0].headers).toEqual({ 'x-org': 'acme' });+ expect(providers[0].headers?.['x-org']).toMatch(/^\$CINDY_PI_KEY_/);+ expect(providers[0].headers?.authorization).toMatch(/^\$CINDY_PI_KEY_/);+ expect(Object.values(providers[0].headers ?? {})).not.toContain('Bearer header-secret');+ expect(Object.values(env)).toEqual(expect.arrayContaining(['acme', 'Bearer header-secret']));expect(providers[0].models[0]).toMatchObject({ id: 'm1', name: 'M1', contextWindow: 8000 });});});diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.tsindex b9d2b4bdf8..ee9f1bb6fb 100644--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts@@ -35,6 +35,7 @@ import {stripNonAnthropicFields,stripToolUseProviderSpecificFields,type ProxyHandle,+ type RoutingDecision,type RoutingTransform,} from '@cindy/anthropic-compat-proxy';@@ -84,6 +85,7 @@ import {createClaudeSessionActivityResponseObserver,recordClaudeApiActivity,} from './claude-session-background-activity.js';+import { authenticatePiProxySession } from './pi-proxy-session-auth.js';// scope = 'cc-proxy' → logger.ts 的 emit() 路由把这条流量并入统一 agent 流// (agent-*.ndjson, source=proxy)。child(sub) 会继续保持 'cc-proxy/sub' 前缀, routing 一致。@@ -154,13 +156,41 @@ function headerValue(headers: Readonly<Record<string, string>>, name: string): s* chip 用全局活性状态重算会与 child 真实路由发散。export 仅供单测。*/export function createModelRoutingTransform(): RoutingTransform {- return (body, ctx) => {- const piSessionId = headerValue(ctx.headers, 'x-cindy-pi-session-id');+ const route: RoutingTransform = (body, ctx) => {+ const claimedPiSessionId = headerValue(ctx.headers, 'x-cindy-pi-session-id');+ if (+ claimedPiSessionId+ && !authenticatePiProxySession(+ claimedPiSessionId,+ headerValue(ctx.headers, 'x-cindy-pi-session-token'),+ )+ ) {+ // Loopback is not an authentication boundary: another local process can+ // forge a business session id. Reject before provider routing so it can+ // never borrow that session's OAuth token or gateway key.+ return {+ localHandler: async ({ res }) => {+ const payload = JSON.stringify({+ type: 'error',+ error: {+ type: 'authentication_error',+ code: 'invalid_pi_session_token',+ message: 'Invalid or expired Pi proxy session token.',+ },+ });+ res.writeHead(401, {+ 'content-type': 'application/json; charset=utf-8',+ 'cache-control': 'no-store',+ });+ res.end(payload);+ },+ };+ }+ const piSessionId = claimedPiSessionId;const requestAgent = piSessionId ? 'pi' : 'claude-code';// 后台活动检测(claude-session-background-activity):凡带 cc 会话标头的请求- // 都记一笔活动时刻。注意 routingTransform 只在 JSON POST 上被调用(server.ts- // 按 content-type 门控),GET / 非 JSON 请求不经过这里 —— 它们由响应侧的- // createClaudeSessionActivityResponseObserver 覆盖(观察器对所有响应生效)。+ // 都记一笔活动时刻。routingTransform 会处理无 body 控制面请求与 JSON 请求;+ // 非 JSON 的 POST/PUT/PATCH 不经过这里,由响应侧 observer 兜底观察活动。// 开销 = 一次 header 读 + 一次活跃会话表反解 + Map.set,非 per-token 路径。const sdkSessionId = ctx.headers['x-claude-code-session-id'];const ccSessionId = sdkSessionId && _resolveCcSessionId@@ -285,6 +315,31 @@ export function createModelRoutingTransform(): RoutingTransform {}return null;};+ return (body, ctx) => {+ const decision = route(body, ctx);+ const hasInternalPiHeader =+ headerValue(ctx.headers, 'x-cindy-pi-session-id') !== null+ || headerValue(ctx.headers, 'x-cindy-pi-session-token') !== null;+ if (!hasInternalPiHeader) return decision;+ const stripInternalPiHeaders = (+ resolved: RoutingDecision | null,+ ): RoutingDecision | null => {+ if (resolved?.localHandler) return resolved;+ return {+ ...(resolved ?? {}),+ headerDelete: [+ ...new Set([+ ...(resolved?.headerDelete ?? []),+ 'x-cindy-pi-session-id',+ 'x-cindy-pi-session-token',+ ]),+ ],+ };+ };+ return decision instanceof Promise+ ? decision.then(stripInternalPiHeaders)+ : stripInternalPiHeaders(decision);+ };}/**diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex 1ac4d47966..21eea2cfec 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -39,6 +39,7 @@ import hostSystemPrompt from './host-system-prompt.md?raw';import piSystemPrompt from './pi-system-prompt.md?raw';import { createLogger } from '../logger.js';import { readMemorySettings } from './memory-settings-store.js';+import { registerPiProxySession } from './pi-proxy-session-auth.js';const log = createLogger('pi-host');@@ -233,7 +234,8 @@ export function piNativeKeyEnvVar(providerId: string): string {* - 无 pi runtime → 跳过;* - oauth 形态 → 跳过(pi models.json 仅支持 radius oauth,不通用);* - apiKey 形态但读不到 key → 跳过(pi 无 key 不显示该模型,避免半可用);- * - none(keyless,本机 Ollama 等)→ apiKeyEnvVar 留空,models.json 写 dummy key。+ * - none(keyless,本机 Ollama 等)→ apiKeyEnvVar 留空,models.json 写 dummy key;+ * - 自定义 header 值全部搬进子进程 env,models.json 只保留 `$ENV` 引用。* 直连用户端点,不过 anthropic-compat 代理(设计原则:pi 主导,禁双重转义)。*/export function buildPiNativeProvidersFromConfigs(@@ -291,13 +293,22 @@ export function buildPiNativeProvidersFromConfigs(apiKeyEnvVar = uniqueEnvVar(cfg.id);env[apiKeyEnvVar] = key;}+ const headers = rt.headers+ ? Object.fromEntries(+ Object.entries(rt.headers).map(([name, value]) => {+ const envVar = uniqueEnvVar(`${cfg.id}_HEADER_${name}`);+ env[envVar] = value;+ return [name, `$${envVar}`];+ }),+ )+ : undefined;providers.push({id: cfg.id,name: cfg.name,baseUrl: rt.baseUrl,api: wireProtocolToPiApi(rt.wireProtocol),apiKeyEnvVar,- ...(rt.headers && Object.keys(rt.headers).length > 0 ? { headers: rt.headers } : {}),+ ...(headers && Object.keys(headers).length > 0 ? { headers } : {}),models: rt.models.map((m) => ({ id: m.id, name: m.name, contextWindow: m.contextWindow })),});}@@ -339,6 +350,7 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {makerMemory: opts.makerMemory,resolvePiAgentHome: () => path.join(app.getPath('userData'), 'pi-agent-home'),preparePiExtraSpawnConfig: (providers, ctx) => getPiExtraSpawnConfig(providers, opts.logger, ctx),+ registerPiProxySession,resolvePiNativeProviders: () => resolvePiNativeProviders(),});}diff --git a/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts b/apps/desktop/src/main/maker-host/pi-proxy-session-auth.tsnew file mode 100644index 0000000000..6ef57baf6c--- /dev/null+++ b/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts@@ -0,0 +1,34 @@+/**+ * Per-session authentication for Pi requests entering the shared loopback+ * Anthropic compatibility proxy.+ *+ * A business session id is routing metadata, not a credential. Pi receives a+ * separate random token through its child-process environment; only the exact+ * active `(sessionId, token)` pair may select host-managed provider secrets.+ */++import { timingSafeEqual } from 'node:crypto';++const activeTokens = new Map<string, string>();++export function registerPiProxySession(sessionId: string, token: string): () => void {+ if (!sessionId || !token) throw new Error('Pi proxy session registration requires an id and token');+ activeTokens.set(sessionId, token);+ return () => {+ if (activeTokens.get(sessionId) === token) activeTokens.delete(sessionId);+ };+}++export function authenticatePiProxySession(sessionId: string, candidate: string | null): boolean {+ const expected = activeTokens.get(sessionId);+ if (!expected || !candidate) return false;+ const expectedBytes = Buffer.from(expected);+ const candidateBytes = Buffer.from(candidate);+ return expectedBytes.length === candidateBytes.length+ && timingSafeEqual(expectedBytes, candidateBytes);+}++/** Test isolation only. */+export function resetPiProxySessionsForTest(): void {+ activeTokens.clear();+}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.tsindex c93b3e5d73..ecb378a3c3 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts@@ -25,6 +25,17 @@ describe('maker auth IPC handlers', () => {expect(getAgentAuthState).toHaveBeenCalledWith('codex');});+ it('accepts Pi at the auth IPC boundary exposed by preload', async () => {+ const harness = new IpcHarness();+ const getAgentAuthState = vi.fn().mockResolvedValue({ authenticated: true });+ registerMakerAuthHandlers(harness, createMakerStub({ getAgentAuthState }), vi.fn(), () => null);++ await expect(harness.invoke(MAKER_INVOKE.AUTH_GET_STATE, 'pi')).resolves.toEqual({+ authenticated: true,+ });+ expect(getAgentAuthState).toHaveBeenCalledWith('pi');+ });+it('normalizes login progress and broadcasts final auth state', async () => {const harness = new IpcHarness();const broadcast = vi.fn();diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.tsindex ef0a8bf4b7..5900885e80 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts@@ -676,6 +676,30 @@ describe('provider:custom:* CRUD handlers', () => {expect(deps.broadcastChanged).toHaveBeenCalledOnce();});+ it('accepts and stages a Pi-native runtime key', async () => {+ mountDb();+ const harness = new IpcHarness();+ const storeCustomProviderKey = vi.fn(() => true);+ registerProviderHandlers(harness, makeDeps({ storeCustomProviderKey }));+ const config: CustomProviderConfig = {+ id: 'pi-native',+ name: 'Pi Native',+ auth: { method: 'apiKey' },+ runtimes: {+ pi: {+ baseUrl: 'https://pi-native.example/v1',+ wireProtocol: 'openai-chat',+ models: [{ id: 'native-model', name: 'Native Model' }],+ },+ },+ };++ await expect(+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config, { pi: 'pi-secret' }),+ ).resolves.toEqual({ ok: true });+ expect(storeCustomProviderKey).toHaveBeenCalledWith('pi-native', 'pi', 'pi-secret');+ });+it('rolls back partial create keys before any provider config is committed', async () => {mountDb();const harness = new IpcHarness();@@ -1410,6 +1434,28 @@ describe('provider:test-connection handler', () => {});});+ it('accepts a Pi-native connection probe', async () => {+ const harness = new IpcHarness();+ const testConnection = vi.fn(async () => ({ ok: true as const, latencyMs: 2 }));+ registerProviderHandlers(harness, makeDeps({ testConnection }));++ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_TEST_CONNECTION, {+ kind: 'adhoc',+ spec: {+ agent: 'pi',+ wireProtocol: 'openai-chat',+ baseUrl: 'https://pi.example/v1',+ modelId: 'pi-model',+ authMethod: 'apiKey',+ apiKey: 'k',+ },+ })).resolves.toMatchObject({ ok: true });+ expect(testConnection).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'adhoc',+ spec: expect.objectContaining({ agent: 'pi', wireProtocol: 'openai-chat' }),+ }));+ });+it('rejects remote no-auth adhoc probes before invoking the network dependency', async () => {const harness = new IpcHarness();const deps = makeDeps();diff --git a/apps/desktop/src/main/maker-ipc/authHandlers.ts b/apps/desktop/src/main/maker-ipc/authHandlers.tsindex 89f894e746..6f1212387d 100644--- a/apps/desktop/src/main/maker-ipc/authHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/authHandlers.ts@@ -18,7 +18,7 @@ const log = createLogger('maker-ipc:authHandlers');export type MakerIpcBroadcast = (channel: string, payload: unknown) => void;/** IPC 允许的 agent 种类;运行时枚举校验不能靠 TypeScript 强转替代。 */-const AGENT_KINDS = ['claude-code', 'codex'] as const satisfies readonly AgentKind[];+const AGENT_KINDS = ['claude-code', 'codex', 'pi'] as const satisfies readonly AgentKind[];const AGENT_LOGIN_MODES = ['browser', 'device-code'] as const satisfies readonly AgentLoginMode[];const MAX_LOGIN_PROGRESS_CHARS = 16_384;const LOGIN_OWNER_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;diff --git a/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.ts b/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.tsindex cb003ebaf2..d2ec4026b2 100644--- a/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.ts+++ b/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.ts@@ -238,7 +238,7 @@ export class PendingCredentialSwitchService {if (!resolveRoute) return { providerId: target.providerId, apply: true };try {if (!target.agentKind) {- for (const agent of ['claude-code', 'codex'] as AgentKind[]) {+ for (const agent of ['claude-code', 'codex', 'pi'] as AgentKind[]) {const resolved = await resolveRoute(agent, target.model, target.providerId);if (resolved.model !== target.model ||diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.tsindex 2d6bf4384b..42b2a95ed5 100644--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts@@ -57,7 +57,7 @@ import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';const log = createLogger('maker-ipc:provider');-const VALID_AGENTS: readonly string[] = ['claude-code', 'codex'];+const VALID_AGENTS: readonly string[] = ['claude-code', 'codex', 'pi'];const VALID_ADHOC_AUTH_METHODS: readonly string[] = ['apiKey', 'oauth', 'none'];const PROVIDER_OAUTH_OWNER_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;type RuntimeKeys = Partial<Record<AgentKind, string>>;diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsxindex ca682aa02a..b50257fe99 100644--- a/apps/desktop/src/renderer/App.tsx+++ b/apps/desktop/src/renderer/App.tsx@@ -31,6 +31,7 @@ import { installSystemNetworkErrorToastListener } from '@/lib/systemNetworkErrorimport { installSilentInstallToastListener } from '@/lib/silentInstallToast';import { installProviderUpstreamErrorToastListener } from '@/lib/providerUpstreamErrorToast';import { installAutoPermissionFallbackToastListener } from '@/lib/autoPermissionFallbackToast';+import { agentKindToVendor } from '@/components/sidebar/VendorIcon';import { installCcMgrUpgradeListener } from '@/state/ccMgrUpgradeStore';import {preloadLocalCatalogSnapshot,@@ -184,7 +185,7 @@ export function App() {useEffect(() => {const offDraft = window.electronAPI.onMakerDraftPrefApply(({ agent, providerId, modelId, active, effort, fast, markModelChoice }) => {- const vendor = agent === 'claude-code' ? 'cc' : 'codex';+ const vendor = agentKindToVendor(agent);if (active) {const patch = markModelChoice === false ? patchVendorPrefsPreservingModelChoice : patchVendorPrefs;const shouldPatchActiveModel = markModelChoice !== false || effort !== undefined;diff --git a/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts b/apps/desktop/src/renderer/__tests__/newMakerDraft.test.tsindex 19b1d1ddc4..11d19fe777 100644--- a/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts@@ -55,6 +55,7 @@ describe('newMakerDraft store', () => {expect(d.lastByVendor.cc.model.length).toBeGreaterThan(0);expect(d.lastByVendor.codex.permissionMode).toBe('auto');expect(d.lastByVendor.codex.effort).toBe('high');+ expect(d.lastByVendor.pi.permissionMode).toBe('auto');// 种子模型不再写死在 store 里(原先是 'gpt-5.4',与 modelDefinitions 写死的 'gpt-5.5'// 漂移,且两者在目录里都是默认隐藏的模型)。现在统一从 getDefaultModelForVendor 取,// capabilities 未加载时它给冷启动占位 id —— 这里只锁「非空且与那个入口同源」。@@ -67,6 +68,15 @@ describe('newMakerDraft store', () => {expect(d.worktreePreferenceCustomized).toBe(false);});+ it('persists an explicit Pi model choice across reload', async () => {+ const m1 = await loadModule();+ m1.patchVendorPrefs('pi', { model: 'chatgpt/gpt-5.6' });+ vi.resetModules();+ const m2 = await loadModule();+ expect(m2.getDraft().modelChosenByVendor.pi).toBe(true);+ expect(m2.getPersistedVendorModel('pi')).toBe('chatgpt/gpt-5.6');+ });+it('Effort 按模型记忆:get/set + 同值短路 + 持久化', async () => {const m1 = await loadModule();expect(m1.getEffortForModel('claude-opus-4-7')).toBeUndefined();diff --git a/apps/desktop/src/renderer/state/newMakerDraft.ts b/apps/desktop/src/renderer/state/newMakerDraft.tsindex 17a77afed5..debc66c601 100644--- a/apps/desktop/src/renderer/state/newMakerDraft.ts+++ b/apps/desktop/src/renderer/state/newMakerDraft.ts@@ -163,8 +163,8 @@ function defaultVendorPrefs(vendor: MakerVendor): VendorPrefs {// 目录未含该 id 时由 ChatInput 的 vendor 回退逻辑纠正。model: 'claude-sonnet-5',effort: 'high',- // pi 当前 capabilities 仅暴露完全访问档(ask 档随 cindy-bridge extension 上线)。- permissionMode: 'bypassPermissions',+ // 新 Pi 草稿默认走 Auto Review;完全访问只能由用户显式选择并持久化。+ permissionMode: 'auto',planMode: false,providerId: null,};@@ -341,7 +341,7 @@ function sanitize(raw: unknown): NewMakerDraft {? (r.modelChosenByVendor as Record<string, unknown>): {};const modelChosenByVendor: Partial<Record<MakerVendor, boolean>> = {};- for (const v of ['cc', 'orca', 'codex'] as const) {+ for (const v of ['cc', 'orca', 'codex', 'pi'] as const) {if (modelChosenRaw[v] === true) modelChosenByVendor[v] = true;}// 2026-07 已落盘但尚无显式标记的 true,只可能来自用户把当时默认 false 切到 true,diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 2a8c9ecb13..4fcffa37af 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -286,6 +286,13 @@ export interface AgentDeps {ctx?: PiExtraSpawnConfigContext,) => Promise<PiExtraSpawnConfig | null>;+ /**+ * Pi-only: authenticate a child process to the host's loopback model proxy.+ * PiAgent creates a high-entropy token per session, registers it before spawn,+ * and disposes the exact registration when startup fails or the session closes.+ */+ registerPiProxySession?: (sessionId: string, token: string) => (() => void) | void;+/*** BYOM:host 解析出当前会话可用的 pi **原生 provider**(用户自定义/本地模型)+ 需注入的* env(api keys)。PiAgent 把这些写进 models.json 的独立 provider 块(直连用户端点,不过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 117acda312..56cbd36931 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@@ -19,6 +19,7 @@ const captured = vi.hoisted(() => ({env: {} as Record<string, string | undefined>,onEvent: null as ((event: unknown) => void) | null,sent: [] as Array<Record<string, unknown>>,+ proxyRegistration: null as { sessionId: string; token: string } | null,}));vi.mock('../rpc-client.js', () => ({@@ -70,6 +71,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {captured.env = {};captured.onEvent = null;captured.sent = [];+ captured.proxyRegistration = null;agentHome = mkdtempSync(path.join(tmpdir(), 'pi-dispatch-home-'));cwd = mkdtempSync(path.join(tmpdir(), 'pi-dispatch-cwd-'));savedNoProxy = process.env.NO_PROXY;@@ -110,6 +112,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {],},resolvePiAgentHome: () => agentHome,+ registerPiProxySession: (sessionId, token) => {+ captured.proxyRegistration = { sessionId, token };+ },reviewAutoPermissionAction,};}@@ -147,6 +152,11 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {expect(captured.args[idx + 1]).toBe('You are Cindy.');expect(captured.env.PI_OFFLINE).toBe('1');expect(captured.env.PI_CACHE_RETENTION).toBe('long');+ expect(captured.proxyRegistration).toEqual({+ sessionId: 's1',+ token: captured.env.CINDY_PI_SESSION_TOKEN,+ });+ expect(captured.env.CINDY_PI_SESSION_TOKEN).toMatch(/^[A-Za-z0-9_-]{40,}$/);const noProxy = (captured.env.NO_PROXY ?? '').split(',');for (const entry of ['corp.internal', '127.0.0.1', 'localhost', '::1']) {expect(noProxy).toContain(entry);@@ -158,11 +168,21 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {await start();const { readFileSync } = await import('node:fs');const config = JSON.parse(readFileSync(path.join(agentHome, 'models.json'), 'utf8')) as {- providers: { cindy: { models: Array<{ id: string; maxTokens: number; cost: Record<string, number> }> } };+ providers: {+ cindy: {+ headers: Record<string, string>;+ models: Array<{ id: string; maxTokens: number; cost: Record<string, number> }>;+ };+ };};const m = config.providers.cindy.models.find((x) => x.id === 'm');expect(m?.maxTokens).toBe(64_000);expect(m?.cost).toEqual({ input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 });+ expect(config.providers.cindy.headers).toEqual({+ 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',+ 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',+ });+ expect(JSON.stringify(config)).not.toContain(captured.env.CINDY_PI_SESSION_TOKEN);});it('auto mode silently approves in-workspace writes without consulting the resolver', async () => {@@ -186,7 +206,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {resolverCalls++;return { kind: 'permission', behavior: 'deny' } as never;});- await handle.send({ role: 'user', content: 'Update the system hosts mapping for this test.' });+ await handle.send({ type: 'user', content: 'Update the system hosts mapping for this test.' });firePermissionRequest('r2', 'write', { path: '/etc/hosts' });await flush();expect(review).toHaveBeenCalledWith(expect.objectContaining({@@ -202,7 +222,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {it('auto mode gives the current-model reviewer complete MCP tool evidence', async () => {const review = vi.fn(async () => ({ verdict: 'allow' as const }));const handle = await start('auto', review);- await handle.send({ role: 'user', content: 'Start a review team.' });+ await handle.send({ type: 'user', content: 'Start a review team.' });firePermissionRequest('r3', 'mcp__cindy_orca__start_team', {});await flush();expect(review).toHaveBeenCalledWith(expect.objectContaining({diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.tsindex 648084a745..25f1083c87 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.ts@@ -60,6 +60,17 @@ describe('classifyPiToolForAutoReview', () => {expect(verdict('grep', { path: '/proc/999/task/1000/environ' })).toBe('prompt-each-time');});+ it.each([+ '/Users/t/.azure/accessTokens.json',+ '/Users/t/.git-credentials',+ '/Users/t/.cargo/credentials.toml',+ '/Users/t/.m2/settings.xml',+ '/Users/t/.config/gh/hosts.yml',+ '/Users/t/.config/containers/auth.json',+ ])('keeps Pi readonly access behind approval for canonical credential path %s', (credentialPath) => {+ expect(verdict('read', { path: credentialPath })).toBe('prompt-each-time');+ });+it('recurses into array / nested-object inputs for credential paths', () => {expect(verdict('read', { paths: ['/tmp/ok.txt', '/Users/t/.ssh/id_rsa'] })).toBe('prompt-each-time');expect(verdict('grep', { opts: { path: '/Users/t/.aws/credentials' } })).toBe('prompt-each-time');diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.tsindex 1ff21355cf..c1dab0882d 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts@@ -56,12 +56,14 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {let agentHome = '';let cwd = '';let disposed = 0;+ let proxyDisposed = 0;beforeEach(() => {knobs.ctorThrows = false;knobs.getStateRejects = false;knobs.closeCount = 0;disposed = 0;+ proxyDisposed = 0;agentHome = mkdtempSync(path.join(tmpdir(), 'pi-cleanup-home-'));cwd = mkdtempSync(path.join(tmpdir(), 'pi-cleanup-cwd-'));});@@ -89,6 +91,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {],},resolvePiAgentHome: () => agentHome,+ registerPiProxySession: () => () => { proxyDisposed++; },// 注册身份并回传 disposeSessionCtx 探针(servers 空,无需真桥)。preparePiExtraSpawnConfig: async () => ({mcpBridge: { token: 'itest', servers: [] },@@ -104,6 +107,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {const agent = new PiAgent(buildDeps());await expect(agent.startSession(opts())).rejects.toThrow(/spawn failed/);expect(disposed).toBe(1);+ expect(proxyDisposed).toBe(1);expect(knobs.closeCount).toBe(0); // 构造失败没有 proc 可关});@@ -112,6 +116,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {const agent = new PiAgent(buildDeps());await expect(agent.startSession(opts())).rejects.toThrow(/get_state rejected/);expect(disposed).toBe(1);+ expect(proxyDisposed).toBe(1);expect(knobs.closeCount).toBe(1); // 已 spawn → 必须关掉,避免僵尸持有 ?session= 路由});@@ -119,7 +124,9 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {const agent = new PiAgent(buildDeps());const handle = await agent.startSession(opts());expect(disposed).toBe(0);+ expect(proxyDisposed).toBe(0);await handle.close();expect(disposed).toBe(1); // close() 才注销+ expect(proxyDisposed).toBe(1);});});diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex e95d801445..e8dd1713ec 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -23,6 +23,8 @@* 更新方式:PiAgent 每次 startSession 覆写该文件;改这里 = 改下次会话的桥行为。*/+import { SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS } from '../shared/sensitive-credential-paths.js';+export const CINDY_BRIDGE_EXTENSION_FILENAME = 'cindy-bridge.ts';export const CINDY_BRIDGE_EXTENSION_SOURCE = String.raw`/**@@ -35,18 +37,10 @@ const PERMISSION_TITLE = 'cindy:permission';const READONLY_BUILTINS = new Set(['read', 'grep', 'find', 'ls']);const FILE_WRITE_BUILTINS = new Set(['edit', 'write']);-// 凭证/密钥路径特征 —— 与 maker-core shared/auto-review.ts 的 CREDENTIAL_PATH_PATTERNS-// 保持同步(bridge 自包含,不能 import;改那边记得改这边)。只读工具入参命中即不再-// 直通,升级走 Cindy 审批:读 ~/.ssh、~/.aws 等即使是"只读"也是侦察面。-const CREDENTIAL_PATH_PATTERNS = [- /(?:^|[\\/\s'"~])\.(?:ssh|aws|gnupg|kube|docker|claude|codex)\b/i,- /(?:^|[\\/\s'"~])\.(?:netrc|npmrc|pgpass|pypirc)\b/i,- /\bapplication_default_credentials\b/i,- /\bcredentials\.json\b/i,- /[\\/](?:codex|claude|gcloud)[\\/]auth\.json\b/i,- /\/proc\/[^\s]*\/environ\b/i, // /proc/self/environ、/proc/<pid>/environ、/proc/<pid>/task/<tid>/environ- /\bid_rsa\b|\bid_ed25519\b|\bid_ecdsa\b|\bid_dsa\b|\.pem\b|\.p12\b/i,-];+// 凭证/密钥路径特征由 maker-core 的单一来源生成。bridge 自包含、运行时不能 import,+// 但不再维护第二份手写名单,避免新增凭证目录时 Pi 静默漏拦。+const CREDENTIAL_PATH_PATTERNS = ${JSON.stringify(SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS)}+ .map(({ source, flags }) => new RegExp(source, flags));// 递归扫全部字符串叶子(含数组 / 嵌套对象),深度上限防环/超大入参。工具入参把路径// 放进 { paths: [...] } 或 { opts: { path } } 时也能命中,不止顶层 string 字段。diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 3bb085458b..038ba93db0 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -22,6 +22,7 @@import os from 'node:os';import path from 'node:path';import { promises as fs } from 'node:fs';+import { randomBytes } from 'node:crypto';import {AgentNotAuthenticatedError,@@ -86,6 +87,7 @@ import {const PI_PROVIDER_ID = 'cindy';const PI_API_KEY_ENV = 'CINDY_PI_API_KEY';const PI_SESSION_ID_ENV = 'CINDY_PI_SESSION_ID';+const PI_SESSION_TOKEN_ENV = 'CINDY_PI_SESSION_TOKEN';/** 手动压缩 = 一次完整 LLM 摘要调用(大上下文 + 网关排队),远超默认 30s RPC 超时。 */const PI_COMPACT_TIMEOUT_MS = 600_000;/** 分支摘要同样可能触发一次完整 LLM 调用。 */@@ -360,6 +362,7 @@ export class PiAgent extends BaseAgent {apiKey: `$${PI_API_KEY_ENV}`,headers: {'x-cindy-pi-session-id': `$${PI_SESSION_ID_ENV}`,+ 'x-cindy-pi-session-token': `$${PI_SESSION_TOKEN_ENV}`,},models,},@@ -618,13 +621,31 @@ export class PiAgent extends BaseAgent {// preparePiExtraSpawnConfig 注册、但 handle 尚未交出,close() 不会跑 → 单独// 兜底注销 ctx 再抛(构造失败没有 proc 可关)。catch 必抛,故其后 proc 恒已赋值。let proc: PiRpcProcess;+ const proxySessionToken = randomBytes(32).toString('base64url');+ let disposeProxySession: (() => void) | undefined;+ const disposeSessionRegistrations = (): void => {+ let firstError: unknown;+ for (const dispose of [disposeProxySession, disposeSessionCtx]) {+ try {+ dispose?.();+ } catch (error) {+ firstError ??= error;+ }+ }+ if (firstError) throw firstError;+ };try {+ if (opts.sessionId && this.deps.registerPiProxySession) {+ const disposer = this.deps.registerPiProxySession(opts.sessionId, proxySessionToken);+ if (typeof disposer === 'function') disposeProxySession = disposer;+ }const spawnEnv: NodeJS.ProcessEnv = {...process.env,...authEnv,// BYOM 原生 provider 的 api keys(键名对应 spec.apiKeyEnvVar,models.json 用 $ENV 引用)。...nativeEnv,[PI_SESSION_ID_ENV]: opts.sessionId ?? '',+ [PI_SESSION_TOKEN_ENV]: proxySessionToken,PI_CODING_AGENT_DIR: agentHome,CINDY_PI_PERMISSION_FILE: permissionFile,// 嵌入式 runtime 不做启动期联网:关掉 pi 的版本检查与安装遥测@@ -680,7 +701,7 @@ export class PiAgent extends BaseAgent {});} catch (err) {try {- disposeSessionCtx?.();+ disposeSessionRegistrations();} catch {/* best-effort:注销失败不掩盖原始构造错误 */}@@ -794,7 +815,7 @@ export class PiAgent extends BaseAgent {}} catch (err) {try {- disposeSessionCtx?.();+ disposeSessionRegistrations();} catch {/* best-effort:注销失败不掩盖原始启动错误 */}@@ -853,9 +874,9 @@ export class PiAgent extends BaseAgent {// 先注销 bridge 身份注册(幂等),再关子进程。放前面:即便 proc.close 抛错// 也不泄漏 ctx —— 该 sessionId 的 `?session=` 路由必须随会话结束失效。try {- disposeSessionCtx?.();+ disposeSessionRegistrations();} catch (err) {- deps.logger.warn('pi disposeSessionCtx failed (non-fatal)', {+ deps.logger.warn('pi dispose session registration failed (non-fatal)', {message: err instanceof Error ? err.message : String(err),});}diff --git a/packages/maker-core/src/agents/shared/auto-review.ts b/packages/maker-core/src/agents/shared/auto-review.tsindex 17db4662cd..8271498e26 100644--- a/packages/maker-core/src/agents/shared/auto-review.ts+++ b/packages/maker-core/src/agents/shared/auto-review.ts@@ -37,6 +37,13 @@* - **DNS 重绑定 / 符号链接**:见 isInternalFetchTarget / isInsideWorkspace 各自注释;属网络出口过滤 / fs.realpath 层。*/+import {+ isSensitiveCredentialPath,+ SENSITIVE_CREDENTIAL_PATH_PATTERNS,+} from './sensitive-credential-paths.js';++export { isSensitiveCredentialPath } from './sensitive-credential-paths.js';+export type ReviewVerdict = 'auto-approve' | 'prompt' | 'prompt-each-time';/**@@ -136,24 +143,6 @@ const COMMAND_WRAPPERS: ReadonlySet<string> = new Set([// 前缀类含反斜杠 `\\`:Windows 路径(C:\Users\me\.ssh\id_rsa)的分隔符是 `\`。全部大小写不敏感(`i`):// Windows FS 大小写不敏感,`.AWS` 等同 `.aws`;Linux 上少量混合大小写误升级也是 fail-closed 方向。// 与 apps/desktop/src/main/filePathPolicy.ts 的 CREDENTIAL_HOME_DIRS/FILES 保持一致(codex 报的缺口)。-const CREDENTIAL_PATH_PATTERNS: readonly RegExp[] = [- /(?:^|[\\/\s'"~])\.(?:ssh|aws|gnupg|kube|docker|azure|claude|codex)\b/i, // 凭证/密钥 + 云/agent 配置目录(含 OAuth 凭证)- /(?:^|[\\/\s'"~])\.(?:netrc|npmrc|pgpass|pypirc|git-credentials)\b/i, // 含 token 的凭证配置文件- /[\\/]\.cargo[\\/]credentials(?:\.toml)?\b/i, // cargo registry 凭证(新旧命名)- /[\\/]\.m2[\\/]settings(?:-security)?\.xml\b/i, // Maven settings(可含 server 密码)- /\bapplication_default_credentials\b/i, // gcloud 默认凭证文件- /\bcredentials\.json\b/i, // Claude 等的 OAuth 凭证文件(.credentials.json)- /[\\/](?:codex|claude|gcloud|containers)[\\/]auth\.json\b/i, // agent/registry 认证文件(~/.config/codex|containers/auth.json 等)- /[\\/]\.config[\\/](?:gh|hub|glab|op|gcloud)\b/i, // GitHub/GitLab/Op/gcloud CLI 的 OAuth/Token 凭证目录(~/.config/gh/hosts.yml、~/.config/gcloud/credentials.db 等)- /\/proc\/[^\s]*\/environ\b/i, // procfs 环境变量(/proc/self/environ、/proc/<pid>/environ、/proc/<pid>/task/<tid>/environ 都 dump 含凭证的环境)- /\bid_rsa\b|\bid_ed25519\b|\bid_ecdsa\b|\bid_dsa\b|\.pem\b|\.p12\b/i, // 私钥文件-];--/** 路径是否触碰已知凭证/密钥位置(shell 命令与内置 Read 工具共用同一判定)。 */-export function isSensitiveCredentialPath(target: string): boolean {- return typeof target === 'string' && CREDENTIAL_PATH_PATTERNS.some((re) => re.test(target));-}-/*** 无法由主 Agent 换安全做法绕开的高影响同意边界。命中才 `prompt-each-time`:* 提权 / 系统与磁盘控制 / 凭证访问 / fork bomb / 全局权限放宽。@@ -166,7 +155,7 @@ const ALWAYS_ASK_PATTERNS: readonly RegExp[] = [/:\s*\(\s*\)\s*\{.*\|.*&.*\}/, // fork bomb :(){ :|:& };:/\bchmod\b[^|;&]*\s(?:-R\s+)?[0-7]*7{2,3}\b/, // chmod 777 之类数字放宽权限/\bchmod\b[^|;&]*\s[ugoa]*[oa][ugoa]*[-+=][^\s]*w/, // chmod 符号型对 other/all 开放写(a+w / o+w / a+rwx)- ...CREDENTIAL_PATH_PATTERNS, // 凭证/密钥路径(见上)+ ...SENSITIVE_CREDENTIAL_PATH_PATTERNS, // 凭证/密钥路径(见上)/\bsecurity\s+(?:find|dump|export|add)-/, // macOS keychain/\$\{?[A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|APIKEY|_PAT)[A-Za-z0-9_]*\}?/i, // 敏感环境变量展开(echo "$API_KEY" 等)];diff --git a/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts b/packages/maker-core/src/agents/shared/sensitive-credential-paths.tsnew file mode 100644index 0000000000..e83412691d--- /dev/null+++ b/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts@@ -0,0 +1,27 @@+/**+ * Credential-bearing path patterns shared by every harness permission adapter.+ *+ * Keep the serializable `{ source, flags }` form as the source of truth: the Pi+ * bridge runs in a standalone child process and embeds these specs into its+ * generated extension instead of maintaining a second handwritten regex list.+ */+export const SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS = [+ { source: String.raw`(?:^|[\\/\s'"~])\.(?:ssh|aws|gnupg|kube|docker|azure|claude|codex)\b`, flags: 'i' },+ { source: String.raw`(?:^|[\\/\s'"~])\.(?:netrc|npmrc|pgpass|pypirc|git-credentials)\b`, flags: 'i' },+ { source: String.raw`[\\/]\.cargo[\\/]credentials(?:\.toml)?\b`, flags: 'i' },+ { source: String.raw`[\\/]\.m2[\\/]settings(?:-security)?\.xml\b`, flags: 'i' },+ { source: String.raw`\bapplication_default_credentials\b`, flags: 'i' },+ { source: String.raw`\bcredentials\.json\b`, flags: 'i' },+ { source: String.raw`[\\/](?:codex|claude|gcloud|containers)[\\/]auth\.json\b`, flags: 'i' },+ { source: String.raw`[\\/]\.config[\\/](?:gh|hub|glab|op|gcloud)\b`, flags: 'i' },+ { source: String.raw`/proc/[^\s]*/environ\b`, flags: 'i' },+ { source: String.raw`\bid_rsa\b|\bid_ed25519\b|\bid_ecdsa\b|\bid_dsa\b|\.pem\b|\.p12\b`, flags: 'i' },+] as const;++export const SENSITIVE_CREDENTIAL_PATH_PATTERNS: readonly RegExp[] =+ SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS.map(({ source, flags }) => new RegExp(source, flags));++export function isSensitiveCredentialPath(target: string): boolean {+ return typeof target === 'string'+ && SENSITIVE_CREDENTIAL_PATH_PATTERNS.some((pattern) => pattern.test(target));+}diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex 16146baf5f..4ebb15ea8e 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -64,6 +64,21 @@ function createLogger() {return logger;}+describe('Maker agent status', () => {+ it('represents an optional unregistered runtime as binary-missing', async () => {+ const maker = new Maker({+ agents: {},+ storage: createStorage(),+ logger: createLogger(),+ });+ await expect(maker.getAgentStatus('pi')).resolves.toEqual({+ binaryReady: false,+ binaryPath: null,+ authReady: false,+ });+ });+});+function createAgent(startSession: (opts: CreateSessionOptions) => Promise<unknown>,kind: AgentKind = 'codex',diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.tsindex 1d12c65d9d..edc3970273 100644--- a/packages/maker-core/src/maker.ts+++ b/packages/maker-core/src/maker.ts@@ -741,17 +741,23 @@ export class Maker {* Agent 联合状态查询 (binary 是否就绪 + 是否登录)。* 老 codex:binary:status 的功能等价物, 现在跨 agent 统一。*- * binaryReady: maker-core 构造期已校验 binaryPath 非空, 这里返回 true 即可- * (host 真正在 splash 阶段做下载, 走到这里时 binary 必然 ready)。+ * binaryReady: 已注册 agent 由其 binaryPath 判定;平台不支持或 provision 尚未完成的+ * optional runtime 不注册 agent,并在这里明确返回 false。* authReady / identity: 走 deps.auth.getState()。*/async getAgentStatus(agentKind: AgentKind): Promise<{binaryReady: boolean;- binaryPath: string;+ binaryPath: string | null;authReady: boolean;identity?: string;}> {- const agent = this.requireAgent(agentKind);+ const agent = this.agents[agentKind];+ // Optional runtimes (currently Pi on unsupported/unprepared platforms) are+ // intentionally not registered. Status is the one discovery API that must+ // represent that state instead of throwing and hiding it as an auth error.+ if (!agent) {+ return { binaryReady: false, binaryPath: null, authReady: false };+ }const auth = await agent.getAuthState();return {binaryReady: !!agent.getBinaryPath(),