Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Fix ChatGPT plan token renewal during Codex turns

gaokui2010d59929fa8904
diff --git a/scripts/bundle-server.mjs b/scripts/bundle-server.mjs
index 854a12446e..f4db99c90a 100644
--- a/scripts/bundle-server.mjs
+++ b/scripts/bundle-server.mjs
@@ -57,6 +57,7 @@ const ENTRY_POINTS = [
"drivers/agents-proxy.ts",
"drivers/dweb-proxy.ts",
"drivers/phone-proxy.ts",
+ "drivers/chatgpt-plan-token-command.ts",
// the bot box (server/bot-box): the in-box bridge, the probe the self-check runs inside a box, and the check by hand
"bot-box/box-bridge.ts",
"bot-box/box-probe.ts",
diff --git a/scripts/verify-codex-token-refresh.mjs b/scripts/verify-codex-token-refresh.mjs
new file mode 100644
index 0000000000..0a3951c4ea
--- /dev/null
+++ b/scripts/verify-codex-token-refresh.mjs
@@ -0,0 +1,69 @@
+// Real Codex, synthetic credentials and a loopback Responses service; never touches a user's Codex home.
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { createServer } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { startChatGptTokenBridge } from "../server/drivers/chatgpt-plan-token-bridge.ts";
+
+const cli = process.env.PROBE_CODEX || "codex";
+const helper = process.env.PROBE_HELPER || fileURLToPath(new URL("../server/drivers/chatgpt-plan-token-command.ts", import.meta.url));
+const runtime = process.env.PROBE_RUNTIME || process.execPath;
+const event = (type, data) => `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`;
+async function scenario(dynamic) {
+ const dir = mkdtempSync(join(tmpdir(), "omb-codex-refresh-"));
+ const marker = join(dir, "tool-count");
+ let expired = false, requests = [];
+ const bridge = dynamic ? await startChatGptTokenBridge(async () => expired ? "fake-B" : "fake-A") : null;
+ const server = createServer((req, res) => {
+ req.resume();
+ req.on("end", () => {
+ if (!req.url?.includes("/responses")) { res.writeHead(404); res.end(); return; }
+ const token = (req.headers.authorization || "").replace("Bearer ", "");
+ requests.push(token);
+ if (requests.length > 1 && token === "fake-A") {
+ expired = true;
+ res.writeHead(401, { "content-type": "application/json" });
+ res.end(JSON.stringify({ error: { code: "token_expired", message: "synthetic token expired" } }));
+ return;
+ }
+ const item = requests.length === 1 ? {
+ id: "fc_fixture", type: "function_call", status: "completed", name: "exec_command", call_id: "call_fixture",
+ arguments: JSON.stringify({ cmd: `if [ -n "$OMB_CODEX_AUTH_SECRET" ]; then printf leak >> '${marker}'; else printf x >> '${marker}'; fi` }),
+ } : { id: "msg_fixture", type: "message", status: "completed", role: "assistant", content: [{ type: "output_text", text: "fixture ok", annotations: [] }] };
+ const id = `resp_fixture${requests.length}`;
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ res.end(event("response.created", { type: "response.created", response: { id, status: "in_progress", output: [] } }) +
+ event("response.output_item.added", { type: "response.output_item.added", output_index: 0, item }) +
+ event("response.output_item.done", { type: "response.output_item.done", output_index: 0, item }) +
+ event("response.completed", { type: "response.completed", response: { id, status: "completed", output: [item], usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } } }));
+ });
+ });
+ try {
+ await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); });
+ const args = ["exec", "--skip-git-repo-check", "--ephemeral", "--sandbox", "workspace-write", "-m", "gpt-5",
+ "-c", 'model_provider="fixture"', "-c", 'model_providers.fixture.name="Fixture"',
+ "-c", `model_providers.fixture.base_url="http://127.0.0.1:${server.address().port}/v1"`,
+ "-c", 'model_providers.fixture.wire_api="responses"', "-c", "model_providers.fixture.requires_openai_auth=false",
+ "-c", "model_providers.fixture.supports_websockets=false", "-c", "model_providers.fixture.stream_max_retries=0",
+ "-c", "model_providers.fixture.request_max_retries=0", "-c", "features.shell_snapshot=false",
+ "-c", 'shell_environment_policy.exclude=["OMB_CODEX_AUTH_SECRET","OMB_CODEX_AUTH_SOCKET","ELECTRON_RUN_AS_NODE"]',
+ ...(dynamic ? ["-c", `model_providers.fixture.auth.command=${JSON.stringify(runtime)}`,
+ "-c", `model_providers.fixture.auth.args=[${JSON.stringify(helper)}]`, "-c", "model_providers.fixture.auth.refresh_interval_ms=30000",
+ "-c", "model_providers.fixture.auth.timeout_ms=60000"] : ["-c", 'model_providers.fixture.env_key="FIXTURE_TOKEN"']), "Run fixture tool"];
+ const env = { PATH: process.env.PATH, HOME: dir, CODEX_HOME: dir, NO_PROXY: "127.0.0.1,localhost", FIXTURE_TOKEN: "fake-A", ELECTRON_RUN_AS_NODE: "1", ...bridge?.env };
+ const child = spawn(cli, args, { cwd: dir, env, stdio: ["ignore", "pipe", "pipe"] });
+ let output = ""; child.stdout.on("data", x => { output += x; }); child.stderr.on("data", x => { output += x; });
+ const timer = setTimeout(() => child.kill("SIGTERM"), 45000);
+ const code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); });
+ clearTimeout(timer);
+ assert.equal(existsSync(marker) ? readFileSync(marker, "utf8") : "", "x", `tool must run once without the bridge secret: ${output.slice(-1200)}`);
+ assert.deepEqual(requests, dynamic ? ["fake-A", "fake-A", "fake-B"] : ["fake-A", "fake-A"]);
+ assert.equal(code, dynamic ? 0 : 1, output.slice(-1200));
+ console.log(`${dynamic ? "dynamic" : "static"}: ${dynamic ? "recovered" : "failed as expected"}; tool ran once`);
+ } finally { bridge?.close(); server.close(); rmSync(dir, { recursive: true, force: true }); }
+}
+await scenario(false);
+await scenario(true);
diff --git a/server/drivers/chatgpt-plan-token-bridge.test.ts b/server/drivers/chatgpt-plan-token-bridge.test.ts
new file mode 100644
index 0000000000..2532638a21
--- /dev/null
+++ b/server/drivers/chatgpt-plan-token-bridge.test.ts
@@ -0,0 +1,39 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { fileURLToPath } from "node:url";
+import { startChatGptTokenBridge } from "./chatgpt-plan-token-bridge.ts";
+
+const exec = promisify(execFile);
+const helper = fileURLToPath(new URL("./chatgpt-plan-token-command.ts", import.meta.url));
+const bridges: Awaited<ReturnType<typeof startChatGptTokenBridge>>[] = [];
+const start = async (get: () => Promise<string>) => { const bridge = await startChatGptTokenBridge(get); bridges.push(bridge); return bridge; };
+const request = (env: Record<string, string>) => exec(process.execPath, [helper], { env: { ...process.env, ...env } });
+afterEach(() => { for (const bridge of bridges.splice(0)) bridge.close(); });
+
+describe("ChatGPT run token bridge", () => {
+ it("obtains the current token without emitting it on stderr", async () => {
+ let token = "synthetic-A";
+ const bridge = await start(async () => token);
+ expect(await request(bridge.env)).toMatchObject({ stdout: "synthetic-A", stderr: "" });
+ token = "synthetic-B";
+ expect((await request(bridge.env)).stdout).toBe("synthetic-B");
+ });
+ it("rejects other capabilities and revokes access after a run ends", async () => {
+ const bridge = await start(async () => "synthetic-token");
+ await expect(request({ ...bridge.env, OMB_CODEX_AUTH_SECRET: "wrong" })).rejects.toThrow();
+ bridge.close();
+ await expect(request(bridge.env)).rejects.toThrow();
+ });
+ it("does not return a token when the bridge is closed while refresh is pending", async () => {
+ let resolve!: (token: string) => void;
+ let started!: () => void;
+ const waiting = new Promise<void>(r => { started = r; });
+ const bridge = await start(() => { started(); return new Promise(r => { resolve = r; }); });
+ const result = request(bridge.env);
+ await waiting;
+ bridge.close();
+ resolve("synthetic-token");
+ await expect(result).rejects.toThrow();
+ });
+});
diff --git a/server/drivers/chatgpt-plan-token-bridge.ts b/server/drivers/chatgpt-plan-token-bridge.ts
new file mode 100644
index 0000000000..52e554947e
--- /dev/null
+++ b/server/drivers/chatgpt-plan-token-bridge.ts
@@ -0,0 +1,49 @@
+import { randomBytes, timingSafeEqual } from "node:crypto";
+import { mkdtempSync, rmSync } from "node:fs";
+import { createServer, type Socket } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+/** A short-lived capability for a single Codex run. No OAuth credentials cross the command line. */
+export async function startChatGptTokenBridge(accessToken: () => Promise<string>) {
+ const secret = randomBytes(32).toString("hex");
+ const directory = process.platform === "win32" ? undefined : mkdtempSync(join(tmpdir(), "omb-auth-"));
+ const path = directory ? join(directory, "s") : `\\\\.\\pipe\\omb-auth-${randomBytes(16).toString("hex")}`;
+ const connections = new Set<Socket>();
+ let closed = false;
+ const server = createServer((socket) => {
+ connections.add(socket);
+ socket.on("close", () => connections.delete(socket));
+ socket.on("error", () => {});
+ let input = "";
+ socket.setTimeout(60_000, () => socket.destroy());
+ socket.on("data", (chunk) => {
+ input += chunk.toString();
+ if (input.length > 128) return socket.destroy();
+ if (!input.endsWith("\n")) return;
+ socket.removeAllListeners("data");
+ const actual = Buffer.from(input.trim());
+ const expected = Buffer.from(secret);
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) return socket.destroy();
+ void accessToken().then((token) => {
+ if (!closed) socket.end(token);
+ }, () => socket.destroy());
+ });
+ });
+ try {
+ await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(path, resolve); });
+ } catch (error) {
+ if (directory) rmSync(directory, { recursive: true, force: true });
+ throw error;
+ }
+ return {
+ env: { OMB_CODEX_AUTH_SOCKET: path, OMB_CODEX_AUTH_SECRET: secret },
+ close() {
+ if (closed) return;
+ closed = true;
+ for (const socket of connections) socket.destroy();
+ server.close();
+ if (directory) rmSync(directory, { recursive: true, force: true });
+ },
+ };
+}
diff --git a/server/drivers/chatgpt-plan-token-command.ts b/server/drivers/chatgpt-plan-token-command.ts
new file mode 100644
index 0000000000..58db84e90f
--- /dev/null
+++ b/server/drivers/chatgpt-plan-token-command.ts
@@ -0,0 +1,16 @@
+import { createConnection } from "node:net";
+
+// Invoked by Codex. stdout must contain only the token; failures disclose no credentials.
+const path = process.env.OMB_CODEX_AUTH_SOCKET;
+const secret = process.env.OMB_CODEX_AUTH_SECRET;
+if (!path || !secret) process.exit(1);
+const socket = createConnection(path);
+socket.setTimeout(55_000, () => socket.destroy());
+socket.on("connect", () => socket.write(`${secret}\n`));
+socket.on("error", () => { process.exitCode = 1; });
+let response = "";
+socket.on("data", (data) => { response += data.toString(); if (response.length > 16384) socket.destroy(); });
+socket.on("close", () => {
+ if (!response || response.length > 16384) { process.exitCode = 1; return; }
+ process.stdout.write(response);
+});
diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.ts
index a831a8d7d7..ae3b9cf508 100644
--- a/server/drivers/codex.test.ts
+++ b/server/drivers/codex.test.ts
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
import { once } from "node:events";
import { spawn } from "node:child_process";
+import { createConnection } from "node:net";
import { createInterface } from "node:readline";
import { tmpdir } from "node:os";
import { dirname, join, sep } from "node:path";
@@ -1367,6 +1368,47 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
vi.spyOn(ChatGptPlanAuthController.prototype, "models").mockResolvedValue({ default: "gpt-6.1-sol", options: [{ id: "gpt-6.1-sol", label: "GPT-6.1 Sol" }] });
};
+ it("uses a task-scoped command for a supported Codex and excludes its capability from tools", async () => {
+ process.env.FAKE_CODEX_VERSION = "codex-cli 0.165.0";
+ plan();
+ await create({ authMode: "chatgpt-plan" });
+ const dump = join(scratch, "plan-command.json");
+ process.env.FAKE_CODEX_DUMP = dump;
+ await instance.adapter.sendTurn({ threadId: "plan-command", text: "go", model: "gpt-6.1-sol" });
+ expect(await recorder.until((event) => event.type === "turn.completed")).toMatchObject({ ok: true });
+ const seen = JSON.parse(readFileSync(dump, "utf8"));
+ expect(seen.argv.join(" ")).toContain("model_providers.openai_chatgpt_plan.auth.command=");
+ expect(seen.argv.join(" ")).not.toContain("model_providers.openai_chatgpt_plan.env_key=");
+ expect(seen.env.OPENMAUSBOT_CHATGPT_TOKEN).toBeUndefined();
+ const thread = seen.calls.find((call: { method: string }) => call.method === "thread/start");
+ expect(thread.params.config["shell_environment_policy.exclude"]).toEqual(expect.arrayContaining(["OMB_CODEX_AUTH_SECRET", "OMB_CODEX_AUTH_SOCKET"]));
+ });
+
+ it.each(["new login", "sign out"])("revokes a running task's token capability on %s", async (action) => {
+ process.env.FAKE_CODEX_VERSION = "codex-cli 0.165.0";
+ plan();
+ vi.spyOn(ChatGptPlanAuthController.prototype, "start").mockRejectedValue(new Error("synthetic login"));
+ vi.spyOn(ChatGptPlanAuthController.prototype, "signOut").mockResolvedValue();
+ const dump = join(scratch, "plan-revocation.json");
+ process.env.FAKE_CODEX_DUMP = dump;
+ await create({ authMode: "chatgpt-plan", mode: "approval" });
+ await instance.adapter.sendTurn({ threadId: "plan-revocation", text: "go", model: "gpt-6.1-sol" });
+ await recorder.until(event => event.type === "request.opened");
+ const seen = JSON.parse(readFileSync(dump, "utf8"));
+ const getToken = () => new Promise<string>((resolve) => {
+ const socket = createConnection(seen.env.OMB_CODEX_AUTH_SOCKET);
+ let data = "";
+ socket.on("connect", () => socket.write(`${seen.env.OMB_CODEX_AUTH_SECRET}\n`));
+ socket.on("data", chunk => { data += chunk.toString(); });
+ socket.on("error", () => resolve(""));
+ socket.on("close", () => resolve(data));
+ });
+ expect(await getToken()).toBe("synthetic-plan-token");
+ if (action === "new login") await expect(instance.startAuthentication!()).rejects.toThrow("synthetic login");
+ else await instance.signOut!();
+ expect(await getToken()).toBe("");
+ });
+
it("searches each URL server through the remote proxy, its settings kept from the shell", async () => {
plan();
await create({ authMode: "chatgpt-plan" });
diff --git a/server/drivers/codex.ts b/server/drivers/codex.ts
index 0f2857a7ec..b633183eb4 100644
--- a/server/drivers/codex.ts
+++ b/server/drivers/codex.ts
@@ -16,6 +16,8 @@ import { hostedWorkspaceConfigured } from "../enterprise.ts";
import { cloudHomeConfigured } from "../cloud-home.ts";
import { serverVersion } from "../environment.ts";
import { ChatGptPlanAuthController } from "./chatgpt-plan-auth.ts";
+import { startChatGptTokenBridge } from "./chatgpt-plan-token-bridge.ts";
+import { SPAWNED_PROXIES } from "../proxy-paths.ts";
import { captureCliTree, cliVersionReader, describeSpawnFailure, execCli, killCliTree, spawnCli, waitForExit } from "../procs.ts";
import { codexLaunch, codexLaunchesStarting, codexLaunchSlot, codexRpcTimeoutMs, keepStopping, RELAUNCH_EXIT_WAIT_MS, spawnHoldingSlot, tomlInlineTable, tryCodexLaunchSlot } from "./codex-process.ts";
import { isReservedMcpEnvEntry } from "../mcp-registry.ts";
@@ -87,12 +89,17 @@ function decodeConfig(raw: unknown): CodexConfig {
/** The token-sharing Responses bridge carries no hosted tool_search (Codex 0.159.0 sends none), so
* a plan turn's MCP tools load up front. */
-export function chatgptPlanCodexArgs(): string[] {
+export function chatgptPlanCodexArgs(dynamic = false): string[] {
return [
"-c", 'model_provider="openai_chatgpt_plan"',
"-c", 'model_providers.openai_chatgpt_plan.name="ChatGPT plan"',
"-c", 'model_providers.openai_chatgpt_plan.base_url="https://api.openai.com/v1"',
- "-c", 'model_providers.openai_chatgpt_plan.env_key="OPENMAUSBOT_CHATGPT_TOKEN"',
+ ...(dynamic ? [
+ "-c", `model_providers.openai_chatgpt_plan.auth.command=${JSON.stringify(process.execPath)}`,
+ "-c", `model_providers.openai_chatgpt_plan.auth.args=[${JSON.stringify(SPAWNED_PROXIES.chatgptPlanToken)}]`,
+ "-c", "model_providers.openai_chatgpt_plan.auth.refresh_interval_ms=30000",
+ "-c", "model_providers.openai_chatgpt_plan.auth.timeout_ms=60000",
+ ] : ["-c", 'model_providers.openai_chatgpt_plan.env_key="OPENMAUSBOT_CHATGPT_TOKEN"']),
"-c", 'model_providers.openai_chatgpt_plan.wire_api="responses"',
"-c", "model_providers.openai_chatgpt_plan.requires_openai_auth=false",
"-c", "model_providers.openai_chatgpt_plan.supports_websockets=false",
@@ -489,11 +496,20 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
delete env.OPENAI_API_KEY;
stripWorkspaceCredentialEnv(env);
delete env.OPENMAUSBOT_CHATGPT_TOKEN;
+ delete env.OMB_CODEX_AUTH_SOCKET;
+ delete env.OMB_CODEX_AUTH_SECRET;
if (plan) env.CODEX_HOME = join(planDirectory, "codex");
return env;
};
const catalogEnv = childEnv();
const planAuth = plan ? new ChatGptPlanAuthController({ directory: planDirectory }) : null;
+ // 0.165.0 is the earliest version verified with command authentication here.
+ const dynamicPlanSupport = plan && !planUnavailable ? new Promise<boolean>((resolve) => {
+ execCli(config.cli, ["--version"], { timeout: 8000, env: catalogEnv }, (error, stdout) => {
+ const match = error ? null : stdout.match(/\b(\d+)\.(\d+)\.(\d+)\b/);
+ resolve(!!match && (Number(match[1]) > 0 || Number(match[2]) >= 165));
+ });
+ }) : Promise.resolve(false);
let planGeneration = 0;
let planSigningOut = false;
let disposed = false;
@@ -648,6 +664,18 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "auth_required", cost: null });
return { turnId };
}
+ const dynamicPlan = !!planAuth && await dynamicPlanSupport;
+ assertPlanCurrent();
+ const authBridge = dynamicPlan && planAuth ? await startChatGptTokenBridge(async () => {
+ assertPlanCurrent();
+ if (stopRequested) throw new Error("This task has ended.");
+ const token = await planAuth.accessToken();
+ assertPlanCurrent();
+ if (stopRequested) throw new Error("This task has ended.");
+ return token;
+ }) : null;
+ try { assertPlanCurrent(); } catch (error) { authBridge?.close(); throw error; }
+ if (active.has(threadId)) { authBridge?.close(); throw new Error("a turn is already running on this thread"); }
const retryScale = Number(process.env.FAKE_CODEX_RETRY_SCALE ?? "1");
let announced = false;
const waitForLaunchSlot = async (attempt: number) => {
@@ -659,6 +687,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const slot = await codexLaunchSlot(stopSignal.signal);
if (slot && !stopRequested) return slot;
slot?.();
+ authBridge?.close();
if (active.get(threadId) === waiting) {
active.delete(threadId);
emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "interrupted", cost: null });
@@ -668,10 +697,11 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const launchAttempt = async (attempt: number): Promise<void> => {
const env = childEnv();
const launchedLogin = chatgptTurn ? storedCodexLogin(env) : null;
- if (planToken) env.OPENMAUSBOT_CHATGPT_TOKEN = planToken;
- const appServerArgs = ["app-server", ...(plan ? chatgptPlanCodexArgs() : config.managed ? managedCodexArgs(config.managed) : codexLocalProviderArgs(env, turn.model)), ...codexToolSurfaceArgs(),
+ if (planToken && !authBridge) env.OPENMAUSBOT_CHATGPT_TOKEN = planToken;
+ if (authBridge) Object.assign(env, authBridge.env, { ELECTRON_RUN_AS_NODE: "1" });
+ const appServerArgs = ["app-server", ...(plan ? chatgptPlanCodexArgs(!!authBridge) : config.managed ? managedCodexArgs(config.managed) : codexLocalProviderArgs(env, turn.model)), ...codexToolSurfaceArgs(),
// Native shell snapshots can restore variables the shell policy removed.
- ...(turn.toolScope === undefined ? [] : ["-c", "features.shell_snapshot=false"]),
+ ...(turn.toolScope === undefined && !authBridge ? [] : ["-c", "features.shell_snapshot=false"]),
// A guest-driven turn: no shell, no file reads (-c wins over config files).
...(turn.guestConfined ? GUEST_CONFINED_CODEX_ARGS : [])];
const baseEnv = new Map(Object.entries(env).filter(([, value]) => value !== undefined));
@@ -897,6 +927,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const settle = async (ok: boolean, stopReason: string | null) => {
if (state.settled) return;
state.settled = true;
+ authBridge?.close();
for (const finish of Array.from(asks.values())) finish("deny", "OpenMausBot: the turn ended", "system");
for (const p of rpcPending.values()) p.reject(new Error("turn settled"));
rpcPending.clear();
@@ -1442,9 +1473,9 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
: "Could not read Codex configuration; cannot safely update bot instructions. Retry after checking Codex.",
);
}
- if (privateEnv.length) {
+ if (privateEnv.length || authBridge) {
const snapshot = (effectiveConfig as { features?: { shell_snapshot?: unknown } } | null)?.features?.shell_snapshot;
- if (provenPrivateEnv ? snapshot !== false : snapshot === true) {
+ if (provenPrivateEnv || authBridge ? snapshot !== false : snapshot === true) {
throw new Error("Codex could not disable inherited shell snapshots. No prompt was sent.");
}
}
@@ -1454,7 +1485,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
throw new Error("Codex could not confirm its shell environment policy. No prompt was sent.");
}
selectionConfig.config = { ...selectionConfig.config,
- ...extendShellExclusions((rawPolicy ?? {}) as Record<string, unknown>, [...(plan ? ["OPENMAUSBOT_CHATGPT_TOKEN"] : []), ...privateEnv]) };
+ ...extendShellExclusions((rawPolicy ?? {}) as Record<string, unknown>, [...(plan ? ["OPENMAUSBOT_CHATGPT_TOKEN"] : []), ...(authBridge ? ["OMB_CODEX_AUTH_SOCKET", "OMB_CODEX_AUTH_SECRET", "ELECTRON_RUN_AS_NODE"] : []), ...privateEnv]) };
}
if (turn.toolScope !== undefined) {
const catalog = (effectiveConfig as { mcp_servers?: unknown } | null)?.mcp_servers;
@@ -1640,7 +1671,12 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
}
};
- void launchAttempt(0).catch(() => {});
+ void launchAttempt(0).catch((error: unknown) => {
+ authBridge?.close();
+ if (active.get(threadId)?.turnId === turnId) active.delete(threadId);
+ emit({ ...base(threadId, turnId), type: "runtime.error", message: error instanceof Error ? error.message : String(error) });
+ emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "launch_error", cost: null });
+ });
return { turnId };
};
@@ -1653,8 +1689,11 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
});
if (!("version" in probe)) return { state: "unavailable", reason: probe.reason, ...(plan ? { chatgptPlan: true } : {}) };
const { version } = probe;
- if (planAuth) return { state: "available", version, chatgptPlan: true, billing: "subscription", ...await planAuth.snapshot(), update: await codexReleaseUpdate(version, config.cli),
- ...(planWarning ? { warning: { title: "Check ChatGPT connection", message: planWarning } } : {}) };
+ if (planAuth) {
+ const warning = planWarning ?? (!(await dynamicPlanSupport) ? "Update Codex to 0.165.0 or newer to renew ChatGPT credentials during a running task." : undefined);
+ return { state: "available", version, chatgptPlan: true, billing: "subscription", ...await planAuth.snapshot(), update: await codexReleaseUpdate(version, config.cli),
+ ...(warning ? { warning: { title: "Check ChatGPT connection", message: warning } } : {}) };
+ }
if (config.managed) return { state: "available", version, authenticated: Boolean(input.environment.OPENMAUSBOT_COMPANY_API_KEY && input.environment.CODEX_HOME), billing: "metered" };
const previousCliVersion = modelsCliVersion;
modelsCliVersion = version;
@@ -1683,13 +1722,24 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
if (planUnavailable) throw new Error(planUnavailable);
const env = childEnv();
let providerArgs: string[] = [];
+ let authBridge: Awaited<ReturnType<typeof startChatGptTokenBridge>> | null = null;
if (planAuth) {
if (planSigningOut) throw new Error("This ChatGPT account is being disconnected.");
if (!models.options.length) await refreshModels();
- env.OPENMAUSBOT_CHATGPT_TOKEN = await planAuth.accessToken();
+ const generation = planGeneration;
+ const token = await planAuth.accessToken();
if (planSigningOut || disposed) throw new Error("This ChatGPT account is being disconnected.");
mkdirSync(join(planDirectory, "codex"), { recursive: true, mode: 0o700 });
- providerArgs = chatgptPlanCodexArgs();
+ if (await dynamicPlanSupport) {
+ authBridge = await startChatGptTokenBridge(async () => {
+ if (planSigningOut || disposed || generation !== planGeneration) throw new Error("This ChatGPT account changed.");
+ const value = await planAuth.accessToken();
+ if (planSigningOut || disposed || generation !== planGeneration) throw new Error("This ChatGPT account changed.");
+ return value;
+ });
+ Object.assign(env, authBridge.env, { ELECTRON_RUN_AS_NODE: "1" });
+ } else env.OPENMAUSBOT_CHATGPT_TOKEN = token;
+ providerArgs = chatgptPlanCodexArgs(!!authBridge);
} else if (config.managed) {
if (!input.environment.OPENMAUSBOT_COMPANY_API_KEY || !input.environment.CODEX_HOME) {
throw new Error("Company model access is unavailable. Reconnect your organization; personal billing will not be used.");
@@ -1697,8 +1747,8 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
providerArgs = managedCodexArgs(config.managed);
}
const route = codexBackgroundRoute(models, smallModelsUsable(), options.fallback);
- if (!route) throw new Error("Codex lists no model for background calls. Refresh models in Settings → Model providers → Codex.");
- return runCodexBackgroundRoute(route, (id) => {
+ if (!route) { authBridge?.close(); throw new Error("Codex lists no model for background calls. Refresh models in Settings → Model providers → Codex."); }
+ try { return await runCodexBackgroundRoute(route, (id) => {
const selection = planAuth || config.managed ? { model: id, modelProvider: null } : decodeCodexSelection(id);
return runCodexOneShot({
spawn: spawnCli, kill: killCliTree, cli: config.cli, env, prompt, options,
@@ -1707,7 +1757,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
providerArgs: planAuth || config.managed ? providerArgs : codexLocalProviderArgs(env, id),
describeError: (message) => codexUserError(message, planAuth ? "plan" : selection.modelProvider === OFFICIAL_CODEX_PROVIDER ? "own" : "other"),
});
- }, options);
+ }, options); } finally { authBridge?.close(); }
};
return {
@@ -1726,6 +1776,8 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
startAuthentication: async () => {
if (planUnavailable) throw new Error(planUnavailable);
if (planSigningOut || disposed) throw new Error("This account is being disconnected. Wait before signing in again.");
+ // A new login may replace the account before its status is polled.
+ if (planAuth) planGeneration++;
return (planAuth ?? authentication).start();
},
getAuthentication: async (flowId) => {
diff --git a/server/proxy-paths.ts b/server/proxy-paths.ts
index 6b2e6a9390..6af5d61841 100644
--- a/server/proxy-paths.ts
+++ b/server/proxy-paths.ts
@@ -22,6 +22,7 @@ export const SPAWNED_PROXIES = {
mcpGate: resolveProxy("mcp-gate"),
mcpRemote: resolveProxy("mcp-remote-proxy"),
phone: resolveProxy("drivers/phone-proxy"),
+ chatgptPlanToken: resolveProxy("drivers/chatgpt-plan-token-command"),
hook: resolveProxy("hooks/omb-hook"),
piMcpExtension: resolveProxy("drivers/pi-mcp-extension"),
} as const;