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
24 changes: 13 additions & 11 deletions docs/limit-policy-conformance.md

Large diffs are not rendered by default.

40 changes: 40 additions & 0 deletions packages/opencode/src/codex-request.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,48 @@
import {
type CodexRequestRuntime,
type CodexSessionMetadata,
type FrameTurn,
prepareCodexRequest,
updateHttpTurnMetadata,
uuidV7,
} from '@cortexkit/openai-auth-core/internal'

export type { CodexSessionMetadata } from '@cortexkit/openai-auth-core/internal'
// Keep the benchmark's imports working alongside the host's shared builder.
export { prepareCodexRequest, updateHttpTurnMetadata }

/** The last primary turn sent on either transport, without either transport's history. */
export class CodexPrimaryTurns {
// Key by the live session so forgetting its metadata also forgets the turn.
readonly #latest = new WeakMap<CodexSessionMetadata, FrameTurn>()

record(
session: CodexSessionMetadata,
{
turnID,
turnStartedAt,
}: Pick<CodexSessionMetadata, keyof FrameTurn> = session,
): void {
if (turnStartedAt !== undefined)
this.#latest.set(session, { turnID, turnStartedAt })
}

forAuxiliary(
session: CodexSessionMetadata,
runtime?: CodexRequestRuntime,
): CodexSessionMetadata {
const turn = this.#latest.get(session) ?? {
turnID: (runtime?.uuid ?? uuidV7)(),
turnStartedAt: (runtime?.now ?? Date.now)(),
}
return {
threadID: session.threadID,
windowID: session.windowID,
...turn,
// OpenCode 1 can replay effort changes when it shapes a helper. Let it
// do so without editing entries the next conversational request needs.
pinnedEffort: session.pinnedEffort,
effortUpdates: session.effortUpdates?.map((update) => ({ ...update })),
}
}
}
50 changes: 41 additions & 9 deletions packages/opencode/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ import type {
} from '@opencode-ai/plugin'
import { createAuthMethods } from './auth/methods'
import { applyMidConversationEffort } from './codex-effort'
import { CodexPrimaryTurns } from './codex-request'
import {
codexSessionsSettled,
loadCodexSessions,
Expand Down Expand Up @@ -580,6 +581,7 @@ export async function CodexAuthPlugin(
options.codexApiEndpoint ?? startupSettings.codexApiEndpoint
const installationID = crypto.randomUUID()
const codexSessions = loadCodexSessions(codexSessionStatePath())
const codexPrimaryTurns = new CodexPrimaryTurns()
const persistCodexSessions = () =>
saveCodexSessions(codexSessionStatePath(), codexSessions)
let websocketFetchInstalled = false
Expand Down Expand Up @@ -2645,6 +2647,13 @@ export async function CodexAuthPlugin(

const sessionID = resolveSidebarSessionId(headers)
const agent = headers.get(OPENAI_AGENT_HEADER) ?? undefined
const auxiliary =
agent &&
['title', 'compaction', 'summary', 'generate'].includes(agent)
? agent
: headers.get(OpenAIWebSocketPool.TITLE_HEADER) === 'true'
? 'title'
: undefined

const codexMetadata = sessionID
? getCodexSessionMetadata(
Expand All @@ -2667,21 +2676,30 @@ export async function CodexAuthPlugin(
parsed.pathname.includes('/chat/completions')
? new URL(codexApiEndpoint)
: parsed
const useWebSocket = Boolean(
websocketFetch && parsed.pathname.endsWith('/responses'),
)
const prepared = prepareCodexRequest({
applyEffort: applyMidConversationEffort,
init: {
...init,
headers,
},
headers,
metadata: codexMetadata,
metadata:
auxiliary && codexMetadata
? codexPrimaryTurns.forAuxiliary(codexMetadata)
: codexMetadata,
installationID,
websocket: Boolean(
websocketFetch && parsed.pathname.endsWith('/responses'),
),
websocket: useWebSocket,
skipTurnUpdate: auxiliary !== undefined,
responsesLite: options.responsesLite ?? false,
dumpSessionID: sessionID,
})
const preparedTurn = codexMetadata && {
turnID: codexMetadata.turnID,
turnStartedAt: codexMetadata.turnStartedAt,
}
const requestInit = prepared.init
if (limitsRequest) {
const bindingIsActive = () => {
Expand Down Expand Up @@ -2804,7 +2822,7 @@ export async function CodexAuthPlugin(
sessionId: keepwarmHeaders.get('session-id'),
})
}
if (websocketFetch && parsed.pathname.endsWith('/responses')) {
if (websocketFetch && useWebSocket) {
logT.debug('WS transport', {
pid: process.pid,
pathname: parsed.pathname,
Expand All @@ -2829,10 +2847,22 @@ export async function CodexAuthPlugin(
scopedHeaders.set(OpenAIWebSocketPool.QUOTA_ACCOUNT_HEADER, key)
const release = () => streams.delete(key)
try {
const response = await websocketFetch(url, {
...requestInit,
headers: scopedHeaders,
})
const response = await websocketFetch(
url,
{ ...requestInit, headers: scopedHeaders },
auxiliary
? { kind: 'auxiliary', agent: auxiliary }
: {
kind: 'primary',
record: (turn) => {
if (codexMetadata)
codexPrimaryTurns.record(
codexMetadata,
turn ?? preparedTurn,
)
},
},
)
if (!response.body) {
release()
return reportResponse(response)
Expand Down Expand Up @@ -2876,6 +2906,8 @@ export async function CodexAuthPlugin(
throw redactCredentialError(error, accessToken)
}
}
if (codexMetadata && !auxiliary)
codexPrimaryTurns.record(codexMetadata, preparedTurn)
const finalInit =
OpenAIWebSocketPool.withoutInternalHeaders(requestInit)
if (typeof finalInit?.body !== 'string') {
Expand Down
174 changes: 174 additions & 0 deletions packages/opencode/src/tests/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2397,6 +2397,180 @@ describe('integration: WS quota push', () => {
delete process.env.NODE_ENV
})

it('OC1 WebSocket helpers inherit turns without changing primary resends or continuation', async () => {
writeFileSync(
configFile,
JSON.stringify({
version: 1,
main: { type: 'opencode', provider: 'openai' },
accounts: [],
}),
)
const originalFetch = globalThis.fetch
const httpTurns: string[] = []
globalThis.fetch = (async (url, init) => {
if (!isResponsesSend(url)) return new Response(null, { status: 503 })
httpTurns.push(new Headers(init?.headers).get('x-codex-turn-metadata')!)
return new Response('{}')
}) as typeof fetch
type Frame = {
client_metadata: { 'x-codex-turn-metadata': string }
generate?: boolean
previous_response_id?: string
input: unknown[]
}
const frames: Array<{ frame: Frame; prewarmID: string | undefined }> = []
let prewarms = 0
let incomplete = false
const user = (text: string) => ({
type: 'message',
role: 'user',
content: [{ type: 'input_text', text }],
})
const input = [user('one')]
const tool = { type: 'function_call_output', call_id: 'c1', output: 'ok' }
try {
await withFakeWebSocket(
({ message }) => {
let prewarmID: string | undefined
return {
send(text) {
const frame: Frame = JSON.parse(text)
const prewarm = frame.generate === false
if (prewarm) prewarmID = `warm_${++prewarms}`
else frames.push({ frame, prewarmID })
message(
JSON.stringify({
type:
incomplete && !prewarm
? 'response.incomplete'
: 'response.completed',
response: {
id: prewarm ? prewarmID : `resp_${frames.length}`,
},
}),
)
},
}
},
async () => {
const hooks = await CodexAuthPlugin(createMockPluginInput(), {
experimentalWebSockets: true,
})
scope.ownPlugin(hooks)
const loaded = await hooks.auth!.loader!(
async () => ({
type: 'oauth',
access: 'main-access',
refresh: 'main-refresh',
expires: Date.now() + 3600_000,
accountId: 'chatgpt-main',
}),
{ id: 'openai', models: {} } as never,
)
const fetchOverride = scope.wrap(
(loaded as { fetch: typeof fetch }).fetch,
)
const send = async (
session: string,
agent: string,
items: unknown[],
stream = true,
) => {
const response = await fetchOverride(
'https://api.openai.com/v1/responses',
{
method: 'POST',
headers: {
'content-type': 'application/json',
'session-id': session,
'x-openai-auth-agent': agent,
...(agent === 'title' ? { 'x-opencode-title': 'true' } : {}),
},
body: JSON.stringify({
model: 'gpt-6.1-sol',
input: items,
stream,
}),
},
)
expect(response.status).toBe(200)
await response.text()
if (agent === 'title' || !stream) return { turn: httpTurns.at(-1) }
const { frame, prewarmID } = frames.at(-1)!
return {
frame,
prewarmID,
turn: frame.client_metadata['x-codex-turn-metadata'],
}
}

const early = await send('auxiliary-first', 'generate', input)
const first = await send('auxiliary-first', 'build', input)
expect(first.turn).not.toBe(early.turn)
// On a fresh socket the pool sends an empty request with generation
// disabled. The primary can chain to that response, not the helper's.
expect(first.frame?.previous_response_id).toBe(first.prewarmID)
expect(first.prewarmID).not.toBe(early.prewarmID)

const run = async (session: string, interleave: boolean) => {
incomplete = true
const opening = await send(session, 'build', input)
incomplete = false
if (interleave) {
const summary = await send(session, 'summary', [
user('summarize'),
])
expect(summary.turn).toBe(opening.turn)
expect(summary.frame?.previous_response_id).toBe(
summary.prewarmID,
)
}
const resend = await send(session, 'build', input)
const responseID = `resp_${frames.length}`
if (interleave) {
const compact = await send(session, 'compaction', [
user('compact'),
])
expect(compact.turn).toBe(opening.turn)
const title = await send(session, 'title', [user('title')])
expect(title.turn).toBe(opening.turn)
}
const step = await send(session, 'build', [...input, tool])
expect(step.frame?.previous_response_id).toBe(responseID)
return {
resendKeptTurn: resend.turn === opening.turn,
resendChainedOnlyToPrewarm:
resend.frame?.previous_response_id === resend.prewarmID,
resendInput: resend.frame?.input,
stepKeptTurn: step.turn === opening.turn,
stepInput: step.frame?.input,
}
}
const control = await run('primary-only', false)
expect(control).toEqual({
resendKeptTurn: true,
resendChainedOnlyToPrewarm: true,
resendInput: input,
stepKeptTurn: true,
stepInput: [tool],
})
expect(await run('interleaved', true)).toEqual(control)
const overHttp = await send('mixed', 'build', input, false)
const overWebSocket = await send('mixed', 'generate', [
user('helper'),
])
expect(overWebSocket.turn).toBe(overHttp.turn)
expect(httpTurns).toHaveLength(2)
expect(frames).toHaveLength(11)
},
)
} finally {
await scope.settlePluginWork()
globalThis.fetch = originalFetch
}
})

it('attributes an early fallback WS quota push to the served fallback', async () => {
const now = Date.now()
const fallback = {
Expand Down
Loading
Loading