Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): preserve compressed HTTP subscription requests
xuzini-xznb68b88e98c13
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.tsindex 54f82a36ee..b8d6733d81 100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts@@ -1,5 +1,5 @@import { EventEmitter } from 'node:events';-import { zstdCompressSync, zstdDecompressSync } from 'node:zlib';+import { zstdCompress, zstdDecompress, zstdCompressSync, zstdDecompressSync } from 'node:zlib';import { afterEach, describe, expect, it, vi } from 'vitest';import { createAnthropicCompatProxy } from '@cindy/anthropic-compat-proxy';@@ -13,6 +13,13 @@ const { ownerState } = vi.hoisted(() => ({},}));+// Measure actual asynchronous zstd work on the production HTTP path. The+// synchronous fixture encoder/decoder remains untouched.+vi.mock('node:zlib', async importOriginal => {+ const actual = await importOriginal<typeof import('node:zlib')>();+ return { ...actual, zstdCompress: vi.fn(actual.zstdCompress), zstdDecompress: vi.fn(actual.zstdDecompress) };+});+vi.mock('electron', () => ({app: { getPath: () => '/tmp/cindy-pi-native-forwarding-test' },}));@@ -55,7 +62,8 @@ import {getPiNativeSubscriptionHandler,type PiNativeSubscriptionHandlerDeps,} from '../anthropic-responses-bridge-host.js';-import { setXaiDiscoveredModels } from '../active-catalog.js';+import { buildUserProvider } from '@cindy/model-providers';+import { setCustomProviders, setXaiDiscoveredModels } from '../active-catalog.js';import { registerUsagePricing, clearUsagePricing } from '../model-usage-pricing.js';import { setSessionFastMode } from '../session-effort-store.js';@@ -108,6 +116,7 @@ function deps(overrides: Partial<PiNativeSubscriptionHandlerDeps> = {}): PiNativdescribe('PI native subscription forwarding', () => {afterEach(() => {+ setCustomProviders([]);setXaiDiscoveredModels(null);setSessionFastMode('session-fast', false);clearUsagePricing('session-fast');@@ -115,9 +124,97 @@ describe('PI native subscription forwarding', () => {ownerState.scope = 'cloud:owner-a:1';ownerState.fastAllowed = true;ownerState.afterFastRead = undefined;+ vi.mocked(zstdCompress).mockClear();+ vi.mocked(zstdDecompress).mockClear();+ });++ // The same HTTP request used to decode twice and discard+ // compression when the final Fast restriction applied. Assert real bytes,+ // semantics and codec calls, rather than helper return values.+ it.each(['openai', 'openai-account-fixture'].flatMap(provider => [false, true].flatMap(compressed =>+ [false, true].flatMap(profile => [false, true].map(fastAllowed => ({ provider, compressed, profile, fastAllowed }))))))(+ 'preserves encoding and applies both rewrites once: %j', async ({ provider, compressed, profile, fastAllowed }) => {+ setCustomProviders([buildUserProvider({ id: 'openai-account-fixture', name: 'Fixture account',+ auth: { method: 'oauth', native: 'codex' }, runtimes: {} })]);+ ownerState.fastAllowed = fastAllowed;+ // Exercise the combined compressed rewrite with a 10 MiB history too.+ const repeats = compressed && profile && !fastAllowed ? 655360 : 4096;+ const payload = { model: 'gpt-6.1-sol' + (profile ? '[1m]' : ''), service_tier: 'priority',+ input: [{ role: 'user', content: 'fixture-history-'.repeat(repeats) }] };+ const raw = Buffer.from(JSON.stringify(payload));+ const bytes = compressed ? zstdCompressSync(raw) : raw;+ const injected = deps();+ await getPiNativeSubscriptionHandler(provider, 'fixture-codec-session', injected)({+ rawBody: bytes, parsedBody: compressed ? undefined : payload,+ ctx: { reqId: 1, method: 'POST', url: '/codex/responses', headers: compressed ? { 'content-encoding': 'zstd' } : {} },+ res: responseRecorder(),+ } as never);+ expect(injected.fetch).toHaveBeenCalledOnce();+ const sent = vi.mocked(injected.fetch).mock.calls[0]![1]!;+ const sentBytes = Buffer.from(sent.body as Uint8Array);+ if (compressed) expect(sent.headers).toMatchObject({ 'content-encoding': 'zstd' });+ else expect(sent.headers).not.toHaveProperty('content-encoding');+ const decoded = JSON.parse((compressed ? zstdDecompressSync(sentBytes) : sentBytes).toString());+ expect(decoded).toEqual({ ...payload, model: 'gpt-6.1-sol', service_tier: fastAllowed ? 'priority' : 'default' });+ expect(zstdDecompress).toHaveBeenCalledTimes(compressed ? 1 : 0);+ expect(zstdCompress).toHaveBeenCalledTimes(compressed && (profile || !fastAllowed) ? 1 : 0);+ if (!profile && fastAllowed) expect(sentBytes).toEqual(bytes);+ },+ );++ it.each([false, true])('passes already-standard requests byte-for-byte, compressed=%s', async compressed => {+ ownerState.fastAllowed = false;+ const payload = { model: 'gpt-6.1-sol', service_tier: 'default', input: [] };+ const raw = Buffer.from('{ "model": "gpt-6.1-sol", "service_tier": "default", "input": [] }');+ const bytes = compressed ? zstdCompressSync(raw) : raw;+ const injected = deps();+ await getPiNativeSubscriptionHandler('openai', 'fixture-standard', injected)({+ rawBody: bytes, parsedBody: compressed ? undefined : payload,+ ctx: { reqId: 1, method: 'POST', url: '/codex/responses', headers: compressed ? { 'content-encoding': 'zstd' } : {} },+ res: responseRecorder(),+ } as never);+ const sent = vi.mocked(injected.fetch).mock.calls[0]![1]!;+ expect(Buffer.from(sent.body as Uint8Array)).toEqual(bytes);+ if (compressed) expect(sent.headers).toMatchObject({ 'content-encoding': 'zstd' });+ expect(zstdCompress).not.toHaveBeenCalled();+ expect(zstdDecompress).toHaveBeenCalledTimes(compressed ? 1 : 0);+ });++ it('rechecks Fast after asynchronous profile recompression before dispatch', async () => {+ const actual = await vi.importActual<typeof import('node:zlib')>('node:zlib');+ vi.mocked(zstdCompress).mockImplementationOnce(((...args: unknown[]) => {+ ownerState.fastAllowed = false;+ return Reflect.apply(actual.zstdCompress, actual, args);+ }) as typeof zstdCompress);+ const payload = { model: 'gpt-6.1-sol[1m]', service_tier: 'priority', input: [] };+ const injected = deps();+ await getPiNativeSubscriptionHandler('openai', 'fixture-policy-race', injected)({+ rawBody: zstdCompressSync(Buffer.from(JSON.stringify(payload))), parsedBody: undefined,+ ctx: { reqId: 1, method: 'POST', url: '/codex/responses', headers: { 'content-encoding': 'zstd' } },+ res: responseRecorder(),+ } as never);+ const sent = vi.mocked(injected.fetch).mock.calls[0]![1]!;+ expect(sent.headers).toMatchObject({ 'content-encoding': 'zstd' });+ expect(JSON.parse(zstdDecompressSync(Buffer.from(sent.body as Uint8Array)).toString()))+ .toEqual({ ...payload, model: 'gpt-6.1-sol', service_tier: 'default' });+ expect(zstdDecompress).toHaveBeenCalledOnce();+ });++ it.each([false, true])('does not dispatch malformed restricted requests, compressed=%s', async compressed => {+ ownerState.fastAllowed = false;+ const malformed = Buffer.from('{invalid json');+ const injected = deps();+ const res = responseRecorder();+ await getPiNativeSubscriptionHandler('openai', 'fixture-malformed', injected)({+ rawBody: compressed ? zstdCompressSync(malformed) : malformed, parsedBody: undefined,+ ctx: { reqId: 1, method: 'POST', url: '/codex/responses', headers: compressed ? { 'content-encoding': 'zstd' } : {} },+ res,+ } as never);+ expect(injected.fetch).not.toHaveBeenCalled();+ expect(res.status).toBe(502);});- it.each(['relax', 'owner'] as const)('preserves the final boundary when %s changes during speed decompression', async action => {+ it.each(['relax', 'owner'] as const)('preserves the final boundary when %s changes during request rewriting', async action => {ownerState.fastAllowed = false;ownerState.afterFastRead = action;const injected = deps();@@ -134,8 +231,8 @@ describe('PI native subscription forwarding', () => {} else {expect(injected.fetch).toHaveBeenCalledOnce();const sent = vi.mocked(injected.fetch).mock.calls[0][1]!;- expect(JSON.parse(Buffer.from(sent.body as Uint8Array).toString()).service_tier).toBe('default');- expect(sent.headers).not.toHaveProperty('content-encoding');+ expect(JSON.parse(zstdDecompressSync(Buffer.from(sent.body as Uint8Array)).toString()).service_tier).toBe('default');+ expect(sent.headers).toMatchObject({ 'content-encoding': 'zstd' });}});diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.tsindex 478a31275b..62fa3ec2b3 100644--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts@@ -28,7 +28,7 @@ import { isXaiSubscriptionProviderId } from './subscription-account-auth.js';import { app } from 'electron';import fsp from 'node:fs/promises';import path from 'node:path';-import { promisify } from 'node:util';+import { isDeepStrictEqual, promisify } from 'node:util';import { zstdCompress, zstdDecompress } from 'node:zlib';import {@@ -539,32 +539,6 @@ function withOpenaiContextProfileModel(body: unknown): Record<string, unknown> |return { ...body, model: body.model.slice(0, -'[1m]'.length) };}-async function rewriteOpenaiContextProfileRequest(- rawBody: Buffer,- parsedBody: unknown,- contentEncoding: string | undefined,-): Promise<{ body: Buffer; contentEncoding: string | undefined } | null> {- const parsedProfile = withOpenaiContextProfileModel(parsedBody);- if (parsedProfile) {- return { body: Buffer.from(JSON.stringify(parsedProfile)), contentEncoding: undefined };- }- if (parsedBody !== undefined || contentEncoding?.toLowerCase() !== 'zstd') return null;- try {- // Near-1M-token payloads are large enough to stall Electron main. Node's async- // zstd APIs move compression work to the libuv worker pool.- const decodedBody = await zstdDecompressAsync(rawBody);- const decoded = JSON.parse(decodedBody.toString('utf8')) as unknown;- const compressedProfile = withOpenaiContextProfileModel(decoded);- if (!compressedProfile) return null;- return {- body: await zstdCompressAsync(Buffer.from(JSON.stringify(compressedProfile))),- contentEncoding,- };- } catch {- return null;- }-}-function parseJsonRecord(rawBody: Buffer): Record<string, unknown> | null {try {const parsed: unknown = JSON.parse(rawBody.toString('utf8'));@@ -792,14 +766,44 @@ export function getPiNativeSubscriptionHandler(let outboundBody = rawBody;let contentEncoding: string | undefined = ctx.headers['content-encoding'];if (isOpenAiSubscriptionProviderId(providerId)) {- const rewritten = await rewriteOpenaiContextProfileRequest(- rawBody,- parsedBody,- contentEncoding,- );- if (rewritten) {- outboundBody = rewritten.body;- contentEncoding = rewritten.contentEncoding;+ // Retain the decoded object across both rewrites. Unchanged requests keep+ // their original bytes; changed zstd requests stay compressed on the wire.+ let forceStandard = !subscriptionRequestAllowsFast(sessionId, providerId);+ const compressed = parsedBody === undefined && contentEncoding?.toLowerCase() === 'zstd';+ let current: unknown = parsedBody;+ let decodeError: unknown;+ try {+ if (current === undefined) {+ const bytes = compressed ? await zstdDecompressAsync(rawBody) : rawBody;+ current = JSON.parse(bytes.toString('utf8')) as unknown;+ }+ } catch (error) {+ decodeError = error;+ }+ const profile = withOpenaiContextProfileModel(current);+ current = profile ?? current;+ let changed = profile !== null;+ let standardApplied = false;+ for (;;) {+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);+ // Restrictions may tighten while decoding or encoding. Once restricted,+ // this request cannot regain priority while an asynchronous codec runs.+ forceStandard ||= !subscriptionRequestAllowsFast(sessionId, providerId);+ if (forceStandard && !standardApplied) {+ if (decodeError) throw decodeError;+ const standard = standardSpeedRequest(current);+ changed ||= !isDeepStrictEqual(standard, current);+ current = standard;+ standardApplied = true;+ }+ if (!changed) break;+ const bytes = Buffer.from(JSON.stringify(current));+ // Keep large codecs off Electron main, as in the existing profile path.+ outboundBody = compressed ? await zstdCompressAsync(bytes) : bytes;+ if (!compressed) contentEncoding = undefined;+ changed = false;+ if (standardApplied || !compressed) break;+ // A profile-only compression can yield to a newly restrictive policy.}} else if (isXaiSubscriptionProviderId(providerId)) {const parsed = isPlainRecord(parsedBody)@@ -820,17 +824,8 @@ export function getPiNativeSubscriptionHandler(contentEncoding = undefined;}}- throwIfOwnerBoundDispatchUnsafe(scopeAtStart);if (contentEncoding) headers['content-encoding'] = contentEncoding;- // Native Pi sends each tool-loop request here; recheck after auth/context awaits.- if (isOpenAiSubscriptionProviderId(providerId) && !subscriptionRequestAllowsFast(sessionId, providerId)) {- const bytes = contentEncoding?.toLowerCase() === 'zstd' ? await zstdDecompressAsync(outboundBody) : outboundBody;- const standard = standardSpeedRequest(JSON.parse(bytes.toString('utf8')));- outboundBody = Buffer.from(JSON.stringify(standard));- delete headers['content-encoding'];- }-throwIfOwnerBoundDispatchUnsafe(scopeAtStart);const response = await deps.fetch(upstream.url, {method: 'POST',