oc-codex-multi-auth 6.0.0
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.
- package/LICENSE +21 -0
- package/README.md +162 -0
- package/assets/opencode-logo-ornate-dark.svg +18 -0
- package/assets/readme-hero.svg +31 -0
- package/config/README.md +96 -0
- package/config/minimal-opencode.json +13 -0
- package/config/opencode-legacy.json +871 -0
- package/config/opencode-modern.json +358 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5008 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/accounts/rate-limits.d.ts +22 -0
- package/dist/lib/accounts/rate-limits.d.ts.map +1 -0
- package/dist/lib/accounts/rate-limits.js +63 -0
- package/dist/lib/accounts/rate-limits.js.map +1 -0
- package/dist/lib/accounts.d.ts +134 -0
- package/dist/lib/accounts.d.ts.map +1 -0
- package/dist/lib/accounts.js +795 -0
- package/dist/lib/accounts.js.map +1 -0
- package/dist/lib/audit.d.ts +45 -0
- package/dist/lib/audit.d.ts.map +1 -0
- package/dist/lib/audit.js +154 -0
- package/dist/lib/audit.js.map +1 -0
- package/dist/lib/auth/auth.d.ts +51 -0
- package/dist/lib/auth/auth.d.ts.map +1 -0
- package/dist/lib/auth/auth.js +191 -0
- package/dist/lib/auth/auth.js.map +1 -0
- package/dist/lib/auth/browser.d.ts +17 -0
- package/dist/lib/auth/browser.d.ts.map +1 -0
- package/dist/lib/auth/browser.js +90 -0
- package/dist/lib/auth/browser.js.map +1 -0
- package/dist/lib/auth/device-code.d.ts +28 -0
- package/dist/lib/auth/device-code.d.ts.map +1 -0
- package/dist/lib/auth/device-code.js +215 -0
- package/dist/lib/auth/device-code.js.map +1 -0
- package/dist/lib/auth/login-runner.d.ts +55 -0
- package/dist/lib/auth/login-runner.d.ts.map +1 -0
- package/dist/lib/auth/login-runner.js +631 -0
- package/dist/lib/auth/login-runner.js.map +1 -0
- package/dist/lib/auth/server.d.ts +10 -0
- package/dist/lib/auth/server.d.ts.map +1 -0
- package/dist/lib/auth/server.js +98 -0
- package/dist/lib/auth/server.js.map +1 -0
- package/dist/lib/auth/token-utils.d.ts +60 -0
- package/dist/lib/auth/token-utils.d.ts.map +1 -0
- package/dist/lib/auth/token-utils.js +416 -0
- package/dist/lib/auth/token-utils.js.map +1 -0
- package/dist/lib/auth-rate-limit.d.ts +20 -0
- package/dist/lib/auth-rate-limit.d.ts.map +1 -0
- package/dist/lib/auth-rate-limit.js +91 -0
- package/dist/lib/auth-rate-limit.js.map +1 -0
- package/dist/lib/auto-update-checker.d.ts +10 -0
- package/dist/lib/auto-update-checker.d.ts.map +1 -0
- package/dist/lib/auto-update-checker.js +129 -0
- package/dist/lib/auto-update-checker.js.map +1 -0
- package/dist/lib/circuit-breaker.d.ts +34 -0
- package/dist/lib/circuit-breaker.d.ts.map +1 -0
- package/dist/lib/circuit-breaker.js +124 -0
- package/dist/lib/circuit-breaker.js.map +1 -0
- package/dist/lib/cli.d.ts +46 -0
- package/dist/lib/cli.d.ts.map +1 -0
- package/dist/lib/cli.js +192 -0
- package/dist/lib/cli.js.map +1 -0
- package/dist/lib/config.d.ts +42 -0
- package/dist/lib/config.d.ts.map +1 -0
- package/dist/lib/config.js +314 -0
- package/dist/lib/config.js.map +1 -0
- package/dist/lib/constants.d.ts +90 -0
- package/dist/lib/constants.d.ts.map +1 -0
- package/dist/lib/constants.js +90 -0
- package/dist/lib/constants.js.map +1 -0
- package/dist/lib/context-overflow.d.ts +27 -0
- package/dist/lib/context-overflow.d.ts.map +1 -0
- package/dist/lib/context-overflow.js +124 -0
- package/dist/lib/context-overflow.js.map +1 -0
- package/dist/lib/errors.d.ts +113 -0
- package/dist/lib/errors.d.ts.map +1 -0
- package/dist/lib/errors.js +103 -0
- package/dist/lib/errors.js.map +1 -0
- package/dist/lib/health.d.ts +33 -0
- package/dist/lib/health.d.ts.map +1 -0
- package/dist/lib/health.js +70 -0
- package/dist/lib/health.js.map +1 -0
- package/dist/lib/index.d.ts +20 -0
- package/dist/lib/index.d.ts.map +1 -0
- package/dist/lib/index.js +20 -0
- package/dist/lib/index.js.map +1 -0
- package/dist/lib/logger.d.ts +40 -0
- package/dist/lib/logger.d.ts.map +1 -0
- package/dist/lib/logger.js +337 -0
- package/dist/lib/logger.js.map +1 -0
- package/dist/lib/oauth-success.html +712 -0
- package/dist/lib/parallel-probe.d.ts +28 -0
- package/dist/lib/parallel-probe.d.ts.map +1 -0
- package/dist/lib/parallel-probe.js +97 -0
- package/dist/lib/parallel-probe.js.map +1 -0
- package/dist/lib/proactive-refresh.d.ts +67 -0
- package/dist/lib/proactive-refresh.d.ts.map +1 -0
- package/dist/lib/proactive-refresh.js +161 -0
- package/dist/lib/proactive-refresh.js.map +1 -0
- package/dist/lib/prompts/codex-opencode-bridge.d.ts +20 -0
- package/dist/lib/prompts/codex-opencode-bridge.d.ts.map +1 -0
- package/dist/lib/prompts/codex-opencode-bridge.js +126 -0
- package/dist/lib/prompts/codex-opencode-bridge.js.map +1 -0
- package/dist/lib/prompts/codex.d.ts +41 -0
- package/dist/lib/prompts/codex.d.ts.map +1 -0
- package/dist/lib/prompts/codex.js +400 -0
- package/dist/lib/prompts/codex.js.map +1 -0
- package/dist/lib/prompts/opencode-codex.d.ts +25 -0
- package/dist/lib/prompts/opencode-codex.d.ts.map +1 -0
- package/dist/lib/prompts/opencode-codex.js +223 -0
- package/dist/lib/prompts/opencode-codex.js.map +1 -0
- package/dist/lib/recovery/constants.d.ts +12 -0
- package/dist/lib/recovery/constants.d.ts.map +1 -0
- package/dist/lib/recovery/constants.js +25 -0
- package/dist/lib/recovery/constants.js.map +1 -0
- package/dist/lib/recovery/index.d.ts +12 -0
- package/dist/lib/recovery/index.d.ts.map +1 -0
- package/dist/lib/recovery/index.js +12 -0
- package/dist/lib/recovery/index.js.map +1 -0
- package/dist/lib/recovery/storage.d.ts +24 -0
- package/dist/lib/recovery/storage.d.ts.map +1 -0
- package/dist/lib/recovery/storage.js +362 -0
- package/dist/lib/recovery/storage.js.map +1 -0
- package/dist/lib/recovery/types.d.ts +116 -0
- package/dist/lib/recovery/types.d.ts.map +1 -0
- package/dist/lib/recovery/types.js +7 -0
- package/dist/lib/recovery/types.js.map +1 -0
- package/dist/lib/recovery.d.ts +31 -0
- package/dist/lib/recovery.d.ts.map +1 -0
- package/dist/lib/recovery.js +313 -0
- package/dist/lib/recovery.js.map +1 -0
- package/dist/lib/refresh-queue.d.ts +131 -0
- package/dist/lib/refresh-queue.d.ts.map +1 -0
- package/dist/lib/refresh-queue.js +297 -0
- package/dist/lib/refresh-queue.js.map +1 -0
- package/dist/lib/request/fetch-helpers.d.ts +142 -0
- package/dist/lib/request/fetch-helpers.d.ts.map +1 -0
- package/dist/lib/request/fetch-helpers.js +749 -0
- package/dist/lib/request/fetch-helpers.js.map +1 -0
- package/dist/lib/request/helpers/input-utils.d.ts +7 -0
- package/dist/lib/request/helpers/input-utils.d.ts.map +1 -0
- package/dist/lib/request/helpers/input-utils.js +214 -0
- package/dist/lib/request/helpers/input-utils.js.map +1 -0
- package/dist/lib/request/helpers/model-map.d.ts +22 -0
- package/dist/lib/request/helpers/model-map.d.ts.map +1 -0
- package/dist/lib/request/helpers/model-map.js +183 -0
- package/dist/lib/request/helpers/model-map.js.map +1 -0
- package/dist/lib/request/helpers/tool-utils.d.ts +29 -0
- package/dist/lib/request/helpers/tool-utils.d.ts.map +1 -0
- package/dist/lib/request/helpers/tool-utils.js +117 -0
- package/dist/lib/request/helpers/tool-utils.js.map +1 -0
- package/dist/lib/request/rate-limit-backoff.d.ts +17 -0
- package/dist/lib/request/rate-limit-backoff.d.ts.map +1 -0
- package/dist/lib/request/rate-limit-backoff.js +83 -0
- package/dist/lib/request/rate-limit-backoff.js.map +1 -0
- package/dist/lib/request/request-transformer.d.ts +107 -0
- package/dist/lib/request/request-transformer.d.ts.map +1 -0
- package/dist/lib/request/request-transformer.js +930 -0
- package/dist/lib/request/request-transformer.js.map +1 -0
- package/dist/lib/request/response-handler.d.ts +23 -0
- package/dist/lib/request/response-handler.d.ts.map +1 -0
- package/dist/lib/request/response-handler.js +245 -0
- package/dist/lib/request/response-handler.js.map +1 -0
- package/dist/lib/request/retry-budget.d.ts +19 -0
- package/dist/lib/request/retry-budget.d.ts.map +1 -0
- package/dist/lib/request/retry-budget.js +99 -0
- package/dist/lib/request/retry-budget.js.map +1 -0
- package/dist/lib/rotation.d.ts +130 -0
- package/dist/lib/rotation.d.ts.map +1 -0
- package/dist/lib/rotation.js +301 -0
- package/dist/lib/rotation.js.map +1 -0
- package/dist/lib/runtime-contracts.d.ts +16 -0
- package/dist/lib/runtime-contracts.d.ts.map +1 -0
- package/dist/lib/runtime-contracts.js +24 -0
- package/dist/lib/runtime-contracts.js.map +1 -0
- package/dist/lib/schemas.d.ts +457 -0
- package/dist/lib/schemas.d.ts.map +1 -0
- package/dist/lib/schemas.js +283 -0
- package/dist/lib/schemas.js.map +1 -0
- package/dist/lib/shutdown.d.ts +7 -0
- package/dist/lib/shutdown.d.ts.map +1 -0
- package/dist/lib/shutdown.js +43 -0
- package/dist/lib/shutdown.js.map +1 -0
- package/dist/lib/storage/migrations.d.ts +65 -0
- package/dist/lib/storage/migrations.d.ts.map +1 -0
- package/dist/lib/storage/migrations.js +44 -0
- package/dist/lib/storage/migrations.js.map +1 -0
- package/dist/lib/storage/paths.d.ts +16 -0
- package/dist/lib/storage/paths.d.ts.map +1 -0
- package/dist/lib/storage/paths.js +92 -0
- package/dist/lib/storage/paths.js.map +1 -0
- package/dist/lib/storage.d.ts +157 -0
- package/dist/lib/storage.d.ts.map +1 -0
- package/dist/lib/storage.js +1169 -0
- package/dist/lib/storage.js.map +1 -0
- package/dist/lib/table-formatter.d.ts +32 -0
- package/dist/lib/table-formatter.d.ts.map +1 -0
- package/dist/lib/table-formatter.js +44 -0
- package/dist/lib/table-formatter.js.map +1 -0
- package/dist/lib/types.d.ts +131 -0
- package/dist/lib/types.d.ts.map +1 -0
- package/dist/lib/types.js +2 -0
- package/dist/lib/types.js.map +1 -0
- package/dist/lib/ui/ansi.d.ts +22 -0
- package/dist/lib/ui/ansi.d.ts.map +1 -0
- package/dist/lib/ui/ansi.js +38 -0
- package/dist/lib/ui/ansi.js.map +1 -0
- package/dist/lib/ui/auth-menu.d.ts +39 -0
- package/dist/lib/ui/auth-menu.d.ts.map +1 -0
- package/dist/lib/ui/auth-menu.js +186 -0
- package/dist/lib/ui/auth-menu.js.map +1 -0
- package/dist/lib/ui/beginner.d.ts +62 -0
- package/dist/lib/ui/beginner.d.ts.map +1 -0
- package/dist/lib/ui/beginner.js +259 -0
- package/dist/lib/ui/beginner.js.map +1 -0
- package/dist/lib/ui/confirm.d.ts +2 -0
- package/dist/lib/ui/confirm.d.ts.map +1 -0
- package/dist/lib/ui/confirm.js +21 -0
- package/dist/lib/ui/confirm.js.map +1 -0
- package/dist/lib/ui/format.d.ts +9 -0
- package/dist/lib/ui/format.d.ts.map +1 -0
- package/dist/lib/ui/format.js +49 -0
- package/dist/lib/ui/format.js.map +1 -0
- package/dist/lib/ui/runtime.d.ts +11 -0
- package/dist/lib/ui/runtime.d.ts.map +1 -0
- package/dist/lib/ui/runtime.js +31 -0
- package/dist/lib/ui/runtime.js.map +1 -0
- package/dist/lib/ui/select.d.ts +20 -0
- package/dist/lib/ui/select.d.ts.map +1 -0
- package/dist/lib/ui/select.js +343 -0
- package/dist/lib/ui/select.js.map +1 -0
- package/dist/lib/ui/theme.d.ts +34 -0
- package/dist/lib/ui/theme.d.ts.map +1 -0
- package/dist/lib/ui/theme.js +84 -0
- package/dist/lib/ui/theme.js.map +1 -0
- package/dist/lib/utils.d.ts +29 -0
- package/dist/lib/utils.d.ts.map +1 -0
- package/dist/lib/utils.js +54 -0
- package/dist/lib/utils.js.map +1 -0
- package/package.json +113 -0
- package/scripts/audit-dev-allowlist.js +114 -0
- package/scripts/copy-oauth-success.js +37 -0
- package/scripts/install-oc-codex-multi-auth-core.js +381 -0
- package/scripts/install-oc-codex-multi-auth.js +15 -0
- package/scripts/test-all-models.sh +260 -0
- package/scripts/validate-model-map.sh +97 -0
|
@@ -0,0 +1,749 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helper functions for the custom fetch implementation
|
|
3
|
+
* These functions break down the complex fetch logic into manageable, testable units
|
|
4
|
+
*/
|
|
5
|
+
import { queuedRefresh } from "../refresh-queue.js";
|
|
6
|
+
import { logRequest, logError, logWarn } from "../logger.js";
|
|
7
|
+
import { getCodexInstructions, getModelFamily } from "../prompts/codex.js";
|
|
8
|
+
import { transformRequestBody, normalizeModel } from "./request-transformer.js";
|
|
9
|
+
import { convertSseToJson, ensureContentType } from "./response-handler.js";
|
|
10
|
+
import { CodexAuthError } from "../errors.js";
|
|
11
|
+
import { DEACTIVATED_WORKSPACE_ERROR_CODE } from "../runtime-contracts.js";
|
|
12
|
+
import { isRecord } from "../utils.js";
|
|
13
|
+
import { CODEX_BASE_URL, HTTP_STATUS, OPENAI_HEADERS, OPENAI_HEADER_VALUES, URL_PATHS, ERROR_MESSAGES, LOG_STAGES, } from "../constants.js";
|
|
14
|
+
const CODEX_BASE_URL_OBJECT = new URL(CODEX_BASE_URL);
|
|
15
|
+
const CODEX_BASE_PATH_PREFIX = CODEX_BASE_URL_OBJECT.pathname.endsWith("/")
|
|
16
|
+
? CODEX_BASE_URL_OBJECT.pathname.slice(0, -1)
|
|
17
|
+
: CODEX_BASE_URL_OBJECT.pathname;
|
|
18
|
+
const CHATGPT_CODEX_UNSUPPORTED_MODEL_CODE = "model_not_supported_with_chatgpt_account";
|
|
19
|
+
const CHATGPT_CODEX_UNSUPPORTED_MODEL_PATTERN = /model is not supported when using codex with a chatgpt account/i;
|
|
20
|
+
const NORMALIZED_UNSUPPORTED_MODEL_PATTERN = /the model ['"]([^'"]+)['"] is not currently available for this chatgpt account/i;
|
|
21
|
+
export const DEFAULT_UNSUPPORTED_CODEX_FALLBACK_CHAIN = {
|
|
22
|
+
"gpt-5.4-pro": ["gpt-5.4"],
|
|
23
|
+
"gpt-5.3-codex-spark": ["gpt-5-codex", "gpt-5.3-codex", "gpt-5.2-codex"],
|
|
24
|
+
"gpt-5.3-codex": ["gpt-5-codex", "gpt-5.2-codex"],
|
|
25
|
+
"gpt-5.2-codex": ["gpt-5-codex"],
|
|
26
|
+
"gpt-5.1-codex": ["gpt-5-codex"],
|
|
27
|
+
};
|
|
28
|
+
function canonicalizeModelName(model) {
|
|
29
|
+
if (!model)
|
|
30
|
+
return undefined;
|
|
31
|
+
const trimmed = model.trim().toLowerCase();
|
|
32
|
+
if (!trimmed)
|
|
33
|
+
return undefined;
|
|
34
|
+
const stripped = trimmed.includes("/")
|
|
35
|
+
? (trimmed.split("/").pop() ?? trimmed)
|
|
36
|
+
: trimmed;
|
|
37
|
+
return stripped.replace(/-(none|minimal|low|medium|high|xhigh)$/i, "");
|
|
38
|
+
}
|
|
39
|
+
function normalizeFallbackChain(customChain) {
|
|
40
|
+
const normalized = {};
|
|
41
|
+
for (const [key, values] of Object.entries(DEFAULT_UNSUPPORTED_CODEX_FALLBACK_CHAIN)) {
|
|
42
|
+
const normalizedKey = canonicalizeModelName(key);
|
|
43
|
+
if (!normalizedKey)
|
|
44
|
+
continue;
|
|
45
|
+
normalized[normalizedKey] = values
|
|
46
|
+
.map((value) => canonicalizeModelName(value))
|
|
47
|
+
.filter((value) => !!value);
|
|
48
|
+
}
|
|
49
|
+
if (!customChain) {
|
|
50
|
+
return normalized;
|
|
51
|
+
}
|
|
52
|
+
for (const [key, values] of Object.entries(customChain)) {
|
|
53
|
+
const normalizedKey = canonicalizeModelName(key);
|
|
54
|
+
if (!normalizedKey || !Array.isArray(values))
|
|
55
|
+
continue;
|
|
56
|
+
const normalizedValues = values
|
|
57
|
+
.map((value) => canonicalizeModelName(value))
|
|
58
|
+
.filter((value) => !!value);
|
|
59
|
+
if (normalizedValues.length > 0) {
|
|
60
|
+
normalized[normalizedKey] = normalizedValues;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return normalized;
|
|
64
|
+
}
|
|
65
|
+
export function extractUnsupportedCodexModelFromText(bodyText) {
|
|
66
|
+
const directMatch = bodyText.match(/['"]([^'"]+)['"]\s+model is not supported when using codex with a chatgpt account/i);
|
|
67
|
+
if (directMatch?.[1]) {
|
|
68
|
+
return canonicalizeModelName(directMatch[1]);
|
|
69
|
+
}
|
|
70
|
+
const normalizedMatch = bodyText.match(NORMALIZED_UNSUPPORTED_MODEL_PATTERN);
|
|
71
|
+
if (normalizedMatch?.[1]) {
|
|
72
|
+
return canonicalizeModelName(normalizedMatch[1]);
|
|
73
|
+
}
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
function isUnsupportedCodexModelForChatGpt(status, bodyText) {
|
|
77
|
+
if (status !== HTTP_STATUS.BAD_REQUEST)
|
|
78
|
+
return false;
|
|
79
|
+
if (!bodyText)
|
|
80
|
+
return false;
|
|
81
|
+
return CHATGPT_CODEX_UNSUPPORTED_MODEL_PATTERN.test(bodyText);
|
|
82
|
+
}
|
|
83
|
+
export function getUnsupportedCodexModelInfo(errorBody) {
|
|
84
|
+
if (!isRecord(errorBody)) {
|
|
85
|
+
return { isUnsupported: false };
|
|
86
|
+
}
|
|
87
|
+
const maybeError = errorBody.error;
|
|
88
|
+
if (!isRecord(maybeError)) {
|
|
89
|
+
return { isUnsupported: false };
|
|
90
|
+
}
|
|
91
|
+
const code = typeof maybeError.code === "string" ? maybeError.code : undefined;
|
|
92
|
+
const message = typeof maybeError.message === "string" ? maybeError.message : undefined;
|
|
93
|
+
const unsupportedModelFromPayload = typeof maybeError.unsupported_model === "string"
|
|
94
|
+
? maybeError.unsupported_model
|
|
95
|
+
: undefined;
|
|
96
|
+
const unsupportedModel = unsupportedModelFromPayload
|
|
97
|
+
? canonicalizeModelName(unsupportedModelFromPayload)
|
|
98
|
+
: extractUnsupportedCodexModelFromText(message ?? "");
|
|
99
|
+
const isUnsupported = code === CHATGPT_CODEX_UNSUPPORTED_MODEL_CODE ||
|
|
100
|
+
(message ? CHATGPT_CODEX_UNSUPPORTED_MODEL_PATTERN.test(message) : false);
|
|
101
|
+
return {
|
|
102
|
+
isUnsupported,
|
|
103
|
+
code,
|
|
104
|
+
message,
|
|
105
|
+
unsupportedModel: unsupportedModel ?? undefined,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
export function resolveUnsupportedCodexFallbackModel(options) {
|
|
109
|
+
if (!options.fallbackOnUnsupportedCodexModel)
|
|
110
|
+
return undefined;
|
|
111
|
+
const unsupported = getUnsupportedCodexModelInfo(options.errorBody);
|
|
112
|
+
if (!unsupported.isUnsupported)
|
|
113
|
+
return undefined;
|
|
114
|
+
const requestedModel = canonicalizeModelName(options.requestedModel);
|
|
115
|
+
const currentModel = requestedModel ?? unsupported.unsupportedModel;
|
|
116
|
+
if (!currentModel)
|
|
117
|
+
return undefined;
|
|
118
|
+
const attempted = new Set();
|
|
119
|
+
for (const model of options.attemptedModels ?? []) {
|
|
120
|
+
const normalized = canonicalizeModelName(model);
|
|
121
|
+
if (normalized)
|
|
122
|
+
attempted.add(normalized);
|
|
123
|
+
}
|
|
124
|
+
const chain = normalizeFallbackChain(options.customChain);
|
|
125
|
+
const targets = chain[currentModel] ?? [];
|
|
126
|
+
if (targets.length === 0)
|
|
127
|
+
return undefined;
|
|
128
|
+
for (const target of targets) {
|
|
129
|
+
if (!options.fallbackToGpt52OnUnsupportedGpt53 &&
|
|
130
|
+
currentModel === "gpt-5.3-codex" &&
|
|
131
|
+
target === "gpt-5.2-codex") {
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (target === currentModel)
|
|
135
|
+
continue;
|
|
136
|
+
if (attempted.has(target))
|
|
137
|
+
continue;
|
|
138
|
+
return target;
|
|
139
|
+
}
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Returns true when the legacy `gpt-5.3-codex -> gpt-5.2-codex` edge is available.
|
|
144
|
+
*/
|
|
145
|
+
export function shouldFallbackToGpt52OnUnsupportedGpt53(requestedModel, errorBody) {
|
|
146
|
+
if (canonicalizeModelName(requestedModel) !== "gpt-5.3-codex") {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
return (resolveUnsupportedCodexFallbackModel({
|
|
150
|
+
requestedModel,
|
|
151
|
+
errorBody,
|
|
152
|
+
// Skip the canonical `gpt-5-codex` step and probe whether the legacy
|
|
153
|
+
// gpt-5.2 edge is still active under current policy/toggles.
|
|
154
|
+
attemptedModels: ["gpt-5-codex"],
|
|
155
|
+
fallbackOnUnsupportedCodexModel: true,
|
|
156
|
+
fallbackToGpt52OnUnsupportedGpt53: true,
|
|
157
|
+
}) === "gpt-5.2-codex");
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Checks if an error code indicates an entitlement/subscription issue
|
|
161
|
+
* These errors should NOT be treated as rate limits because:
|
|
162
|
+
* 1. They won't resolve by waiting
|
|
163
|
+
* 2. They won't resolve by switching accounts (all accounts likely have same issue)
|
|
164
|
+
* 3. User needs to upgrade their subscription
|
|
165
|
+
*/
|
|
166
|
+
export function isEntitlementError(code, bodyText) {
|
|
167
|
+
const haystack = `${code} ${bodyText}`.toLowerCase();
|
|
168
|
+
// "usage_not_included" means the subscription doesn't include this feature
|
|
169
|
+
// This is different from "usage_limit_reached" which is a temporary quota limit
|
|
170
|
+
return /usage_not_included|not.included.in.your.plan|subscription.does.not.include/i.test(haystack);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Creates a user-friendly entitlement error response
|
|
174
|
+
*/
|
|
175
|
+
export function createEntitlementErrorResponse(_bodyText) {
|
|
176
|
+
const message = "This model is not included in your ChatGPT subscription. " +
|
|
177
|
+
"Please check that your account or workspace has access to Codex models (Plus/Pro/Business/Enterprise). " +
|
|
178
|
+
"If you recently subscribed or switched workspaces, try logging out and back in with `opencode auth login`.";
|
|
179
|
+
const payload = {
|
|
180
|
+
error: {
|
|
181
|
+
message,
|
|
182
|
+
type: "entitlement_error",
|
|
183
|
+
code: "usage_not_included",
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
return new Response(JSON.stringify(payload), {
|
|
187
|
+
status: 403, // Forbidden - not a rate limit
|
|
188
|
+
statusText: "Forbidden",
|
|
189
|
+
headers: { "content-type": "application/json; charset=utf-8" },
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
function getStructuredErrorCode(errorBody) {
|
|
193
|
+
if (!isRecord(errorBody))
|
|
194
|
+
return undefined;
|
|
195
|
+
const directCode = errorBody.code;
|
|
196
|
+
if (typeof directCode === "string" && directCode.trim())
|
|
197
|
+
return directCode.trim();
|
|
198
|
+
const detail = errorBody.detail;
|
|
199
|
+
if (isRecord(detail)) {
|
|
200
|
+
const detailCode = detail.code;
|
|
201
|
+
if (typeof detailCode === "string" && detailCode.trim())
|
|
202
|
+
return detailCode.trim();
|
|
203
|
+
}
|
|
204
|
+
const nestedError = errorBody.error;
|
|
205
|
+
if (isRecord(nestedError)) {
|
|
206
|
+
const nestedCode = nestedError.code ?? nestedError.type;
|
|
207
|
+
if (typeof nestedCode === "string" && nestedCode.trim())
|
|
208
|
+
return nestedCode.trim();
|
|
209
|
+
}
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
export function isDeactivatedWorkspaceError(errorBody, status) {
|
|
213
|
+
if (status !== undefined && status !== 402)
|
|
214
|
+
return false;
|
|
215
|
+
const code = getStructuredErrorCode(errorBody);
|
|
216
|
+
return code === DEACTIVATED_WORKSPACE_ERROR_CODE;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Determines if the current auth token needs to be refreshed
|
|
220
|
+
* @param auth - Current authentication state
|
|
221
|
+
* @returns True if token is expired or invalid
|
|
222
|
+
*/
|
|
223
|
+
export function shouldRefreshToken(auth, skewMs = 0) {
|
|
224
|
+
if (auth.type !== "oauth")
|
|
225
|
+
return true;
|
|
226
|
+
if (!auth.access)
|
|
227
|
+
return true;
|
|
228
|
+
const safeSkewMs = Math.max(0, Math.floor(skewMs));
|
|
229
|
+
return auth.expires <= Date.now() + safeSkewMs;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Refreshes the OAuth token and updates stored credentials
|
|
233
|
+
* @param currentAuth - Current auth state
|
|
234
|
+
* @param client - Opencode client for updating stored credentials
|
|
235
|
+
* @returns Updated auth (throws on failure)
|
|
236
|
+
*/
|
|
237
|
+
export async function refreshAndUpdateToken(currentAuth, client) {
|
|
238
|
+
const refreshToken = currentAuth.type === "oauth" ? currentAuth.refresh : "";
|
|
239
|
+
const refreshResult = await queuedRefresh(refreshToken);
|
|
240
|
+
if (refreshResult.type === "failed") {
|
|
241
|
+
throw new CodexAuthError(ERROR_MESSAGES.TOKEN_REFRESH_FAILED, { retryable: false });
|
|
242
|
+
}
|
|
243
|
+
await client.auth.set({
|
|
244
|
+
path: { id: "openai" },
|
|
245
|
+
body: {
|
|
246
|
+
type: "oauth",
|
|
247
|
+
access: refreshResult.access,
|
|
248
|
+
refresh: refreshResult.refresh,
|
|
249
|
+
expires: refreshResult.expires,
|
|
250
|
+
multiAccount: true,
|
|
251
|
+
},
|
|
252
|
+
});
|
|
253
|
+
// Update current auth reference if it's OAuth type
|
|
254
|
+
if (currentAuth.type === "oauth") {
|
|
255
|
+
currentAuth.access = refreshResult.access;
|
|
256
|
+
currentAuth.refresh = refreshResult.refresh;
|
|
257
|
+
currentAuth.expires = refreshResult.expires;
|
|
258
|
+
}
|
|
259
|
+
return currentAuth;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Extracts URL string from various request input types
|
|
263
|
+
* @param input - Request input (string, URL, or Request object)
|
|
264
|
+
* @returns URL string
|
|
265
|
+
*/
|
|
266
|
+
export function extractRequestUrl(input) {
|
|
267
|
+
if (typeof input === "string")
|
|
268
|
+
return input;
|
|
269
|
+
if (input instanceof URL)
|
|
270
|
+
return input.toString();
|
|
271
|
+
return input.url;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Rewrites OpenAI API URLs to Codex backend URLs
|
|
275
|
+
* @param url - Original URL
|
|
276
|
+
* @returns Rewritten URL for Codex backend
|
|
277
|
+
*/
|
|
278
|
+
export function rewriteUrlForCodex(url) {
|
|
279
|
+
const parsedUrl = new URL(url);
|
|
280
|
+
const rewrittenPath = parsedUrl.pathname.includes(URL_PATHS.RESPONSES)
|
|
281
|
+
? parsedUrl.pathname.replace(URL_PATHS.RESPONSES, URL_PATHS.CODEX_RESPONSES)
|
|
282
|
+
: parsedUrl.pathname;
|
|
283
|
+
const normalizedPath = rewrittenPath === CODEX_BASE_PATH_PREFIX ||
|
|
284
|
+
rewrittenPath.startsWith(`${CODEX_BASE_PATH_PREFIX}/`)
|
|
285
|
+
? rewrittenPath
|
|
286
|
+
: `${CODEX_BASE_PATH_PREFIX}${rewrittenPath.startsWith("/") ? rewrittenPath : `/${rewrittenPath}`}`;
|
|
287
|
+
parsedUrl.protocol = CODEX_BASE_URL_OBJECT.protocol;
|
|
288
|
+
parsedUrl.username = "";
|
|
289
|
+
parsedUrl.password = "";
|
|
290
|
+
parsedUrl.host = CODEX_BASE_URL_OBJECT.host;
|
|
291
|
+
parsedUrl.pathname = normalizedPath;
|
|
292
|
+
return parsedUrl.toString();
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Transforms request body and logs the transformation
|
|
296
|
+
* Fetches model-specific Codex instructions based on the request model
|
|
297
|
+
*
|
|
298
|
+
* @param init - Request init options
|
|
299
|
+
* @param url - Request URL
|
|
300
|
+
* @param userConfig - User configuration
|
|
301
|
+
* @param codexMode - Enable CODEX_MODE (bridge prompt instead of tool remap)
|
|
302
|
+
* @param parsedBody - Pre-parsed body to avoid double JSON.parse (optional)
|
|
303
|
+
* @returns Transformed body and updated init, or undefined if no body
|
|
304
|
+
*/
|
|
305
|
+
export async function transformRequestForCodex(init, url, userConfig, codexMode = true, parsedBody, options) {
|
|
306
|
+
const hasParsedBody = parsedBody !== undefined &&
|
|
307
|
+
parsedBody !== null &&
|
|
308
|
+
typeof parsedBody === "object" &&
|
|
309
|
+
Object.keys(parsedBody).length > 0;
|
|
310
|
+
if (!init?.body && !hasParsedBody)
|
|
311
|
+
return undefined;
|
|
312
|
+
try {
|
|
313
|
+
// Use pre-parsed body if provided, otherwise parse from init.body
|
|
314
|
+
let body;
|
|
315
|
+
if (hasParsedBody) {
|
|
316
|
+
body = parsedBody;
|
|
317
|
+
}
|
|
318
|
+
else {
|
|
319
|
+
if (typeof init?.body !== "string")
|
|
320
|
+
return undefined;
|
|
321
|
+
body = JSON.parse(init.body);
|
|
322
|
+
}
|
|
323
|
+
const originalModel = body.model;
|
|
324
|
+
const requestTransformMode = options?.requestTransformMode ?? "legacy";
|
|
325
|
+
if (requestTransformMode === "native") {
|
|
326
|
+
logRequest(LOG_STAGES.BEFORE_TRANSFORM, {
|
|
327
|
+
url,
|
|
328
|
+
originalModel,
|
|
329
|
+
model: body.model,
|
|
330
|
+
hasTools: !!body.tools,
|
|
331
|
+
hasInput: !!body.input,
|
|
332
|
+
inputLength: body.input?.length,
|
|
333
|
+
requestTransformMode,
|
|
334
|
+
body: body,
|
|
335
|
+
});
|
|
336
|
+
logRequest(LOG_STAGES.AFTER_TRANSFORM, {
|
|
337
|
+
url,
|
|
338
|
+
originalModel,
|
|
339
|
+
normalizedModel: body.model,
|
|
340
|
+
hasTools: !!body.tools,
|
|
341
|
+
hasInput: !!body.input,
|
|
342
|
+
inputLength: body.input?.length,
|
|
343
|
+
requestTransformMode,
|
|
344
|
+
body: body,
|
|
345
|
+
});
|
|
346
|
+
return {
|
|
347
|
+
body,
|
|
348
|
+
updatedInit: { ...(init ?? {}), body: JSON.stringify(body) },
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
// Normalize model first to determine which instructions to fetch
|
|
352
|
+
// This ensures we get the correct model-specific prompt
|
|
353
|
+
const normalizedModel = normalizeModel(originalModel);
|
|
354
|
+
const modelFamily = getModelFamily(normalizedModel);
|
|
355
|
+
// Log original request
|
|
356
|
+
logRequest(LOG_STAGES.BEFORE_TRANSFORM, {
|
|
357
|
+
url,
|
|
358
|
+
originalModel,
|
|
359
|
+
model: body.model,
|
|
360
|
+
hasTools: !!body.tools,
|
|
361
|
+
hasInput: !!body.input,
|
|
362
|
+
inputLength: body.input?.length,
|
|
363
|
+
codexMode,
|
|
364
|
+
requestTransformMode,
|
|
365
|
+
body: body,
|
|
366
|
+
});
|
|
367
|
+
// Fetch model-specific Codex instructions (cached per model family)
|
|
368
|
+
const codexInstructions = await getCodexInstructions(normalizedModel);
|
|
369
|
+
// Transform request body
|
|
370
|
+
const transformedBody = await transformRequestBody(body, codexInstructions, userConfig, codexMode, options?.fastSession ?? false, options?.fastSessionStrategy ?? "hybrid", options?.fastSessionMaxInputItems ?? 30);
|
|
371
|
+
// Log transformed request
|
|
372
|
+
logRequest(LOG_STAGES.AFTER_TRANSFORM, {
|
|
373
|
+
url,
|
|
374
|
+
originalModel,
|
|
375
|
+
normalizedModel: transformedBody.model,
|
|
376
|
+
modelFamily,
|
|
377
|
+
hasTools: !!transformedBody.tools,
|
|
378
|
+
hasInput: !!transformedBody.input,
|
|
379
|
+
inputLength: transformedBody.input?.length,
|
|
380
|
+
reasoning: transformedBody.reasoning,
|
|
381
|
+
textVerbosity: transformedBody.text?.verbosity,
|
|
382
|
+
include: transformedBody.include,
|
|
383
|
+
requestTransformMode,
|
|
384
|
+
body: transformedBody,
|
|
385
|
+
});
|
|
386
|
+
return {
|
|
387
|
+
body: transformedBody,
|
|
388
|
+
updatedInit: { ...(init ?? {}), body: JSON.stringify(transformedBody) },
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
catch (e) {
|
|
392
|
+
logError(`${ERROR_MESSAGES.REQUEST_PARSE_ERROR}`, e);
|
|
393
|
+
return undefined;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Creates headers for Codex API requests
|
|
398
|
+
* @param init - Request init options
|
|
399
|
+
* @param accountId - ChatGPT account ID
|
|
400
|
+
* @param accessToken - OAuth access token
|
|
401
|
+
* @param opts - Optional parameters including model, promptCacheKey, and organizationId
|
|
402
|
+
* @returns Headers object with all required Codex headers
|
|
403
|
+
*/
|
|
404
|
+
export function createCodexHeaders(init, accountId, accessToken, opts) {
|
|
405
|
+
const headers = new Headers(init?.headers ?? {});
|
|
406
|
+
headers.delete("x-api-key"); // Remove any existing API key
|
|
407
|
+
headers.set("Authorization", `Bearer ${accessToken}`);
|
|
408
|
+
headers.set(OPENAI_HEADERS.ACCOUNT_ID, accountId);
|
|
409
|
+
headers.set(OPENAI_HEADERS.BETA, OPENAI_HEADER_VALUES.BETA_RESPONSES);
|
|
410
|
+
headers.set(OPENAI_HEADERS.ORIGINATOR, OPENAI_HEADER_VALUES.ORIGINATOR_CODEX);
|
|
411
|
+
const cacheKey = opts?.promptCacheKey;
|
|
412
|
+
if (cacheKey) {
|
|
413
|
+
headers.set(OPENAI_HEADERS.CONVERSATION_ID, cacheKey);
|
|
414
|
+
headers.set(OPENAI_HEADERS.SESSION_ID, cacheKey);
|
|
415
|
+
}
|
|
416
|
+
else {
|
|
417
|
+
headers.delete(OPENAI_HEADERS.CONVERSATION_ID);
|
|
418
|
+
headers.delete(OPENAI_HEADERS.SESSION_ID);
|
|
419
|
+
}
|
|
420
|
+
const organizationId = opts?.organizationId;
|
|
421
|
+
if (organizationId) {
|
|
422
|
+
headers.set(OPENAI_HEADERS.ORGANIZATION_ID, organizationId);
|
|
423
|
+
}
|
|
424
|
+
headers.set("accept", "text/event-stream");
|
|
425
|
+
return headers;
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Handles error responses from the Codex API
|
|
429
|
+
* @param response - Error response from API
|
|
430
|
+
* @returns Original response or mapped retryable response
|
|
431
|
+
*/
|
|
432
|
+
export async function handleErrorResponse(response, options) {
|
|
433
|
+
const bodyText = await safeReadBody(response);
|
|
434
|
+
const mapped = mapUsageLimit404WithBody(response, bodyText);
|
|
435
|
+
// Entitlement errors return a ready-to-use Response with 403 status
|
|
436
|
+
if (mapped && mapped.status === HTTP_STATUS.FORBIDDEN) {
|
|
437
|
+
return { response: mapped, rateLimit: undefined, errorBody: undefined };
|
|
438
|
+
}
|
|
439
|
+
const finalResponse = mapped ?? response;
|
|
440
|
+
const rateLimit = extractRateLimitInfoFromBody(finalResponse, bodyText);
|
|
441
|
+
let errorBody;
|
|
442
|
+
try {
|
|
443
|
+
errorBody = bodyText ? JSON.parse(bodyText) : undefined;
|
|
444
|
+
}
|
|
445
|
+
catch {
|
|
446
|
+
errorBody = { message: bodyText };
|
|
447
|
+
}
|
|
448
|
+
const diagnostics = extractErrorDiagnostics(finalResponse, options);
|
|
449
|
+
const normalizedError = normalizeErrorPayload(errorBody, bodyText, finalResponse.statusText, finalResponse.status, diagnostics);
|
|
450
|
+
const errorResponse = ensureJsonErrorResponse(finalResponse, normalizedError);
|
|
451
|
+
if (finalResponse.status === HTTP_STATUS.UNAUTHORIZED) {
|
|
452
|
+
logWarn("Codex upstream returned 401 Unauthorized", diagnostics);
|
|
453
|
+
}
|
|
454
|
+
logRequest(LOG_STAGES.ERROR_RESPONSE, {
|
|
455
|
+
status: finalResponse.status,
|
|
456
|
+
statusText: finalResponse.statusText,
|
|
457
|
+
diagnostics,
|
|
458
|
+
});
|
|
459
|
+
return { response: errorResponse, rateLimit, errorBody: normalizedError };
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Handles successful responses from the Codex API
|
|
463
|
+
* Converts SSE to JSON for non-streaming requests (generateText)
|
|
464
|
+
* Passes through SSE for streaming requests (streamText)
|
|
465
|
+
* @param response - Success response from API
|
|
466
|
+
* @param isStreaming - Whether this is a streaming request (stream=true in body)
|
|
467
|
+
* @returns Processed response (SSE→JSON for non-streaming, stream for streaming)
|
|
468
|
+
*/
|
|
469
|
+
export async function handleSuccessResponse(response, isStreaming, options) {
|
|
470
|
+
// Check for deprecation headers (RFC 8594)
|
|
471
|
+
const deprecation = response.headers.get("Deprecation");
|
|
472
|
+
const sunset = response.headers.get("Sunset");
|
|
473
|
+
if (deprecation || sunset) {
|
|
474
|
+
logWarn(`API deprecation notice`, { deprecation, sunset });
|
|
475
|
+
}
|
|
476
|
+
const responseHeaders = ensureContentType(response.headers);
|
|
477
|
+
// For non-streaming requests (generateText), convert SSE to JSON
|
|
478
|
+
if (!isStreaming) {
|
|
479
|
+
return await convertSseToJson(response, responseHeaders, options);
|
|
480
|
+
}
|
|
481
|
+
// For streaming requests (streamText), return stream as-is
|
|
482
|
+
return new Response(response.body, {
|
|
483
|
+
status: response.status,
|
|
484
|
+
statusText: response.statusText,
|
|
485
|
+
headers: responseHeaders,
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
async function safeReadBody(response) {
|
|
489
|
+
try {
|
|
490
|
+
return await response.clone().text();
|
|
491
|
+
}
|
|
492
|
+
catch {
|
|
493
|
+
return "";
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
function mapUsageLimit404WithBody(response, bodyText) {
|
|
497
|
+
if (response.status !== HTTP_STATUS.NOT_FOUND)
|
|
498
|
+
return null;
|
|
499
|
+
if (!bodyText)
|
|
500
|
+
return null;
|
|
501
|
+
let code = "";
|
|
502
|
+
try {
|
|
503
|
+
const parsed = JSON.parse(bodyText);
|
|
504
|
+
code = (parsed?.error?.code ?? parsed?.error?.type ?? "").toString();
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
code = "";
|
|
508
|
+
}
|
|
509
|
+
// Check for entitlement errors first - these should NOT be treated as rate limits
|
|
510
|
+
if (isEntitlementError(code, bodyText)) {
|
|
511
|
+
return createEntitlementErrorResponse(bodyText);
|
|
512
|
+
}
|
|
513
|
+
const haystack = `${code} ${bodyText}`.toLowerCase();
|
|
514
|
+
if (!/usage_limit_reached|rate_limit_exceeded|usage limit/i.test(haystack)) {
|
|
515
|
+
return null;
|
|
516
|
+
}
|
|
517
|
+
const headers = new Headers(response.headers);
|
|
518
|
+
return new Response(bodyText, {
|
|
519
|
+
status: HTTP_STATUS.TOO_MANY_REQUESTS,
|
|
520
|
+
statusText: "Too Many Requests",
|
|
521
|
+
headers,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
function extractRateLimitInfoFromBody(response, bodyText) {
|
|
525
|
+
const isStatusRateLimit = response.status === HTTP_STATUS.TOO_MANY_REQUESTS;
|
|
526
|
+
const parsed = parseRateLimitBody(bodyText);
|
|
527
|
+
const haystack = `${parsed?.code ?? ""} ${bodyText}`.toLowerCase();
|
|
528
|
+
// Entitlement errors should not be treated as rate limits
|
|
529
|
+
if (isEntitlementError(parsed?.code ?? "", bodyText)) {
|
|
530
|
+
return undefined;
|
|
531
|
+
}
|
|
532
|
+
const isRateLimit = isStatusRateLimit ||
|
|
533
|
+
/usage_limit_reached|rate_limit_exceeded|rate_limit|usage limit/i.test(haystack);
|
|
534
|
+
if (!isRateLimit)
|
|
535
|
+
return undefined;
|
|
536
|
+
const retryAfterMs = parseRetryAfterMs(response, parsed) ?? 60000;
|
|
537
|
+
return { retryAfterMs, code: parsed?.code };
|
|
538
|
+
}
|
|
539
|
+
function parseRateLimitBody(body) {
|
|
540
|
+
if (!body)
|
|
541
|
+
return undefined;
|
|
542
|
+
try {
|
|
543
|
+
const parsed = JSON.parse(body);
|
|
544
|
+
const error = parsed?.error ?? {};
|
|
545
|
+
const code = (error.code ?? error.type ?? "").toString();
|
|
546
|
+
const resetsAt = toNumber(error.resets_at ?? error.reset_at);
|
|
547
|
+
const retryAfterMs = toNumber(error.retry_after_ms ?? error.retry_after);
|
|
548
|
+
return { code, resetsAt, retryAfterMs };
|
|
549
|
+
}
|
|
550
|
+
catch {
|
|
551
|
+
return undefined;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
function normalizeErrorPayload(errorBody, bodyText, statusText, status, diagnostics) {
|
|
555
|
+
if (isDeactivatedWorkspaceError(errorBody, status)) {
|
|
556
|
+
const payload = {
|
|
557
|
+
error: {
|
|
558
|
+
message: "The selected ChatGPT workspace is deactivated. This workspace entry should be removed from rotation or re-authorized before retrying.",
|
|
559
|
+
type: "workspace_deactivated",
|
|
560
|
+
code: DEACTIVATED_WORKSPACE_ERROR_CODE,
|
|
561
|
+
},
|
|
562
|
+
};
|
|
563
|
+
if (diagnostics && Object.keys(diagnostics).length > 0) {
|
|
564
|
+
payload.error.diagnostics = diagnostics;
|
|
565
|
+
}
|
|
566
|
+
return payload;
|
|
567
|
+
}
|
|
568
|
+
if (isUnsupportedCodexModelForChatGpt(status, bodyText)) {
|
|
569
|
+
const unsupportedModel = extractUnsupportedCodexModelFromText(bodyText) ?? "requested model";
|
|
570
|
+
const payload = {
|
|
571
|
+
error: {
|
|
572
|
+
message: `The model '${unsupportedModel}' is not currently available for this ChatGPT account when using Codex OAuth. ` +
|
|
573
|
+
"This is an account/workspace entitlement gate, not a temporary rate limit. " +
|
|
574
|
+
"Try 'gpt-5.4' (latest general), 'gpt-5-codex' (canonical), or legacy aliases like 'gpt-5.3-codex'/'gpt-5.2-codex', or enable automatic fallback via " +
|
|
575
|
+
'unsupportedCodexPolicy: "fallback" (or CODEX_AUTH_UNSUPPORTED_MODEL_POLICY=fallback). ' +
|
|
576
|
+
"(Legacy: CODEX_AUTH_FALLBACK_UNSUPPORTED_MODEL=1 or fallbackOnUnsupportedCodexModel).",
|
|
577
|
+
type: "entitlement_error",
|
|
578
|
+
code: CHATGPT_CODEX_UNSUPPORTED_MODEL_CODE,
|
|
579
|
+
unsupported_model: unsupportedModel,
|
|
580
|
+
},
|
|
581
|
+
};
|
|
582
|
+
if (diagnostics && Object.keys(diagnostics).length > 0) {
|
|
583
|
+
payload.error.diagnostics = diagnostics;
|
|
584
|
+
}
|
|
585
|
+
return payload;
|
|
586
|
+
}
|
|
587
|
+
if (isRecord(errorBody)) {
|
|
588
|
+
const maybeError = errorBody.error;
|
|
589
|
+
if (isRecord(maybeError) && typeof maybeError.message === "string") {
|
|
590
|
+
const payload = {
|
|
591
|
+
error: {
|
|
592
|
+
message: maybeError.message,
|
|
593
|
+
},
|
|
594
|
+
};
|
|
595
|
+
if (typeof maybeError.type === "string") {
|
|
596
|
+
payload.error.type = maybeError.type;
|
|
597
|
+
}
|
|
598
|
+
if (typeof maybeError.code === "string" || typeof maybeError.code === "number") {
|
|
599
|
+
payload.error.code = maybeError.code;
|
|
600
|
+
}
|
|
601
|
+
if (diagnostics && Object.keys(diagnostics).length > 0) {
|
|
602
|
+
payload.error.diagnostics = diagnostics;
|
|
603
|
+
}
|
|
604
|
+
if (status === HTTP_STATUS.UNAUTHORIZED) {
|
|
605
|
+
payload.error.message = `${payload.error.message} (run \`opencode auth login\` if this persists)`;
|
|
606
|
+
}
|
|
607
|
+
return payload;
|
|
608
|
+
}
|
|
609
|
+
if (typeof errorBody.message === "string") {
|
|
610
|
+
const payload = { error: { message: errorBody.message } };
|
|
611
|
+
if (diagnostics && Object.keys(diagnostics).length > 0) {
|
|
612
|
+
payload.error.diagnostics = diagnostics;
|
|
613
|
+
}
|
|
614
|
+
if (status === HTTP_STATUS.UNAUTHORIZED) {
|
|
615
|
+
payload.error.message = `${payload.error.message} (run \`opencode auth login\` if this persists)`;
|
|
616
|
+
}
|
|
617
|
+
return payload;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
const trimmed = bodyText.trim();
|
|
621
|
+
if (trimmed) {
|
|
622
|
+
const payload = { error: { message: trimmed } };
|
|
623
|
+
if (diagnostics && Object.keys(diagnostics).length > 0) {
|
|
624
|
+
payload.error.diagnostics = diagnostics;
|
|
625
|
+
}
|
|
626
|
+
if (status === HTTP_STATUS.UNAUTHORIZED) {
|
|
627
|
+
payload.error.message = `${payload.error.message} (run \`opencode auth login\` if this persists)`;
|
|
628
|
+
}
|
|
629
|
+
return payload;
|
|
630
|
+
}
|
|
631
|
+
if (statusText) {
|
|
632
|
+
const payload = { error: { message: statusText } };
|
|
633
|
+
if (diagnostics && Object.keys(diagnostics).length > 0) {
|
|
634
|
+
payload.error.diagnostics = diagnostics;
|
|
635
|
+
}
|
|
636
|
+
if (status === HTTP_STATUS.UNAUTHORIZED) {
|
|
637
|
+
payload.error.message = `${payload.error.message} (run \`opencode auth login\` if this persists)`;
|
|
638
|
+
}
|
|
639
|
+
return payload;
|
|
640
|
+
}
|
|
641
|
+
const payload = { error: { message: "Request failed" } };
|
|
642
|
+
if (diagnostics && Object.keys(diagnostics).length > 0) {
|
|
643
|
+
payload.error.diagnostics = diagnostics;
|
|
644
|
+
}
|
|
645
|
+
if (status === HTTP_STATUS.UNAUTHORIZED) {
|
|
646
|
+
payload.error.message = `${payload.error.message} (run \`opencode auth login\` if this persists)`;
|
|
647
|
+
}
|
|
648
|
+
return payload;
|
|
649
|
+
}
|
|
650
|
+
function ensureJsonErrorResponse(response, payload) {
|
|
651
|
+
const headers = new Headers(response.headers);
|
|
652
|
+
headers.set("content-type", "application/json; charset=utf-8");
|
|
653
|
+
return new Response(JSON.stringify(payload), {
|
|
654
|
+
status: response.status,
|
|
655
|
+
statusText: response.statusText,
|
|
656
|
+
headers,
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
function parseRetryAfterMs(response, parsedBody) {
|
|
660
|
+
if (parsedBody?.retryAfterMs !== undefined) {
|
|
661
|
+
return normalizeRetryAfter(parsedBody.retryAfterMs);
|
|
662
|
+
}
|
|
663
|
+
const retryAfterMsHeader = response.headers.get("retry-after-ms");
|
|
664
|
+
if (retryAfterMsHeader) {
|
|
665
|
+
const parsed = Number.parseInt(retryAfterMsHeader, 10);
|
|
666
|
+
if (!Number.isNaN(parsed) && parsed > 0) {
|
|
667
|
+
return parsed;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
const retryAfterHeader = response.headers.get("retry-after");
|
|
671
|
+
if (retryAfterHeader) {
|
|
672
|
+
const parsed = Number.parseInt(retryAfterHeader, 10);
|
|
673
|
+
if (!Number.isNaN(parsed) && parsed > 0) {
|
|
674
|
+
return parsed * 1000;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
const resetAtHeaders = [
|
|
678
|
+
"x-codex-primary-reset-at",
|
|
679
|
+
"x-codex-secondary-reset-at",
|
|
680
|
+
"x-ratelimit-reset",
|
|
681
|
+
];
|
|
682
|
+
const now = Date.now();
|
|
683
|
+
const resetCandidates = [];
|
|
684
|
+
for (const header of resetAtHeaders) {
|
|
685
|
+
const value = response.headers.get(header);
|
|
686
|
+
if (!value)
|
|
687
|
+
continue;
|
|
688
|
+
const parsed = Number.parseInt(value, 10);
|
|
689
|
+
if (!Number.isNaN(parsed) && parsed > 0) {
|
|
690
|
+
const timestamp = parsed < 10_000_000_000 ? parsed * 1000 : parsed;
|
|
691
|
+
const delta = timestamp - now;
|
|
692
|
+
if (delta > 0)
|
|
693
|
+
resetCandidates.push(delta);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
if (parsedBody?.resetsAt) {
|
|
697
|
+
const timestamp = parsedBody.resetsAt < 10_000_000_000
|
|
698
|
+
? parsedBody.resetsAt * 1000
|
|
699
|
+
: parsedBody.resetsAt;
|
|
700
|
+
const delta = timestamp - now;
|
|
701
|
+
if (delta > 0)
|
|
702
|
+
resetCandidates.push(delta);
|
|
703
|
+
}
|
|
704
|
+
if (resetCandidates.length > 0) {
|
|
705
|
+
return Math.min(...resetCandidates);
|
|
706
|
+
}
|
|
707
|
+
return null;
|
|
708
|
+
}
|
|
709
|
+
function normalizeRetryAfter(value) {
|
|
710
|
+
if (!Number.isFinite(value))
|
|
711
|
+
return 60000;
|
|
712
|
+
let ms;
|
|
713
|
+
if (value > 0 && value < 1000) {
|
|
714
|
+
ms = Math.floor(value * 1000);
|
|
715
|
+
}
|
|
716
|
+
else {
|
|
717
|
+
ms = Math.floor(value);
|
|
718
|
+
}
|
|
719
|
+
const MAX_RETRY_DELAY_MS = 5 * 60 * 1000;
|
|
720
|
+
return Math.min(ms, MAX_RETRY_DELAY_MS);
|
|
721
|
+
}
|
|
722
|
+
function toNumber(value) {
|
|
723
|
+
if (value === null || value === undefined)
|
|
724
|
+
return undefined;
|
|
725
|
+
const parsed = Number(value);
|
|
726
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
727
|
+
}
|
|
728
|
+
function extractErrorDiagnostics(response, options) {
|
|
729
|
+
const requestId = response.headers.get("x-request-id") ??
|
|
730
|
+
response.headers.get("request-id") ??
|
|
731
|
+
response.headers.get("openai-request-id") ??
|
|
732
|
+
response.headers.get("x-openai-request-id") ??
|
|
733
|
+
undefined;
|
|
734
|
+
const cfRay = response.headers.get("cf-ray") ?? undefined;
|
|
735
|
+
const diagnostics = {
|
|
736
|
+
httpStatus: response.status,
|
|
737
|
+
requestId,
|
|
738
|
+
cfRay,
|
|
739
|
+
correlationId: options?.requestCorrelationId,
|
|
740
|
+
threadId: options?.threadId,
|
|
741
|
+
};
|
|
742
|
+
for (const [key, value] of Object.entries(diagnostics)) {
|
|
743
|
+
if (value === undefined || value === "") {
|
|
744
|
+
delete diagnostics[key];
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
return Object.keys(diagnostics).length > 0 ? diagnostics : undefined;
|
|
748
|
+
}
|
|
749
|
+
//# sourceMappingURL=fetch-helpers.js.map
|