Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(chatgptWeb): use live-entitled Codex model slugs — authenticated users could not chat
Salman Qureshid6c5ae435c68
diff --git a/src/auth/chatgpt-models.ts b/src/auth/chatgpt-models.tsindex 88b5c02d..d7f77fa0 100644--- a/src/auth/chatgpt-models.ts+++ b/src/auth/chatgpt-models.ts@@ -4,13 +4,19 @@ import { CHATGPT_BACKEND_API } from './chatgpt-session.js';// Models available to ChatGPT Plus/Pro subscribers via OAuth.// Sorted by preference (newest/best first).// Only models supported on the ChatGPT codex/responses endpoint.-// gpt-4o, o3, o4-mini, gpt-5.4-nano etc. are NOT supported there.+// IMPORTANT (2026-09): the codex backend validates the slug against the+// account's LIVE entitlements and rejects everything else with HTTP 400+// "The 'X' model is not supported when using Codex with a ChatGPT account."+// Plain dotted slugs only — hyphenated web-app slugs (gpt-5-6-thinking) and+// -thinking/-codex variants are NOT supported, and gpt-5.4*/gpt-5.3*/gpt-5.2+// have been dropped. The authoritative list comes from+// GET /backend-api/codex/models?client_version=1.0.0 (entitled for the plan).const CHATGPT_PREFERRED_MODELS = [+ 'gpt-5.6-sol',+ 'gpt-5.6-terra','gpt-5.5',- 'gpt-5.4',- 'gpt-5.4-mini',- 'gpt-5.3-codex',- 'gpt-5.2',+ 'gpt-6-astra',+ 'gpt-5.6-luna',] as const;/**@@ -26,23 +32,27 @@ export function getChatGPTHeaders(accessToken: string, accountId: string): Recor}/**- * Fetches available models from the ChatGPT codex API.- * Uses the same endpoint structure as the Responses API.+ * Fetches the account's live-entitled Codex model slugs.+ *+ * Endpoint: GET /backend-api/codex/models?client_version=1.0.0 — this is the+ * list the codex/responses endpoint actually accepts for the account's plan.+ * Do NOT use /backend-api/models: that is the ChatGPT WEB-APP model list+ * (hyphenated slugs like `gpt-5-6-thinking`) which the codex/responses+ * endpoint rejects with HTTP 400 for every request.*/export async function fetchChatGPTModels(accessToken: string,accountId: string,): Promise<ProviderModelCatalog> {- // Try fetching from the models endpointtry {- const response = await fetch(`${CHATGPT_BACKEND_API}/models`, {+ const response = await fetch(`${CHATGPT_BACKEND_API}/codex/models?client_version=1.0.0`, {headers: getChatGPTHeaders(accessToken, accountId),signal: AbortSignal.timeout(15_000),});if (response.ok) {const data = (await response.json()) as Record<string, any>;- const models = (data.models ?? [])+ const models = (Array.isArray(data.models) ? data.models : []).map((m: any) => (m.slug?.trim() ?? m.id?.trim() ?? '') as string).filter((slug: string) => slug.length > 0);diff --git a/src/core/agent.ts b/src/core/agent.tsindex 85734f2b..af5a5d13 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -423,6 +423,12 @@ export function whitelabelProviderError(err: any): string {if (/403|forbidden|permission/i.test(combined)) {return 'The provider refused the request (permissions/quota)';}+ // OpenAI Codex usage limit: the error body carries a reset timestamp —+ // surface it, the user needs to know when the plan window reopens.+ const resetsAt = Number((err as any)?.resets_at ?? /"resets_at":\s*(\d+)/.exec(body)?.[1]);+ if (Number.isFinite(resetsAt) && resetsAt > 0) {+ return `Usage limit reached on this plan — resets ${new Date(resetsAt * 1000).toLocaleTimeString()}`;+ }if (/429|rate limit|too many requests/i.test(combined)) {return 'Rate limited — too many requests right now';}diff --git a/src/core/provider-error-notice.test.ts b/src/core/provider-error-notice.test.tsindex f542ca47..f239cfaf 100644--- a/src/core/provider-error-notice.test.ts+++ b/src/core/provider-error-notice.test.ts@@ -31,6 +31,15 @@ describe('whitelabelProviderError', () => {expect(whitelabelProviderError({ message: 'fetch failed: ECONNRESET' })).toContain('server error or network timeout');});+ it('surfaces the Codex usage-limit reset time', () => {+ const out = whitelabelProviderError({+ message: 'The usage limit has been reached',+ responseBody: '{"error":{"type":"usage_limit_reached","resets_at":1789387519}}',+ });+ expect(out).toContain('Usage limit reached');+ expect(out).toContain('resets');+ });+it('keeps unknown errors concise (first line, no stack)', () => {const out = whitelabelProviderError({ message: 'weird provider quirk\n at deep stack frame\n more frames' });expect(out).toBe('weird provider quirk');@@ -58,6 +67,28 @@ describe('durable fallback notices', () => {expect(cliSrc).toContain('sendSystemNotice');expect(agentCliWiring()).toBe(true);});++ it('config: stale chatgptWeb slugs migrate to the entitled Codex slug', async () => {+ const { migrateLegacyChatGPTModel } = await import('../utils/config.js');++ // The exact slug the old catalog produced — rejected by the codex backend.+ const stale = migrateLegacyChatGPTModel({+ providers: { chatgptWeb: { name: 'chatgptWeb', enabled: true, apiKey: '', baseUrl: '', model: 'gpt-5-6-thinking' } },+ } as any);+ expect(stale.providers.chatgptWeb.model).toBe('gpt-5.6-sol');++ // Already-entitled models stay untouched.+ const current = migrateLegacyChatGPTModel({+ providers: { chatgptWeb: { name: 'chatgptWeb', enabled: true, apiKey: '', baseUrl: '', model: 'gpt-5.5' } },+ } as any);+ expect(current.providers.chatgptWeb.model).toBe('gpt-5.5');++ // Disabled provider is not migrated.+ const disabled = migrateLegacyChatGPTModel({+ providers: { chatgptWeb: { name: 'chatgptWeb', enabled: false, apiKey: '', baseUrl: '', model: 'gpt-5-6-thinking' } },+ } as any);+ expect(disabled.providers.chatgptWeb.model).toBe('gpt-5-6-thinking');+ });});function agentCliWiring(): boolean {diff --git a/src/utils/config.ts b/src/utils/config.tsindex 5a233626..6ad7a20a 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -3,6 +3,7 @@ import { join, resolve } from 'node:path';import { homedir } from 'node:os';import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';import { config as loadDotenv } from 'dotenv';+import { logger } from './logger.js';import type { SignalAccessUser, SignalPendingRequest, DiscordAccessUser, DiscordPendingRequest, SlackAccessUser, SlackPendingRequest } from '../types/channel.js';import {LEGACY_SEED_API_URL,@@ -446,21 +447,54 @@ export function loadConfig(): MercuryConfig {const raw = readFileSync(CONFIG_PATH, 'utf-8');const fileConfig = parseYaml(raw) as Partial<MercuryConfig>;const defaults = getDefaultConfig();- return normalizeCloudConfig(migrateLegacyDiscordAccess(- migrateLegacyOllamaLocalBaseUrl(- migrateLegacyOllamaCloudBaseUrl(- migrateLegacySignalAccess(- migrateLegacyTelegramAccess(deepMerge(defaults, fileConfig)),+ return normalizeCloudConfig(migrateLegacyChatGPTModel(+ migrateLegacyDiscordAccess(+ migrateLegacyOllamaLocalBaseUrl(+ migrateLegacyOllamaCloudBaseUrl(+ migrateLegacySignalAccess(+ migrateLegacyTelegramAccess(deepMerge(defaults, fileConfig)),+ ),),),),));}- return normalizeCloudConfig(migrateLegacyDiscordAccess(- migrateLegacyTelegramAccess(getDefaultConfig()),+ return normalizeCloudConfig(migrateLegacyChatGPTModel(+ migrateLegacyDiscordAccess(+ migrateLegacyTelegramAccess(getDefaultConfig()),+ ),));}+/**+ * 2026-09: OpenAI's Codex-for-ChatGPT backend now validates the model slug+ * against the account's LIVE entitlements and rejects everything else with+ * HTTP 400 "The 'X' model is not supported when using Codex with a ChatGPT+ * account." The old catalog fetched the ChatGPT web-app list+ * (/backend-api/models), whose hyphenated slugs (e.g. `gpt-5-6-thinking`) are+ * ALL rejected — authenticated users could not chat. Migrate any+ * non-entitled chatgptWeb model to the current recommended Codex slug.+ */+const CHATGPT_CODEX_MODEL_SLUGS = [+ 'gpt-5.6-sol',+ 'gpt-5.6-terra',+ 'gpt-5.6-luna',+ 'gpt-5.5',+ 'gpt-6-astra',+ 'gpt-reserve',+] as const;++const DEFAULT_CHATGPT_CODEX_MODEL = 'gpt-5.6-sol';++export function migrateLegacyChatGPTModel(config: MercuryConfig): MercuryConfig {+ const chatgpt = config.providers?.chatgptWeb;+ if (chatgpt?.enabled && !((CHATGPT_CODEX_MODEL_SLUGS as readonly string[]).includes(chatgpt.model))) {+ logger.warn({ staleModel: chatgpt.model, replacement: DEFAULT_CHATGPT_CODEX_MODEL }, 'chatgptWeb model not entitled on the Codex backend — migrating');+ chatgpt.model = DEFAULT_CHATGPT_CODEX_MODEL;+ }+ return config;+}+export function normalizeCloudConfig(config: MercuryConfig): MercuryConfig {// Single source of truth: cloud.apiUrl/wsUrl define the Mercury Cloud backend.// providers.mercuryCloud.baseUrl is derived for the OpenAI-compatible client.diff --git a/src/utils/provider-models.ts b/src/utils/provider-models.tsindex ad7ebf15..b9f23d18 100644--- a/src/utils/provider-models.ts+++ b/src/utils/provider-models.ts@@ -80,11 +80,11 @@ const MIMO_TOKEN_PLAN_PREFERRED_MODELS = MIMO_PREFERRED_MODELS;const OPENAI_COMPAT_PREFERRED_MODELS = [] as const;const CHATGPT_WEB_PREFERRED_MODELS = [+ 'gpt-5.6-sol',+ 'gpt-5.6-terra','gpt-5.5',- 'gpt-5.4',- 'gpt-5.4-mini',- 'gpt-5.3-codex',- 'gpt-5.2',+ 'gpt-6-astra',+ 'gpt-5.6-luna',] as const;const GITHUB_COPILOT_PREFERRED_MODELS = [