@opengeni/codex 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ import type { FetchLike } from "./fetch";
2
+ /**
3
+ * Maps connector tool names to a Responses-API-legal charset and back. One
4
+ * instance per codex_apps transport (i.e. per turn): tools/list populates it,
5
+ * tools/call reads it. Idempotent across repeat listings.
6
+ */
7
+ export declare class ToolNameMapper {
8
+ private readonly sanitizedToOriginal;
9
+ private readonly used;
10
+ /** Return a legal, unique name (<= EFFECTIVE_MAX_TOOL_NAME_LEN, so `<prefix>__name` <= 64) for `original`, recording the reverse mapping. */
11
+ sanitize(original: string): string;
12
+ /** Reverse a sanitized name back to the MCP server's original, if known. */
13
+ toOriginal(sanitized: string): string | undefined;
14
+ }
15
+ /** Sanitize a single JSON body (application/json MCP response). */
16
+ export declare function sanitizeMcpJsonBody(text: string, mapper?: ToolNameMapper, namespaceSink?: Set<string>): string;
17
+ /** Sanitize an SSE body: each JSON-RPC message rides on a `data:` line. */
18
+ export declare function sanitizeMcpSseBody(text: string, mapper?: ToolNameMapper, namespaceSink?: Set<string>): string;
19
+ /** Reverse a sanitized tools/call name back to the original; returns null if no rewrite is needed. */
20
+ export declare function remapToolCallRequestBody(body: string, mapper: ToolNameMapper): string | null;
21
+ /**
22
+ * Wrap a base fetch so the codex_apps MCP transport is Responses-API-compatible:
23
+ * tools/list responses get their names sanitized + bad outputSchemas dropped (and
24
+ * the name mapping recorded), and tools/call requests get their name reversed back
25
+ * to the MCP server's original. Only the POST request/response is buffered; the
26
+ * long-lived GET notification SSE stream is passed through untouched.
27
+ *
28
+ * P4 (Part B.1): an optional `namespaceSink` Set accumulates the ORIGINAL-dotted
29
+ * connector namespaces seen across every tools/list this turn (captured before the
30
+ * dot is sanitized away). The worker reads the (live, by-reference) Set after the
31
+ * turn to cache the serving account's connector set — packages/codex stays db-free.
32
+ */
33
+ export declare function codexAppsSanitizingFetch(base?: FetchLike, namespaceSink?: Set<string>): FetchLike;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Canonical model-facing tool-output truncation.
3
+ *
4
+ * Ported from openai/codex `rust-v0.144.6` (commit
5
+ * 5d1fbf26c43abc65a203928b2e31561cb039e06d):
6
+ *
7
+ * - `codex-rs/utils/string/src/truncate.rs`
8
+ * - `codex-rs/utils/output-truncation/src/lib.rs`
9
+ * - `codex-rs/core/src/context_manager/history.rs`
10
+ *
11
+ * The live gpt-5.6 model catalog declares a 10,000-token truncation policy.
12
+ * Codex applies a 1.2x allowance before serializing a function-call output, so
13
+ * the effective textual payload budget is 12,000 approximate tokens. Images,
14
+ * files, and encrypted content are preserved; textual content shares one
15
+ * sequential budget and carries an explicit head/tail truncation marker.
16
+ *
17
+ * This module deliberately has no database or Agents SDK dependency. Both the
18
+ * runtime request seam and the database history boundary call the same pure
19
+ * function, so replayed conversation truth is identical to live model input.
20
+ */
21
+ export { MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL } from "./oversized-image-card";
22
+ export type ModelHistoryItem = Record<string, unknown>;
23
+ export declare const CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS = 10000;
24
+ export declare const CODEX_TOOL_OUTPUT_SERIALIZATION_ALLOWANCE = 1.2;
25
+ export declare const DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS = 10000;
26
+ export declare const MODEL_TOOL_OUTPUT_OPAQUE_PAYLOAD_MAX_BYTES: number;
27
+ export declare function modelToolOutputSerializationBudgetTokens(policyTokens?: number): number;
28
+ export declare function approximateTokenCount(value: string): number;
29
+ /** Exact Codex-style middle truncation for a token policy. */
30
+ export declare function truncateMiddleWithTokenBudget(value: string, maxTokens: number): string;
31
+ /**
32
+ * Bound every model-visible tool-result item. Non-result items are returned by
33
+ * reference. Result items are cloned only when their textual output changes.
34
+ */
35
+ export declare function boundModelToolOutputItem<T extends ModelHistoryItem>(item: T, policyTokens?: number): T;
36
+ export declare function boundModelToolOutputItems<T extends ModelHistoryItem>(items: readonly T[], policyTokens?: number): T[];
@@ -0,0 +1,8 @@
1
+ /** Mutates a parsed Responses request body in place and returns it. Pure + synchronous + unit-testable. */
2
+ export declare function normalizeCodexRequestBody(body: Record<string, unknown>, resolveModel: (slug: string) => string): Record<string, unknown>;
3
+ /**
4
+ * Build a longest-prefix model resolver. Catalog slugs come from GET /models
5
+ * (api-client.ts). One leading `namespace/` segment is stripped first; an
6
+ * unknown slug returns the fallback (caller should log — spec §1.4 step 4).
7
+ */
8
+ export declare function buildModelResolver(liveSlugs: readonly string[], fallbackSlug: string): (slug: string) => string;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Protocol-valid image shown to the model when an inline tool image exceeds the
3
+ * hard model-input allowance. The image channel cannot carry a text marker, so
4
+ * the omission itself is rendered as a legible PNG instead of corrupting the
5
+ * original base64 or pretending the placeholder is the real screenshot.
6
+ *
7
+ * Generated with the dependency-free bitmap/PNG encoder documented in
8
+ * `scripts/gen-screenshot-error-card.mjs`; the source image is 1,076x284 RGBA
9
+ * and 5,255 bytes. Rendered text:
10
+ *
11
+ * SCREEN CAPTURE OMITTED
12
+ * THE SCREEN CAPTURE IS TOO LARGE.
13
+ * THIS IS A PLACEHOLDER, NOT THE REAL SCREEN.
14
+ * DO NOT SAY THIS IS THE REAL SCREEN.
15
+ * TELL THE USER TO TAKE A SMALLER CAPTURE.
16
+ */
17
+ export declare const MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDQAAAEcCAYAAAA4KeSGAAAUTklEQVR42u3cO5JTvRaAUcZAEXTA0BhZT9GJE8fNEBojbWk/VrCi+2OMjqzHd6vOj88/P78AAAAAKvlhEAAAAABBAwAAAEDQAAAAABA0AAAAAEEDAAAAQNAAAAAAEDQAAAAAQQMAAABA0AAAAAAQNAAAAABBAwAAAEDQAAAAABA0AAAAAEEDAAAAQNAAAAAAEDQ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ff+qNj7V17/T58Pq+5egIWgIGoKGoCFoCBqChvVH0BA0BA1Bw/4laAgaggaChqAhaDjwCxoOhIKGoCFoCBrmp6AhaAgagoaggaAhaLhQCBqChqAhaAgagoagIWgIGoKGoCFoCBqCBgAAAICgAQAAACBoAAAAAIIGAAAAgKABAAAAIGgAAAAAggYAAACAoAEAAAAgaAAAAACCBgAAAICgAQAAACBoAAAAAAgaAAAAgKABAAAAIGgAAAAACBoAAACAoAEAAAAgaAAAAAAIGgAAAICgAQAAACBoAAAAAAgaAAAAgKABAAAAIGgAAAAAbPAXSdffkpULfXUAAAAASUVORK5CYII=";
@@ -0,0 +1,28 @@
1
+ import type { CodexFetch } from "./device-code";
2
+ /** Permanent — the workspace must reconnect (status => needs_relogin). */
3
+ export declare class CodexReloginRequired extends Error {
4
+ constructor(message: string);
5
+ }
6
+ /** Transient — safe to retry later. */
7
+ export declare class CodexRefreshTransient extends Error {
8
+ constructor(message: string);
9
+ }
10
+ /** Only present fields are returned (the server may rotate any subset). */
11
+ export type CodexRefreshTokens = {
12
+ idToken?: string | undefined;
13
+ accessToken?: string | undefined;
14
+ refreshToken?: string | undefined;
15
+ };
16
+ /** POST {issuer}/oauth/token JSON {client_id, grant_type:"refresh_token", refresh_token}. manager.rs:1336-1340 */
17
+ export declare function refreshCodexToken(refreshToken: string, fetchImpl?: CodexFetch, timeoutMs?: number): Promise<CodexRefreshTokens>;
18
+ /** Decode a JWT payload (base64url, no signature check). */
19
+ export declare function decodeJwtPayload(jwt: string): Record<string, unknown> | null;
20
+ /** access-token `exp` claim -> Date | null. token_data.rs:101-105 */
21
+ export declare function accessTokenExpiry(accessToken: string): Date | null;
22
+ /** id_token -> {chatgptAccountId, planType, isFedramp}. server.rs:827-832; token_data.rs:71-99 */
23
+ export declare function parseIdToken(idToken: string): {
24
+ chatgptAccountId: string | null;
25
+ planType: string | null;
26
+ isFedramp: boolean;
27
+ email: string | null;
28
+ };
@@ -0,0 +1,99 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ export type CodexTokenSnapshot = {
3
+ accessToken: string;
4
+ chatgptAccountId: string | null;
5
+ isFedramp: boolean;
6
+ };
7
+ /**
8
+ * Multi-account P4 (Part A): a full usage snapshot scraped FOR FREE from the
9
+ * `x-codex-primary-*` / `x-codex-secondary-*` response headers the codex backend
10
+ * stamps on every `/codex/responses` turn (success AND 429 hard-cap). Integer-
11
+ * identical to GET /wham/usage but with zero extra round-trip. parseCodexUsageHeaders
12
+ * returns this only when BOTH windows parse, so a write is always a full 5-column
13
+ * snapshot (no partial-window clobber). Shape mirrors db's CodexAccountUsageSnapshot
14
+ * (non-null here: a partial read is filtered to null upstream, never half-written).
15
+ */
16
+ export type CodexUsageHeaderSnapshot = {
17
+ primaryUsedPercent: number;
18
+ primaryResetAt: Date;
19
+ secondaryUsedPercent: number;
20
+ secondaryResetAt: Date;
21
+ checkedAt: Date;
22
+ };
23
+ export type CodexResponseTimeoutClass = "connect" | "headers" | "idle_stream" | "whole_request";
24
+ export type CodexResponseTimeoutPolicy = {
25
+ /** Maximum wait for response headers, including DNS/TCP/TLS establishment. */
26
+ headersTimeoutMs: number;
27
+ /** Maximum silence between response-body chunks after headers arrive. */
28
+ streamIdleTimeoutMs: number;
29
+ /** Maximum wall time for one logical Responses request. */
30
+ wholeRequestTimeoutMs: number;
31
+ /**
32
+ * Reserved compatibility field. It is currently normalized to zero because
33
+ * an absent response does not prove that the provider never accepted a
34
+ * request, so automatic replay is not safe without an operation receipt.
35
+ */
36
+ noByteRetries: number;
37
+ retryBackoffMs: number;
38
+ };
39
+ export type CodexModelRequestEvent = {
40
+ requestId: string;
41
+ transportAttempt: number;
42
+ phase: "started" | "headers" | "first_byte" | "completed" | "failed" | "timed_out";
43
+ model?: string;
44
+ durationMs: number;
45
+ responseObserved: boolean;
46
+ timeoutPolicy: CodexResponseTimeoutPolicy;
47
+ timeoutClass?: CodexResponseTimeoutClass;
48
+ providerRequestId?: string;
49
+ status?: number;
50
+ willRetry?: boolean;
51
+ };
52
+ export type CodexRequestContext = {
53
+ clientVersion: string;
54
+ /**
55
+ * Stable per-session affinity id, sent as the `session_id` header on every
56
+ * request. This is the backend's STICKY CACHE-ROUTING key — measured
57
+ * 2026-07-12 with byte-identical ~99k-token gpt-5.6-sol requests on one idle
58
+ * account: without the header, repeat requests hit the prompt cache ~50% of
59
+ * the time (a per-request routing lottery across cache shards; matches the
60
+ * prod fleet's 48.6%); with a stable session_id, 10/10 requests hit at the
61
+ * 99.0% ceiling — Codex CLI parity (the CLI always sends it; its own last-3d
62
+ * token-weighted rate here is 94%). `prompt_cache_key` in the body only
63
+ * influences routing and does NOT pin it. Use the SAME value as
64
+ * prompt_cache_key (the OpenGeni sessionId) so routing and cache key agree.
65
+ */
66
+ sessionId?: string;
67
+ /** Worker-supplied: proactive refresh + single-flight + db persist. */
68
+ getToken: () => Promise<CodexTokenSnapshot>;
69
+ /** Forced refresh used for the 401 retry. */
70
+ refresh: () => Promise<CodexTokenSnapshot>;
71
+ /** Model-slug resolver (longest-prefix against the live catalog). */
72
+ resolveModel: (slug: string) => string;
73
+ /**
74
+ * Multi-account P4 (Part A): fire-and-forget usage-header sink. Called by
75
+ * codexSubscriptionFetch on EVERY response (sync, non-throwing, never awaited)
76
+ * with the parsed full-window snapshot. The worker records the latest into the
77
+ * P2 usage cache once per turn in its `finally` — packages/codex stays db-free.
78
+ */
79
+ onUsageHeaders?: (snapshot: CodexUsageHeaderSnapshot) => void;
80
+ /** Optional per-run override, primarily for deterministic transport tests. */
81
+ responseTimeoutPolicy?: Partial<CodexResponseTimeoutPolicy>;
82
+ /** Worker-owned durable audit sink; payloads never contain request bodies or auth. */
83
+ onModelRequestEvent?: (event: CodexModelRequestEvent) => Promise<void> | void;
84
+ /** Stable request identity supplied by the owning durable execution. */
85
+ nextRequestId?: () => string;
86
+ /**
87
+ * Optional Codex beta feature flags advertised as `x-codex-beta-features`
88
+ * (comma-separated). Used for remote compaction v2 (`remote_compaction_v2`).
89
+ */
90
+ betaFeatures?: readonly string[];
91
+ /**
92
+ * Optional turn analytics / routing metadata sent as `x-codex-turn-metadata`
93
+ * (JSON). Body `metadata` is stripped by normalize — never put request_kind there.
94
+ */
95
+ turnMetadata?: Record<string, unknown>;
96
+ };
97
+ export declare const codexRequestStorage: AsyncLocalStorage<CodexRequestContext>;
98
+ /** Nest a Codex ALS scope with header overrides (e.g. remote compaction v2). */
99
+ export declare function withCodexRequestOverrides<T>(overrides: Pick<CodexRequestContext, "betaFeatures" | "turnMetadata">, fn: () => T): T;
@@ -0,0 +1,33 @@
1
+ export declare const CODEX_RATE_LIMIT_RESET_OUTCOMES: readonly ["reset", "nothingToReset", "noCredit", "alreadyRedeemed"];
2
+ export type CodexRateLimitResetOutcome = (typeof CODEX_RATE_LIMIT_RESET_OUTCOMES)[number];
3
+ export type CodexRateLimitResetType = "codexRateLimits" | "unknown";
4
+ export type CodexRateLimitResetCreditStatus = "available" | "redeeming" | "redeemed" | "unknown";
5
+ export type CodexRateLimitResetCredit = {
6
+ id: string;
7
+ resetType: CodexRateLimitResetType;
8
+ status: CodexRateLimitResetCreditStatus;
9
+ /** Unix seconds, matching account/rateLimits/read in Codex v0.144.6. */
10
+ grantedAt: number;
11
+ /** Unix seconds, or null when the provider says the credit does not expire. */
12
+ expiresAt: number | null;
13
+ title: string | null;
14
+ description: string | null;
15
+ };
16
+ export type CodexRateLimitResetCreditsDetails = {
17
+ availableCount: number;
18
+ credits: CodexRateLimitResetCredit[];
19
+ };
20
+ export type CodexRateLimitResetCreditsSummary = {
21
+ availableCount: number;
22
+ /** null means the provider supplied an authoritative count but no detail rows. */
23
+ credits: null;
24
+ };
25
+ export type CodexRateLimitResetConsumeResponse = {
26
+ outcome: CodexRateLimitResetOutcome;
27
+ };
28
+ /** Parse the exact detailed-credit backend response. Unknown rows stay view-only. */
29
+ export declare function parseCodexRateLimitResetCreditsDetails(payload: unknown): CodexRateLimitResetCreditsDetails | null;
30
+ /** Parse the count-only summary carried by GET /wham/usage. */
31
+ export declare function parseCodexRateLimitResetCreditsSummary(payload: unknown): CodexRateLimitResetCreditsSummary | null;
32
+ /** Parse one of the exact four v0.144.6 consume outcomes. Unknowns fail closed. */
33
+ export declare function parseCodexRateLimitResetConsumeResponse(payload: unknown): CodexRateLimitResetConsumeResponse | null;
@@ -0,0 +1,28 @@
1
+ import type { CodexResponseTimeoutClass, CodexResponseTimeoutPolicy } from "./request-context";
2
+ export declare const CODEX_RESPONSE_TIMEOUT_ERROR_TYPE = "opengeni_codex_response_timeout";
3
+ export declare const DEFAULT_CODEX_RESPONSE_TIMEOUT_POLICY: CodexResponseTimeoutPolicy;
4
+ export declare function resolveCodexResponseTimeoutPolicy(override: Partial<CodexResponseTimeoutPolicy> | undefined): CodexResponseTimeoutPolicy;
5
+ export declare class CodexResponseTimeoutError extends Error {
6
+ readonly timeoutClass: CodexResponseTimeoutClass;
7
+ readonly requestId: string;
8
+ readonly responseObserved: boolean;
9
+ readonly code = "opengeni_codex_response_timeout";
10
+ readonly type = "opengeni_codex_response_timeout";
11
+ constructor(timeoutClass: CodexResponseTimeoutClass, requestId: string, responseObserved: boolean, message?: string);
12
+ }
13
+ export type CodexResponseTimeoutInfo = {
14
+ timeoutClass: CodexResponseTimeoutClass;
15
+ requestId: string | null;
16
+ responseObserved: boolean;
17
+ message: string;
18
+ };
19
+ /**
20
+ * Recover structured transport timeouts through SDK wrapping. The optional
21
+ * legacy match is deliberately opt-in: `Request timed out.` alone has no
22
+ * provider provenance and the worker enables it only for a confirmed Codex
23
+ * subscription turn.
24
+ */
25
+ export declare function classifyCodexResponseTimeoutError(error: unknown, options?: {
26
+ allowLegacyRequestTimeout?: boolean;
27
+ }): CodexResponseTimeoutInfo | null;
28
+ export declare function isPreHeadersTimeoutError(error: unknown): CodexResponseTimeoutClass | null;
@@ -0,0 +1,61 @@
1
+ import { type CodexRateLimitResetCreditsSummary } from "./reset-credits";
2
+ /** The 5-hour (primary) window's `limit_window_seconds`. */
3
+ export declare const CODEX_FIVE_HOUR_WINDOW_SECONDS = 18000;
4
+ /** The weekly (secondary) window's `limit_window_seconds`. */
5
+ export declare const CODEX_WEEKLY_WINDOW_SECONDS = 604800;
6
+ /** One normalized usage window (applied to BOTH primary_window and secondary_window). */
7
+ export type CodexUsageWindow = {
8
+ used: number;
9
+ limit: number;
10
+ remaining: number;
11
+ percent: number;
12
+ resetAt: string | null;
13
+ resetAfterSeconds: number | null;
14
+ limitWindowSeconds: number;
15
+ };
16
+ /** One additional (per-feature) limit (forward-compat; P2 renders nothing from it). */
17
+ export type CodexAdditionalLimit = {
18
+ limitName: string;
19
+ meteredFeature: string;
20
+ fiveHour: CodexUsageWindow | null;
21
+ weekly: CodexUsageWindow | null;
22
+ };
23
+ export type CodexUsageStatus = "ok" | "limit_reached" | "error" | "no-data";
24
+ /** The normalized usage payload — the P2/P3 contract. */
25
+ export type CodexUsagePayload = {
26
+ status: CodexUsageStatus;
27
+ planType: string | null;
28
+ fiveHour: CodexUsageWindow | null;
29
+ weekly: CodexUsageWindow | null;
30
+ limitReached: boolean;
31
+ fetchedAt: string;
32
+ /**
33
+ * Authoritative count-only reset-credit summary from the usage response.
34
+ * Detail rows are fetched separately and are never synthesized from this.
35
+ */
36
+ rateLimitResetCredits: CodexRateLimitResetCreditsSummary | null;
37
+ /** Present only on a refresh/auth failure path; carries the precise reason. */
38
+ reason?: "needs_relogin" | undefined;
39
+ additionalLimits?: CodexAdditionalLimit[] | undefined;
40
+ credits?: {
41
+ hasCredits: boolean;
42
+ unlimited: boolean;
43
+ overageLimitReached: boolean;
44
+ balance: string;
45
+ } | undefined;
46
+ };
47
+ /**
48
+ * Build a normalized window from the PERSISTED cache columns (used_percent +
49
+ * absolute reset timestamp). The same 0–100 synthesis as the live path, with the
50
+ * skew-free countdown derived from `resetAt − now` at read time. Returns null when
51
+ * there is no cached percent yet. `limitWindowSeconds` is the constant that
52
+ * identifies the window (18000 ⇒ 5h, 604800 ⇒ weekly).
53
+ */
54
+ export declare function buildCodexUsageWindowFromCache(usedPercent: number | null | undefined, resetAt: Date | string | null | undefined, limitWindowSeconds: number): CodexUsageWindow | null;
55
+ /**
56
+ * Normalize a /wham/usage fetch result into the P2/P3 contract.
57
+ *
58
+ * @param httpStatus the HTTP status from fetchCodexUsage (404 ⇒ a limit body)
59
+ * @param rawPayload the parsed JSON body (or null when the body was unreadable)
60
+ */
61
+ export declare function normalizeCodexUsage(httpStatus: number, rawPayload: unknown): CodexUsagePayload;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/codex",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "description": "ChatGPT/Codex subscription auth + transport: device-code login, token refresh, and the Responses-backend fetch. Pure HTTP + transforms; no database dependency.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -32,8 +32,8 @@
32
32
  "provenance": true
