Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
ChatGPT plan: plain error for a refused model, and hide it for that account (#4369)
Aditya Umale15e2070ca9d7
diff --git a/server/drivers/chatgpt-plan-auth.test.ts b/server/drivers/chatgpt-plan-auth.test.tsindex 07fd01f4a1..aa53d3405d 100644--- a/server/drivers/chatgpt-plan-auth.test.ts+++ b/server/drivers/chatgpt-plan-auth.test.ts@@ -129,6 +129,31 @@ describe("official ChatGPT plan OAuth", () => {expect(statSync(join(home, "chatgpt-plan", "host-id.json")).mode & 0o777).toBe(0o600);}});+ it("hides a model ChatGPT refused for this account only, until it signs in again or signs out", async () => {+ const controller = create(); await callback(controller);+ await controller.refuseModel("gpt-6.1-sol");+ expect(controller.refusedModels()).toEqual(["gpt-6.1-sol"]);+ expect(await controller.models()).toEqual({ default: "gpt-fixture", options: [{ id: "gpt-fixture", label: "Fixture" }] });+ if (process.platform !== "win32") expect(statSync(join(directory, "refused-models.json")).mode & 0o777).toBe(0o600);+ const other = create("account-two"); await callback(other);+ expect((await other.models()).default).toBe("gpt-6.1-sol");+ await callback(controller);+ expect(controller.refusedModels()).toEqual([]);+ expect((await controller.models()).default).toBe("gpt-6.1-sol");+ await controller.refuseModel("gpt-6.1-sol");+ await controller.signOut();+ expect(controller.refusedModels()).toEqual([]);+ });+ it("knows a refusal at once and never overwrites a saved list it can't read", async () => {+ const controller = create(); await callback(controller);+ const saving = controller.refuseModel("gpt-6.1-sol");+ expect(controller.refusedModels()).toEqual(["gpt-6.1-sol"]);+ await saving;+ const path = join(directory, "refused-models.json");+ writeFileSync(path, "{not json", { mode: 0o600 });+ await expect(controller.refuseModel("gpt-fixture")).rejects.toThrow();+ expect(readFileSync(path, "utf8")).toBe("{not json");+ });it.each(["nonce", "issuer", "audience", "future", "expired", "signature"])("rejects %s identity errors without saving credentials", async (failure) => {mode = failure; const controller = create();expect(await callback(controller)).toMatchObject({ phase: "failed", message: expect.stringContaining("could not be verified") });diff --git a/server/drivers/chatgpt-plan-auth.ts b/server/drivers/chatgpt-plan-auth.tsindex 21a4e10b28..77993884e5 100644--- a/server/drivers/chatgpt-plan-auth.ts+++ b/server/drivers/chatgpt-plan-auth.ts@@ -1,5 +1,5 @@import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";-import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";+import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs";import { createServer, type Server } from "node:http";import { dirname, isAbsolute, join } from "node:path";import { setTimeout as delay } from "node:timers/promises";@@ -86,6 +86,8 @@ export class ChatGptPlanAuthController {private disposed = false;private starting: Promise<ProviderAuthenticationStart> | null = null;private retryClientId: string | null = null;+ /** Refusals this run already knows about, cleared with the saved list on sign-in and sign-out. */+ private readonly refusedNow = new Set<string>();constructor(options: Options) {if (!isAbsolute(options.directory)) throw new Error("ChatGPT credential storage must use an absolute path.");@@ -124,6 +126,42 @@ export class ChatGptPlanAuthController {private save(record: Credentials): void {writeFileAtomic(join(this.options.directory, "credentials.json"), JSON.stringify(record), { mode: 0o600 });}+ private refusedPath(): string { return join(this.options.directory, "refused-models.json"); }+ private savedRefused(subject: string): string[] {+ const raw = readJson(this.refusedPath());+ if (raw === null) return [];+ const saved = object(raw);+ return saved.subject === subject && Array.isArray(saved.models) ? saved.models.filter((slug): slug is string => string(slug, 256)) : [];+ }+ private refusedFor(subject: string): string[] {+ let saved: string[] = [];+ try { saved = this.savedRefused(subject); } catch { /* An unreadable list hides nothing it can't read. */ }+ return [...new Set([...saved, ...this.refusedNow])];+ }+ private clearRefused(): void {+ this.refusedNow.clear();+ rmSync(this.refusedPath(), { force: true });+ }+ /** Models ChatGPT refused for the signed-in account although /models lists them ("The 'gpt-6.1-sol' model is not+ * supported when using Codex with a ChatGPT account."). Kept until this account signs out or signs in again. */+ refusedModels(): string[] {+ try {+ const subject = this.read()?.subject;+ return subject ? this.refusedFor(subject) : [];+ } catch { return []; }+ }+ async refuseModel(slug: string): Promise<void> {+ if (this.disposed || !string(slug, 256)) return;+ // Seen at once by the next turn, before the saved list below is written under the lock.+ this.refusedNow.add(slug);+ this.prepare();+ await locked(this.options.directory, async () => {+ const subject = this.read()?.subject;+ // A saved list that can't be read throws here, so it is never overwritten with this one model.+ const models = subject ? this.savedRefused(subject) : [];+ if (subject && !models.includes(slug)) writeFileAtomic(this.refusedPath(), JSON.stringify({ subject, models: [...models, slug] }), { mode: 0o600 });+ });+ }private async hostId(): Promise<string> {const parent = dirname(this.options.directory);return locked(parent, async () => {@@ -287,6 +325,7 @@ export class ChatGptPlanAuthController {if (this.disposed || flow.status.phase !== "waiting" || flow.abort.signal.aborted) return;if (JSON.stringify(this.read()) !== JSON.stringify(flow.previous)) throw new Error("The selected ChatGPT account changed during sign-in. Start again.");this.save({ clientId, hostId: flow.hostId, ...identity, tokens });+ this.clearRefused();this.retryClientId = null;this.finish(flow, tokens.scopes.includes(DIRECT_SCOPE) ? "succeeded" : "failed", tokens.scopes.includes(DIRECT_SCOPE) ? undefined : CONSENT);});@@ -354,7 +393,9 @@ export class ChatGptPlanAuthController {});}async models(): Promise<ModelCatalog> {- if (!this.read()?.tokens?.scopes.includes(DIRECT_SCOPE)) return { default: "", options: [] };+ const record = this.read();+ if (!record?.tokens?.scopes.includes(DIRECT_SCOPE)) return { default: "", options: [] };+ const refused = this.refusedFor(record.subject);const token = await this.accessToken();const { response, body } = await this.request(`${this.resource}/models`, { headers: { Authorization: `Bearer ${token}` } });if (!response.ok) throw new Error(response.status === 401 || response.status === 403@@ -365,7 +406,7 @@ export class ChatGptPlanAuthController {for (const entry of body.models) {if (!entry || typeof entry !== "object") continue;const row = entry as Record<string, unknown>;- if (row.visibility !== "list" || !string(row.slug, 256) || /[\s\p{Cc}]/u.test(row.slug) || !string(row.display_name, 256) || options.some((item) => item.id === row.slug)) continue;+ if (row.visibility !== "list" || !string(row.slug, 256) || /[\s\p{Cc}]/u.test(row.slug) || !string(row.display_name, 256) || options.some((item) => item.id === row.slug) || refused.includes(row.slug)) continue;options.push({ id: row.slug, label: row.display_name });}return { default: options[0]?.id ?? "", options };@@ -395,6 +436,7 @@ export class ChatGptPlanAuthController {} catch { /* Sign-out is local even if OpenAI is temporarily unavailable. */ }delete record.tokens;this.save(record);+ this.clearRefused();if (!revoked) throw Object.assign(new Error("Signed out locally, but remote revocation was not confirmed. Disconnect OpenMausBot in ChatGPT Settings → Usage to end access there."), { code: "chatgpt_revocation_unconfirmed" });});}diff --git a/server/drivers/codex-app-approval.ts b/server/drivers/codex-app-approval.tsnew file mode 100644index 0000000000..8fc6ddcd1e--- /dev/null+++ b/server/drivers/codex-app-approval.ts@@ -0,0 +1,86 @@+// The MCP app-access approval forms Codex asks for, moved out of codex.ts (file-size ratchet).++export type McpApprovalForm = {+ tool: string;+ summary: string;+ allowResult: { action: "accept"; content: Record<string, string> };+};++export const plainRecord = (value: unknown): Record<string, unknown> | null =>+ value && typeof value === "object" && !Array.isArray(value)+ ? value as Record<string, unknown>+ : null;++export const containsControlCharacter = (value: string): boolean => {+ for (const character of value) {+ const code = character.charCodeAt(0);+ if (code <= 0x1f || code === 0x7f) return true;+ }+ return false;+};++export function boundedLabel(value: unknown): string | null {+ if (typeof value !== "string") return null;+ const label = value.trim();+ return label && label.length <= 160 && !containsControlCharacter(label) ? label : null;+}++function ordinaryApprovalValue(value: string): boolean {+ const normalized = value.trim().toLowerCase();+ if (/session|always|permanent|forever|persistent/.test(normalized)) return false;+ return normalized === "once" || /^(?:accept|approve|allow)(?:ed|[-_]?once)?$/.test(normalized);+}++/** Only schema-backed app-access approvals; any other MCP form (credentials, free text, URLs) stays+ * user input and is declined, and Full access never fabricates one. */+export function mcpAppApprovalForm(params: unknown): McpApprovalForm | null {+ const request = plainRecord(params);+ if (!request || request.mode !== "form") return null;+ const metadata = plainRecord(request._meta);+ const target = plainRecord(metadata?.target);+ const toolParams = plainRecord(metadata?.tool_params);+ const message = boundedLabel(request.message) ?? "App access requested";+ const appName = [+ metadata?.app_name,+ metadata?.appName,+ metadata?.app,+ target?.app,+ target?.name,+ toolParams?.app_name,+ toolParams?.app,+ metadata?.connector_name,+ metadata?.connectorName,+ ].map(boundedLabel).find(Boolean) ?? message.match(/^Allow ChatGPT to use (.+?)\?$/i)?.[1]?.trim();+ if (!appName) return null;++ const schema = plainRecord(request.requestedSchema);+ const properties = plainRecord(schema?.properties);+ const required = schema?.required;+ if (+ !properties ||+ !Array.isArray(required) ||+ required.length === 0 ||+ required.length > 8 ||+ !required.every((key) => typeof key === "string" && key.length > 0 && key.length <= 100)+ ) return null;++ const content: Record<string, string> = {};+ for (const key of required as string[]) {+ const field = plainRecord(properties[key]);+ if (!field) return null;+ const enumValues = Array.isArray(field.enum)+ ? field.enum.filter((value): value is string => typeof value === "string")+ : [];+ const oneOfValues = Array.isArray(field.oneOf)+ ? field.oneOf+ .map((option) => boundedLabel(plainRecord(option)?.const))+ .filter((value): value is string => Boolean(value))+ : [];+ const chosen = [...oneOfValues, ...enumValues].find(ordinaryApprovalValue);+ if (!chosen) return null;+ content[key] = chosen;+ }++ const tool = boundedLabel(appName) ?? boundedLabel(request.serverName) ?? "app_access";+ return { tool, summary: message, allowResult: { action: "accept", content } };+}diff --git a/server/drivers/codex-errors.ts b/server/drivers/codex-errors.tsindex aa8ae25c27..5a02255679 100644--- a/server/drivers/codex-errors.ts+++ b/server/drivers/codex-errors.ts@@ -60,7 +60,19 @@ export function codexLimitFacts(raw: string, route: CodexRoute, codexErrorInfo?:return { limit: /\busage limit for \S+?\.(?:\s|$)/i.test(raw) ? "model" : "engine", ...(at === undefined ? {} : { limitResetsAt: at }) };}+// ChatGPT's words, reported 2026-11-03, for a model its /models lists but the plan can't use through Codex:+// "The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account."+const PLAN_MODEL_REFUSED = /model is not supported when using Codex with a ChatGPT account/i;++/** A ChatGPT plan turn refused because the signed-in account can't use the selected model. */+export function codexPlanModelRefused(value: string, route: CodexRoute): boolean {+ return route === "plan" && PLAN_MODEL_REFUSED.test(value);+}+export function codexUserError(value: string, route: CodexRoute, codexErrorInfo?: unknown): string {+ if (codexPlanModelRefused(value, route)) {+ return "This model isn't available on your ChatGPT plan, so it's now hidden from this account's model list. Pick another model.";+ }if (route === "plan" && value.includes("subscription_sharing_usage_limit_exceeded")) {return "subscription_sharing_usage_limit_exceeded: Your ChatGPT plan usage limit was reached. Manage usage in ChatGPT Settings, or explicitly choose another provider.";}diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.tsindex b1161a50db..3f37f0cfb0 100644--- a/server/drivers/codex.test.ts+++ b/server/drivers/codex.test.ts@@ -53,6 +53,9 @@ describe("CodexDriver.decodeConfig", () => {expect(codexUserError("provider_not_configured", "own")).toContain("Continue with ChatGPT");expect(codexUserError("provider_not_configured", "plan")).toContain("API billing will not be used");expect(codexUserError("x".repeat(500) + "subscription_sharing_usage_limit_exceeded", "plan")).toMatch(/^subscription_sharing_usage_limit_exceeded:/);+ const refusal = "The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account.";+ expect(codexUserError(refusal, "plan")).toBe("This model isn't available on your ChatGPT plan, so it's now hidden from this account's model list. Pick another model.");+ expect(codexUserError(refusal, "own")).toBe(refusal);expect(() => CodexDriver.decodeConfig({ authMode: "chatgpt-plan", managed: {} })).toThrow("cannot be combined");});it("defaults to the codex binary with fullAuto off", () => {@@ -1397,6 +1400,52 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)expect(argv).not.toContain("mcp_servers.whop.default_tools_approval_mode");});+ it("hides a model ChatGPT refuses for this account and runs later turns on the account's next model", async () => {+ plan();+ vi.spyOn(ChatGptPlanAuthController.prototype, "models").mockResolvedValue({ default: "gpt-6.1-sol", options: [{ id: "gpt-6.1-sol", label: "GPT-6.1 Sol" }, { id: "gpt-fixture", label: "Fixture" }] });+ let refused: string[] = [];+ vi.spyOn(ChatGptPlanAuthController.prototype, "refusedModels").mockImplementation(() => refused);+ const refuse = vi.spyOn(ChatGptPlanAuthController.prototype, "refuseModel").mockImplementation(async (slug) => { refused = [...refused, slug]; });+ await create({ mode: "plan-model-refused", authMode: "chatgpt-plan" });+ const first = await instance.adapter.sendTurn({ threadId: "t-plan-refused", text: "go", model: "gpt-6.1-sol" });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === first.turnId);+ const errors = recorder.events.filter((event) => event.type === "runtime.error" && event.turnId === first.turnId);+ expect(errors).toHaveLength(1);+ expect((errors[0] as { message: string }).message).toContain("isn't available on your ChatGPT plan");+ expect(refuse).toHaveBeenCalledExactlyOnceWith("gpt-6.1-sol");+ const dump = join(scratch, "plan-refused.json");+ process.env.FAKE_CODEX_DUMP = dump;+ const next = await instance.adapter.sendTurn({ threadId: "t-plan-refused-next", text: "go", model: "gpt-6.1-sol" });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === next.turnId);+ const seen = JSON.parse(readFileSync(dump, "utf8"));+ expect(seen.calls.find((call: { method: string }) => call.method === "thread/start").params.model).toBe("gpt-fixture");+ });++ it("takes the refused model off the menu at once, even when it was the account's only model", async () => {+ plan();+ let refused: string[] = [];+ vi.spyOn(ChatGptPlanAuthController.prototype, "models").mockImplementation(async () => {+ const options = [{ id: "gpt-6.1-sol", label: "GPT-6.1 Sol" }].filter((option) => !refused.includes(option.id));+ return { default: options[0]?.id ?? "", options };+ });+ vi.spyOn(ChatGptPlanAuthController.prototype, "refusedModels").mockImplementation(() => refused);+ vi.spyOn(ChatGptPlanAuthController.prototype, "refuseModel").mockImplementation(async (slug) => { refused = [...refused, slug]; });+ await create({ mode: "plan-model-refused", authMode: "chatgpt-plan" });+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-plan-only-refused", text: "go", model: "gpt-6.1-sol" });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ expect(instance.models).toEqual({ default: "", options: [] });+ });++ it("never hides a model for a ChatGPT plan error that isn't ChatGPT refusing that model", async () => {+ plan();+ const refuse = vi.spyOn(ChatGptPlanAuthController.prototype, "refuseModel").mockResolvedValue();+ await create({ mode: "usage-limit", authMode: "chatgpt-plan" });+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-plan-limit", text: "go", model: "gpt-6.1-sol" });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ expect(recorder.events.some((event) => event.type === "runtime.error" && event.turnId === turnId)).toBe(true);+ expect(refuse).not.toHaveBeenCalled();+ });+it("passes the person's proxy settings to the proxy, which Codex would otherwise drop", async () => {plan();await create({ authMode: "chatgpt-plan", environment: { HTTPS_PROXY: "http://proxy.example.test:3128", NODE_EXTRA_CA_CERTS: "/etc/corp-ca.pem" } });diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 7cd0e82789..07881d2216 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -47,7 +47,8 @@ import { volatileContextNote, withContextNote } from "./prompt-split.ts";import type { ApprovalMode } from "../../shared/approval-mode.ts";import { CodexDeviceAuthController } from "./codex-device-auth.ts";import { codexAccountEmail, codexHome } from "./codex-identity.ts";-import { archivedNativeCodexThread, CODEX_MISSING_CREDENTIALS, CODEX_SIGN_IN_EXPIRED, codexLimitFacts, codexNotSignedIn, CodexRpcError, codexSignInExpired, codexSignInRefused, codexUserError, missingNativeCodexThread, type CodexRoute } from "./codex-errors.ts";+import { boundedLabel, containsControlCharacter, mcpAppApprovalForm, plainRecord } from "./codex-app-approval.ts";+import { archivedNativeCodexThread, CODEX_MISSING_CREDENTIALS, CODEX_SIGN_IN_EXPIRED, codexLimitFacts, codexNotSignedIn, CodexRpcError, codexSignInExpired, codexPlanModelRefused, codexSignInRefused, codexUserError, missingNativeCodexThread, type CodexRoute } from "./codex-errors.ts";import { codexLoginCheck, codexLoginStatus, storedCodexLogin } from "./codex-login.ts";import { keyRejected, noteKeyAccepted, noteKeyRejected } from "../key-rejections.ts";import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";@@ -167,91 +168,6 @@ function additionalPermissionSummary(permissions: unknown, reason: unknown): strreturn `${prefix}Requested permissions: ${exact}`;}-type McpApprovalForm = {- tool: string;- summary: string;- allowResult: { action: "accept"; content: Record<string, string> };-};--const plainRecord = (value: unknown): Record<string, unknown> | null =>- value && typeof value === "object" && !Array.isArray(value)- ? value as Record<string, unknown>- : null;--const containsControlCharacter = (value: string): boolean => {- for (const character of value) {- const code = character.charCodeAt(0);- if (code <= 0x1f || code === 0x7f) return true;- }- return false;-};--function boundedLabel(value: unknown): string | null {- if (typeof value !== "string") return null;- const label = value.trim();- return label && label.length <= 160 && !containsControlCharacter(label) ? label : null;-}--function ordinaryApprovalValue(value: string): boolean {- const normalized = value.trim().toLowerCase();- if (/session|always|permanent|forever|persistent/.test(normalized)) return false;- return normalized === "once" || /^(?:accept|approve|allow)(?:ed|[-_]?once)?$/.test(normalized);-}--/** Only schema-backed app-access approvals; any other MCP form (credentials, free text, URLs) stays- * user input and is declined, and Full access never fabricates one. */-function mcpAppApprovalForm(params: unknown): McpApprovalForm | null {- const request = plainRecord(params);- if (!request || request.mode !== "form") return null;- const metadata = plainRecord(request._meta);- const target = plainRecord(metadata?.target);- const toolParams = plainRecord(metadata?.tool_params);- const message = boundedLabel(request.message) ?? "App access requested";- const appName = [- metadata?.app_name,- metadata?.appName,- metadata?.app,- target?.app,- target?.name,- toolParams?.app_name,- toolParams?.app,- metadata?.connector_name,- metadata?.connectorName,- ].map(boundedLabel).find(Boolean) ?? message.match(/^Allow ChatGPT to use (.+?)\?$/i)?.[1]?.trim();- if (!appName) return null;-- const schema = plainRecord(request.requestedSchema);- const properties = plainRecord(schema?.properties);- const required = schema?.required;- if (- !properties ||- !Array.isArray(required) ||- required.length === 0 ||- required.length > 8 ||- !required.every((key) => typeof key === "string" && key.length > 0 && key.length <= 100)- ) return null;-- const content: Record<string, string> = {};- for (const key of required as string[]) {- const field = plainRecord(properties[key]);- if (!field) return null;- const enumValues = Array.isArray(field.enum)- ? field.enum.filter((value): value is string => typeof value === "string")- : [];- const oneOfValues = Array.isArray(field.oneOf)- ? field.oneOf- .map((option) => boundedLabel(plainRecord(option)?.const))- .filter((value): value is string => Boolean(value))- : [];- const chosen = [...oneOfValues, ...enumValues].find(ordinaryApprovalValue);- if (!chosen) return null;- content[key] = chosen;- }-- const tool = boundedLabel(appName) ?? boundedLabel(request.serverName) ?? "app_access";- return { tool, summary: message, allowResult: { action: "accept", content } };-}-/** Thread-config overrides adding `patterns` to the person's shell exclusions. Codex keeps two* representations, the `exclude`/`include_only` lists and the `filters` table, and a higher layer* that writes one drops the other below it (codex-cli 0.160, which reports unset fields as null). */@@ -521,6 +437,13 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {}try { writeStartupModelCache(instanceId, models); } catch {}};+ // Only ChatGPT's refusal of a model for this account hides it from the account's list; other errors never do.+ const hidePlanRefusedModel = (model: string | undefined, raw: string, route: CodexRoute) => {+ if (!planAuth || !model || !codexPlanModelRefused(raw, route)) return;+ const options = models.options.filter(option => option.id !== model);+ models = { default: models.default === model ? options[0]?.id ?? "" : models.default, options };+ void planAuth.refuseModel(model).then(() => refreshModels(true)).catch(() => {});+ };// Codex's model list ships with the CLI: updating 0.155.1 to 0.162.1 in place adds gpt-6.1-sol.let modelsCliVersion: string | null = null;let startupModelRefresh: Promise<void> | null = null;@@ -598,6 +521,13 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {const planToken = planAuth ? await planAuth.accessToken() : undefined;assertPlanCurrent();if (planAuth) {+ // ChatGPT refused this model for this account in an earlier turn: carry on with the account's first usable model.+ const refused = planAuth.refusedModels();+ if (turn.model && refused.includes(turn.model)) {+ if (!models.options.length) { await refreshModels(); assertPlanCurrent(); }+ const usable = models.options.find(option => !refused.includes(option.id));+ if (usable) turn = { ...turn, model: usable.id };+ }if (!turn.model || !models.options.some(model => model.id === turn.model)) {await refreshModels();assertPlanCurrent();@@ -638,6 +568,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {const chatgptTurn = ownLogin &&decodeCodexSelection(turn.model || models.default).modelProvider === OFFICIAL_CODEX_PROVIDER;const route: CodexRoute = plan ? "plan" : chatgptTurn ? "own" : "other";+ const hideRefusedModel = (raw: string) => hidePlanRefusedModel(turn.model, raw, route);const signedOut = chatgptTurn && await loginCheck(childEnv()) === "missing";assertPlanCurrent();if (active.has(threadId)) throw new Error("a turn is already running on this thread");@@ -1126,6 +1057,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {if (message === state.lastError && (state.lastErrorSetup || !setup)) return;state.lastError = message;state.lastErrorSetup ||= setup;+ hideRefusedModel(raw);emit({ ...base(threadId, turnId), type: "runtime.error", message, ...(setup ? { setup: true } : {}), ...codexLimitFacts(raw, route, error.codexErrorInfo) });};const handleNotification = (msg: any) => {@@ -1621,6 +1553,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {const failure = e instanceof Error ? e : { text: String(e) };const raw = e instanceof Error ? e.message : String(e);const refused = chatgptTurn && loginMark() !== null && codexSignInRefused({ message: raw });+ hideRefusedModel(raw);const message = refused ? codexSignInExpired(raw) : codexUserError(raw, route);const needsAuth = refused || /(?:\b401\b|unauthorized|missing bearer|authentication required)/i.test(raw);const verdict = classifyError(failure);@@ -1705,7 +1638,11 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {model: selection.model ?? id,modelProvider: selection.modelProvider,providerArgs: planAuth || config.managed ? providerArgs : codexLocalProviderArgs(env, id),- describeError: (message) => codexUserError(message, planAuth ? "plan" : selection.modelProvider === OFFICIAL_CODEX_PROVIDER ? "own" : "other"),+ describeError: (message) => {+ const route: CodexRoute = planAuth ? "plan" : selection.modelProvider === OFFICIAL_CODEX_PROVIDER ? "own" : "other";+ hidePlanRefusedModel(selection.model ?? id, message, route);+ return codexUserError(message, route);+ },});}, options);};diff --git a/server/testing/fake-codex-app-server.ts b/server/testing/fake-codex-app-server.tsindex 41929842c9..c14eba2f42 100755--- a/server/testing/fake-codex-app-server.ts+++ b/server/testing/fake-codex-app-server.ts@@ -736,6 +736,14 @@ process.stdin.on("data", (chunk) => {break;}}+ if (mode === "plan-model-refused") {+ out({ jsonrpc: "2.0", id: msg.id, result: { turn: { id: nativeTurnId } } });+ // The reporter's words (2026-11-03): ChatGPT lists gpt-6.1-sol, then refuses it for a ChatGPT account.+ const error = { message: "unexpected status 400 Bad Request: invalid_request_error model_not_found: The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account.", codexErrorInfo: null, additionalDetails: null };+ notify("error", { willRetry: false, error });+ notify("turn/completed", { turn: { status: "failed", error } });+ break;+ }if (mode === "usage-limit") {out({ jsonrpc: "2.0", id: msg.id, result: { turn: { id: nativeTurnId } } });const error = { message: "You've hit your usage limit. Upgrade to Pro (https://chatgpt.com/explore/pro), visit https://chatgpt.com/codex/settings/usage to purchase more credits or try again at 5:23 PM.", codexErrorInfo: "usageLimitExceeded", additionalDetails: null };