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
4 changes: 4 additions & 0 deletions packages/ai/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## [Unreleased]

### Fixed

- Fixed OpenAI Codex websocket continuations to retry with full context when `previous_response_id` expires server-side instead of surfacing `previous_response_not_found`.

## [14.6.2] - 2026-05-03
### Added

Expand Down
41 changes: 41 additions & 0 deletions packages/ai/src/providers/openai-codex-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1221,6 +1221,9 @@ async function recoverCodexStreamError(
if (await tryReconnectCodexWebSocketOnConnectionLimit(context, runtime, error)) {
return true;
}
if (await tryRecoverCodexPreviousResponseNotFound(context, runtime, error)) {
return true;
}
if (await tryReplayWebsocketFailureOverSse(context, runtime, error)) {
return true;
}
Expand Down Expand Up @@ -1279,6 +1282,44 @@ async function tryReconnectCodexWebSocketOnConnectionLimit(
return true;
}

function isCodexPreviousResponseNotFound(error: unknown): boolean {
return error instanceof CodexProviderStreamError && error.code === "previous_response_not_found";
}

async function tryRecoverCodexPreviousResponseNotFound(
context: CodexStreamProcessingContext,
runtime: CodexStreamRuntime,
error: unknown,
): Promise<boolean> {
const websocketState = context.requestContext.websocketState;
if (
!isCodexPreviousResponseNotFound(error) ||
!websocketState ||
runtime.transport !== "websocket" ||
context.output.content.length > 0 ||
context.options?.signal?.aborted ||
runtime.providerRetryAttempt >= CODEX_MAX_RETRIES
) {
return false;
}

runtime.providerRetryAttempt += 1;
resetCodexWebSocketAppendState(websocketState);
resetCodexSessionMetadata(websocketState);
runtime.currentItem = null;
runtime.currentBlock = null;
runtime.sawTerminalEvent = false;
runtime.nativeOutputItems.length = 0;
resetOutputState(context.output);
context.firstTokenTime = undefined;

logCodexDebug("codex previous_response_id expired; retrying with full context", {
retry: runtime.providerRetryAttempt,
});
await reopenCodexWebSocketRuntimeStream(context, runtime, websocketState);
return true;
}

async function tryReplayWebsocketFailureOverSse(
context: CodexStreamProcessingContext,
runtime: CodexStreamRuntime,
Expand Down
108 changes: 108 additions & 0 deletions packages/ai/test/openai-codex-stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1416,6 +1416,114 @@ describe("openai-codex streaming", () => {
});
});

it("retries websocket continuations with full context when previous_response_id expires", async () => {
const tempDir = TempDir.createSync("@pi-codex-stream-");
setAgentDir(tempDir.path());
const token = createCodexTestToken();
const sentRequests: Array<Record<string, unknown>> = [];
const fetchMock = vi.fn(async () => {
throw new Error("SSE fallback should not be called");
});
global.fetch = fetchMock as unknown as typeof fetch;

class PreviousResponseMissingWebSocket extends MockWebSocket {
constructor(url: string, options?: { headers?: WsHeaders }) {
super(url, options);
this.scheduleOpen();
}

send(data: string): void {
const request = JSON.parse(data) as Record<string, unknown>;
sentRequests.push(request);
const requestIndex = sentRequests.length;

if (requestIndex === 1) {
this.emitCodexResponse({
messageId: "msg_1",
responseId: "resp_1",
text: "First answer",
terminalType: "response.completed",
includeCreated: true,
});
return;
}

if (requestIndex === 2) {
expect(request.previous_response_id).toBe("resp_1");
this.sendJson({
type: "error",
code: "previous_response_not_found",
message: "Previous response with id 'resp_1' not found.",
});
return;
}

if (requestIndex === 3) {
expect(request.previous_response_id).toBeUndefined();
this.emitCodexResponse({
messageId: "msg_3",
responseId: "resp_3",
text: "Second answer",
terminalType: "response.completed",
includeCreated: true,
});
return;
}

throw new Error(`Unexpected websocket request index: ${requestIndex}`);
}
}

global.WebSocket = PreviousResponseMissingWebSocket as unknown as typeof WebSocket;
const model = createCodexTestModel("https://chatgpt.com/backend-api");
const providerSessionState = new Map<string, ProviderSessionState>();
const firstContext: Context = {
systemPrompt: "You are a helpful assistant.",
messages: [{ role: "user", content: "First question", timestamp: Date.now() }],
};
const firstResponse = await streamOpenAICodexResponses(model, firstContext, {
apiKey: token,
sessionId: "ws-expired-previous-response-session",
providerSessionState,
}).result();
const secondContext: Context = {
systemPrompt: "You are a helpful assistant.",
messages: [
...firstContext.messages,
firstResponse,
{ role: "user", content: "Second question", timestamp: Date.now() + 1 },
],
};

const secondResponse = await streamOpenAICodexResponses(model, secondContext, {
apiKey: token,
sessionId: "ws-expired-previous-response-session",
providerSessionState,
}).result();

expect(secondResponse.stopReason).toBe("stop");
expect(JSON.stringify(secondResponse.content)).toContain("Second answer");
expect(fetchMock).not.toHaveBeenCalled();
expect(sentRequests).toHaveLength(3);
expect(sentRequests[2]?.prompt_cache_key).toBe("ws-expired-previous-response-session");
const retryInput = sentRequests[2]?.input;
expect(Array.isArray(retryInput)).toBe(true);
expect(JSON.stringify(retryInput)).toContain("First question");
expect(JSON.stringify(retryInput)).toContain("Second question");

const stats = getOpenAICodexWebSocketDebugStats(model, {
sessionId: "ws-expired-previous-response-session",
providerSessionState,
});
expect(stats).toEqual({
fullContextRequests: 2,
deltaRequests: 1,
lastInputItems: (retryInput as unknown[]).length,
lastDeltaInputItems: undefined,
lastPreviousResponseId: undefined,
});
});

it("uses low Codex text verbosity by default while preserving explicit overrides", async () => {
const tempDir = TempDir.createSync("@pi-codex-verbosity-");
setAgentDir(tempDir.path());
Expand Down
Loading