Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep Codex background text on the bot's own provider (#4833)
Milind Soni6bb2f019b724
diff --git a/server/drivers/codex-background-text.test.ts b/server/drivers/codex-background-text.test.tsindex e8f078d07d..42b540ab3d 100644--- a/server/drivers/codex-background-text.test.ts+++ b/server/drivers/codex-background-text.test.ts@@ -15,7 +15,9 @@ import {CODEX_BACKGROUND_TIMEOUT_MS,codexBackgroundArgs,codexBackgroundModel,+ codexBackgroundProviderArgs,codexBackgroundRoute,+ runCodexBackgroundRoute,runCodexOneShot,} from "./codex-background-text.ts";@@ -67,6 +69,106 @@ describe("codexBackgroundRoute", () => {expect(codexBackgroundRoute(catalog, true, fallback("gpt-6-sol", ["gpt-5.4-mini"]))).toEqual({ model: "gpt-6-astra", retry: "gpt-6-sol" });expect(codexBackgroundRoute(catalog, true, fallback("gpt-6-astra", ["gpt-5.4-mini"]))).toEqual({ model: "gpt-6-astra" });});++ it("stays on the provider the bot's own model runs on, never OpenAI's small models", () => {+ const gateway = { default: "gpt-6-astra", options: [...catalog.options, { id: "mygw::glm-5", label: "GLM 5", custom: true }] };+ expect(codexBackgroundRoute(gateway, true, fallback("mygw::glm-5"))).toEqual({ model: "mygw::glm-5" });+ expect(codexBackgroundRoute(gateway, false, fallback("mygw::glm-5"))).toEqual({ model: "mygw::glm-5" });+ expect(codexBackgroundRoute({ ...gateway, default: "mygw::glm-5" }, true)).toEqual({ model: "mygw::glm-5" });+ const withSmall = { ...gateway, options: [...gateway.options, { id: "mygw::glm-5-mini", label: "GLM 5 mini", custom: true }] };+ expect(codexBackgroundRoute(withSmall, true, fallback("mygw::glm-5"))).toEqual({ model: "mygw::glm-5-mini", retry: "mygw::glm-5" });+ expect(codexBackgroundRoute(withSmall, true, fallback("mygw::glm-5", ["mygw::glm-5-mini"]))).toEqual({ model: "mygw::glm-5" });+ });++ it("goes straight to the bot's own model once OpenAI turned a background call away", () => {+ expect(codexBackgroundRoute(catalog, true, fallback("gpt-6-sol"), true)).toEqual({ model: "gpt-6-sol" });+ expect(codexBackgroundRoute(catalog, true, undefined, true)).toEqual({ model: "gpt-6-astra" });+ });+});++describe("runCodexBackgroundRoute", () => {+ const blocked = 'unexpected status 403 Forbidden: {"error":{"code":"unsupported_country_region_territory","message":"Country, region, or territory not supported"}}';+ const failOn = (failing: string, message: string) => {+ const ran: string[] = [];+ return { ran, run: async (model: string) => { ran.push(model); if (model === failing) throw new Error(message); return `from ${model}`; } };+ };++ it("runs once more on the bot's own model when OpenAI blocks or cannot be reached, and says so", async () => {+ for (const message of [blocked, "Codex background call timed out: Reconnecting... waiting for network (Connection failed: error sending request)"]) {+ const { ran, run } = failOn("gpt-5.4-mini", message);+ const onRefused = vi.fn();+ const unreachable = vi.fn();+ await expect(runCodexBackgroundRoute({ model: "gpt-5.4-mini", retry: "mygw::glm-5" }, run, { fallback: { refused: new Set(), onRefused } }, unreachable)).resolves.toBe("from mygw::glm-5");+ expect(ran).toEqual(["gpt-5.4-mini", "mygw::glm-5"]);+ expect(unreachable).toHaveBeenCalledOnce();+ expect(onRefused).not.toHaveBeenCalled();+ }+ });++ it("fails as before off OpenAI, without a listener, or for another error", async () => {+ const unreachable = vi.fn();+ const own = failOn("mygw::glm-5-mini", blocked);+ await expect(runCodexBackgroundRoute({ model: "mygw::glm-5-mini", retry: "mygw::glm-5" }, own.run, {}, unreachable)).rejects.toThrow(/403/);+ const managed = failOn("gpt-6-luna", blocked);+ await expect(runCodexBackgroundRoute({ model: "gpt-6-luna", retry: "company-large" }, managed.run)).rejects.toThrow(/403/);+ const signedOut = failOn("gpt-6-luna", "unexpected status 401 Unauthorized");+ await expect(runCodexBackgroundRoute({ model: "gpt-6-luna", retry: "gpt-6-sol" }, signedOut.run, {}, unreachable)).rejects.toThrow(/401/);+ expect([own.ran, managed.ran, signedOut.ran]).toEqual([["mygw::glm-5-mini"], ["gpt-6-luna"], ["gpt-6-luna"]]);+ expect(unreachable).not.toHaveBeenCalled();+ });+});++describe("codexBackgroundProviderArgs", () => {+ let home: string;+ beforeEach(() => { home = mkdtempSync(join(tmpdir(), "omb-codex-provider-test-")); });+ afterEach(async () => { await removeTempDir(home); });++ const argsFor = (toml: string, model = "mygw::glm-5", file = "config.toml") => {+ writeFileSync(join(home, file), toml);+ const env: Record<string, string | undefined> = { CODEX_HOME: home };+ const args = codexBackgroundProviderArgs(env, model);+ return { env, args, overrides: args.filter((_, index) => args[index - 1] === "-c") };+ };++ it("carries the person's config.toml provider, its token and headers in the environment only", () => {+ const { env, args, overrides } = argsFor([+ 'model = "glm-5"', 'model_provider = "mygw"', "",+ "[model_providers.other]", 'base_url = "https://other.example/v1"', "",+ "[model_providers.mygw]", 'name = "My gateway" # mine', 'base_url = "https://gw.example/v1"', 'wire_api = "responses"',+ 'experimental_bearer_token = "sk-gateway-secret"', "request_max_retries = 2", "query_params = [", ' "a",', ' "b",', "]", "",+ "[model_providers.mygw.http_headers]", '"X-Team" = "team-secret"', "",+ "[mcp_servers.mine]", 'command = "mine-mcp"',+ ].join("\n"));+ expect(overrides).toEqual([+ 'model_providers.mygw.name="My gateway"',+ 'model_providers.mygw.base_url="https://gw.example/v1"',+ 'model_providers.mygw.wire_api="responses"',+ "model_providers.mygw.request_max_retries=2",+ 'model_providers.mygw.query_params=[ "a", "b", ]',+ 'model_providers.mygw.env_http_headers.X-Team="OPENMAUSBOT_CODEX_MYGW_HEADER_1"',+ 'model_providers.mygw.env_key="OPENMAUSBOT_CODEX_MYGW_TOKEN"',+ ]);+ expect(args.join(" ")).not.toMatch(/secret|other\.example|mine-mcp/);+ expect(env.OPENMAUSBOT_CODEX_MYGW_TOKEN).toBe("sk-gateway-secret");+ expect(env.OPENMAUSBOT_CODEX_MYGW_HEADER_1).toBe("team-secret");+ });++ it("reads inline and dotted provider tables, and a profile file's", () => {+ expect(argsFor('[model_providers]\nmygw = { name = "GW", base_url = "https://gw.example/v1" }\n').overrides)+ .toEqual(['model_providers.mygw={ name = "GW", base_url = "https://gw.example/v1" }']);+ expect(argsFor('model_providers.mygw.base_url = "https://gw.example/v1"\nmodel_providers.mygw.env_key = "GW_KEY"\n').overrides)+ .toEqual(['model_providers.mygw.base_url="https://gw.example/v1"', 'model_providers.mygw.env_key="GW_KEY"']);+ writeFileSync(join(home, "config.toml"), 'model_provider = "mygw"\n');+ expect(argsFor('[model_providers.mygw]\nbase_url = "https://work.example/v1"\n', "mygw::glm-5", "work.config.toml").overrides)+ .toEqual(['model_providers.mygw.base_url="https://work.example/v1"']);+ });++ it("adds nothing for OpenAI, Codex's own providers or a provider config.toml does not declare", () => {+ const toml = '[model_providers.ollama]\nbase_url = "http://localhost:1/v1"\n[model_providers.openai]\nname = "x"\n';+ expect(argsFor(toml, "gpt-6-luna").args).toEqual([]);+ expect(argsFor(toml, "ollama::llama3").args).toEqual([]);+ expect(argsFor(toml, "absent::model").args).toEqual([]);+ });});describe("codexBackgroundArgs", () => {@@ -284,6 +386,35 @@ describe("Codex generateMemoryText (fake CLI)", () => {expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ [codex.instanceId]: ["gpt-6-luna"] });});+ it("writes on the bot's own gateway model with the gateway's provider table, never OpenAI's small model", async () => {+ apiKeyLogin();+ writeFileSync(join(scratch, ".codex", "config.toml"), [+ 'model = "glm-5"', 'model_provider = "mygw"',+ "[model_providers.mygw]", 'name = "My gateway"', 'base_url = "http://127.0.0.1:9/v1"', 'env_key = "MYGW_KEY"',+ ].join("\n"));+ const codex = await create({ FAKE_CODEX_LUNA: "1", FAKE_CODEX_TEXT_BLOCK: "gpt-6-luna" });+ await expect(codex.generateMemoryText!("hello", { fallback: ownModel("mygw::glm-5").fallback })).resolves.toBe("fake background answer");+ await expect(codex.generateMemoryText!("hello")).resolves.toBe("fake background answer");+ expect(modelsRun()).toEqual(["glm-5", "glm-5"]);+ for (const { argv } of calls()) {+ expect(argv).toContain('model_provider="mygw"');+ expect(argv).toContain('model_providers.mygw.base_url="http://127.0.0.1:9/v1"');+ expect(argv).toContain("--ignore-user-config");+ }+ });++ it("runs once more on the bot's own model when OpenAI blocks this region, then goes straight there", async () => {+ apiKeyLogin();+ const codex = await create({ FAKE_CODEX_LUNA: "1", FAKE_CODEX_TEXT_BLOCK: "gpt-6-luna" });+ const { fallback, onRefused } = ownModel("gpt-fake-default");+ const usage: TextGenerationUsage[] = [];+ await expect(codex.generateMemoryText!("hello", { fallback, onUsage: (entry) => usage.push(entry) })).resolves.toBe("fake background answer");+ await expect(codex.generateMemoryText!("again", { fallback })).resolves.toBe("fake background answer");+ expect(modelsRun()).toEqual(["gpt-6-luna", "gpt-fake-default", "gpt-fake-default"]);+ expect(onRefused).not.toHaveBeenCalled();+ expect(usage).toEqual([expect.objectContaining({ model: "gpt-fake-default" })]);+ });+it("reads past Codex's banners, notices and reasoning to the answer", async () => {const codex = await create({ FAKE_CODEX_TEXT_MODE: "noisy", FAKE_CODEX_TEXT_REPLY: "only this" });await expect(codex.generateMemoryText!("hello")).resolves.toBe("only this");diff --git a/server/drivers/codex-background-text.ts b/server/drivers/codex-background-text.tsindex 909842aa9e..c31b3f8326 100644--- a/server/drivers/codex-background-text.ts+++ b/server/drivers/codex-background-text.ts@@ -11,7 +11,9 @@ import type { ModelCatalog, SmallModelFallback, TextGenerationOptions, TextGenerimport type { killCliTree, spawnCli } from "../procs.ts";import { refusesModel } from "../quick-model-fallback.ts";import { decodeCodexSelection, OFFICIAL_CODEX_PROVIDER } from "./codex-catalog.ts";+import { codexConfigProviderArgs } from "./codex-config-provider.ts";import { codexToolSurfaceArgs } from "./codex-tool-surface.ts";+import { codexLocalProviderArgs } from "./local-inject.ts";export const CODEX_BACKGROUND_TIMEOUT_MS = 120_000;export const CODEX_BACKGROUND_MAX_CHARS = 200_000;@@ -22,11 +24,16 @@ export const CODEX_BACKGROUND_MODELS = ["gpt-6-luna", "gpt-5.6-luna", "gpt-5.4-mexport const CODEX_BACKGROUND_EFFORT = "low";const SMALL_MODEL = /(?:^|[-.])(?:luna|mini|nano)(?:$|[-.])/i;-export function codexBackgroundModel(catalog: ModelCatalog, refused: ReadonlySet<string> = new Set()): string | null {- const official = catalog.options.filter((option) => !option.custom && !refused.has(option.id) &&- decodeCodexSelection(option.id).modelProvider === OFFICIAL_CODEX_PROVIDER);- for (const id of CODEX_BACKGROUND_MODELS) if (official.some((option) => option.id === id)) return id;- return official.find((option) => SMALL_MODEL.test(option.id))?.id ?? accountDefault(catalog);+const providerOf = (id: string) => decodeCodexSelection(id).modelProvider ?? OFFICIAL_CODEX_PROVIDER;++/** A small model `provider` lists (OpenAI's in the documented order), or else for OpenAI the account's default. */+export function codexBackgroundModel(catalog: ModelCatalog, refused: ReadonlySet<string> = new Set(), provider: string = OFFICIAL_CODEX_PROVIDER): string | null {+ const official = provider === OFFICIAL_CODEX_PROVIDER;+ const listed = catalog.options.filter((option) => !(official && option.custom) && !refused.has(option.id) &&+ decodeCodexSelection(option.id).modelProvider === provider);+ if (official) for (const id of CODEX_BACKGROUND_MODELS) if (listed.some((option) => option.id === id)) return id;+ const small = listed.find((option) => SMALL_MODEL.test(decodeCodexSelection(option.id).model ?? option.id))?.id;+ return small ?? (official ? accountDefault(catalog) : null);}function accountDefault(catalog: ModelCatalog): string | null {@@ -35,28 +42,50 @@ function accountDefault(catalog: ModelCatalog): string | null {export interface CodexBackgroundRoute {model: string;- /** Run once more on this when the provider refuses `model`. */+ /** Run once more on this when the provider refuses `model`, or OpenAI is blocked or unreachable from here. */retry?: string;}-/** A sign-in that cannot use small models writes on the bot's own model, or the account's default without one. */-export function codexBackgroundRoute(catalog: ModelCatalog, smallModelsUsable: boolean, fallback?: SmallModelFallback): CodexBackgroundRoute | null {+/** Background text stays on the provider the bot's own model runs on (a person's gateway when OpenAI is blocked+ * where they are). A sign-in that cannot use small models, or one OpenAI already turned away here, writes on the bot's+ * own model, or the account's default without one. */+export function codexBackgroundRoute(catalog: ModelCatalog, smallModelsUsable: boolean, fallback?: SmallModelFallback, openaiUnreachable = false): CodexBackgroundRoute | null {const own = fallback?.model || accountDefault(catalog);- const model = smallModelsUsable ? codexBackgroundModel(catalog, fallback?.refused) : own;+ const provider = own ? providerOf(own) : OFFICIAL_CODEX_PROVIDER;+ const small = smallModelsUsable && !(openaiUnreachable && provider === OFFICIAL_CODEX_PROVIDER);+ const model = (small ? codexBackgroundModel(catalog, fallback?.refused, provider) : null) ?? own;if (!model) return null;return own && own !== model ? { model, retry: own } : { model };}-export async function runCodexBackgroundRoute(route: CodexBackgroundRoute, run: (model: string) => Promise<string>, options: TextGenerationOptions = {}): Promise<string> {+/** OpenAI refusing this region (403 unsupported_country_region_territory), or no connection to it at all. */+const OPENAI_UNREACHABLE = /country, region,? or territory|unsupported_country|\b403\b|forbidden|error sending request|connection refused|dns error|failed to lookup address|network is unreachable/i;++export async function runCodexBackgroundRoute(+ route: CodexBackgroundRoute,+ run: (model: string) => Promise<string>,+ options: TextGenerationOptions = {},+ /** Told once OpenAI is blocked or unreachable from here; the next routes then skip its small models. */+ onOpenaiUnreachable?: () => void,+): Promise<string> {try {return await run(route.model);} catch (error) {- if (!route.retry || !refusesModel(error instanceof Error ? error.message : String(error), route.model)) throw error;- options.fallback?.onRefused(route.model);+ const message = error instanceof Error ? error.message : String(error);+ if (!route.retry) throw error;+ if (refusesModel(message, route.model)) options.fallback?.onRefused(route.model);+ else if (onOpenaiUnreachable && providerOf(route.model) === OFFICIAL_CODEX_PROVIDER && OPENAI_UNREACHABLE.test(message)) onOpenaiUnreachable();+ else throw error;return run(route.retry);}}+/** `--ignore-user-config` drops the person's own providers: a local host's or config.toml's comes along as overrides. */+export function codexBackgroundProviderArgs(env: Record<string, string | undefined>, modelId: string): string[] {+ const local = codexLocalProviderArgs(env, modelId);+ return local.length ? local : codexConfigProviderArgs(env, modelId);+}+/** Features off (codex-cli 0.160.1 `codex features list`); an older Codex ignores unknown names. */const BACKGROUND_FEATURES_OFF = ["shell_tool", "unified_exec", "shell_snapshot", "view_image", "image_generation",@@ -148,7 +177,7 @@ export async function runCodexOneShot(input: CodexOneShotInput): Promise<string>else resolve(answer.trim());};const abort = () => void finish(new Error("Codex background call aborted"));- const timer = setTimeout(() => void finish(new Error("Codex background call timed out")), input.timeoutMs ?? input.options?.timeoutMs ?? CODEX_BACKGROUND_TIMEOUT_MS);+ const timer = setTimeout(() => void finish(new Error(`Codex background call timed out${fatal ? `: ${describe(fatal)}` : ""}`)), input.timeoutMs ?? input.options?.timeoutMs ?? CODEX_BACKGROUND_TIMEOUT_MS);timer.unref?.();const onEvent = (event: any) => {diff --git a/server/drivers/codex-config-provider.ts b/server/drivers/codex-config-provider.tsnew file mode 100644index 0000000000..9334f7ab2a--- /dev/null+++ b/server/drivers/codex-config-provider.ts@@ -0,0 +1,142 @@+// `codex exec --ignore-user-config` skips config.toml and every provider the person declared there: a background+// call on one fails with "Model provider `x` not found" (codex-cli 0.167). Such a call carries the provider's own+// table as `-c` overrides. A bearer token, or a header in its own `http_headers` table, moves into the child's+// environment instead of argv.+import { readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";++import { decodeCodexSelection } from "./codex-catalog.ts";+import { codexHome } from "./codex-identity.ts";++/** Providers Codex defines itself. */+const BUILT_IN = new Set(["openai", "oss", "ollama", "lmstudio"]);+const BARE_KEY = /^[A-Za-z0-9_-]+$/;+const KEY_PART = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;+const KEY_LINE = new RegExp(String.raw`^(${KEY_PART}(?:\s*\.\s*${KEY_PART})*)\s*=\s*(.*)$`);++/** A key path below `model_providers.<id>` (empty for an inline table) and its TOML value as written. */+interface Entry { path: string[]; raw: string }++export function codexConfigProviderArgs(env: Record<string, string | undefined>, modelId: string | null | undefined): string[] {+ const provider = decodeCodexSelection(modelId).modelProvider;+ const home = codexHome(env);+ if (!provider || BUILT_IN.has(provider) || !BARE_KEY.test(provider) || !home) return [];+ let profiles: string[] = [];+ try {+ profiles = readdirSync(home).filter((file) => file.endsWith(".config.toml")).sort();+ } catch {}+ for (const file of ["config.toml", ...profiles]) {+ let text: string;+ try {+ text = readFileSync(join(home, file), "utf8");+ } catch {+ continue;+ }+ const entries = providerTable(text, provider);+ if (entries.length) return overrides(env, provider, entries);+ }+ return [];+}++function splitKey(text: string): string[] | null {+ const parts: string[] = [];+ const part = new RegExp(String.raw`\s*(?:([A-Za-z0-9_-]+)|"((?:[^"\\]|\\.)*)"|'([^']*)')\s*(\.|$)`, "y");+ for (let index = 0; index < text.length;) {+ part.lastIndex = index;+ const match = part.exec(text);+ if (!match) return null;+ parts.push(match[1] ?? match[2] ?? match[3] ?? "");+ index = part.lastIndex;+ if (!match[4]) break;+ }+ return parts.length ? parts : null;+}++/** The value starting `text` on line `at`, up to its comment; an open array runs on to the next lines. */+function scanValue(lines: string[], at: number, text: string): { raw: string | null; next: number } {+ const triple = /^("""|''')/.exec(text)?.[1];+ if (triple) {+ let next = at + 1;+ if (!text.slice(3).includes(triple)) while (next < lines.length && !lines[next++]!.includes(triple));+ return { raw: null, next };+ }+ let raw = "";+ let depth = 0;+ let quote = "";+ for (let index = at, line = text; ; line = lines[index]?.trim() ?? "") {+ let end = line.length;+ for (let i = 0; i < line.length; i++) {+ const char = line[i];+ if (quote) {+ if (char === "\\" && quote === '"') i++;+ else if (char === quote) quote = "";+ } else if (char === '"' || char === "'") quote = char;+ else if (char === "[" || char === "{") depth++;+ else if (char === "]" || char === "}") depth--;+ else if (char === "#") { end = i; break; }+ }+ raw += `${raw ? " " : ""}${line.slice(0, end).trim()}`;+ index++;+ if (depth <= 0 || quote || index >= lines.length) return { raw: depth === 0 && !quote && raw ? raw : null, next: index };+ }+}++/** Every key under `model_providers.<id>`, whether set in its table, a subtable, a parent table or dotted. */+function providerTable(text: string, provider: string): Entry[] {+ const entries: Entry[] = [];+ const lines = text.split(/\r?\n/);+ let table: string[] | null = [];+ for (let index = 0; index < lines.length;) {+ const line = lines[index]!.trim();+ if (!line || line.startsWith("#")) { index++; continue; }+ if (line.startsWith("[")) {+ const header = /^\[([^[\]]+)\]\s*(?:#.*)?$/.exec(line);+ table = header ? splitKey(header[1]!) : null;+ index++;+ continue;+ }+ const match = KEY_LINE.exec(line);+ if (!match) { index++; continue; }+ const { raw, next } = scanValue(lines, index, match[2]!);+ index = next;+ const key = splitKey(match[1]!);+ const path = table && key ? [...table, ...key] : [];+ if (raw && path[0] === "model_providers" && path[1] === provider) entries.push({ path: path.slice(2), raw });+ }+ return entries;+}++function stringValue(raw: string): string | null {+ if (raw.startsWith("'")) return raw.length >= 2 && raw.endsWith("'") ? raw.slice(1, -1) : null;+ try {+ const value: unknown = JSON.parse(raw);+ return typeof value === "string" ? value : null;+ } catch {+ return null;+ }+}++function overrides(env: Record<string, string | undefined>, provider: string, entries: Entry[]): string[] {+ const args: string[] = [];+ const variable = (suffix: string) => `OPENMAUSBOT_CODEX_${provider.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_${suffix}`;+ const set = (key: string, raw: string) => args.push("-c", `model_providers.${[provider, key].filter(Boolean).join(".")}=${raw}`);+ const token = entries.find((entry) => entry.path.join(".") === "experimental_bearer_token");+ const bearer = token ? stringValue(token.raw) : null;+ let headers = 0;+ for (const { path, raw } of entries) {+ if (!path.every((part) => BARE_KEY.test(part)) || path[0] === "experimental_bearer_token" || (bearer !== null && path[0] === "env_key")) continue;+ const value = path[0] === "http_headers" && path.length === 2 ? stringValue(raw) : null;+ if (value === null) {+ set(path.join("."), raw);+ continue;+ }+ const name = variable(`HEADER_${++headers}`);+ env[name] = value;+ set(`env_http_headers.${path[1]}`, JSON.stringify(name));+ }+ if (bearer !== null) {+ env[variable("TOKEN")] = bearer;+ set("env_key", JSON.stringify(variable("TOKEN")));+ }+ return args;+}diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex c3f2e9805e..e08aaf5b38 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -41,8 +41,7 @@ import type {} from "../contracts.ts";import { newEventId, newId } from "../contracts.ts";import { codexSelectedProviderArgs, decodeCodexSelection, OFFICIAL_CODEX_PROVIDER, readCodexModelCatalog, STATIC_CODEX_MODELS } from "./codex-catalog.ts";-import { codexLocalProviderArgs } from "./local-inject.ts";-import { codexBackgroundRoute, runCodexBackgroundRoute, runCodexOneShot } from "./codex-background-text.ts";+import { codexBackgroundProviderArgs, codexBackgroundRoute, runCodexBackgroundRoute, runCodexOneShot } from "./codex-background-text.ts";import { augmentedPath } from "../env-path.ts";import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.ts";import { appendNative } from "./native.ts";@@ -1581,6 +1580,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {};};+ let openaiUnreachable = false; // set once OpenAI turned a background call away: later ones go straight to the bot's model/** The background one-shot: `codex exec` with no tools or session, in an empty folder. Never* generateText, or titles and compaction would each start a Codex process. */const generateMemoryText = async (prompt: string, options: TextGenerationOptions = {}): Promise<string> => {@@ -1606,7 +1606,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {}providerArgs = managedCodexArgs(config.managed);}- const route = codexBackgroundRoute(models, smallModelsUsable(), options.fallback);+ const route = codexBackgroundRoute(models, smallModelsUsable(), options.fallback, openaiUnreachable);if (!route) throw new Error("Codex lists no model for background calls. Refresh models in Settings → Model providers → Codex.");return runCodexBackgroundRoute(route, (id) => {const selection = planAuth || routed ? { model: id, modelProvider: null } : decodeCodexSelection(id);@@ -1614,14 +1614,14 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {spawn: spawnCli, kill: killCliTree, cli: config.cli, env, prompt, options,model: selection.model ?? id,modelProvider: selection.modelProvider,- providerArgs: planAuth || routed ? providerArgs : codexLocalProviderArgs(env, id),+ providerArgs: planAuth || routed ? providerArgs : codexBackgroundProviderArgs(env, id),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);+ }, options, planAuth || config.managed ? undefined : () => { openaiUnreachable = true; });};return {diff --git a/server/testing/fake-codex-app-server.ts b/server/testing/fake-codex-app-server.tsindex 3b57a6323c..7dfc2a004f 100755--- a/server/testing/fake-codex-app-server.ts+++ b/server/testing/fake-codex-app-server.ts@@ -49,6 +49,7 @@// FAKE_CODEX_TEXT_LOG `codex exec`: append {argv, cwd, prompt, env} per call// FAKE_CODEX_TEXT_MODE `codex exec`: ok (default) | fail | exit | hang | tool | noisy// FAKE_CODEX_TEXT_REFUSE `codex exec`: comma-separated models answered with the 400 a ChatGPT account gets for gpt-5.4-mini+// FAKE_CODEX_TEXT_BLOCK `codex exec`: comma-separated models answered with the 403 OpenAI sends a region it does not serve// FAKE_CODEX_LUNA "1": model/list also offers gpt-6-luna// FAKE_CODEX_UPDATED_FILE while this file exists, the CLI was updated in place: --version answers codex-cli 0.162.1// and model/list also offers gpt-6.1-sol@@ -140,6 +141,12 @@ if (process.argv[2] === "exec") {event({ type: "turn.failed", error: { message } });process.exit(1);}+ if (process.env.FAKE_CODEX_TEXT_BLOCK?.split(",").includes(model)) {+ const message = 'unexpected status 403 Forbidden: {"error":{"code":"unsupported_country_region_territory","message":"Country, region, or territory not supported","param":null,"type":"request_forbidden"}}';+ event({ type: "error", message });+ event({ type: "turn.failed", error: { message } });+ process.exit(1);+ }if (textMode === "fail") {event({ type: "error", message: "unexpected status 401 Unauthorized" });event({ type: "turn.failed", error: { message: "unexpected status 401 Unauthorized" } });