Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 171 additions & 0 deletions packages/pi/src/codex-websocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
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'

type WebSocketOptions = string | string[] | { headers?: Record<string, string> }
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
sessionId?: string | undefined
onMessage(data: string): void
}

type ScopedAttempt = WebSocketAttempt & {
cacheKey?: string | undefined
settled: boolean
}

const attemptScope = new AsyncLocalStorage<ScopedAttempt>()
const cachedSockets = new Map<string, PiRawCodexWebSocket>()

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 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)
return JSON.stringify([sessionId, accountId])
}

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<unknown> },
>(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: Pick<WebSocketAttempt, 'url' | 'token' | 'owner'>
private readonly cacheKey?: string
private activeAttempt?: ScopedAttempt

constructor(attempt: ScopedAttempt, headers: Record<string, string>) {
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.activeAttempt?.onMessage(data)
})
}

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 (
this.readyState === 1 &&
this.activeAttempt?.settled &&
!this.matches(attempt)
) {
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()
}
// 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))
}
}

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
}
}
}
73 changes: 73 additions & 0 deletions packages/pi/src/codex-wire.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>) {
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 }
}
64 changes: 4 additions & 60 deletions packages/pi/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> }
| 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<string, string>, 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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) =>
Expand Down
Loading
Loading