Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): reuse native subscription websocket context
xuzini-xznbd5235b2a85d
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.tsindex 6510018325..0724abf812 100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts@@ -114,6 +114,9 @@ it('materializes a separate native ChatGPT provider for each independent accountexpect(account.inheritModels).toBe(false);expect(account.api).toBe('openai-codex-responses');expect(account.headers).toMatchObject({ 'x-cindy-pi-provider-id': 'openai-second' });+ expect(account.apiKeyEnvVar).not.toBe(builtin.apiKeyEnvVar);+ const placeholderAccount = (envKey: string) => JSON.parse(Buffer.from(result.env[envKey]!.split('.')[1], 'base64url').toString())['https://api.openai.com/auth'].chatgpt_account_id;+ expect(placeholderAccount(account.apiKeyEnvVar!)).not.toBe(placeholderAccount(builtin.apiKeyEnvVar!));expect(account.models.length).toBeGreaterThan(0);expect(account.models.every((model) => model.api === 'openai-codex-responses')).toBe(true);expect(account.models.map((model) => model.id)).toEqual(builtin.models.map((model) => model.id));diff --git a/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.e2e.test.ts b/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.e2e.test.tsnew file mode 100644index 0000000000..2c6ab7cee0--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.e2e.test.ts@@ -0,0 +1,203 @@+import { spawn } from 'node:child_process';+import { randomBytes } from 'node:crypto';+import { once } from 'node:events';+import { existsSync } from 'node:fs';+import { mkdtemp, writeFile, rm } from 'node:fs/promises';+import { createServer } from 'node:http';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { zstdDecompressSync } from 'node:zlib';+import { WebSocketServer } from 'ws';+import sharp from 'sharp';+import { beforeAll, describe, expect, it, vi } from 'vitest';+import { createAnthropicCompatProxy } from '@cindy/anthropic-compat-proxy';+import { PI_NATIVE_PROVIDER_ADAPTER_SOURCE } from '../../../../../../packages/maker-core/src/agents/pi/native-provider-adapter-source.js';+import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../../../../../../packages/maker-core/src/agents/pi/cindy-bridge-source.js';++vi.mock('../../appSessionState.js', () => ({ activeOwnerScopeKey: () => 'fixture-owner', isAppSessionBoundaryPending: () => false }));+vi.mock('../codex-account-auth.js', () => ({ isOpenAiSubscriptionProviderId: (id: string) => id === 'openai' || id === 'account-b' }));+vi.mock('../session-provider-store.js', () => ({ getSessionProvider: () => null, hasHostedSessionModelAccess: () => false }));+vi.mock('../guest-provider-route-store.js', () => ({ guestProviderRouteForSession: () => null }));+vi.mock('../anthropic-responses-bridge-host.js', () => ({ getChatgptBridgeAuthForDispatch: vi.fn() }));+import { createPiWebSocketRequestPreparer, resolvePiWebSocketUpstream } from '../pi-subscription-websocket.js';+import { registerPiProxySession } from '../pi-proxy-session-auth.js';++const binary = process.env.CINDY_TEST_PI_BINARY ?? resolve('../../apps/pi-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'pi.exe' : 'pi');+const fastHookStart = CINDY_BRIDGE_EXTENSION_SOURCE.indexOf('async function nativeFastPayload(');+const fastHookEnd = CINDY_BRIDGE_EXTENSION_SOURCE.indexOf('type CindyAdapterAlias', fastHookStart);+if (fastHookStart < 0 || fastHookEnd <= fastHookStart) throw new Error('Production Fast hook fixture is unavailable');+const fastHookSource = CINDY_BRIDGE_EXTENSION_SOURCE.slice(fastHookStart, fastHookEnd);+let image: string;++function responseEvents(index: number, tool: boolean) {+ const item = tool+ ? { type: 'function_call', id: `fc_${index}`, call_id: `call_${index}`, name: 'fixture_probe', arguments: '{}', status: 'completed' }+ : { type: 'message', id: `msg_${index}`, role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'fixture-complete', annotations: [], logprobs: [] }] };+ const response = { id: `resp_${index}`, status: 'completed', output: [item], model: 'gpt-6-astra',+ usage: { input_tokens: 100, input_tokens_details: { cached_tokens: index ? 90 : 0 }, output_tokens: 5, output_tokens_details: { reasoning_tokens: 0 }, total_tokens: 105 } };+ return [+ { type: 'response.created', response: { ...response, status: 'in_progress', output: [], usage: null } },+ { type: 'response.output_item.added', output_index: 0, item: { ...item, ...(tool ? { arguments: '' } : { content: [] }) } },+ ...(tool+ ? [{ type: 'response.function_call_arguments.delta', output_index: 0, delta: '{}' }, { type: 'response.function_call_arguments.done', output_index: 0, arguments: '{}' }]+ : [{ type: 'response.content_part.added', output_index: 0, content_index: 0, part: { type: 'output_text', text: '', annotations: [] } },+ { type: 'response.output_text.delta', output_index: 0, content_index: 0, delta: 'fixture-complete' },+ { type: 'response.output_text.done', output_index: 0, content_index: 0, text: 'fixture-complete' }]),+ { type: 'response.output_item.done', output_index: 0, item },+ { type: 'response.completed', response },+ ];+}++describe.skipIf(!existsSync(binary))('actual Pi subscription incremental transport', () => {+ beforeAll(async () => {+ image = (await sharp(randomBytes(512 * 512 * 3), { raw: { width: 512, height: 512, channels: 3 } }).png().toBuffer()).toString('base64');+ });+ it.each([+ { label: 'standard', source: 'openai', provider: 'openai-codex', fast: false, fallback: false, reconnect: false },+ { label: 'fast and context profile', source: 'openai', provider: 'openai-codex', fast: true, fallback: false, reconnect: false },+ { label: 'independent account', source: 'account-b', provider: 'openai-codex-account', fast: false, fallback: false, reconnect: false },+ { label: 'reconnect', source: 'openai', provider: 'openai-codex', fast: false, fallback: false, reconnect: true },+ { label: 'native SSE fallback', source: 'openai', provider: 'openai-codex', fast: false, fallback: true, reconnect: false },+ { label: 'original SSE baseline', source: 'openai', provider: 'openai-codex', fast: false, fallback: false, reconnect: false, baseline: true },+ { label: 'live Fast change', source: 'openai', provider: 'openai-codex', fast: false, fallback: false, reconnect: false, toggleFast: true },+ { label: 'missing continuation', source: 'openai', provider: 'openai-codex', fast: false, fallback: false, reconnect: false, missingContinuation: true },+ ])('preserves tool/image history and native recovery: $label', async scenario => {+ const directory = await mkdtemp(join(tmpdir(), 'cindy-pi-ws-'));+ const requests: Array<Record<string, any>> = [];+ const handshakes: Array<Record<string, any>> = [];+ const ws = new WebSocketServer({ noServer: true });+ let acknowledgeDisconnect!: () => void;+ const disconnected = new Promise<void>(resolve => { acknowledgeDisconnect = resolve; });+ const upstream = createServer((_req, res) => { void disconnected.then(() => res.end('closed')); });+ let connections = 0;+ let continuationRejected = false;+ upstream.on('upgrade', (req, socket, head) => {+ handshakes.push({ ...req.headers });+ if (scenario.fallback) { socket.end('HTTP/1.1 426 Upgrade Required\r\nConnection: close\r\n\r\n'); return; }+ connections++;+ ws.handleUpgrade(req, socket, head, client => {+ client.once('close', acknowledgeDisconnect);+ client.on('message', async raw => {+ const body = JSON.parse(raw.toString());+ const index = requests.length - (continuationRejected ? 1 : 0);+ requests.push(body);+ if (scenario.missingContinuation && index === 2 && !continuationRejected) {+ continuationRejected = true;+ client.send(JSON.stringify({ type: 'error', code: 'previous_response_not_found', message: 'Fixture continuation expired' }));+ return;+ }+ if (scenario.toggleFast && index === 0) await writeFile(join(directory, 'options.json'), JSON.stringify({ fast: true }));+ for (const event of responseEvents(index, index < 3)) client.send(JSON.stringify(event));+ if (scenario.reconnect && index === 1) client.close();+ });+ });+ });+ await new Promise<void>(resolve => upstream.listen(0, '127.0.0.1', resolve));+ const upstreamUrl = `http://127.0.0.1:${(upstream.address() as import('node:net').AddressInfo).port}`;+ const closeAuth = registerPiProxySession('fixture-session', 'fixture-token', () => scenario.source);+ const prepare = createPiWebSocketRequestPreparer(async () => ({ accessToken: 'fixture-upstream-token', accountId: 'fixture-upstream-account', canDispatch: () => true }));+ const proxy = await createAnthropicCompatProxy({+ upstream: upstreamUrl, transformRequest: [],+ resolveWebSocketUpstream: ctx => resolvePiWebSocketUpstream(ctx) ? upstreamUrl : null,+ prepareWebSocketRequest: prepare,+ routingTransform: () => ({ localHandler: async ({ rawBody, parsedBody, ctx, res }) => {+ const index = requests.length;+ const decoded = parsedBody ?? JSON.parse((ctx.headers['content-encoding'] === 'zstd' ? zstdDecompressSync(rawBody) : rawBody).toString());+ requests.push({ ...decoded, fallback: true });+ res.writeHead(200, { 'content-type': 'text/event-stream' });+ for (const event of responseEvents(index, index < 3)) res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);+ res.end();+ } }),+ });+ let child: ReturnType<typeof spawn> | undefined;+ try {+ const model = scenario.fast ? 'gpt-6-astra[1m]' : 'gpt-6-astra';+ const key = `fixture.${Buffer.from(JSON.stringify({ 'https://api.openai.com/auth': { chatgpt_account_id: 'child-placeholder' } })).toString('base64url')}.fixture`;+ await writeFile(join(directory, 'models.json'), JSON.stringify({ providers: { [scenario.provider]: {+ baseUrl: proxy.url, api: 'openai-codex-responses', apiKey: '$CINDY_FIXTURE_KEY',+ headers: { 'x-cindy-pi-session-id': 'fixture-session', 'x-cindy-pi-session-token': 'fixture-token', 'x-cindy-pi-provider-id': scenario.source },+ models: [{ id: model, name: 'Fixture', api: 'openai-codex-responses', contextWindow: 2_000_000, maxTokens: 4096, input: ['text', 'image'], reasoning: false,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],+ } } }));+ await writeFile(join(directory, 'auth.json'), '{}');+ await writeFile(join(directory, 'options.json'), JSON.stringify({ fast: scenario.fast }));+ // Keep the global setting at SSE: only the production subscription adapter may override it.+ await writeFile(join(directory, 'settings.json'), JSON.stringify({ transport: 'sse', retry: { enabled: false } }));+ await writeFile(join(directory, 'adapter.ts'), PI_NATIVE_PROVIDER_ADAPTER_SOURCE + '\n' + fastHookSource + `+import { Type } from '@earendil-works/pi-ai';+import { readFileSync } from 'node:fs';+export default async function(pi: any) {+ await registerCindyNativeProviderAdapters(pi);+ if (!${Boolean(scenario.baseline)}) pi.on('before_provider_request', (event, ctx) => nativeFastPayload(event.payload, ctx.model, {+ ui: { input: async () => JSON.stringify(JSON.parse(readFileSync(process.env.CINDY_FIXTURE_OPTIONS_FILE, 'utf8'))) },+ }));+ let count = 0;+ pi.registerTool({ name: 'fixture_probe', label: 'Fixture', description: 'Fixture probe', parameters: Type.Object({}),+ execute: async () => {+ ++count;+ if (${scenario.reconnect} && count === 2) await fetch('${upstreamUrl}/wait-for-disconnect');+ return { content: count === 1+ ? [{ type: 'image', data: '${image}', mimeType: 'image/png' }]+ : [{ type: 'text', text: 'fixture-tool-ok' }], details: {} };+ } });+}+`);+ // Supply the large initial history through a file rather than exceeding argv limits.+ await writeFile(join(directory, 'prompt.txt'), 'Run the fixture tool.\n' + 'fixture-context '.repeat(65_536));+ child = spawn(binary, ['--print', '--mode', 'json', '--no-session', '--no-extensions', '--extension', join(directory, 'adapter.ts'),+ '--provider', scenario.provider, '--model', model, `@${join(directory, 'prompt.txt')}`], {+ cwd: directory, env: { ...process.env, HOME: directory, PI_CODING_AGENT_DIR: directory, PI_OFFLINE: '1',+ CINDY_FIXTURE_KEY: key, CINDY_FIXTURE_OPTIONS_FILE: join(directory, 'options.json'),+ CINDY_PI_FAST_MODELS: JSON.stringify([{ provider: scenario.provider, id: model }]),+ CINDY_PI_NATIVE_PROVIDER_ADAPTERS: JSON.stringify([{ id: scenario.provider, provider: scenario.provider, cachedCodex: !scenario.baseline, keyEnv: 'CINDY_FIXTURE_KEY' }]),+ }, stdio: ['ignore', 'pipe', 'pipe'],+ });+ let output = ''; let errors = '';+ child.stdout!.on('data', chunk => { output += chunk; });+ child.stderr!.on('data', chunk => { errors += chunk; });+ const timer = setTimeout(() => child?.kill(), 20_000);+ const [exit] = await once(child, 'exit'); clearTimeout(timer);+ expect(exit, errors + output.slice(-3000)).toBe(0);+ expect(output).toContain('fixture-complete');+ expect(requests).toHaveLength(scenario.missingContinuation ? 5 : 4);+ if (scenario.baseline) {+ expect(handshakes).toHaveLength(0);+ expect(requests.every(body => body.fallback && !body.previous_response_id && JSON.stringify(body).length > 900_000)).toBe(true);+ expect(JSON.stringify(requests[3].input)).toContain('data:image/png;base64,');+ } else if (scenario.fallback) {+ expect(requests.every(body => body.fallback)).toBe(true);+ } else {+ expect(requests.every((body, index) => body.model === 'gpt-6-astra' && body.service_tier === (scenario.fast || (scenario.toggleFast && index > 0) ? 'priority' : undefined))).toBe(true);+ expect(JSON.stringify(requests[0]).length).toBeGreaterThan(900_000);+ expect(JSON.stringify(requests[1].input)).toContain('data:image/png;base64,');+ expect(requests[1].previous_response_id).toBe(scenario.toggleFast ? undefined : 'resp_0');+ const last = requests.at(-1)!;+ expect(last.previous_response_id).toBe('resp_2');+ expect(JSON.stringify(last).length).toBeLessThan(20_000);+ expect(JSON.stringify(last.input)).not.toContain('data:image/png;base64,');+ if (scenario.reconnect) {+ expect(connections).toBe(2);+ expect(requests[2].previous_response_id).toBeUndefined();+ expect(JSON.stringify(requests[2].input)).toContain('data:image/png;base64,');+ } else if (scenario.missingContinuation) {+ expect(requests[2].previous_response_id).toBe('resp_1');+ expect(requests[3].previous_response_id).toBeUndefined();+ expect(JSON.stringify(requests[3].input)).toContain('data:image/png;base64,');+ } else {+ expect(connections).toBe(1);+ expect(requests[2].previous_response_id).toBe('resp_1');+ expect(JSON.stringify(requests[2].input)).not.toContain('data:image/png;base64,');+ }+ }+ if (!scenario.baseline) {+ expect(handshakes[0]).toMatchObject({ authorization: 'Bearer fixture-upstream-token', 'chatgpt-account-id': 'fixture-upstream-account' });+ expect(Object.keys(handshakes[0]).some(key => key.startsWith('x-cindy-'))).toBe(false);+ }+ } finally {+ child?.kill(); closeAuth(); await proxy.dispose();+ for (const client of ws.clients) client.terminate(); ws.close();+ upstream.closeAllConnections(); await new Promise<void>(resolve => upstream.close(() => resolve()));+ await rm(directory, { recursive: true, force: true });+ }+ }, 30_000);+});diff --git a/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.test.ts b/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.test.tsnew file mode 100644index 0000000000..f94b550c5e--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.test.ts@@ -0,0 +1,104 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({ owner: 'owner-a', pending: false, provider: 'openai' as string | null, guest: false, hosted: false }));+vi.mock('../../appSessionState.js', () => ({ activeOwnerScopeKey: () => state.owner, isAppSessionBoundaryPending: () => state.pending }));+vi.mock('../codex-account-auth.js', () => ({ isOpenAiSubscriptionProviderId: (id: string) => id === 'openai' || id === 'account-b' }));+vi.mock('../session-provider-store.js', () => ({ getSessionProvider: () => state.provider, hasHostedSessionModelAccess: () => state.hosted }));+vi.mock('../guest-provider-route-store.js', () => ({ guestProviderRouteForSession: () => state.guest ? {} : null }));+vi.mock('../anthropic-responses-bridge-host.js', () => ({ getChatgptBridgeAuthForDispatch: vi.fn() }));++import { createPiWebSocketRequestPreparer, resolvePiWebSocketUpstream } from '../pi-subscription-websocket.js';+import { registerPiProxySession, resetPiProxySessionsForTest } from '../pi-proxy-session-auth.js';++const context = (provider = 'openai', token = 'fixture-token') => ({ url: '/codex/responses', headers: {+ 'x-cindy-pi-session-id': 'fixture-session', 'x-cindy-pi-session-token': token,+ 'x-cindy-pi-provider-id': provider, authorization: 'Bearer child-placeholder',+ 'chatgpt-account-id': 'child-placeholder', session_id: 'native-session',+ 'sec-websocket-key': 'fixture-handshake', 'sec-websocket-version': '13',+ 'openai-beta': 'responses_websockets=2026-02-06',+} });++describe('Pi subscription WebSocket routing', () => {+ beforeEach(() => {+ resetPiProxySessionsForTest();+ state.owner = 'owner-a'; state.pending = false; state.provider = 'openai';+ state.guest = false; state.hosted = false;+ });++ it('keeps hosted and shared-provider routes on HTTP for live per-model authorization', () => {+ registerPiProxySession('fixture-session', 'fixture-token', () => 'openai');+ state.guest = true; expect(resolvePiWebSocketUpstream(context())).toBeNull();+ state.guest = false; state.hosted = true; expect(resolvePiWebSocketUpstream(context())).toBeNull();+ });++ it('rejects forged, wrong-provider, expired, non-subscription and wrong-path requests', () => {+ expect(resolvePiWebSocketUpstream(context())).toBeNull();+ const close = registerPiProxySession('fixture-session', 'fixture-token', () => 'openai');+ expect(resolvePiWebSocketUpstream(context())).toBe('https://chatgpt.com/backend-api');+ expect(resolvePiWebSocketUpstream(context('openai', 'forged'))).toBeNull();+ expect(resolvePiWebSocketUpstream(context('account-b'))).toBeNull();+ expect(resolvePiWebSocketUpstream(context('xai'))).toBeNull();+ expect(resolvePiWebSocketUpstream({ ...context(), url: '/messages' })).toBeNull();+ state.provider = 'account-b'; expect(resolvePiWebSocketUpstream(context())).toBeNull();+ state.provider = 'openai'; state.pending = true; expect(resolvePiWebSocketUpstream(context())).toBeNull();+ state.pending = false; close(); expect(resolvePiWebSocketUpstream(context())).toBeNull();+ });++ it('injects the selected account, preserves the native session and strips local secrets', async () => {+ state.provider = 'account-b';+ const close = registerPiProxySession('fixture-session', 'fixture-token', () => 'account-b');+ const read = vi.fn(async () => ({ accessToken: 'fixture-upstream-token', accountId: 'fixture-upstream-account', canDispatch: () => true }));+ const prepared = await createPiWebSocketRequestPreparer(read)(context('account-b'));+ expect(read).toHaveBeenCalledWith('account-b');+ expect(prepared.headers).toMatchObject({ authorization: 'Bearer fixture-upstream-token',+ 'chatgpt-account-id': 'fixture-upstream-account', session_id: 'native-session',+ 'openai-beta': 'responses_websockets=2026-02-06', 'sec-websocket-key': 'fixture-handshake' });+ expect(Object.keys(prepared.headers).some(key => key.startsWith('x-cindy-'))).toBe(false);+ expect(prepared.signal.aborted).toBe(false);+ close(); expect(prepared.signal.aborted).toBe(true);+ });++ it('rejects revoked or replaced native OAuth proof during establishment and socket reuse', async () => {+ registerPiProxySession('fixture-session', 'fixture-token', () => 'openai');+ let connected = true;+ const prepare = createPiWebSocketRequestPreparer(async () => ({ accessToken: 'fixture-token', accountId: null, canDispatch: () => connected }));+ const prepared = await prepare(context());+ expect(prepared.authorize?.()).toBe(true);+ connected = false;+ expect(prepared.authorize?.()).toBe(false);+ await expect(prepare(context())).rejects.toThrow('PI_WEBSOCKET_ROUTE_CHANGED');+ });++ it.each(['owner', 'pending', 'provider', 'guest', 'hosted'])('rejects %s changes on an already established socket', async kind => {+ registerPiProxySession('fixture-session', 'fixture-token', () => 'openai');+ const prepared = await createPiWebSocketRequestPreparer(async () => ({ accessToken: 'fixture-token', accountId: null, canDispatch: () => true }))(context());+ expect(prepared.authorize?.()).toBe(true);+ if (kind === 'owner') state.owner = 'owner-b';+ if (kind === 'pending') state.pending = true;+ if (kind === 'provider') state.provider = 'account-b';+ if (kind === 'guest') state.guest = true;+ if (kind === 'hosted') state.hosted = true;+ expect(prepared.authorize?.()).toBe(false);+ });++ it.each(['owner', 'pending', 'provider', 'revoked', 'replaced'])('revalidates %s changes while authentication is pending', async kind => {+ const close = registerPiProxySession('fixture-session', 'fixture-token', () => 'openai');+ const read = vi.fn(async () => {+ if (kind === 'owner') state.owner = 'owner-b';+ if (kind === 'pending') state.pending = true;+ if (kind === 'provider') state.provider = 'account-b';+ if (kind === 'revoked') close();+ if (kind === 'replaced') registerPiProxySession('fixture-session', 'fixture-token', () => 'openai');+ return { accessToken: 'fixture-token', accountId: null, canDispatch: () => true };+ });+ await expect(createPiWebSocketRequestPreparer(read)(context())).rejects.toThrow('PI_WEBSOCKET_ROUTE_CHANGED');+ });++ it('keeps provider-scoped children independent of the parent route and token lifetime', async () => {+ const closeParent = registerPiProxySession('fixture-session', 'parent-token', () => 'openai');+ registerPiProxySession('fixture-session', 'fixture-token', () => 'account-b', { scope: 'subagent-route' });+ const prepared = await createPiWebSocketRequestPreparer(async () => ({ accessToken: 'fixture-token', accountId: null, canDispatch: () => true }))(context('account-b'));+ closeParent(); expect(prepared.signal.aborted).toBe(false);+ expect(resolvePiWebSocketUpstream(context('account-b'))).toBe('https://chatgpt.com/backend-api');+ });+});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 33cada2fd5..efc67fed41 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@@ -53,6 +53,7 @@ import { outboundFetch } from './outbound-fetch.js';import { invocationModelRecord, requiresNativeProviderAuth } from './pi-provider-transport.js';import { createClaudeProviderBridge } from './claude-provider-bridge.js';import { isOpenAiSubscriptionProviderId } from './codex-account-auth.js';+import { createPiWebSocketRequestPreparer, resolvePiWebSocketUpstream } from './pi-subscription-websocket.js';import { isClaudeSubscriptionProviderId, isXaiSubscriptionProviderId } from './subscription-account-auth.js';import {getPiNativeSubscriptionHandler,@@ -1163,6 +1164,8 @@ export async function ensureAnthropicCompatProxyReady(): Promise<void> {// 函数形态:model-access 凭据同步可能在 proxy 启动(splash)后才把 endpoint// 换成下发值;每请求现取才能保证与当前 key 同租户(proxy 内部按值 memoize)。upstream: () => claudeUpstreamEndpoint(),+ resolveWebSocketUpstream: resolvePiWebSocketUpstream,+ prepareWebSocketRequest: createPiWebSocketRequestPreparer(),oversizedRequestRecovery: createAttachmentRecovery(headers => {const piSessionId = headerValue(headers, 'x-cindy-pi-session-id');if (piSessionId) {diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex 418b0ec120..5e30bf6fbc 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -184,11 +184,13 @@ const PI_NATIVE_APIS = new Set<PiNativeApi>([* authenticated loopback proxy replaces it with the real host-owned token and* account id before forwarding upstream.*/-function piOpenaiProxyPlaceholderJwt(): string {+function piOpenaiProxyPlaceholderJwt(providerId = 'openai'): string {const encode = (value: unknown): string =>Buffer.from(JSON.stringify(value)).toString('base64url');return `${encode({ alg: 'none', typ: 'JWT' })}.${encode({- 'https://api.openai.com/auth': { chatgpt_account_id: 'cindy-pi-proxy' },+ // Pi caches sockets by native session + account id, without comparing headers.+ // Separate logical accounts must therefore have separate placeholder identities.+ 'https://api.openai.com/auth': { chatgpt_account_id: providerId === 'openai' ? 'cindy-pi-proxy' : `cindy-pi-proxy:${providerId}` },})}.`;}@@ -727,8 +729,12 @@ export function buildPiSubscriptionNativeProviders(retainedProviderId === account.id ? retainedOpenAiModel : null,).providers.find((provider) => provider.sourceProviderId === brand);if (!projected) continue;+ const openaiKeyEnv = brand === 'openai'+ ? `CINDY_PI_KEY_OPENAI_PROXY_${Buffer.from(account.id).toString('hex').toUpperCase()}` : undefined;+ if (openaiKeyEnv) env[openaiKeyEnv] = piOpenaiProxyPlaceholderJwt(account.id);providers.push({...projected,+ ...(openaiKeyEnv ? { apiKeyEnvVar: openaiKeyEnv } : {}),id: `${brand === 'openai' ? 'openai-codex' : brand}-${account.id}`,sourceProviderId: account.id,name: account.name,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.tsindex 0116e2e1be..0837d70062 100644--- a/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts+++ b/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts@@ -11,6 +11,7 @@ import { timingSafeEqual } from 'node:crypto';interface ActivePiProxySession {token: string;+ controller: AbortController;resolveProviderId: () => string | null;scope: 'session' | 'subagent-route';}@@ -45,15 +46,18 @@ export function registerPiProxySession(throw new Error('Pi proxy session registration requires an id and token');const registration = {token,+ controller: new AbortController(),resolveProviderId,scope: options.scope === 'subagent-route' ? 'subagent-route' as const : 'session' as const,};const registrations = activeSessions.get(sessionId) ?? new Map();+ registrations.get(token)?.controller.abort();registrations.set(token, registration);activeSessions.set(sessionId, registrations);return () => {const current = activeSessions.get(sessionId);if (current?.get(token) !== registration) return;+ registration.controller.abort();current.delete(token);if (current.size === 0) activeSessions.delete(sessionId);};@@ -63,6 +67,11 @@ export function authenticatePiProxySession(sessionId: string, candidate: stringreturn findPiProxySession(sessionId, candidate) !== null;}+/** Lifetime of the exact authenticated runtime, including separately scoped children. */+export function getPiProxySessionSignal(sessionId: string, candidate: string | null): AbortSignal | null {+ return findPiProxySession(sessionId, candidate)?.controller.signal ?? null;+}+/*** Host-resolved provider bound to the authenticated Pi process. Callers must* authenticate the same session immediately before reading this value.@@ -83,5 +92,8 @@ export function isPiProxySubagentRoute(/** Test isolation only. */export function resetPiProxySessionsForTest(): void {+ for (const registrations of activeSessions.values()) {+ for (const registration of registrations.values()) registration.controller.abort();+ }activeSessions.clear();}diff --git a/apps/desktop/src/main/maker-host/pi-subscription-websocket.ts b/apps/desktop/src/main/maker-host/pi-subscription-websocket.tsnew file mode 100644index 0000000000..5ab2da156f--- /dev/null+++ b/apps/desktop/src/main/maker-host/pi-subscription-websocket.ts@@ -0,0 +1,61 @@+import { type ProxyOptions } from '@cindy/anthropic-compat-proxy';+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';+import { getChatgptBridgeAuthForDispatch } from './anthropic-responses-bridge-host.js';+import { isOpenAiSubscriptionProviderId } from './codex-account-auth.js';+import { buildChatgptBridgeHeaders } from './chatgpt-bridge-headers.js';+import {+ authenticatePiProxySession,+ getPiProxySessionProvider,+ getPiProxySessionSignal,+ isPiProxySubagentRoute,+} from './pi-proxy-session-auth.js';+import { getSessionProvider, hasHostedSessionModelAccess } from './session-provider-store.js';+import { guestProviderRouteForSession } from './guest-provider-route-store.js';++type Context = Parameters<NonNullable<ProxyOptions['resolveWebSocketUpstream']>>[0];++function authenticatedRoute({ url, headers }: Context): { sessionId: string; providerId: string; signal: AbortSignal } | null {+ if (url !== '/codex/responses' || isAppSessionBoundaryPending()) return null;+ const sessionId = headers['x-cindy-pi-session-id'];+ const token = headers['x-cindy-pi-session-token'];+ const providerId = headers['x-cindy-pi-provider-id'];+ if (!sessionId || !token || !isOpenAiSubscriptionProviderId(providerId)+ || !authenticatePiProxySession(sessionId, token)+ || getPiProxySessionProvider(sessionId, token) !== providerId) return null;+ // These routes require a live per-model grant check for every request body.+ // A transparent socket tunnel cannot enforce that contract.+ if (guestProviderRouteForSession(sessionId) || hasHostedSessionModelAccess(sessionId)) return null;+ const selectedProvider = getSessionProvider(sessionId);+ if (!isPiProxySubagentRoute(sessionId, token) && selectedProvider !== null && selectedProvider !== providerId) return null;+ const signal = getPiProxySessionSignal(sessionId, token);+ return signal && !signal.aborted ? { sessionId, providerId, signal } : null;+}++/** Only authenticated ChatGPT subscription requests can reach the fixed upstream. */+export const resolvePiWebSocketUpstream: NonNullable<ProxyOptions['resolveWebSocketUpstream']> = (ctx) =>+ authenticatedRoute(ctx) ? 'https://chatgpt.com/backend-api' : null;++export function createPiWebSocketRequestPreparer(+ readAuth: (providerId: string) => ReturnType<typeof getChatgptBridgeAuthForDispatch>+ = providerId => getChatgptBridgeAuthForDispatch(providerId),+): NonNullable<ProxyOptions['prepareWebSocketRequest']> {+ return async (ctx) => {+ const owner = activeOwnerScopeKey();+ const route = authenticatedRoute(ctx);+ if (!route) throw new Error('PI_WEBSOCKET_ROUTE_UNAVAILABLE');+ const auth = await readAuth(route.providerId);+ const current = authenticatedRoute(ctx);+ if (owner !== activeOwnerScopeKey() || !current || route.signal !== current.signal+ || route.providerId !== current.providerId || !auth.canDispatch()) throw new Error('PI_WEBSOCKET_ROUTE_CHANGED');+ const headers = buildChatgptBridgeHeaders({ ...auth, sessionId: ctx.headers.session_id ?? route.sessionId });+ // Preserve negotiated transport metadata, never child credentials or Cindy-only headers.+ for (const name of ['sec-websocket-key', 'sec-websocket-version', 'sec-websocket-protocol', 'sec-websocket-extensions', 'openai-beta']) {+ if (ctx.headers[name]) headers[name] = ctx.headers[name];+ }+ return { headers, signal: route.signal, authorize: () => {+ const live = authenticatedRoute(ctx);+ return auth.canDispatch() && owner === activeOwnerScopeKey() && live?.signal === route.signal+ && live.providerId === route.providerId;+ } };+ };+}diff --git a/packages/anthropic-compat-proxy/src/server-websocket.test.ts b/packages/anthropic-compat-proxy/src/server-websocket.test.tsindex abc63c86ec..8614508ff9 100644--- a/packages/anthropic-compat-proxy/src/server-websocket.test.ts+++ b/packages/anthropic-compat-proxy/src/server-websocket.test.ts@@ -183,6 +183,68 @@ function startUpgradeUpstream(opts: { handshakeDelayMs?: number } = {}): Promise}describe('anthropic-compat-proxy websocket upgrades', () => {+ it('prepares host authentication without forwarding client credentials and revokes live sockets', async () => {+ const upstream = await startUpgradeUpstream();+ const controller = new AbortController();+ proxy = await createAnthropicCompatProxy({+ upstream: 'http://unused.invalid', transformRequest: [],+ resolveWebSocketUpstream: () => upstream.url,+ prepareWebSocketRequest: async ({ headers }) => ({ headers: {+ authorization: 'Bearer fixture-host-token', 'sec-websocket-key': headers['sec-websocket-key'],+ 'sec-websocket-version': headers['sec-websocket-version'],+ }, signal: controller.signal }),+ });+ const client = await openUpgrade(proxy.url, '/codex/responses', Buffer.alloc(0), [+ 'Authorization: Bearer client-placeholder', 'X-Cindy-Pi-Session-Token: fixture-local-secret',+ ]);+ expect(client.head).toContain('101 Switching Protocols');+ expect(upstream.requests[0].url).toBe('/codex/responses');+ expect(upstream.requests[0].headers.authorization).toBe('Bearer fixture-host-token');+ expect(upstream.requests[0].headers['x-cindy-pi-session-token']).toBeUndefined();+ const closed = new Promise<void>(resolve => client.socket.once('close', () => resolve()));+ controller.abort(); await closed;+ expect(client.socket.destroyed).toBe(true);+ });++ it('rechecks live authorization on reused sockets while preserving compression negotiation', async () => {+ const upstream = await startUpgradeUpstream();+ let authorized = true;+ proxy = await createAnthropicCompatProxy({+ upstream: 'http://unused.invalid', transformRequest: [],+ resolveWebSocketUpstream: () => upstream.url,+ prepareWebSocketRequest: async ({ headers }) => ({ headers: { ...headers },+ signal: new AbortController().signal, authorize: () => authorized }),+ });+ const client = await openUpgrade(proxy.url);+ expect(client.head).toContain('permessage-deflate');+ client.socket.write('PING');+ await waitForSocketText(client.socket, client.rest, 'PONG');+ const closed = new Promise<void>(resolve => client.socket.once('close', () => resolve()));+ authorized = false;+ client.socket.write('FORBIDDEN');+ await closed;+ expect(upstream.received.join('')).not.toContain('FORBIDDEN');+ });++ it('does not dispatch when authorization is revoked while preparation is pending', async () => {+ const upstream = await startUpgradeUpstream();+ const controller = new AbortController();+ proxy = await createAnthropicCompatProxy({+ upstream: 'http://unused.invalid', transformRequest: [],+ resolveWebSocketUpstream: () => upstream.url,+ prepareWebSocketRequest: async () => {+ controller.abort(); return { headers: {}, signal: controller.signal };+ },+ });+ const endpoint = new URL(proxy.url);+ const socket = connect(Number(endpoint.port), endpoint.hostname); sockets.add(socket);+ await new Promise<void>((resolve, reject) => {+ socket.once('error', reject); socket.once('close', () => resolve());+ socket.once('connect', () => socket.write(upgradeRequest('/codex/responses', endpoint.host)));+ });+ expect(upstream.requests).toHaveLength(0);+ });+it('forwards the upgrade handshake, strips /v1, and pipes buffered bytes both ways', async () => {const upstream = await startUpgradeUpstream();proxy = await createAnthropicCompatProxy({diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.tsindex b9e30b7899..ba55aee342 100644--- a/packages/anthropic-compat-proxy/src/server.ts+++ b/packages/anthropic-compat-proxy/src/server.ts@@ -19,7 +19,7 @@ import { createHash } from 'node:crypto';import { createServer, request as httpRequest, type ClientRequest, type IncomingMessage, type RequestOptions, type Server, type ServerResponse } from 'node:http';import { request as httpsRequest } from 'node:https';import type { Socket, TcpSocketConnectOpts } from 'node:net';-import { PassThrough, Readable, type Transform } from 'node:stream';+import { PassThrough, Readable, Transform } from 'node:stream';import { URL } from 'node:url';import { brotliDecompressSync, gunzipSync, inflateRawSync, inflateSync } from 'node:zlib';@@ -2872,6 +2872,8 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Prlet upstreamReqForEarlyClose: ClientRequest | null = null;let reconnectTimer: ReturnType<typeof setTimeout> | null = null;let upstreamAttempt = 0;+ let removeAuthorizationListener: (() => void) | undefined;+ let authorizeWebSocket: (() => boolean) | undefined;// bundled Codex 0.145.0 的 startup-prewarm / reconnect 都带稳定 thread-id。// 真正无 scope 的非 Codex / 通用 socket 仍保留空值隔离;不能把泛用的// x-client-request-id 当作稳定 recovery key,误逐出其它 thread 的连接。@@ -2903,6 +2905,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Prconst settle = (why: string, err?: Error): void => {if (settled) return;settled = true;+ removeAuthorizationListener?.();if (reconnectTimer !== null) {clearTimeout(reconnectTimer);reconnectTimer = null;@@ -2987,6 +2990,23 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Prvoid (async () => {const outbound = await resolveOutboundForTarget(target, reqId);if (settled || clientSocket.destroyed) return;+ let outboundHeaders = headers;+ if (opts.prepareWebSocketRequest) {+ const prepared = await opts.prepareWebSocketRequest({ url, headers });+ if (settled || clientSocket.destroyed) return;+ const revoke = (): void => {+ settle('host-authorization-revoked');+ upstreamReqForEarlyClose?.destroy();+ connection.upstreamSocket?.destroy();+ clientSocket.destroy();+ };+ if (prepared.signal.aborted) { revoke(); return; }+ removeAuthorizationListener?.();+ prepared.signal.addEventListener('abort', revoke, { once: true });+ removeAuthorizationListener = () => prepared.signal.removeEventListener('abort', revoke);+ outboundHeaders = prepared.headers;+ authorizeWebSocket = prepared.authorize;+ }let attemptSettled = false;// codex 构造 WS URL 的规则是 `base_url + "/responses"`。宿主给 codex 的 base_url@@ -3019,7 +3039,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Prmethod: req.method ?? 'GET',path: upstreamPath,headers: {- ...headers,+ ...outboundHeaders,host: formatHostHeader(target.hostname, target.port, target.protocol),connection: 'Upgrade',upgrade: 'websocket',@@ -3134,13 +3154,31 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Prguarded.outbound.pipe(upstreamSocket);guarded.inbound.pipe(clientSocket);}+ // Check the live host route even on a reused socket. This gate preserves+ // compressed/fragmented bytes and does not buffer model context.+ const authorizationGate = authorizeWebSocket ? new Transform({+ transform(chunk, _encoding, callback) {+ try {+ if (!authorizeWebSocket!()) { callback(new Error('WEBSOCKET_AUTHORIZATION_CHANGED')); return; }+ callback(null, chunk);+ } catch (error) {+ callback(error instanceof Error ? error : new Error('WEBSOCKET_AUTHORIZATION_CHANGED'));+ }+ },+ }) : undefined;+ if (authorizationGate) {+ authorizationGate.on('error', abort('host-authorization-changed'));+ clientSocket.once('close', () => authorizationGate.destroy());+ authorizationGate.pipe(guarded?.outbound ?? upstreamSocket);+ }+ const outboundStream = authorizationGate ?? guarded?.outbound ?? upstreamSocket;try {if (!locallyAcceptedForReconnect) {clientSocket.write(serializeResponseHead(upstreamRes));}// 双向把握手时已缓冲的首包补上, 再对接。if (upstreamHead?.length) (guarded?.inbound ?? clientSocket).write(upstreamHead);- if (head?.length) (guarded?.outbound ?? upstreamSocket).write(head);+ if (head?.length) outboundStream.write(head);clientSocket.setNoDelay(true);upstreamSocket.setNoDelay(true);@@ -3152,7 +3190,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr}upstreamSocket.pipe(guarded?.inbound ?? clientSocket);- clientSocket.pipe(guarded?.outbound ?? upstreamSocket);+ clientSocket.pipe(outboundStream);if (locallyAcceptedForReconnect) clientSocket.resume();logger.info?.('◀ websocket established', {reqId, status: upstreamRes.statusCode, live: liveWebSockets,diff --git a/packages/anthropic-compat-proxy/src/types.ts b/packages/anthropic-compat-proxy/src/types.tsindex 014bfc0865..cecec96b0a 100644--- a/packages/anthropic-compat-proxy/src/types.ts+++ b/packages/anthropic-compat-proxy/src/types.ts@@ -353,6 +353,17 @@ export interface ProxyOptions {readonly url: string;readonly headers: Readonly<Record<string, string>>;}) => string | null;+ /** Optional host authentication immediately before opening an upstream socket.+ * Replaces outbound headers, preserving only host-approved handshake metadata.+ * The signal revokes pending and established connections with the owning runtime.+ * authorize rechecks mutable route ownership before forwarding each outbound chunk,+ * without decoding frames or changing compression negotiation.+ * Omitted by existing callers, whose forwarding remains unchanged.+ */+ prepareWebSocketRequest?: (ctx: {+ readonly url: string;+ readonly headers: Readonly<Record<string, string>>;+ }) => Promise<{ headers: Record<string, string>; signal: AbortSignal; authorize?: () => boolean }>;/*** 对带稳定 thread id、且此前已真实完成过上游 101 的 WebSocket 重连启用 Cindy 侧保活。* proxy 会先用已证明一致的协商参数接住该条客户端 socket,再以有界退避回探上游;只要diff --git a/packages/lizi-mcps/src/browser/recipe-loader.ts b/packages/lizi-mcps/src/browser/recipe-loader.tsindex 8e3dbfbd79..8a4e988ac3 100644--- a/packages/lizi-mcps/src/browser/recipe-loader.ts+++ b/packages/lizi-mcps/src/browser/recipe-loader.ts@@ -1,3 +1,5 @@+/// <reference path="../vite-env.d.ts" />+/*** Site Recipe + SiteGuide registry.*diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.tsindex ed8863ad5f..f8f04fbb43 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts@@ -2498,7 +2498,7 @@ describe('Pi same-turn library native mapping', () => {});-it('applies native Fast only to the exact declared connection and fails closed on invalid host replies', async () => {+it.each(['openai-responses', 'openai-codex-responses'])('applies native Fast only to the exact declared %s connection and fails closed on invalid host replies', async api => {const start = CINDY_BRIDGE_EXTENSION_SOURCE.indexOf('async function nativeFastPayload(');const end = CINDY_BRIDGE_EXTENSION_SOURCE.indexOf('export default async function cindyBridge');const helpers = ts.transpileModule(CINDY_BRIDGE_EXTENSION_SOURCE.slice(start, end), {@@ -2510,7 +2510,7 @@ it('applies native Fast only to the exact declared connection and fails closed o} });const ctx = { ui: { input: async () => { if (reply instanceof Error) throw reply; return reply; } } };const original = { model: 'gpt-6-sol', reasoning: { effort: 'high' }, input: 'hello' };- const model = { provider: 'relay-a', id: 'gpt-6-sol', api: 'openai-responses' };+ const model = { provider: 'relay-a', id: 'gpt-6-sol', api };expect(await adapt(original, model, ctx)).toEqual({ ...original, service_tier: 'priority' });expect(await adapt(original, { ...model, provider: 'relay-b' }, ctx)).toBeUndefined();expect(await adapt(original, { ...model, id: 'other-model' }, ctx)).toBeUndefined();diff --git a/packages/maker-core/src/agents/pi/__tests__/nativeProviderAdapterAliases.test.ts b/packages/maker-core/src/agents/pi/__tests__/nativeProviderAdapterAliases.test.tsindex 6520f92600..338d412b9b 100644--- a/packages/maker-core/src/agents/pi/__tests__/nativeProviderAdapterAliases.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/nativeProviderAdapterAliases.test.ts@@ -29,4 +29,23 @@ describe('nativeProviderAdapterAliases', () => {expect(PI_NATIVE_PROVIDER_ADAPTER_SOURCE).toContain('pi-native-keyless');expect(PI_NATIVE_PROVIDER_ADAPTER_SOURCE).toContain("options?.headers?.['cf-aig-authorization']");});++ it('enables cached transport only for host-authenticated Codex subscription providers', () => {+ expect(nativeProviderAdapterAliases([+ { id: 'openai-codex', name: 'ChatGPT', headers: { 'x-cindy-pi-provider-id': 'openai' }, models: [{ id: 'gpt', api: 'openai-codex-responses' }] },+ { id: 'openai-codex-account', name: 'Other account', headers: { 'x-cindy-pi-provider-id': 'account' }, api: 'openai-codex-responses' },+ { id: 'byom', name: 'BYOM', models: [{ id: 'gpt', api: 'openai-codex-responses' }] },+ { id: 'xai', name: 'Grok', headers: { 'x-cindy-pi-provider-id': 'xai' }, models: [{ id: 'grok', api: 'openai-responses' }] },+ ])).toEqual([+ { id: 'openai-codex', name: 'ChatGPT', provider: 'openai-codex', cachedCodex: true },+ { id: 'openai-codex-account', name: 'Other account', provider: 'openai-codex-account', cachedCodex: true },+ ]);+ });++ it('retains per-model HTTP checks for hosted and shared-provider tasks', () => {+ const providers = [{ id: 'openai-codex', name: 'ChatGPT', api: 'openai-codex-responses',+ headers: { 'x-cindy-pi-provider-id': 'openai' }, models: [{ id: 'gpt' }] }];+ expect(nativeProviderAdapterAliases(providers, undefined, true)[0]).not.toHaveProperty('cachedCodex');+ expect(nativeProviderAdapterAliases(providers, ['gpt'])[0]).not.toHaveProperty('cachedCodex');+ });});diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.tsindex e84f01a802..3745b77dc0 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts@@ -636,7 +636,7 @@ describe("PiAgent native auto-compaction ownership", () => {},);- function readLatestPiSettings(): { compaction?: { reserveTokens?: number }; skills?: string[]; packages?: Array<{ source: string; skills?: string[] }> } {+ function readLatestPiSettings(): { compaction?: { reserveTokens?: number; modelOverrides?: Record<string, { reserveTokens?: number }> }; skills?: string[]; packages?: Array<{ source: string; skills?: string[] }> } {const files: string[] = [];const walk = (dir: string): void => {for (const entry of readdirSync(dir, { withFileTypes: true })) {diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.tsindex d2d4dca043..e67b608d3f 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts@@ -8420,6 +8420,10 @@ describe("Pi provider-aware model routing", () => {const config = JSON.parse(readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR!, "models.json"), "utf8"));expect(config.providers["native-openai"].headers["x-cindy-pi-provider-id"]).toBe("openai");expect(config.providers["native-account-b"].headers["x-cindy-pi-provider-id"]).toBe("account-b");+ expect(JSON.parse(captured.env.CINDY_PI_NATIVE_PROVIDER_ADAPTERS!)).toEqual(expect.arrayContaining([+ expect.objectContaining({ id: 'native-openai', cachedCodex: true }),+ expect.objectContaining({ id: 'native-account-b', cachedCodex: true }),+ ]));expect(subagentAccounts).toEqual(expect.arrayContaining(["openai", "account-b"]));for (const account of ["account-b", "openai"]) {await handle.setModel!(model, { providerId: account });diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex 926b72bd50..3993a1bd5d 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -4033,7 +4033,7 @@ function astraResponsesPayload(payload, model) {async function nativeFastPayload(payload, model, ctx) {if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return undefined;- if (!model || !['openai-responses', 'azure-openai-responses', 'openai-completions'].includes(model.api)) return undefined;+ if (!model || !['openai-responses', 'azure-openai-responses', 'openai-completions', 'openai-codex-responses'].includes(model.api)) return undefined;let models;try { models = JSON.parse(process.env.CINDY_PI_FAST_MODELS || '[]'); } catch { return undefined; }if (!Array.isArray(models) || !models.some(item => item.provider === model.provider && item.id === model.id)) return undefined;diff --git a/packages/maker-core/src/agents/pi/native-provider-adapter-source.ts b/packages/maker-core/src/agents/pi/native-provider-adapter-source.tsindex 5d278bd7ef..60c0d9ba47 100644--- a/packages/maker-core/src/agents/pi/native-provider-adapter-source.ts+++ b/packages/maker-core/src/agents/pi/native-provider-adapter-source.ts@@ -1,12 +1,15 @@/** Preserve Pi's provider-specific serializers for independently named Cindy connections. */export function nativeProviderAdapterAliases(nativeProviders: Array<{ id: string; name: string; adapterProvider?: string; apiKeyEnvVar?: string;- sourceProviderId?: string; models?: Array<{ id: string; wireId?: string }>; modelIdAliases?: Record<string, string> }>,+ sourceProviderId?: string; api?: string; headers?: Record<string, string>;+ models?: Array<{ id: string; wireId?: string; api?: string }>; modelIdAliases?: Record<string, string> }>,guestModelIds?: readonly string[],hosted = false,-): Array<{ id: string; name: string; provider: string; keyEnv?: string; remoteProviderId?: string; models?: Array<{ id: string; grant: string }> }> {+): Array<{ id: string; name: string; provider: string; keyEnv?: string; cachedCodex?: boolean; remoteProviderId?: string; models?: Array<{ id: string; grant: string }> }> {return nativeProviders.flatMap((provider) => {- const adapter = provider.adapterProvider ?? (hosted || guestModelIds ? provider.id : undefined);+ const cachedCodex = !hosted && !guestModelIds && Boolean(provider.headers?.['x-cindy-pi-provider-id'])+ && (provider.api === 'openai-codex-responses' || provider.models?.some(model => model.api === 'openai-codex-responses'));+ const adapter = provider.adapterProvider ?? (hosted || guestModelIds || cachedCodex ? provider.id : undefined);const source = provider.sourceProviderId ?? provider.id;const models = guestModelIds ? (provider.models ?? []).flatMap(model => {const grant = guestModelIds.find(id => id === model.id || provider.modelIdAliases?.[id] === model.id@@ -17,6 +20,7 @@ export function nativeProviderAdapterAliases(id: provider.id,name: provider.name,provider: adapter,+ ...(cachedCodex ? { cachedCodex: true } : {}),...(hosted && !guestModelIds ? { remoteProviderId: source } : {}),...(provider.apiKeyEnvVar ? { keyEnv: provider.apiKeyEnvVar } : {}),...(models ? { models } : {}),@@ -26,7 +30,7 @@ export function nativeProviderAdapterAliases(}export const PI_NATIVE_PROVIDER_ADAPTER_SOURCE = String.raw`-type CindyAdapterAlias = { id: string; name: string; provider: string; keyEnv?: string; remoteProviderId?: string; models?: Array<{ id: string; grant: string }> };+type CindyAdapterAlias = { id: string; name: string; provider: string; keyEnv?: string; cachedCodex?: boolean; remoteProviderId?: string; models?: Array<{ id: string; grant: string }> };type CindyProviderRefreshSnapshot = {nonce: string;env: Record<string, string>;@@ -64,6 +68,7 @@ function parseCindyProviderRefreshSnapshot(raw: unknown, nonce: string): CindyPrif (typeof alias.id !== 'string' || !alias.id || seen.has(alias.id)) return undefined;if (typeof alias.name !== 'string') return undefined;if (typeof alias.provider !== 'string' || !alias.provider) return undefined;+ if (alias.cachedCodex !== undefined && typeof alias.cachedCodex !== 'boolean') return undefined;if (alias.remoteProviderId !== undefined && (typeof alias.remoteProviderId !== 'string' || !alias.remoteProviderId)) return undefined;if (alias.keyEnv !== undefined && (typeof alias.keyEnv !== 'string'@@ -74,6 +79,7 @@ function parseCindyProviderRefreshSnapshot(raw: unknown, nonce: string): CindyPr!model || typeof model.id !== 'string' || !model.id || typeof model.grant !== 'string' || !model.grant))) return undefined;seen.add(alias.id);aliases.push({ id: alias.id, name: alias.name, provider: alias.provider,+ ...(alias.cachedCodex === true ? { cachedCodex: true } : {}),...(alias.remoteProviderId ? { remoteProviderId: alias.remoteProviderId } : {}),...(alias.keyEnv ? { keyEnv: alias.keyEnv } : {}),...(alias.models ? { models: alias.models.map((model: any) => ({ id: model.id, grant: model.grant })) } : {}) });@@ -127,11 +133,21 @@ async function registerCindyNativeProviderAdapters(pi: any) {const placeholderKey = !token || ['pi-native-keyless', 'cindy-pi-provider-auth-placeholder', 'cindy-local-provider'].includes(token);const gatewayKey = token && !placeholderKey? 'Bearer ' + token : options?.headers?.['cf-aig-authorization'];- const nativeOptions = alias.provider === 'cloudflare-ai-gateway'+ let nativeOptions = alias.provider === 'cloudflare-ai-gateway'? { ...options, apiKey: undefined, headers: { ...options?.headers,...(gatewayKey ? { 'cf-aig-authorization': gatewayKey } : {}),Authorization: null, 'x-api-key': null } }: options;+ if (alias.cachedCodex && model.api === 'openai-codex-responses') {+ nativeOptions = { ...nativeOptions, transport: 'websocket-cached',+ onPayload: async (payload: any, requestModel: any) => {+ const next = await options?.onPayload?.(payload, requestModel);+ const body = next === undefined ? payload : next;+ return typeof body?.model === 'string' && body.model.endsWith('[1m]')+ ? { ...body, model: body.model.slice(0, -4) } : body;+ },+ };+ }const events = simple ? api.streamSimple(nativeModel, nativeContext, nativeOptions) : api.stream(nativeModel, nativeContext, nativeOptions);return (async function* () {for await (const event of events) yield { ...event,