From 6f44360c1b046ee94caa2fdc5f609aedc284d37c Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:15:14 +0100 Subject: [PATCH 1/3] mason: bind Pi Codex wire shaping to the transport --- packages/pi/src/codex-websocket.ts | 102 ++++ packages/pi/src/codex-wire.ts | 73 +++ packages/pi/src/index.ts | 64 +-- packages/pi/src/runtime.ts | 184 +++---- packages/pi/src/tests/codex-payload.test.ts | 523 +++++++++++++++++++- packages/pi/src/tests/pool-routing.test.ts | 4 +- packages/pi/src/tests/vault.test.ts | 176 ++++++- 7 files changed, 927 insertions(+), 199 deletions(-) create mode 100644 packages/pi/src/codex-websocket.ts create mode 100644 packages/pi/src/codex-wire.ts diff --git a/packages/pi/src/codex-websocket.ts b/packages/pi/src/codex-websocket.ts new file mode 100644 index 00000000..ebb397c9 --- /dev/null +++ b/packages/pi/src/codex-websocket.ts @@ -0,0 +1,102 @@ +import { AsyncLocalStorage } from 'node:async_hooks' +import { shapePiCodexWebSocketFrame } from './codex-wire.ts' +import { RawWebSocket } from './raw-ws-node.ts' + +type WebSocketOptions = string | string[] | { headers?: Record } +type WebSocketArgs = [url: string | URL, options?: WebSocketOptions] +type GlobalWebSocketSlot = { WebSocket?: unknown } +const global = globalThis as unknown as GlobalWebSocketSlot + +type WebSocketAttempt = { + url: string + token: string + owner: object + onMessage(data: string): void +} + +const attemptScope = new AsyncLocalStorage() + +export function withPiCodexWebSocketAttempt( + attempt: WebSocketAttempt, + run: () => T, +): T { + return attemptScope.run(attempt, run) +} + +let installCount = 0 +let originalWebSocket: unknown + +class PiRawCodexWebSocket extends RawWebSocket { + private readonly binding: Omit + private onAttemptMessage?: WebSocketAttempt['onMessage'] + + constructor( + { url, token, owner }: WebSocketAttempt, + headers: Record, + ) { + super(url, headers) + this.binding = { url, token, owner } + this.addEventListener('message', (event) => { + const data = (event as { data?: unknown } | null)?.data + if (typeof data === 'string') this.onAttemptMessage?.(data) + }) + } + + override send(data: string): void { + const attempt = attemptScope.getStore() + if ( + !attempt || + attempt.owner !== this.binding.owner || + attempt.url !== this.binding.url || + attempt.token !== this.binding.token + ) { + // pi-ai caches by session and account, not by endpoint or bearer token. + // A stale connection must not send with the previous attempt's credential. + throw new Error('Cached Codex WebSocket does not match the request') + } + this.onAttemptMessage = attempt.onMessage + super.send(shapePiCodexWebSocketFrame(data)) + } +} + +const shim: typeof PiRawCodexWebSocket = new Proxy(PiRawCodexWebSocket, { + construct(target, args: WebSocketArgs, newTarget) { + const [url, options] = args + const attempt = attemptScope.getStore() + if (installCount && attempt && String(url) === attempt.url) { + const headers = + options && typeof options === 'object' && !Array.isArray(options) + ? (options.headers ?? {}) + : {} + if ( + new Headers(headers).get('authorization') === `Bearer ${attempt.token}` + ) + return Reflect.construct(target, [attempt, headers], newTarget) + } + + // Bun's pi-ai constructor can retain this shim after the global is restored. + const original = installCount ? originalWebSocket : global.WebSocket + if (typeof original !== 'function' || original === shim) { + throw new TypeError( + 'WebSocket transport is not available in this runtime', + ) + } + return Reflect.construct(original, args) + }, +}) + +export function installRawCodexWebSocket(): () => void { + if (installCount++ === 0) { + originalWebSocket = global.WebSocket + global.WebSocket = shim + } + let installed = true + return () => { + if (!installed) return + installed = false + if (--installCount === 0) { + if (global.WebSocket === shim) global.WebSocket = originalWebSocket + originalWebSocket = undefined + } + } +} diff --git a/packages/pi/src/codex-wire.ts b/packages/pi/src/codex-wire.ts new file mode 100644 index 00000000..e1ee560c --- /dev/null +++ b/packages/pi/src/codex-wire.ts @@ -0,0 +1,73 @@ +import { zstdDecompressSync } from 'node:zlib' +import { + isRecord, + moveInstructionsToDeveloperMessage, + restoreReplayedCallStatus, +} from '@cortexkit/openai-auth-core/internal' + +export const PI_CODEX_BASE_URL = 'https://chatgpt.com/backend-api' + +// Match pi-ai's URL derivation before applying any plugin wire changes. +export function piCodexHttpUrl(baseUrl: string): string { + const base = (baseUrl?.trim() ? baseUrl : PI_CODEX_BASE_URL).replace( + /\/+$/, + '', + ) + if (base.endsWith('/codex/responses')) return base + return `${base}${base.endsWith('/codex') ? '/responses' : '/codex/responses'}` +} + +export function piCodexWebSocketUrl(httpUrl: string): string { + const url = new URL(httpUrl) + if (url.protocol === 'https:') url.protocol = 'wss:' + else if (url.protocol === 'http:') url.protocol = 'ws:' + return url.href +} + +function shapeFullBody(body: Record) { + const input = restoreReplayedCallStatus(body.input, body.model) + if (input !== body.input) body.input = input + moveInstructionsToDeveloperMessage(body) +} + +export function shapePiCodexWebSocketFrame(data: string): string { + // pi-ai has already compared its logical input and chosen full or delta. + const frame: unknown = JSON.parse(data) + if (!isRecord(frame) || frame.type !== 'response.create') return data + if ( + typeof frame.previous_response_id === 'string' && + frame.previous_response_id + ) { + delete frame.instructions + } else { + shapeFullBody(frame) + } + return JSON.stringify(frame) +} + +export function shapePiCodexHttpRequest( + init: RequestInit | undefined, +): RequestInit | undefined { + if (!init?.body) return init + const headers = new Headers(init.headers) + const encoding = headers.get('content-encoding') + const compressed = encoding === 'zstd' + let json: string + if (compressed && ArrayBuffer.isView(init.body)) { + const { buffer, byteOffset, byteLength } = init.body + json = zstdDecompressSync( + Buffer.from(buffer, byteOffset, byteLength), + ).toString('utf8') + } else if (!encoding && typeof init.body === 'string') { + json = init.body + } else { + return init + } + const body: unknown = JSON.parse(json) + if (isRecord(body)) shapeFullBody(body) + const shaped = JSON.stringify(body) + if (!compressed && shaped === json) return init + headers.delete('content-encoding') + headers.delete('content-length') + return { ...init, headers, body: shaped } +} diff --git a/packages/pi/src/index.ts b/packages/pi/src/index.ts index 22cae8d9..2f2f30af 100644 --- a/packages/pi/src/index.ts +++ b/packages/pi/src/index.ts @@ -20,70 +20,16 @@ import { } from '@earendil-works/pi-ai/compat' import type { ExtensionAPI } from '@earendil-works/pi-coding-agent' +import { installRawCodexWebSocket } from './codex-websocket.ts' +import { PI_CODEX_BASE_URL } from './codex-wire.ts' import { registerCommands } from './commands.ts' -import { RawWebSocket } from './raw-ws-node.ts' import { PiOpenAIRuntime, type PiOpenAIRuntimeDeps } from './runtime.ts' import { preparePiSettingsStartup } from './settings-startup.ts' import { VAULT_PLACEHOLDER_KEY } from './vault-slot.ts' -const BASE_URL = 'https://chatgpt.com/backend-api' +export { installRawCodexWebSocket } from './codex-websocket.ts' type CodexModel = Model<'openai-codex-responses'> -type WebSocketOptions = - | string - | string[] - | { headers?: Record } - | undefined - -type GlobalWebSocketSlot = { WebSocket?: unknown } - -/** - * Receives every text frame of a Codex WebSocket with the headers the socket - * was opened with, so a `codex.rate_limits` frame is recorded against the - * account whose token opened it. Set by the extension. - */ -let webSocketObserver: - | ((headers: Record, data: string) => void) - | undefined - -class PiRawCodexWebSocket extends RawWebSocket { - constructor(url: string | URL, options?: WebSocketOptions) { - const headers = - options && typeof options === 'object' && !Array.isArray(options) - ? (options.headers ?? {}) - : {} - super(String(url), headers) - const observer = webSocketObserver - if (observer) { - this.addEventListener('message', (event) => { - const data = (event as { data?: unknown } | null)?.data - if (typeof data === 'string') observer(headers, data) - }) - } - } -} - -let rawWebSocketInstallCount = 0 -let originalWebSocket: unknown - -export function installRawCodexWebSocket() { - const global = globalThis as unknown as GlobalWebSocketSlot - if (rawWebSocketInstallCount === 0) { - originalWebSocket = global.WebSocket - global.WebSocket = PiRawCodexWebSocket - } - rawWebSocketInstallCount++ - - return () => { - rawWebSocketInstallCount = Math.max(0, rawWebSocketInstallCount - 1) - if (rawWebSocketInstallCount === 0) { - if (global.WebSocket === PiRawCodexWebSocket) { - global.WebSocket = originalWebSocket - } - originalWebSocket = undefined - } - } -} /** * Codex models a ChatGPT login can use that a Pi release may not list yet, each @@ -179,7 +125,7 @@ export function registerPiProvider( runtime: PiOpenAIRuntime, ): void { pi.registerProvider('openai-codex', { - baseUrl: BASE_URL, + baseUrl: PI_CODEX_BASE_URL, api: 'openai-codex-responses', name: 'OpenAI Codex (CortexKit)', // Pi's built-in Codex provider is OAuth-only. This enables its api_key @@ -219,8 +165,6 @@ export default async function cortexKitPiOpenAIAuth(pi: ExtensionAPI) { settingsStartup.paths, settingsStartup.snapshot, ) - webSocketObserver = (headers, data) => - runtime.observeWebSocketMessage(headers, data) let refresh: (() => unknown) | undefined let notify: ((message: string, level: 'error') => void) | undefined const syncSlot = (explicit = true) => diff --git a/packages/pi/src/runtime.ts b/packages/pi/src/runtime.ts index 19ea6f25..190a6fc8 100644 --- a/packages/pi/src/runtime.ts +++ b/packages/pi/src/runtime.ts @@ -53,7 +53,6 @@ import { isRecord, limitAccountKey, loadAccounts, - moveInstructionsToDeveloperMessage, normalizeQuotaHeaders, normalizeWsFrame, type OAuthQuotaSnapshot, @@ -66,7 +65,6 @@ import { redactCredentialResponse, redactCredentialText, reportVaultRoutingLimit, - restoreReplayedCallStatus, type SessionDispatch, sessionCacheKeepPlan, startVaultRoutingWait, @@ -102,6 +100,12 @@ import type { Model, SimpleStreamOptions, } from '@earendil-works/pi-ai' +import { withPiCodexWebSocketAttempt } from './codex-websocket.ts' +import { + piCodexHttpUrl, + piCodexWebSocketUrl, + shapePiCodexHttpRequest, +} from './codex-wire.ts' import { PiMainAccount } from './main-account.ts' import { getPiAccountPaths } from './paths.ts' import { @@ -163,9 +167,6 @@ export interface PiOpenAIRuntimeDeps { waitForPi?: typeof waitForPi } -/** How many vault tokens are remembered, so a WebSocket frame finds its account. */ -const VAULT_TOKENS_KEPT = 64 - // Pi's agent retries by matching the error text, so provider details must not // appear in the terminal error of an attempt that has already published output. const TERMINAL_AFTER_OUTPUT_MESSAGE = @@ -250,13 +251,10 @@ export function blockedMessage(block: PoolBlock): string { } } -function bearerOf(headers: Record): string | undefined { - for (const [name, value] of Object.entries(headers)) { - if (name.toLowerCase() !== 'authorization') continue - const match = /^Bearer\s+(.+)$/i.exec(value.trim()) - return match?.[1] - } - return undefined +type PiQuotaDispatch = { + accountId: string + token: string + receipt?: QuotaReceipt } export class PiOpenAIRuntime { @@ -273,17 +271,6 @@ export class PiOpenAIRuntime { * is written once when an account starts serving on them. */ private readonly creditsServing = new CreditsServing() - /** - * The vault account behind each recent vault token, with the receipt the - * vault served the token under, newest last, so a rate-limit frame - * arriving on a WebSocket opened with one is recorded against that - * account. The vault keeps a reading only while the account still holds - * the receipt's credential and ChatGPT account. - */ - private readonly vaultTokens = new Map< - string, - { id: string; receipt: QuotaReceipt } - >() private readonly now: () => number private readonly paths: () => AccountPaths private slot: PiSlot | undefined @@ -630,80 +617,42 @@ export class PiOpenAIRuntime { return this.pool.requestReading(id) } - private rememberVaultToken( - token: string, - entry: { id: string; receipt: QuotaReceipt }, - ): void { - this.vaultTokens.delete(token) - this.vaultTokens.set(token, entry) - while (this.vaultTokens.size > VAULT_TOKENS_KEPT) { - const oldest = this.vaultTokens.keys().next().value - if (oldest === undefined) break - this.vaultTokens.delete(oldest) - } - } - // ------------------------------------------------------------------------- // Quota observed on the wire // ------------------------------------------------------------------------- private recordHeaders( - accountId: string, - token: string, + dispatch: PiQuotaDispatch, headers: Record, ): void { const parsed = new Headers(headers) - const snapshot = normalizeQuotaHeaders(parsed) as Record - const complete = isCompleteQuotaHeaderFrame(parsed) - const vaultEntry = this.vaultTokens.get(token) - if (vaultEntry?.id === accountId) { - this.vault.reportUsage(accountId, { headers: parsed }, vaultEntry.receipt) - void this.vault.recordSnapshot( - accountId, - snapshot, - complete, - vaultEntry.receipt, - ) - } else if (accountId === FORMER_MAIN_ID) - this.main.record(snapshot, token, complete) - else this.pool.recordSnapshot(accountId, snapshot, token, complete) + this.recordQuota( + dispatch, + normalizeQuotaHeaders(parsed) as Record, + isCompleteQuotaHeaderFrame(parsed), + { headers: parsed }, + ) } - /** - * Records a `codex.rate_limits` frame that arrived on a WebSocket opened - * with `token`, against the account the token belongs to. A WebSocket may - * outlive the request that opened it, so the token, not the request, - * names the account. - */ - recordRateLimitFrame( - token: string, + private recordQuota( + { accountId, token, receipt }: PiQuotaDispatch, snapshot: Record, - frame?: Record, + complete: boolean, + reply: { headers: Headers } | { frame: unknown }, ): void { - // A vault token first: in vault mode it may sign in as the same ChatGPT - // account as Pi's own login, and the reading is the vault account's. - const vaultEntry = this.vaultTokens.get(token) - if (vaultEntry) { - if (frame) - this.vault.reportUsage(vaultEntry.id, { frame }, vaultEntry.receipt) - void this.vault.recordSnapshot( - vaultEntry.id, - snapshot, - true, - vaultEntry.receipt, - ) - return + if (receipt) { + this.vault.reportUsage(accountId, reply, receipt) + void this.vault.recordSnapshot(accountId, snapshot, complete, receipt) + } else if (accountId === FORMER_MAIN_ID) { + this.main.record(snapshot, token, complete) + } else { + this.pool.recordSnapshot(accountId, snapshot, token, complete) } - if (this.main.record(snapshot, token, true)) return - const row = this.pool.rowForToken(token) - if (row) this.pool.recordSnapshot(row.id, snapshot, token, true) } - /** The handler a raw WebSocket hands its frames to. */ - observeWebSocketMessage(headers: Record, data: string): void { + /** Credit quota to the account and vault credential that sent this request, not the socket's opener. */ + observeWebSocketMessage(dispatch: PiQuotaDispatch, data: string): void { if (!data.includes('codex.rate_limits')) return - const token = bearerOf(headers) - if (!token) return let event: unknown try { event = JSON.parse(data) @@ -716,12 +665,13 @@ export class PiOpenAIRuntime { (event as { type?: unknown }).type !== 'codex.rate_limits' ) return - this.recordRateLimitFrame( - token, + this.recordQuota( + dispatch, normalizeWsFrame( event as Parameters[0], ) as Record, - event as Record, + true, + { frame: event }, ) } @@ -1042,37 +992,42 @@ export class PiOpenAIRuntime { let inner: AssistantMessageEventStream try { const send = options?.fetch ?? globalThis.fetch + const httpUrl = piCodexHttpUrl(model.baseUrl) + const quotaDispatch: PiQuotaDispatch = { + accountId, + token, + ...(receipt && { receipt }), + } // Pi's compaction and summary calls can carry the routing session id, // but disable caching. They must not pin or change conversation effort. const effortSessionId = options?.cacheRetention === 'none' ? undefined : options?.sessionId - inner = this.deps.streamSimple(model, context, { + const useWebSocketShim = + this.deps.installWebSocket && options?.transport !== 'sse' + const streamOptions: SimpleStreamOptions = { ...options, apiKey: token, - // pi-ai uses the transformed body for HTTP and to compute WebSocket deltas. + // On Bun, an explicit environment makes pi-ai read the current WebSocket + // constructor instead of reusing one cached before the shim was installed. + ...(useWebSocketShim && + process.versions.bun && { env: options?.env ?? {} }), + // Effort updates belong in pi-ai's logical history; wire-only changes do not. onPayload: async (payload, payloadModel) => { const replacement = await options?.onPayload?.(payload, payloadModel) const source = replacement === undefined ? payload : replacement - if (!isRecord(source)) return source - const input = restoreReplayedCallStatus(source.input, source.model) - if ( - !effortSessionId && - input === source.input && - (typeof source.instructions !== 'string' || - source.instructions.length === 0) - ) - return source + if (!effortSessionId || !isRecord(source)) return source const body = { ...source } - if (input !== source.input) body.input = input - if (effortSessionId) this.applyEffort(body, effortSessionId) - moveInstructionsToDeveloperMessage(body) + this.applyEffort(body, effortSessionId) return body }, // Scrub before pi-ai parses errors into its shared partial message objects. fetch: Object.assign( async (input: RequestInfo | URL, init?: RequestInit) => { try { - const response = await send(input, init) + const response = await send( + input, + input === httpUrl ? shapePiCodexHttpRequest(init) : init, + ) // Never read an SSE success body: it may be an unbounded stream. // The clone leaves the SDK's error bytes and response untouched. if (response.status >= 400) { @@ -1096,7 +1051,7 @@ export class PiOpenAIRuntime { ), onResponse: async (response, responseModel) => { status = response.status - this.recordHeaders(accountId, token, response.headers) + this.recordHeaders(quotaDispatch, response.headers) const observedAt = this.now() const headersReading = normalizeQuotaHeaders( new Headers(response.headers), @@ -1155,7 +1110,20 @@ export class PiOpenAIRuntime { } await options?.onResponse?.(response, responseModel) }, - }) + } + const start = () => this.deps.streamSimple(model, context, streamOptions) + inner = useWebSocketShim + ? withPiCodexWebSocketAttempt( + { + url: piCodexWebSocketUrl(httpUrl), + token, + owner: this, + onMessage: (data) => + this.observeWebSocketMessage(quotaDispatch, data), + }, + start, + ) + : start() } catch (error) { billing?.end(false, false, status) return { @@ -1264,20 +1232,6 @@ export class PiOpenAIRuntime { const response = await this.vault.send( accountId, async (token, attempt) => { - // Only the receipt's attribution fields are kept, never the token. - this.rememberVaultToken(token, { - id: accountId, - receipt: { - credentialId: attempt.credentialId, - accountIdentitySource: attempt.accountIdentitySource, - ...(attempt.accountIdentity !== undefined - ? { accountIdentity: attempt.accountIdentity } - : {}), - ...(attempt.expectedAccountIdentity !== undefined - ? { expectedAccountIdentity: attempt.expectedAccountIdentity } - : {}), - }, - }) // An attempt the vault retries is dropped unread: it ended without // streaming, so nothing of it reached Pi. last = await this.attempt( diff --git a/packages/pi/src/tests/codex-payload.test.ts b/packages/pi/src/tests/codex-payload.test.ts index fcc186f4..6e2cf6b3 100644 --- a/packages/pi/src/tests/codex-payload.test.ts +++ b/packages/pi/src/tests/codex-payload.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, expect, test } from 'bun:test' +import { afterEach, beforeEach, expect, spyOn, test } from 'bun:test' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -8,9 +8,11 @@ import { type Model, type SimpleStreamOptions, } from '@earendil-works/pi-ai' +import { closeOpenAICodexWebSocketSessions } from '@earendil-works/pi-ai/api/openai-codex-responses' import { streamSimple } from '@earendil-works/pi-ai/compat' import { chatgptAccessToken } from '../../../core/src/tests/fixtures/mock-claustrum.ts' import { installRawCodexWebSocket } from '../index.ts' +import { RawWebSocket } from '../raw-ws-node.ts' import { PiOpenAIRuntime } from '../runtime.ts' const model: Model<'openai-codex-responses'> = { @@ -67,7 +69,39 @@ function developerMessage(text: string, id?: string) { } } -function responseEvents(turn: number) { +function responseEvents(turn: number, functionCall = false) { + if (functionCall) { + const item = { + type: 'function_call', + id: `fc_${turn}`, + call_id: `call_${turn}`, + name: 'read', + } + return [ + { + type: 'response.output_item.added', + output_index: 0, + item: { ...item, status: 'in_progress', arguments: '' }, + }, + { + type: 'response.output_item.done', + output_index: 0, + item: { + ...item, + status: 'completed', + arguments: '{"path":"README.md"}', + }, + }, + { + type: 'response.completed', + response: { + id: `resp_${turn}`, + status: 'completed', + usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 }, + }, + }, + ] + } const item = { type: 'message', id: `msg_${turn}`, role: 'assistant' } return [ { @@ -106,16 +140,36 @@ function mockFetch( let dir: string let runtime: PiOpenAIRuntime +let sdkHttpEncodings: (string | null)[] +let wireHttpEncodings: (string | null)[] beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'pi-codex-payload-')) - runtime = new PiOpenAIRuntime({ - streamSimple, + sdkHttpEncodings = [] + wireHttpEncodings = [] + runtime = makeRuntime(dir) +}) + +function makeRuntime(directory: string) { + return new PiOpenAIRuntime({ + streamSimple(model, context, options) { + const fetch = options?.fetch + return streamSimple(model, context, { + ...options, + fetch: mockFetch(async (input, init) => { + sdkHttpEncodings.push( + new Headers(init?.headers).get('content-encoding'), + ) + if (!fetch) throw new Error('Missing transport wrapper') + return fetch(input, init) + }), + }) + }, createStream: createAssistantMessageEventStream, installWebSocket: installRawCodexWebSocket, paths: () => ({ - configPath: join(dir, 'openai-auth.json'), - statePath: join(dir, 'openai-auth-state.json'), + configPath: join(directory, 'openai-auth.json'), + statePath: join(directory, 'openai-auth-state.json'), }), fetchImpl: mockFetch(async () => Response.json({ @@ -129,7 +183,7 @@ beforeEach(() => { }), ), }) -}) +} afterEach(async () => { await Promise.all([runtime.pool.dispose(), runtime.vault.dispose()]) @@ -153,6 +207,7 @@ async function httpBody( fetch: mockFetch(async (_input, init) => { const payload = new Response(init?.body) const encoded = new Headers(init?.headers).get('content-encoding') + wireHttpEncodings.push(encoded) const json = encoded === 'zstd' ? new TextDecoder().decode( @@ -179,6 +234,16 @@ async function httpBody( return body } +test('Pi sends uncompressed JSON after pi-ai zstd-encodes the HTTP request', async () => { + const sent = await httpBody({ sessionId }) + expect(sdkHttpEncodings).toEqual(['zstd']) + expect(wireHttpEncodings).toEqual([null]) + expect(sent.input).toEqual([ + developerMessage(systemPrompt, systemId), + userItem(firstUser.content), + ]) +}) + test('Pi restores GPT-6.2 replayed call status without instructions and keeps GPT-6.1 bytes', async () => { for (const id of ['gpt-6.1-sol', 'gpt-6.2-sol']) { const requestContext: Context = { @@ -236,6 +301,10 @@ test('Pi restores GPT-6.2 replayed call status without instructions and keeps GP } sdkInput = body.input expect(sdkInput[1]).toEqual(replayed) + body.input = [ + ...sdkInput, + { ...replayed, id: 'fc_explicit', status: 'incomplete' }, + ] sdkBytes = JSON.stringify(body) return body }, @@ -250,6 +319,7 @@ test('Pi restores GPT-6.2 replayed call status without instructions and keeps GP sdkInput[0], { ...replayed, status: 'completed' }, sdkInput[2], + { ...replayed, id: 'fc_explicit', status: 'incomplete' }, ]), ) expect(sdkInput[1]).toEqual(replayed) @@ -395,9 +465,28 @@ test('Codex transforms in-place onPayload edits without mutating the SDK body', expect(sdkBody?.input).toHaveLength(1) }) -async function captureWebSocketFrames(run: (url: string) => Promise) { +function spyOnRawCodexFrames() { + const frames: string[] = [] + const rawSend = RawWebSocket.prototype.send + const seam = spyOn(RawWebSocket.prototype, 'send').mockImplementation( + function (this: RawWebSocket, data: string) { + expect(globalThis.WebSocket.name).toBe('PiRawCodexWebSocket') + expect(this).toBeInstanceOf(globalThis.WebSocket) + frames.push(data) + rawSend.call(this, data) + }, + ) + return { frames, restore: () => seam.mockRestore() } +} + +async function captureWebSocketFrames( + run: (url: string) => Promise, + events = responseEvents, +) { const frames: Record[] = [] + const wireFrames: string[] = [] let connections = 0 + const seam = spyOnRawCodexFrames() const server = Bun.serve({ hostname: '127.0.0.1', port: 0, @@ -410,16 +499,19 @@ async function captureWebSocketFrames(run: (url: string) => Promise) { connections++ }, message(socket, frame) { + wireFrames.push(frame.toString()) frames.push(JSON.parse(frame.toString())) - for (const event of responseEvents(frames.length)) + for (const event of events(frames.length)) socket.send(JSON.stringify(event)) }, }, }) try { await run(server.url.href) + expect(wireFrames).toEqual(seam.frames) return { frames, connections } } finally { + seam.restore() await server.stop(true) } } @@ -533,3 +625,416 @@ test('Pi keeps gpt-6.2-sol WebSocket turns chained after injecting an effort upd ]) expect(payloads.map((input) => input.length)).toEqual([1, 3, 5]) }) + +function cachedWebSocketOptions(): SimpleStreamOptions { + return { + apiKey, + transport: 'websocket-cached', + sessionId, + fetch: mockFetch(async () => { + throw new Error('Expected to send over the WebSocket') + }), + } +} + +const readTool = { + name: 'read', + description: 'Read a file', + parameters: { type: 'object', properties: { path: { type: 'string' } } }, +} + +test('Pi chains GPT-6.2 after a completed call and restores statuses on full WebSocket sends', async () => { + const toolOutput = (id: string): Context['messages'][number] => ({ + role: 'toolResult', + toolCallId: id, + toolName: 'read', + content: [{ type: 'text', text: 'Read result.' }], + isError: false, + timestamp: 3, + }) + const { frames, connections } = await captureWebSocketFrames( + async (baseUrl) => { + const socketModel = { ...effortModel, baseUrl } + const seed: Context['messages'][number] = { + role: 'assistant', + api: model.api, + provider: model.provider, + model: socketModel.id, + content: [ + { + type: 'toolCall', + id: 'call_seed|fc_seed', + name: 'read', + arguments: { path: 'seed' }, + }, + { + type: 'toolCall', + id: 'call_explicit|fc_explicit', + name: 'read', + arguments: { path: 'explicit' }, + }, + ], + stopReason: 'toolUse', + usage: { + input: 1, + output: 1, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 2, + cost: { ...model.cost, total: 0 }, + }, + timestamp: 2, + } + const history: Context['messages'] = [ + firstUser, + seed, + toolOutput('call_seed|fc_seed'), + toolOutput('call_explicit|fc_explicit'), + ] + const options: SimpleStreamOptions = { + ...cachedWebSocketOptions(), + onPayload(raw) { + const body = raw as { input: Record[] } + const explicit = body.input.find((item) => item.id === 'fc_explicit') + if (!explicit) throw new Error('Missing explicit-status fixture') + explicit.status = 'incomplete' + }, + } + const send = () => + runtime + .stream( + socketModel, + { + systemPrompt, + messages: [...history], + tools: [readTool], + }, + options, + ) + .result() + + const first = await send() + expect(first.stopReason).toBe('toolUse') + expect(first.content).toEqual([ + { + type: 'toolCall', + id: 'call_1|fc_1', + name: 'read', + arguments: { path: 'README.md' }, + }, + ]) + history.push(first, toolOutput('call_1|fc_1')) + const second = await send() + expect(second.responseId).toBe('resp_2') + history.push(second, thirdUser) + const third = await send() + expect(third.responseId).toBe('resp_3') + closeOpenAICodexWebSocketSessions(sessionId) + const resend = await send() + expect(resend.responseId).toBe('resp_4') + }, + (turn) => responseEvents(turn, turn === 1), + ) + expect(connections).toBe(2) + expect(frames.map((frame) => frame.previous_response_id)).toEqual([ + undefined, + 'resp_1', + 'resp_2', + undefined, + ]) + for (const frame of frames) expect(frame).not.toHaveProperty('instructions') + const [full, toolDelta, userDelta, resend] = frames.map( + (frame) => frame.input as Record[], + ) + expect(toolDelta).toEqual([ + { type: 'function_call_output', call_id: 'call_1', output: 'Read result.' }, + ]) + expect(userDelta).toEqual([userItem(thirdUser.content)]) + for (const input of [full!, resend!]) { + expect(input[0]).toEqual(developerMessage(systemPrompt, systemId)) + expect(input.filter((item) => item.role === 'developer')).toEqual([ + developerMessage(systemPrompt, systemId), + ]) + } + const callStatuses = (input: Record[]) => + input + .filter((item) => item.type === 'function_call') + .map(({ id, status }) => [id, status]) + expect(callStatuses(full!)).toEqual([ + ['fc_seed', 'completed'], + ['fc_explicit', 'incomplete'], + ]) + expect(callStatuses(resend!)).toEqual([ + ['fc_seed', 'completed'], + ['fc_explicit', 'incomplete'], + ['fc_1', 'completed'], + ]) +}) + +test.each(['prefix', 'tools', 'instructions'] as const)( + 'Pi sends the full WebSocket request if %s changed', + async (change) => { + const { frames, connections } = await captureWebSocketFrames( + async (baseUrl) => { + const socketModel = { ...model, baseUrl } + const options = cachedWebSocketOptions() + const first = await runtime + .stream(socketModel, context, options) + .result() + expect(first.responseId).toBe('resp_1') + const next = await runtime + .stream( + socketModel, + { + systemPrompt: + change === 'instructions' + ? 'A replacement prompt.' + : systemPrompt, + messages: [ + change === 'prefix' + ? { ...firstUser, content: 'Edited user message' } + : firstUser, + first, + secondUser, + ], + ...(change === 'tools' ? { tools: [readTool] } : {}), + }, + options, + ) + .result() + expect(next.responseId).toBe('resp_2') + }, + ) + expect(connections).toBe(1) + expect(frames).toHaveLength(2) + expect(frames[1]).not.toHaveProperty('previous_response_id') + expect(frames[1]).not.toHaveProperty('instructions') + expect(frames[1]?.input).toMatchObject([ + { + role: 'developer', + content: [ + { + type: 'input_text', + text: + change === 'instructions' + ? 'A replacement prompt.' + : systemPrompt, + }, + ], + }, + userItem(change === 'prefix' ? 'Edited user message' : firstUser.content), + { role: 'assistant' }, + userItem(secondUser.content), + ]) + if (change === 'tools') + expect(frames[1]?.tools).toMatchObject([{ name: 'read' }]) + }, +) + +function rateLimitsFrame(usedPercent: number) { + return { + type: 'codex.rate_limits', + rate_limits: { + primary: { used_percent: usedPercent, window_minutes: 300 }, + }, + } +} + +test('Pi binds overlapping Codex sockets by attempt, URL and bearer and leaves foreign sockets untouched', async () => { + const other = makeRuntime(join(dir, 'other')) + const original = globalThis.WebSocket + const seam = spyOnRawCodexFrames() + const firstObserver = spyOn(runtime, 'observeWebSocketMessage') + const otherObserver = spyOn(other, 'observeWebSocketMessage') + const seen: { + label: string + path: string + authorization: string | null + data: string + }[] = [] + const quota = { + priming: 11, + first: 21, + other: 37, + 'foreign-bearer': 82, + 'foreign-path': 93, + } + type Label = keyof typeof quota + const server = Bun.serve<{ + label: Label + path: string + authorization: string | null + }>({ + hostname: '127.0.0.1', + port: 0, + fetch(request, server) { + const label = request.headers.get('x-fixture-socket') as Label + const path = new URL(request.url).pathname + const authorization = request.headers.get('authorization') + if (server.upgrade(request, { data: { label, path, authorization } })) + return + return new Response(null, { status: 400 }) + }, + websocket: { + message(socket, frame) { + const { label } = socket.data + seen.push({ ...socket.data, data: frame.toString() }) + socket.send(JSON.stringify(rateLimitsFrame(quota[label]))) + if (label === 'first' || label === 'other' || label === 'priming') { + const turn = label === 'first' ? 1 : label === 'other' ? 2 : 0 + for (const event of responseEvents(turn)) + socket.send(JSON.stringify(event)) + } + }, + }, + }) + const codexPath = '/codex/responses' + const socketModel = { ...model, baseUrl: server.url.href } + const otherToken = chatgptAccessToken('other-payload-test-account') + const foreignBody = JSON.stringify({ + type: 'response.create', + model: 'gpt-6.2', + instructions: 'Foreign bytes', + input: [], + }) + const foreignSockets: { native: boolean; url: string; response: string }[] = + [] + const awaitingOther = Promise.withResolvers() + const foreignDone = Promise.withResolvers() + async function sendForeign(label: Label, path: string, token: string) { + const url = new URL(path, server.url) + url.protocol = 'ws:' + const socket = Reflect.construct(globalThis.WebSocket, [ + url, + { + headers: { + 'x-fixture-socket': label, + authorization: `Bearer ${token}`, + }, + }, + ]) as WebSocket + try { + const response = await new Promise((resolve, reject) => { + socket.addEventListener('open', () => socket.send(foreignBody)) + socket.addEventListener('message', (event) => resolve(event.data)) + socket.addEventListener('error', () => + reject(new Error('Foreign socket failed')), + ) + }) + foreignSockets.push({ + native: socket instanceof original, + url: socket.url, + response, + }) + } finally { + socket.close() + } + } + try { + const options = cachedWebSocketOptions() + // An unrelated SDK call can cache Bun's constructor while no shim is installed. + const priming = await streamSimple(socketModel, context, { + ...options, + cacheRetention: 'none', + headers: { 'x-fixture-socket': 'priming' }, + }).result() + expect(priming.responseId).toBe('resp_0') + expect(seam.frames).toEqual([]) + const first = runtime.stream(socketModel, context, { + ...options, + headers: { 'x-fixture-socket': 'first' }, + async onPayload() { + await awaitingOther.promise + try { + await sendForeign('foreign-bearer', codexPath, 'foreign-token') + await sendForeign('foreign-path', '/sentinel', apiKey) + } finally { + foreignDone.resolve() + } + }, + }) + const second = other.stream(socketModel, context, { + ...options, + sessionId: `${sessionId}-other`, + apiKey: otherToken, + headers: { 'x-fixture-socket': 'other' }, + async onPayload() { + awaitingOther.resolve() + await foreignDone.promise + }, + }) + expect( + (await Promise.all([first.result(), second.result()])).map( + (result) => result.responseId, + ), + ).toEqual(['resp_1', 'resp_2']) + + const owned = seen.filter( + ({ label }) => label === 'first' || label === 'other', + ) + expect(owned.map(({ data }) => data).sort()).toEqual( + [...seam.frames].sort(), + ) + expect( + owned + .map(({ label, path, authorization, data }) => [ + label, + path, + authorization, + JSON.parse(data).prompt_cache_key, + ]) + .sort(), + ).toEqual([ + ['first', codexPath, `Bearer ${apiKey}`, sessionId], + ['other', codexPath, `Bearer ${otherToken}`, `${sessionId}-other`], + ]) + const observedLimits = (observer: typeof firstObserver) => + observer.mock.calls + .map(([{ token }, data]) => [token, JSON.parse(data)] as const) + .filter(([, frame]) => frame.type === 'codex.rate_limits') + expect(observedLimits(firstObserver)).toEqual([ + [apiKey, rateLimitsFrame(21)], + ]) + expect(observedLimits(otherObserver)).toEqual([ + [otherToken, rateLimitsFrame(37)], + ]) + expect(seen.filter(({ label }) => label.startsWith('foreign-'))).toEqual([ + { + label: 'foreign-bearer', + path: codexPath, + authorization: 'Bearer foreign-token', + data: foreignBody, + }, + { + label: 'foreign-path', + path: '/sentinel', + authorization: `Bearer ${apiKey}`, + data: foreignBody, + }, + ]) + const wsOrigin = server.url.origin.replace(/^http:/, 'ws:') + expect(foreignSockets).toEqual([ + { + native: true, + url: `${wsOrigin}${codexPath}`, + response: JSON.stringify(rateLimitsFrame(82)), + }, + { + native: true, + url: `${wsOrigin}/sentinel`, + response: JSON.stringify(rateLimitsFrame(93)), + }, + ]) + } finally { + firstObserver.mockRestore() + otherObserver.mockRestore() + seam.restore() + closeOpenAICodexWebSocketSessions(sessionId) + closeOpenAICodexWebSocketSessions(`${sessionId}-other`) + await Promise.all([ + server.stop(true), + other.pool.dispose(), + other.vault.dispose(), + ]) + } +}) diff --git a/packages/pi/src/tests/pool-routing.test.ts b/packages/pi/src/tests/pool-routing.test.ts index 3313d654..3ba9521c 100644 --- a/packages/pi/src/tests/pool-routing.test.ts +++ b/packages/pi/src/tests/pool-routing.test.ts @@ -979,12 +979,12 @@ describe('Pi requests on the account pool', () => { ).toBe(10) }) - test('a codex.rate_limits WebSocket frame lands on the account whose token opened the socket', async () => { + test('a codex.rate_limits WebSocket frame lands on the account that sent the request', async () => { const runtime = makeRuntime() await ready(runtime) runtime.observeWebSocketMessage( - { Authorization: `Bearer ${BETA_TOKEN}` }, + { accountId: 'beta', token: BETA_TOKEN }, JSON.stringify({ type: 'codex.rate_limits', rate_limits: { diff --git a/packages/pi/src/tests/vault.test.ts b/packages/pi/src/tests/vault.test.ts index dc4abe36..d306cc7f 100644 --- a/packages/pi/src/tests/vault.test.ts +++ b/packages/pi/src/tests/vault.test.ts @@ -33,6 +33,7 @@ import { createAssistantMessageEventStream, type Model, } from '@earendil-works/pi-ai' +import { closeOpenAICodexWebSocketSessions } from '@earendil-works/pi-ai/api/openai-codex-responses' import { streamSimple } from '@earendil-works/pi-ai/compat' import { chatgptAccessToken, @@ -42,6 +43,8 @@ import { } from '../../../core/src/tests/fixtures/mock-claustrum.ts' import * as vaultRouting from '../../../core/src/vault-routing.ts' import { createPiMenu } from '../commands.ts' +import { installRawCodexWebSocket } from '../index.ts' +import { RawWebSocket } from '../raw-ws-node.ts' import { clearPiStickyRouting } from '../routing.ts' import { PiOpenAIRuntime } from '../runtime.ts' import { VAULT_PLACEHOLDER_KEY } from '../vault-slot.ts' @@ -163,10 +166,11 @@ function vault(): OpenAiVault { }) } -function runtimeWith(target: OpenAiVault): PiOpenAIRuntime { +function runtimeWith(target: OpenAiVault, webSocket = false): PiOpenAIRuntime { return new PiOpenAIRuntime({ streamSimple, createStream: createAssistantMessageEventStream, + ...(webSocket && { installWebSocket: installRawCodexWebSocket }), paths: () => paths, fetchImpl: fakeFetch, firstReadingWaitMs: 0, @@ -492,7 +496,7 @@ describe('Pi and the Claustrum vault', () => { expect(events.at(-1)).toMatchObject({ type: 'done' }) expect(codexTokens).toEqual([localAccess]) runtime.observeWebSocketMessage( - { authorization: `Bearer ${localAccess}` }, + { accountId: 'local', token: localAccess }, JSON.stringify({ type: 'codex.rate_limits', rate_limits: { primary: { used_percent: 43 } }, @@ -1005,6 +1009,7 @@ describe('Pi and the Claustrum vault', () => { async function served(): Promise<{ target: OpenAiVault runtime: PiOpenAIRuntime + dispatch: Parameters[0] }> { daemon = await startMockDaemon({ directory: dir, @@ -1018,20 +1023,25 @@ describe('Pi and the Claustrum vault', () => { await send(runtime) expect(codexTokens).toEqual([VAULT_ACCESS]) expect(primaryUsed(target)).toEqual([10]) - return { target, runtime } + const accountId = target.routes()[0]!.id + const receipt = await target.authorize(accountId) + if (!receipt) + throw new Error('Expected a quota receipt for the vault route') + return { + target, + runtime, + dispatch: { accountId, token: VAULT_ACCESS, receipt }, + } } test('is recorded on the vault account with the receipt the token was served under', async () => { - const { target, runtime } = await served() + const { target, runtime, dispatch } = await served() const report = spyOn( ClaustrumConsumer.prototype, 'reportUsage', ).mockImplementation(() => {}) try { - runtime.observeWebSocketMessage( - { Authorization: `Bearer ${VAULT_ACCESS}` }, - frame, - ) + runtime.observeWebSocketMessage(dispatch, frame) for (let i = 0; i < 200 && primaryUsed(target)[0] !== 77; i++) await Bun.sleep(5) @@ -1057,17 +1067,14 @@ describe('Pi and the Claustrum vault', () => { }) test('is dropped once the vault credential signs in as another account', async () => { - const { target, runtime } = await served() + const { target, runtime, dispatch } = await served() // The vault now serves the same credential for a different ChatGPT // account: a frame from the socket the old account's token opened // describes the old account and must not land on the new one. daemon.credentials['oauth:openai:vault'] = vaultLogin('chatgpt-other') await target.refresh() - runtime.observeWebSocketMessage( - { Authorization: `Bearer ${VAULT_ACCESS}` }, - frame, - ) + runtime.observeWebSocketMessage(dispatch, frame) await Bun.sleep(50) expect(primaryUsed(target)).not.toContain(77) @@ -1075,6 +1082,149 @@ describe('Pi and the Claustrum vault', () => { }) }) + test('Pi attributes quota and billing to each turn on a reused vault WebSocket', async () => { + const credential = 'oauth:openai:vault' + daemon = await startMockDaemon({ + directory: dir, + credentials: { + [credential]: vaultLogin('chatgpt-vault', { record_version: 1 }), + }, + }) + enroll() + const target = vault() + const runtime = runtimeWith(target, true) + const sessionId = 'pi-vault-reused-socket' + const reports: { session: string; payload: Record }[] = [] + Reflect.set(globalThis, routingKey, (session: string) => ({ + report(payload: Record) { + if (payload.kind === 'billing') reports.push({ session, payload }) + }, + })) + const rawSend = RawWebSocket.prototype.send + const rawFrames: string[] = [] + const seam = spyOn(RawWebSocket.prototype, 'send').mockImplementation( + function (this: RawWebSocket, data: string) { + expect(globalThis.WebSocket.name).toBe('PiRawCodexWebSocket') + expect(this).toBeInstanceOf(globalThis.WebSocket) + rawFrames.push(data) + rawSend.call(this, data) + }, + ) + const usage = spyOn(target, 'reportUsage') + const wireFrames: string[] = [] + const upgrades: (string | null)[] = [] + const firstResponse = (await sseOk().text()) + .trim() + .split('\n\n') + .map((line) => line.slice('data: '.length)) + const server = Bun.serve({ + hostname: '127.0.0.1', + port: 0, + fetch(request, server) { + const authorization = request.headers.get('authorization') + if (server.upgrade(request)) { + upgrades.push(authorization) + return + } + return new Response(null, { status: 400 }) + }, + websocket: { + message(socket, frame) { + wireFrames.push(frame.toString()) + const turn = wireFrames.length + socket.send( + JSON.stringify({ + type: 'codex.rate_limits', + rate_limits: { + primary: { used_percent: turn * 10 + 5, window_minutes: 300 }, + }, + }), + ) + for (const event of firstResponse) + socket.send(event.replace('"id":"r1"', `"id":"r${turn}"`)) + }, + }, + }) + try { + await target.refresh() + await target.pollStale(0) + const model = { ...MODEL, baseUrl: server.url.href } + const options = { + transport: 'websocket-cached', + sessionId, + apiKey: VAULT_PLACEHOLDER_KEY, + fetch: fakeFetch, + } as const + const firstStream = runtime.stream(model, CONTEXT, options) + await Array.fromAsync(firstStream) + const first = await firstStream.result() + expect(first.responseId).toBe('r1') + daemon.credentials[credential] = vaultLogin('chatgpt-vault', { + record_version: 2, + }) + await target.refresh() + const secondStream = runtime.stream( + model, + { + messages: [ + ...CONTEXT.messages, + first, + { role: 'user', content: 'next', timestamp: 2 }, + ], + }, + options, + ) + await Array.fromAsync(secondStream) + const second = await secondStream.result() + expect(second.responseId).toBe('r2') + expect(upgrades).toEqual([`Bearer ${VAULT_ACCESS}`]) + expect(wireFrames).toEqual(rawFrames) + expect( + wireFrames.map((frame) => JSON.parse(frame).previous_response_id), + ).toEqual([undefined, 'r1']) + expect( + usage.mock.calls.map(([id, reply, receipt]) => ({ + id, + frame: 'frame' in reply ? reply.frame : null, + version: (receipt as { recordVersion?: number }).recordVersion, + })), + ).toEqual( + [15, 25].map((used_percent, i) => ({ + id: target.routes()[0]!.id, + frame: { + type: 'codex.rate_limits', + rate_limits: { primary: { used_percent, window_minutes: 300 } }, + }, + version: i + 1, + })), + ) + expect( + reports.map(({ session, payload }) => [ + session, + payload.credential_id, + payload.provider_response_id, + payload.outcome, + ]), + ).toEqual([ + [sessionId, credential, 'r1', 'completed'], + [sessionId, credential, 'r2', 'completed'], + ]) + expect(reports[0]!.payload.attempt_id).not.toBe( + reports[1]!.payload.attempt_id, + ) + expect(codexTokens).toEqual([]) + } finally { + usage.mockRestore() + seam.mockRestore() + closeOpenAICodexWebSocketSessions(sessionId) + await Promise.all([ + server.stop(true), + runtime.pool.dispose(), + target.dispose(), + ]) + } + }) + test('a 401 on a vault account is reported to the vault with the version it was served', async () => { daemon = await startMockDaemon({ directory: dir, From 0ed163fc93a00f8036e977ec72334033cdb2ca1e Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:26:18 +0100 Subject: [PATCH 2/3] mason: renew idle Pi sockets after bearer rotation --- packages/pi/src/codex-websocket.ts | 115 +++++++++++++---- packages/pi/src/runtime.ts | 20 ++- packages/pi/src/tests/codex-payload.test.ts | 135 ++++++++++++++++++++ 3 files changed, 241 insertions(+), 29 deletions(-) diff --git a/packages/pi/src/codex-websocket.ts b/packages/pi/src/codex-websocket.ts index ebb397c9..a39ceee7 100644 --- a/packages/pi/src/codex-websocket.ts +++ b/packages/pi/src/codex-websocket.ts @@ -1,4 +1,5 @@ import { AsyncLocalStorage } from 'node:async_hooks' +import { parseJwtClaims } from '@cortexkit/openai-auth-core/internal' import { shapePiCodexWebSocketFrame } from './codex-wire.ts' import { RawWebSocket } from './raw-ws-node.ts' @@ -11,50 +12,118 @@ type WebSocketAttempt = { url: string token: string owner: object + sessionId?: string | undefined onMessage(data: string): void } -const attemptScope = new AsyncLocalStorage() +type ScopedAttempt = WebSocketAttempt & { + cacheKey?: string | undefined + settled: boolean +} + +const attemptScope = new AsyncLocalStorage() +const cachedSockets = new Map() + +function cacheKey({ sessionId, token }: WebSocketAttempt): string | undefined { + if (!sessionId) return + // pi-ai keys the cache by the original session ID and the nested JWT claim, + // not by the clamped prompt_cache_key or the plugin's routing account ID. + const accountId = + parseJwtClaims(token)?.['https://api.openai.com/auth']?.chatgpt_account_id + if (typeof accountId === 'string' && accountId) + return JSON.stringify([sessionId, accountId]) +} -export function withPiCodexWebSocketAttempt( - attempt: WebSocketAttempt, - run: () => T, -): T { - return attemptScope.run(attempt, run) +export function retireIdlePiCodexWebSocket(): void { + const attempt = attemptScope.getStore() + if (!attempt?.cacheKey) return + cachedSockets.get(attempt.cacheKey)?.retireIfIdle(attempt) +} + +export function withPiCodexWebSocketAttempt< + T extends { result(): Promise }, +>(attempt: WebSocketAttempt, run: () => T): T { + const scoped = { ...attempt, cacheKey: cacheKey(attempt), settled: false } + return attemptScope.run(scoped, () => { + retireIdlePiCodexWebSocket() + const finish = () => { + scoped.settled = true + } + try { + const stream = run() + // pi-ai releases the socket before publishing its terminal stream event. + void stream.result().then(finish, finish) + return stream + } catch (error) { + finish() + throw error + } + }) } let installCount = 0 let originalWebSocket: unknown class PiRawCodexWebSocket extends RawWebSocket { - private readonly binding: Omit - private onAttemptMessage?: WebSocketAttempt['onMessage'] + private readonly binding: Pick + private readonly cacheKey?: string + private activeAttempt?: ScopedAttempt - constructor( - { url, token, owner }: WebSocketAttempt, - headers: Record, - ) { + constructor(attempt: ScopedAttempt, headers: Record) { + const { url, token, owner, cacheKey } = attempt super(url, headers) this.binding = { url, token, owner } + // An open incumbent means pi-ai opened this as a temporary socket while + // the cached connection was busy. It must not displace the cached one. + if (cacheKey && cachedSockets.get(cacheKey)?.readyState !== 1) { + this.cacheKey = cacheKey + this.addEventListener('close', () => this.forget()) + } this.addEventListener('message', (event) => { const data = (event as { data?: unknown } | null)?.data - if (typeof data === 'string') this.onAttemptMessage?.(data) + if (typeof data === 'string') this.activeAttempt?.onMessage(data) }) } - override send(data: string): void { - const attempt = attemptScope.getStore() + private matches(attempt: WebSocketAttempt): boolean { + return ( + attempt.owner === this.binding.owner && + attempt.url === this.binding.url && + attempt.token === this.binding.token + ) + } + + retireIfIdle(attempt: ScopedAttempt): void { if ( - !attempt || - attempt.owner !== this.binding.owner || - attempt.url !== this.binding.url || - attempt.token !== this.binding.token + this.readyState === 1 && + this.activeAttempt?.settled && + !this.matches(attempt) ) { - // pi-ai caches by session and account, not by endpoint or bearer token. - // A stale connection must not send with the previous attempt's credential. - throw new Error('Cached Codex WebSocket does not match the request') + this.close() + } + } + + private forget(): void { + if (this.cacheKey && cachedSockets.get(this.cacheKey) === this) + cachedSockets.delete(this.cacheKey) + } + + override close(): void { + this.forget() + super.close() + } + + override send(data: string): void { + const attempt = attemptScope.getStore() + if (!attempt || !this.matches(attempt)) { + // This is a transport guard, not a provider error to show the user. + throw new Error() } - this.onAttemptMessage = attempt.onMessage + // pi-ai has acquired the socket by the first send. An aborted handshake + // never gets here and must not replace the cached entry. + if (!this.activeAttempt && this.cacheKey && this.readyState === 1) + cachedSockets.set(this.cacheKey, this) + this.activeAttempt = attempt super.send(shapePiCodexWebSocketFrame(data)) } } diff --git a/packages/pi/src/runtime.ts b/packages/pi/src/runtime.ts index 190a6fc8..d866a6ae 100644 --- a/packages/pi/src/runtime.ts +++ b/packages/pi/src/runtime.ts @@ -100,7 +100,10 @@ import type { Model, SimpleStreamOptions, } from '@earendil-works/pi-ai' -import { withPiCodexWebSocketAttempt } from './codex-websocket.ts' +import { + retireIdlePiCodexWebSocket, + withPiCodexWebSocketAttempt, +} from './codex-websocket.ts' import { piCodexHttpUrl, piCodexWebSocketUrl, @@ -1014,11 +1017,15 @@ export class PiOpenAIRuntime { // Effort updates belong in pi-ai's logical history; wire-only changes do not. onPayload: async (payload, payloadModel) => { const replacement = await options?.onPayload?.(payload, payloadModel) - const source = replacement === undefined ? payload : replacement - if (!effortSessionId || !isRecord(source)) return source - const body = { ...source } - this.applyEffort(body, effortSessionId) - return body + let source = replacement === undefined ? payload : replacement + if (effortSessionId && isRecord(source)) { + const body = { ...source } + this.applyEffort(body, effortSessionId) + source = body + } + // A cached socket may have gone idle while the caller built its payload. + if (useWebSocketShim) retireIdlePiCodexWebSocket() + return source }, // Scrub before pi-ai parses errors into its shared partial message objects. fetch: Object.assign( @@ -1118,6 +1125,7 @@ export class PiOpenAIRuntime { url: piCodexWebSocketUrl(httpUrl), token, owner: this, + sessionId: effortSessionId, onMessage: (data) => this.observeWebSocketMessage(quotaDispatch, data), }, diff --git a/packages/pi/src/tests/codex-payload.test.ts b/packages/pi/src/tests/codex-payload.test.ts index 6e2cf6b3..ed932079 100644 --- a/packages/pi/src/tests/codex-payload.test.ts +++ b/packages/pi/src/tests/codex-payload.test.ts @@ -831,6 +831,141 @@ test.each(['prefix', 'tools', 'instructions'] as const)( }, ) +test.each([ + [ + 'Pi stays on WebSocket when the bearer rotates for the same account and session', + 'idle', + ], + [ + 'Pi opens a separate WebSocket after bearer rotation while the cached socket is busy', + 'busy', + ], + [ + 'Pi replaces the old WebSocket if it goes idle while the new payload is prepared', + 'payload', + ], +] as const)('%s', async (_title, rotation) => { + const seam = spyOnRawCodexFrames() + const oldSocketClosed = Promise.withResolvers() + const releaseOpening = Promise.withResolvers<() => void>() + let oldWasClosed = false + const upgrades: (string | null)[] = [] + const wire: { socket: number; data: string }[] = [] + const server = Bun.serve({ + hostname: '127.0.0.1', + port: 0, + fetch(request, server) { + const authorization = request.headers.get('authorization') + if (server.upgrade(request, { data: upgrades.length })) { + upgrades.push(authorization) + return + } + return new Response(null, { status: 400 }) + }, + websocket: { + message(socket, frame) { + wire.push({ socket: socket.data, data: frame.toString() }) + const events = responseEvents(wire.length) + const send = (events: unknown[]) => { + for (const event of events) socket.send(JSON.stringify(event)) + } + if (wire.length === 1 && rotation !== 'idle') { + send(events.slice(0, 2)) + releaseOpening.resolve(() => send(events.slice(2))) + } else send(events) + }, + close(socket) { + if (socket.data === 0) { + oldWasClosed = true + oldSocketClosed.resolve() + } + }, + }, + }) + try { + const socketModel = { ...model, baseUrl: server.url.href } + const rotated = chatgptAccessToken('payload-test-account', 'refreshed') + const socketSessionId = `${sessionId}-rotated-${rotation}` + const options = { + ...cachedWebSocketOptions(), + sessionId: socketSessionId, + maxRetries: 0, + fetch: mockFetch(async () => { + throw new Error('Unexpected HTTP fallback after bearer rotation') + }), + } + const start = ( + messages: Context['messages'], + token: string, + onPayload?: SimpleStreamOptions['onPayload'], + ) => + runtime.stream( + socketModel, + { systemPrompt, messages }, + { ...options, apiKey: token, onPayload }, + ) + + const opening = start([firstUser], apiKey) + let secondMessages: Context['messages'] + if (rotation === 'idle') { + const first = await opening.result() + expect(first.responseId).toBe('resp_1') + secondMessages = [firstUser, first, secondUser] + } else { + for await (const event of opening) { + if (event.type === 'error' || event.type === 'done') + throw new Error('Opening turn did not stay active') + if (event.type === 'text_delta') break + } + secondMessages = [firstUser, secondUser] + } + const finishOpening = async () => { + ;(await releaseOpening.promise)() + expect((await opening.result()).responseId).toBe('resp_1') + } + const second = await start( + secondMessages, + rotated, + rotation === 'payload' ? finishOpening : undefined, + ).result() + expect(second.errorMessage).toBeUndefined() + expect(second.responseId).toBe('resp_2') + if (rotation === 'busy') { + expect(oldWasClosed).toBe(false) + await finishOpening() + } else await oldSocketClosed.promise + const third = await start( + [...secondMessages, second, thirdUser], + rotated, + ).result() + expect(third.responseId).toBe('resp_3') + await oldSocketClosed.promise + + expect(upgrades).toEqual([ + `Bearer ${apiKey}`, + `Bearer ${rotated}`, + ...(rotation === 'busy' ? [`Bearer ${rotated}`] : []), + ]) + expect(wire.map(({ socket }) => socket)).toEqual([ + 0, + 1, + rotation === 'busy' ? 2 : 1, + ]) + expect(wire.map(({ data }) => data)).toEqual(seam.frames) + const frames = wire.map(({ data }) => JSON.parse(data)) + expect(frames.map((frame) => frame.previous_response_id)).toEqual([ + undefined, + undefined, + rotation === 'busy' ? undefined : 'resp_2', + ]) + expect(frames[1].input[0]).toMatchObject({ role: 'developer' }) + } finally { + seam.restore() + closeOpenAICodexWebSocketSessions(`${sessionId}-rotated-${rotation}`) + await server.stop(true) + } +}) + function rateLimitsFrame(usedPercent: number) { return { type: 'codex.rate_limits', From 66b5cc70ca1cc91ff45604ca99e4d6b3673f43d9 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:28:10 +0100 Subject: [PATCH 3/3] docs(pi): drop an unexplained term from the socket cache key comment --- packages/pi/src/codex-websocket.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/pi/src/codex-websocket.ts b/packages/pi/src/codex-websocket.ts index a39ceee7..d840dd1f 100644 --- a/packages/pi/src/codex-websocket.ts +++ b/packages/pi/src/codex-websocket.ts @@ -27,7 +27,7 @@ const cachedSockets = new Map() function cacheKey({ sessionId, token }: WebSocketAttempt): string | undefined { if (!sessionId) return // pi-ai keys the cache by the original session ID and the nested JWT claim, - // not by the clamped prompt_cache_key or the plugin's routing account ID. + // not by the prompt_cache_key sent on the wire or the plugin's routing account ID. const accountId = parseJwtClaims(token)?.['https://api.openai.com/auth']?.chatgpt_account_id if (typeof accountId === 'string' && accountId)