-
Notifications
You must be signed in to change notification settings - Fork 1.1k
feat(codex): relay experimental context history and notes #3663
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
y2ambition-ai
wants to merge
2
commits into
lidge-jun:dev
Choose a base branch
from
y2ambition-ai:feat/codex-context-history
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| /** Backend path and opt-in config compatibility for native Codex history/notes. */ | ||
| export const CONTEXT_BACKEND_PREFIX = "/backend-api/codex"; | ||
|
|
||
| const CONTEXT_ENDPOINTS = new Set([ | ||
| "alpha/history/v2/list_windows", "alpha/history/v2/list_items", | ||
| "alpha/history/v2/read_item", "alpha/history/v2/search_contents", | ||
| "alpha/notes/v2/thread_hint", "alpha/notes/v2/list_files_by_prefix", | ||
| "alpha/notes/v2/read_file", "alpha/notes/v2/search_contents", | ||
| "alpha/notes/v2/append_to_file", "alpha/notes/v2/write_file", | ||
| ]); | ||
|
|
||
| export function contextEndpoint(path: string): string | undefined { | ||
| const endpoint = path.startsWith("/v1/") ? path.slice(4) : ""; | ||
| return CONTEXT_ENDPOINTS.has(endpoint) ? endpoint : undefined; | ||
| } | ||
|
|
||
| /** Alias only the data-plane prefix. Existing auth/origin and route gates still run. */ | ||
| export function codexCompatibleUrl(rawUrl: string): URL { | ||
| const url = new URL(rawUrl); | ||
| if (url.pathname === CONTEXT_BACKEND_PREFIX || url.pathname.startsWith(CONTEXT_BACKEND_PREFIX + "/")) { | ||
| url.pathname = "/v1" + url.pathname.slice(CONTEXT_BACKEND_PREFIX.length); | ||
| } | ||
| return url; | ||
| } | ||
|
|
||
| /** Change only marker-managed built-in routing, and only with an explicit context opt-in. */ | ||
| export function contextCompatibleBaseLine(content: string, line: string): string { | ||
| const parsed = Bun.TOML.parse(content) as {features?: {context_management?: {experimental_mode?: boolean}}}; | ||
|
y2ambition-ai marked this conversation as resolved.
Outdated
|
||
| if (parsed.features?.context_management?.experimental_mode !== true) return line; | ||
| const match = /^openai_base_url = "([^"]+)"$/.exec(line); | ||
| if (!match) return line; | ||
| const url = new URL(match[1]); | ||
| if (url.pathname !== "/v1" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)) return line; | ||
| url.pathname = CONTEXT_BACKEND_PREFIX; | ||
| return `openai_base_url = "${url.href}"`; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| /** Native history/notes JSON relay. No interpretation of encrypted tool arguments or retries. */ | ||
| import { formatErrorResponse } from "../bridge"; | ||
| import { | ||
| CodexAccountCooldownError, CodexAuthContextError, CodexMainProfileDrainingError, CodexDirectAuthenticationError, | ||
| CodexPoolAuthenticationError, CodexThreadAffinityExpiredError, | ||
| codexMainProfileDrainingResponse, cooldownErrorResponse, | ||
| headersForCodexAuthContext, isCodexAuthContextUsable, resolveCodexAuthContext, releaseCodexAuthContextProbeLease, | ||
| } from "../codex/auth-context"; | ||
| import { contextEndpoint } from "../codex/context-compat"; | ||
| import { formatCodexProviderForLog } from "../codex/routing"; | ||
| import { listOpenAiForwardSidecarCandidates } from "../providers/openai-sidecar"; | ||
| import { signalWithTimeout } from "../lib/abort"; | ||
| import { readBoundedResponseBytes } from "../lib/bounded-body"; | ||
| import type { AdmissionLease } from "../lib/admission"; | ||
| import type { OcxConfig } from "../types"; | ||
| import { ForwardAdmissionCredentialError, validateForwardAdmissionCredential } from "./auth-cors"; | ||
| import { readJsonRequestBody } from "./request-decompress"; | ||
| import { codexLogAccountId, decodeRequestErrorResponse } from "./responses"; | ||
| import { codexAccountSelectionForTurn } from "./lifecycle"; | ||
| import type { RequestLogContext } from "./request-log"; | ||
|
|
||
| const PROTOCOL_HEADERS = ["x-openai-encrypted-tool-arguments", "x-openai-tool-output-truncation-policy"]; | ||
| const RESPONSE_HEADERS = ["content-type", "retry-after", "x-request-id", "openai-processing-ms", ...PROTOCOL_HEADERS]; | ||
| const MAX_RESPONSE_BYTES = 16 * 1024 * 1024; | ||
|
|
||
| export function contextSelectionHeaders(headers: Headers, sessionId: string): Headers { | ||
| const result = new Headers(headers); | ||
| // Codex history tools carry root session_id in JSON, unlike Responses' HTTP headers. | ||
| // Root model requests use (session-id=root, thread-id=root); don't fabricate a parent key. | ||
| if (!result.has("x-codex-parent-thread-id") && !result.has("session-id") && !result.has("thread-id")) { | ||
| result.set("session-id", sessionId); | ||
| result.set("thread-id", sessionId); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| export async function handleContextHistory( | ||
| req: Request, config: OcxConfig, logCtx: RequestLogContext, | ||
| endpoint: string, turnAdmissionLease?: AdmissionLease, | ||
| ): Promise<Response> { | ||
| if (!contextEndpoint("/v1/" + endpoint) || req.method !== "POST") { | ||
| return formatErrorResponse(404, "not_found", "Unknown context endpoint"); | ||
| } | ||
| try { validateForwardAdmissionCredential(req.headers, config); } | ||
|
y2ambition-ai marked this conversation as resolved.
Outdated
|
||
| catch (err) { | ||
| if (err instanceof ForwardAdmissionCredentialError) return formatErrorResponse(401, "authentication_error", err.message); | ||
| throw err; | ||
| } | ||
| let body: unknown; | ||
| try { body = await readJsonRequestBody(req); } | ||
| catch (err) { return decodeRequestErrorResponse(err, "context_history"); } | ||
| const sessionId = (body as {context?: {session_id?: unknown}} | null)?.context?.session_id; | ||
| if (typeof sessionId !== "string" || !/^[A-Za-z0-9._:-]{1,512}$/.test(sessionId)) { | ||
| return formatErrorResponse(400, "invalid_request_error", "context.session_id must be a bounded nonempty string"); | ||
| } | ||
| const candidate = listOpenAiForwardSidecarCandidates(config)[0]; | ||
| if (!candidate) return formatErrorResponse(400, "invalid_request_error", "History and notes require the native ChatGPT forward provider"); | ||
| let authContext: Awaited<ReturnType<typeof resolveCodexAuthContext>>; | ||
| const headers = new Headers(candidate.provider.headers); | ||
| try { | ||
| authContext = await resolveCodexAuthContext(contextSelectionHeaders(req.headers, sessionId), config, candidate.accountMode, { | ||
| // Non-Spark context tools share the ordinary model quota/affinity scope, not legacy. | ||
| modelId: "context_history", | ||
| beginCodexAccountSelection: codexAccountSelectionForTurn(turnAdmissionLease), | ||
| }); | ||
| if (authContext.kind !== "main" && authContext.probeLeaseId) { | ||
| // History traffic must not occupy or settle the model's quota-recovery probe. | ||
| releaseCodexAuthContextProbeLease(authContext); | ||
| return formatErrorResponse(503, "upstream_error", "Model quota recovery is pending; retry context operation later"); | ||
| } | ||
| if (!isCodexAuthContextUsable(authContext, config)) throw new CodexPoolAuthenticationError("Selected Codex account is unavailable"); | ||
| logCtx.provider = formatCodexProviderForLog(candidate.providerName, codexLogAccountId(authContext), config); | ||
| // Materialization rechecks the current account policy after async selection. | ||
| // Synthetic lane IDs are local selection metadata, never upstream headers. | ||
| for (const [key, value] of headersForCodexAuthContext(req.headers, authContext, config, "context_history")) { | ||
| headers.set(key, value); | ||
| } | ||
| } catch (err) { | ||
| if (err instanceof CodexAccountCooldownError) return cooldownErrorResponse(err); | ||
| if (err instanceof CodexMainProfileDrainingError) return codexMainProfileDrainingResponse(); | ||
| if (err instanceof CodexThreadAffinityExpiredError) return formatErrorResponse(409, "invalid_request_error", "Codex thread account affinity expired; start a new session"); | ||
| if (err instanceof CodexAuthContextError || err instanceof CodexPoolAuthenticationError || err instanceof CodexDirectAuthenticationError) { | ||
| return formatErrorResponse(401, "authentication_error", "Selected Codex account is unavailable or needs reauthentication"); | ||
| } | ||
| throw err; | ||
| } | ||
| headers.set("content-type", "application/json"); | ||
| for (const key of PROTOCOL_HEADERS) { | ||
| const value = req.headers.get(key); if (value !== null) headers.set(key, value); | ||
| } | ||
| const deadline = signalWithTimeout(35_000, req.signal); | ||
| let response: Response | undefined; | ||
| try { | ||
| response = await fetch(`${candidate.provider.baseUrl}/${endpoint}`, { | ||
| method: "POST", headers, body: JSON.stringify(body), signal: deadline.signal, redirect: "manual", | ||
| }); | ||
| const result = await readBoundedResponseBytes(response, {maxBytes: MAX_RESPONSE_BYTES, signal: deadline.signal}); | ||
| if (result.oversized) return formatErrorResponse(502, "upstream_error", "Context response exceeded 16 MiB"); | ||
| const outputHeaders = new Headers(); | ||
| for (const key of RESPONSE_HEADERS) { | ||
| const value = response.headers.get(key); if (value !== null) outputHeaders.set(key, value); | ||
| } | ||
| // A context 403 is not evidence that the model credential is invalid. Don't mutate pool | ||
| // health/quota or retry writes; preserve the real upstream result for the caller. | ||
| return new Response([204,205,304].includes(response.status) ? null : result.bytes, {status:response.status, headers:outputHeaders}); | ||
| } catch { | ||
| if (req.signal.aborted) return formatErrorResponse(499, "client_closed_request", "Context request canceled by client"); | ||
| if (deadline.signal.aborted) return formatErrorResponse(504, "upstream_error", "Context upstream timed out"); | ||
| return formatErrorResponse(502, "upstream_error", "Context upstream connection failed"); | ||
| } finally { | ||
| deadline.cleanup(); | ||
| if (response?.body && !response.body.locked) void response.body.cancel().catch(() => undefined); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.