33
33
  },
34
34
  "scripts": {
35
- "typecheck": "tsgo --noEmit",
36
- "build": "tsup",
35
+ "typecheck": "tsc --noEmit",
36
+ "build": "bun ../../scripts/build-typescript-package.ts",
37
37
  "prepublishOnly": "bash ../../scripts/prepublish-guard"
38
38
  },
39
39
  "dependencies": {
package/src/fetch.ts CHANGED
@@ -63,6 +63,56 @@ export function isCodexTransportError(error: unknown): boolean {
63
63
  return false;
64
64
  }
65
65
 
66
+ export type CodexEncryptedArtifactRejection = {
67
+ status: 400;
68
+ kind: "encrypted_content_rejected";
69
+ };
70
+
71
+ /**
72
+ * Classify only the provider's definitive request rejection for an opaque
73
+ * reasoning artifact that it can no longer decrypt/parse. A Codex transport
74
+ * marker plus HTTP 400 proves this request was rejected before inference; the
75
+ * semantic match prevents unrelated malformed prompts from entering recovery.
76
+ */
77
+ export function classifyCodexEncryptedArtifactRejection(
78
+ error: unknown,
79
+ ): CodexEncryptedArtifactRejection | null {
80
+ if (!isCodexTransportError(error)) return null;
81
+ let current: unknown = error;
82
+ for (let depth = 0; depth < 6 && current && typeof current === "object"; depth += 1) {
83
+ const value = current as Record<string, unknown>;
84
+ const body =
85
+ value.error && typeof value.error === "object"
86
+ ? (value.error as Record<string, unknown>)
87
+ : null;
88
+ const status = Number(value.status ?? body?.status);
89
+ const message = [
90
+ typeof value.message === "string" ? value.message : "",
91
+ typeof body?.message === "string" ? body.message : "",
92
+ typeof value.code === "string" ? value.code : "",
93
+ typeof body?.code === "string" ? body.code : "",
94
+ typeof value.type === "string" ? value.type : "",
95
+ typeof body?.type === "string" ? body.type : "",
96
+ ]
97
+ .join(" ")
98
+ .toLowerCase();
99
+ const unsupportedFieldShape =
100
+ /(?:invalid value|supported values?|unsupported|unknown (?:field|parameter|value))/.test(
101
+ message,
102
+ );
103
+ if (
104
+ status === 400 &&
105
+ !unsupportedFieldShape &&
106
+ /(?:encrypted[_ ]content|encrypted reasoning|reasoning artifact)/.test(message) &&
107
+ /(?:decrypt(?:ed|ion)?|could not be parsed|cannot be parsed|failed to parse)/.test(message)
108
+ ) {
109
+ return { status: 400, kind: "encrypted_content_rejected" };
110
+ }
111
+ current = value.cause;
112
+ }
113
+ return null;
114
+ }
115
+
66
116
  /** Parse an integer header value; null when absent or not a finite integer. */
67
117
  function parseIntHeader(value: string | null): number | null {
68
118
  if (value === null) {
@@ -284,7 +334,9 @@ async function observedResponse(
284
334
  if (externalSignal?.aborted) {
285
335
  abortFromOutside();
286
336
  } else {
287
- externalSignal?.addEventListener("abort", abortFromOutside, { once: true });
337
+ externalSignal?.addEventListener("abort", abortFromOutside, {
338
+ once: true,
339
+ });
288
340
  }
289
341
  },
290
342
  async pull(controller) {
@@ -344,7 +396,11 @@ async function observedResponse(
344
396
  });
345
397
  const headers = new Headers(res.headers);
346
398
  headers.delete("content-length");
347
- return new Response(body, { status: res.status, statusText: res.statusText, headers });
399
+ return new Response(body, {
400
+ status: res.status,
401
+ statusText: res.statusText,
402
+ headers,
403
+ });
348
404
  }
349
405
 
350
406
  function timeoutErrorResponse(info: {
@@ -418,6 +474,15 @@ export function codexSubscriptionFetch(base: FetchLike = globalThis.fetch): Fetc
418
474
  }
419
475
  headers.delete("OpenAI-Beta"); // omit on SSE (spec §1.2); fallback: "responses=experimental" if backend 400s
420
476
  headers.delete("x-api-key");
477
+ // Codex CLI advertises betas via x-codex-beta-features (not OpenAI-Beta).
478
+ if (ctx.betaFeatures && ctx.betaFeatures.length > 0) {
479
+ headers.set("x-codex-beta-features", ctx.betaFeatures.join(","));
480
+ }
481
+ // Turn analytics / request_kind live in x-codex-turn-metadata — body
482
+ // metadata is stripped by normalizeCodexRequestBody and rejected upstream.
483
+ if (ctx.turnMetadata && Object.keys(ctx.turnMetadata).length > 0) {
484
+ headers.set("x-codex-turn-metadata", JSON.stringify(ctx.turnMetadata));
485
+ }
421
486
 
422
487
  // The backend is streaming-only; force stream=true on the wire but remember
423
488
  // the caller's intent so a non-streaming caller (e.g. the compaction
package/src/normalize.ts CHANGED
@@ -16,9 +16,11 @@ const MINIMAL = "minimal";
16
16
  // The ChatGPT/Codex backend is a STRICT ALLOWLIST: it 400s on ANY top-level field
17
17
  // the Codex CLI itself does not send (confirmed live against the backend —
18
18
  // "Unsupported parameter: temperature / top_p / metadata / previous_response_id /
19
- // logprobs / service_tier / user / safety_identifier / truncation / max_tool_calls /
20
- // background / conversation", and "Unsupported tool type: mcp"). Our @openai/agents
21
- // stack adds several of these, so after our transforms we keep ONLY the codex
19
+ // logprobs / user / safety_identifier / truncation / max_tool_calls /
20
+ // background / conversation", and "Unsupported tool type: mcp").
21
+ // `service_tier` is allowlisted for Codex Fast mode (`priority`; config may say
22
+ // `fast` and maps to the same request value). Our @openai/agents stack adds
23
+ // several other fields, so after our transforms we keep ONLY the codex
22
24
  // Responses payload fields (CODEX-SUBSCRIPTION-SPEC §1 field table).
23
25
  const CODEX_ALLOWED_TOP_LEVEL_KEYS = new Set<string>([
24
26
  "model",
@@ -33,6 +35,7 @@ const CODEX_ALLOWED_TOP_LEVEL_KEYS = new Set<string>([
33
35
  "include",
34
36
  "prompt_cache_key",
35
37
  "text",
38
+ "service_tier",
36
39
  ]);
37
40
 
38
41
  /** Mutates a parsed Responses request body in place and returns it. Pure + synchronous + unit-testable. */
@@ -96,6 +96,26 @@ export type CodexRequestContext = {
96
96
  onModelRequestEvent?: (event: CodexModelRequestEvent) => Promise<void> | void;
97
97
  /** Stable request identity supplied by the owning durable execution. */
98
98
  nextRequestId?: () => string;
99
+ /**
100
+ * Optional Codex beta feature flags advertised as `x-codex-beta-features`
101
+ * (comma-separated). Used for remote compaction v2 (`remote_compaction_v2`).
102
+ */
103
+ betaFeatures?: readonly string[];
104
+ /**
105
+ * Optional turn analytics / routing metadata sent as `x-codex-turn-metadata`
106
+ * (JSON). Body `metadata` is stripped by normalize — never put request_kind there.
107
+ */
108
+ turnMetadata?: Record<string, unknown>;
99
109
  };
100
110
 
101
111
  export const codexRequestStorage = new AsyncLocalStorage<CodexRequestContext>();
112
+
113
+ /** Nest a Codex ALS scope with header overrides (e.g. remote compaction v2). */
114
+ export function withCodexRequestOverrides<T>(
115
+ overrides: Pick<CodexRequestContext, "betaFeatures" | "turnMetadata">,
116
+ fn: () => T,
117
+ ): T {
118
+ const current = codexRequestStorage.getStore();
119
+ if (!current) return fn();
120
+ return codexRequestStorage.run({ ...current, ...overrides }, fn);
121
+ }