Skip to content

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

feat(codex): ChatGPT plan turns use the person's own Codex setup (#4835)

Milind Soni8266e509c9ea
diff --git a/server/drivers/codex-shared-home.test.ts b/server/drivers/codex-shared-home.test.ts
new file mode 100644
index 0000000000..4eb926242e
--- /dev/null
+++ b/server/drivers/codex-shared-home.test.ts
@@ -0,0 +1,134 @@
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { linkSharedCodexHome } from "./codex-shared-home.ts";
+
+let root: string;
+let shared: string;
+let plan: string;
+
+function write(path: string, text = "x"): void {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, text);
+}
+const isLink = (path: string) => lstatSync(path).isSymbolicLink();
+const linksTo = (path: string, target: string) => isLink(path) && realpathSync(path) === realpathSync(target);
+const snapshot = () => Object.fromEntries(readdirSync(plan).sort().map(name => [name, isLink(join(plan, name)) ? readlinkSync(join(plan, name)) : "real"]));
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "omb-codex-shared-home-"));
+ shared = join(root, "person", ".codex");
+ plan = join(root, "data", "providers", "chatgpt-plan", "abc", "codex");
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe("linkSharedCodexHome", () => {
+ it("links the person's Codex home into the plan's, but never its sign-in, local folders or SQLite journals", () => {
+ write(join(shared, "config.toml"), '[mcp_servers.notes]\ncommand = "notes"\n');
+ write(join(shared, "skills", "review", "SKILL.md"));
+ write(join(shared, "history.jsonl"));
+ write(join(shared, ".credentials.json"));
+ write(join(shared, "state_5.sqlite"));
+ write(join(shared, "state_5.sqlite-wal"));
+ write(join(shared, "state_5.sqlite-shm"));
+ write(join(shared, "auth.json"), "person's sign-in");
+ write(join(shared, "auth.lock"));
+ write(join(shared, "models_cache.json"));
+ for (const local of ["log", "memories", "tmp"]) mkdirSync(join(shared, local), { recursive: true });
+
+ linkSharedCodexHome(shared, plan);
+
+ for (const name of ["config.toml", "skills", "history.jsonl", ".credentials.json", "state_5.sqlite", "sessions", "plugins", "thread-writer-locks"]) {
+ expect(linksTo(join(plan, name), join(shared, name)), name).toBe(true);
+ }
+ // The shared folders exist in the person's home from the first turn, so what the plan writes lands there.
+ expect(lstatSync(join(shared, "sessions")).isDirectory()).toBe(true);
+ write(join(plan, "sessions", "2026", "rollout.jsonl"));
+ expect(existsSync(join(shared, "sessions", "2026", "rollout.jsonl"))).toBe(true);
+ expect(readFileSync(join(plan, "skills", "review", "SKILL.md"), "utf8")).toBe("x");
+ for (const name of ["auth.json", "auth.lock", "models_cache.json", "log", "memories", "tmp", "state_5.sqlite-wal", "state_5.sqlite-shm"]) {
+ expect(existsSync(join(plan, name)), name).toBe(false);
+ }
+ });
+
+ it("keeps the plan's own sign-in real and removes a link that stands in its place", () => {
+ write(join(shared, "auth.json"), "person's sign-in");
+ write(join(shared, "models_cache.json"), "person's models");
+ write(join(plan, "auth.json"), "plan sign-in");
+ symlinkSync(join(shared, "models_cache.json"), join(plan, "models_cache.json"));
+ symlinkSync(join(shared, "auth.lock"), join(plan, "auth.lock"));
+
+ linkSharedCodexHome(shared, plan);
+
+ expect(isLink(join(plan, "auth.json"))).toBe(false);
+ expect(readFileSync(join(plan, "auth.json"), "utf8")).toBe("plan sign-in");
+ expect(existsSync(join(plan, "models_cache.json"))).toBe(false);
+ expect(() => lstatSync(join(plan, "auth.lock"))).toThrow();
+ expect(readFileSync(join(shared, "models_cache.json"), "utf8")).toBe("person's models");
+ });
+
+ it("keeps what earlier plan turns made, and lets only folders Codex rebuilds itself give way", () => {
+ write(join(shared, "history.jsonl"), "person");
+ write(join(shared, "skills", "review", "SKILL.md"));
+ write(join(plan, "sessions", "2026", "11", "rollout-plan.jsonl"), "plan session");
+ write(join(plan, "history.jsonl"), "plan history");
+ write(join(plan, "skills", ".system", "openai-docs", "SKILL.md"));
+ mkdirSync(join(plan, "plugins"), { recursive: true });
+ write(join(plan, "thread-writer-locks", "thread-1.lock"));
+ write(join(plan, "mcp-oauth-locks", ".coordination.lock"));
+
+ linkSharedCodexHome(shared, plan);
+
+ expect(isLink(join(plan, "sessions"))).toBe(false);
+ expect(readFileSync(join(plan, "sessions", "2026", "11", "rollout-plan.jsonl"), "utf8")).toBe("plan session");
+ expect(readFileSync(join(plan, "history.jsonl"), "utf8")).toBe("plan history");
+ expect(readFileSync(join(shared, "history.jsonl"), "utf8")).toBe("person");
+ // Codex's bundled .system skills and an empty folder are rebuilt; the person's skills take their place.
+ expect(linksTo(join(plan, "skills"), join(shared, "skills"))).toBe(true);
+ expect(linksTo(join(plan, "plugins"), join(shared, "plugins"))).toBe(true);
+ // A lock still in the plan's own folder may guard a live writer: shared on a later turn, once released.
+ expect(isLink(join(plan, "thread-writer-locks"))).toBe(false);
+ expect(linksTo(join(plan, "mcp-oauth-locks"), join(shared, "mcp-oauth-locks"))).toBe(true);
+ expect(console.error).toHaveBeenCalledTimes(1);
+ expect(String(vi.mocked(console.error).mock.calls[0]?.[0])).toContain("sessions, thread-writer-locks, history.jsonl");
+
+ rmSync(join(plan, "thread-writer-locks", "thread-1.lock"));
+ linkSharedCodexHome(shared, plan);
+ expect(linksTo(join(plan, "thread-writer-locks"), join(shared, "thread-writer-locks"))).toBe(true);
+ expect(console.error).toHaveBeenCalledTimes(1);
+ });
+
+ it("changes nothing on a second run, and repoints a link the person's home moved away from", () => {
+ write(join(shared, "config.toml"));
+ write(join(shared, "skills", "review", "SKILL.md"));
+ linkSharedCodexHome(shared, plan);
+ const first = snapshot();
+ linkSharedCodexHome(shared, plan);
+ expect(snapshot()).toEqual(first);
+
+ const moved = join(root, "elsewhere", ".codex");
+ write(join(moved, "config.toml"), "moved");
+ linkSharedCodexHome(moved, plan);
+ expect(linksTo(join(plan, "config.toml"), join(moved, "config.toml"))).toBe(true);
+ expect(readFileSync(join(plan, "config.toml"), "utf8")).toBe("moved");
+ expect(existsSync(join(shared, "config.toml"))).toBe(true);
+ });
+
+ it("only makes the plan home when there is no separate absolute home to share", () => {
+ write(join(plan, "config.toml"), "plan");
+ for (const home of [null, "relative/.codex", plan, dirname(plan), join(plan, "inner")]) linkSharedCodexHome(home, plan);
+ expect(readdirSync(plan)).toEqual(["config.toml"]);
+ expect(existsSync(join(plan, "inner"))).toBe(false);
+
+ const fresh = join(root, "fresh", "codex");
+ linkSharedCodexHome(null, fresh);
+ expect(readdirSync(fresh)).toEqual([]);
+ });
+});
diff --git a/server/drivers/codex-shared-home.ts b/server/drivers/codex-shared-home.ts
new file mode 100644
index 0000000000..2b7763d876
--- /dev/null
+++ b/server/drivers/codex-shared-home.ts
@@ -0,0 +1,93 @@
+// A ChatGPT-plan instance signs in on a Codex home of its own, so its login never mixes with the person's. Everything
+// else the person set up for Codex (config.toml, skills, plugins, sessions, MCP sign-ins) is linked in from their own
+// home, so a plan turn works like their own Codex. Company Codex homes never come here: they stay fully separate.
+import { lstatSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, unlinkSync } from "node:fs";
+import { isAbsolute, join, relative, resolve } from "node:path";
+
+/** Made in the person's home first, so a plan shares them from its first turn. */
+const SHARED_FOLDERS = ["sessions", "archived_sessions", "sqlite", "shell_snapshots", "worktrees", "skills", "plugins", "cache",
+ "logs", "mcp-oauth-locks", "thread-writer-locks"];
+/** The plan's own sign-in and model list: always real files in its own home, never links. */
+const PRIVATE = new Set(["auth.json", "auth.lock", "models_cache.json"]);
+/** Kept per home. */
+const LOCAL = new Set(["log", "memories", "tmp", ".DS_Store"]);
+/** Locks that guard shared state: a plan's own copy gives way to the shared one once no lock in it is held. */
+const RUNTIME_LOCKS = new Set(["mcp-oauth-locks", "thread-writer-locks", ".sqlite-maintenance.lock"]);
+/** What Codex writes into a folder by itself and rebuilds: a plan folder holding nothing else gives way to a link. */
+const REBUILT = new Set([".system", ".DS_Store"]);
+// SQLite opens a database through its link and keeps -wal and -shm beside the real file; a journal linked on its own
+// would pair one home's journal with the other home's database.
+const SQLITE_JOURNAL = /-(?:wal|shm|journal)$/;
+
+const noted = new Set<string>();
+function note(path: string, message: string): void {
+ if (noted.has(path)) return;
+ noted.add(path);
+ console.error(`codex: ${message}`);
+}
+
+function inside(parent: string, child: string): boolean {
+ const path = relative(parent, child);
+ return path === "" || (!path.startsWith("..") && !isAbsolute(path));
+}
+
+/** A real entry the plan made itself that holds nothing of its own, or only locks no one holds any more. */
+function givesWay(path: string, name: string): boolean {
+ const stats = lstatSync(path);
+ if (!stats.isDirectory()) return RUNTIME_LOCKS.has(name);
+ const names = readdirSync(path);
+ if (RUNTIME_LOCKS.has(name)) return !names.some(entry => entry.endsWith(".lock") && entry !== ".coordination.lock");
+ return names.every(entry => REBUILT.has(entry));
+}
+
+/** Links one entry; false when the plan keeps a real one of its own. */
+function linkEntry(target: string, link: string, name: string): boolean {
+ let stats;
+ try { stats = lstatSync(link); } catch { stats = null; }
+ if (stats?.isSymbolicLink()) {
+ try { if (realpathSync(link) === realpathSync(target)) return true; } catch {}
+ unlinkSync(link);
+ } else if (stats) {
+ // Earlier plan turns kept their own sessions and history here: never delete them, keep using them.
+ if (!givesWay(link, name)) return false;
+ rmSync(link, { recursive: true, force: true });
+ }
+ const folder = statSync(target).isDirectory();
+ try {
+ symlinkSync(target, link, process.platform === "win32" ? (folder ? "junction" : "file") : undefined);
+ } catch (error) {
+ // Another turn of the same plan linked it first.
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ }
+ return true;
+}
+
+/** Makes the plan's Codex home and links the person's own Codex home into it. Linking never fails the turn: an entry
+ * that cannot be linked (a file link Windows refuses without Developer Mode) stays as the plan had it. */
+export function linkSharedCodexHome(sharedHome: string | null, planHome: string): void {
+ mkdirSync(planHome, { recursive: true, mode: 0o700 });
+ if (!sharedHome || !isAbsolute(sharedHome) || !isAbsolute(planHome)) return;
+ const shared = resolve(sharedHome), own = resolve(planHome);
+ if (inside(shared, own) || inside(own, shared)) return;
+ let names: string[];
+ try {
+ for (const name of SHARED_FOLDERS) mkdirSync(join(shared, name), { recursive: true, mode: 0o700 });
+ names = readdirSync(shared);
+ } catch (error) {
+ return note(shared, `could not share your Codex home with the ChatGPT plan: ${(error as Error).message}`);
+ }
+ for (const name of PRIVATE) {
+ const path = join(own, name);
+ try { if (lstatSync(path).isSymbolicLink()) unlinkSync(path); } catch {}
+ }
+ const kept: string[] = [];
+ for (const name of new Set([...SHARED_FOLDERS, ...names])) {
+ if (PRIVATE.has(name) || LOCAL.has(name) || SQLITE_JOURNAL.test(name)) continue;
+ try {
+ if (!linkEntry(join(shared, name), join(own, name), name)) kept.push(name);
+ } catch (error) {
+ note(join(own, name), `could not link ${JSON.stringify(name)} of your Codex home for the ChatGPT plan: ${(error as Error).message}`);
+ }
+ }
+ if (kept.length) note(own, `the ChatGPT plan's Codex home keeps its own ${kept.join(", ")} from earlier turns; the rest of your Codex home is shared`);
+}
diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.ts
index 697759811e..38f0642585 100644
--- a/server/drivers/codex.test.ts
+++ b/server/drivers/codex.test.ts
@@ -1998,6 +1998,8 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
if (plan) {
expect(seen.env.CODEX_HOME.startsWith(join(DATA_DIR, "providers", "chatgpt-plan") + sep)).toBe(true);
expect(seen.env.CODEX_HOME).not.toBe(join(scratch, ".codex"));
+ // The plan signs in on its own home; the person's Codex skills, settings and sessions are linked in.
+ expect(realpathSync(join(seen.env.CODEX_HOME, "skills"))).toBe(realpathSync(join(scratch, ".codex", "skills")));
expect(seen.argv.some((arg: string) => arg.startsWith("shell_environment_policy.exclude="))).toBe(false);
} else expect(seen.env.CODEX_HOME).toBe(join(scratch, ".codex"));
const threadCalls = seen.calls.filter((call: { method: string }) => ["thread/start", "thread/resume"].includes(call.method));
diff --git a/server/drivers/codex.ts b/server/drivers/codex.ts
index 9ab05d21a0..dadf4148ac 100644
--- a/server/drivers/codex.ts
+++ b/server/drivers/codex.ts
@@ -9,7 +9,6 @@ import { boxProxyEnvNames, type McpApprovalMode, mountMcpServer } from "./codex-
import { reportUnsupportedCalls, rolloutMark, type RolloutMark } from "./codex-unsupported-calls.ts";
// The `codex` CLI headless over its app-server JSON-RPC (NDJSON on stdio): completion is
// `turn/completed`, approvals arrive as server→client requests, resumeCursor is the codex thread id.
-import { mkdirSync } from "node:fs";
import { createHash } from "node:crypto";
import { join } from "node:path";
import { homedir } from "node:os";
@@ -53,6 +52,7 @@ 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 { linkSharedCodexHome } from "./codex-shared-home.ts";
import { containsControlCharacter, mcpAppApprovalForm, mcpAppApprovalText, mcpElicitationDeclined, plainRecord } from "./codex-app-approval.ts";
import { archivedNativeCodexThread, CODEX_MISSING_CREDENTIALS, codexProviderMismatch, CODEX_SIGN_IN_EXPIRED, codexLimitFacts, codexNotSignedIn, CodexRpcError, codexSignInExpired, codexPlanModelRefused, codexSignInRefused, codexUserError, codexUserFailure, missingNativeCodexThread, type CodexRoute } from "./codex-errors.ts";
import { codexLoginCheck, codexLoginStatus, storedCodexLogin } from "./codex-login.ts";
@@ -494,7 +494,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
assertPlanCurrent();
if (!turn.model || !models.options.some(model => model.id === turn.model)) throw new Error("This model is not available to the selected ChatGPT plan. Refresh models and choose a listed model; API billing will not be used.");
}
- mkdirSync(join(planDirectory, "codex"), { recursive: true, mode: 0o700 });
+ linkSharedCodexHome(codexHome({ ...process.env, ...input.environment }), join(planDirectory, "codex"));
}
if (config.endpoint) {
if (!turn.model || !config.endpoint.models.includes(turn.model)) throw new Error("Select a model configured for this direct API endpoint.");
@@ -1593,7 +1593,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
if (!models.options.length) await refreshModels();
env.OPENMAUSBOT_CHATGPT_TOKEN = await planAuth.accessToken();
if (planSigningOut || disposed) throw new Error("This ChatGPT account is being disconnected.");
- mkdirSync(join(planDirectory, "codex"), { recursive: true, mode: 0o700 });
+ linkSharedCodexHome(codexHome({ ...process.env, ...input.environment }), join(planDirectory, "codex"));
providerArgs = chatgptPlanCodexArgs();
} else if (config.endpoint) {
if (!input.environment.OPENMAUSBOT_CODEX_API_KEY || !input.environment.CODEX_HOME) throw new Error("Direct API key or isolated Codex home is missing. Edit the endpoint in Settings.");
diff --git a/server/imported-skills.test.ts b/server/imported-skills.test.ts
index aaeec0e0b5..9fd9a556f2 100644
--- a/server/imported-skills.test.ts
+++ b/server/imported-skills.test.ts
@@ -131,9 +131,9 @@ describe("skills brought in from this computer", () => {
expect(claude(true)).toEqual(["review"]);
expect(claude(false)).toEqual(["pdf", "review"]);
expect(claude(false, { OMB_CLAUDE_INHERIT_USER_CONFIG: "1" })).toEqual(["review"]);
- // Codex loads $CODEX_HOME/skills from the person's own home; a ChatGPT-plan or company home does not.
+ // Codex loads $CODEX_HOME/skills from the person's own home, linked into a ChatGPT-plan home too; a company home does not.
expect(codex()).toEqual(["pdf"]);
- expect(codex({ authMode: "chatgpt-plan" })).toEqual(["pdf", "review"]);
+ expect(codex({ authMode: "chatgpt-plan" })).toEqual(["pdf"]);
expect(codex(undefined, { CODEX_HOME: join(DATA_DIR, "providers", "company", "codex") })).toEqual(["pdf", "review"]);
expect(names(importedSkillsFor(bot, new Set(), nativeSkillFolders({ driverKind: "geminiAgent" }, { claudeUserSkills: true, home: HOME, env: {} })))).toEqual(["pdf", "review"]);
// Gone from ~/.claude/skills: Claude no longer has it, so the copy stays in.
diff --git a/server/imported-skills.ts b/server/imported-skills.ts
index 531716e8c9..c394ab4641 100644
--- a/server/imported-skills.ts
+++ b/server/imported-skills.ts
@@ -395,7 +395,7 @@ export interface SkillTurnEngine {
}
/** The skill folders a turn's engine loads in place: ~/.claude/skills for Claude Code with "Also use my Claude Code
- * skills" (or OMB_CLAUDE_INHERIT_USER_CONFIG), and $CODEX_HOME/skills for Codex on the person's own CODEX_HOME. */
+ * skills" (or OMB_CLAUDE_INHERIT_USER_CONFIG), and the person's own $CODEX_HOME/skills for Codex, ChatGPT plan included. */
export function nativeSkillFolders(
engine: SkillTurnEngine | undefined,
options: { claudeUserSkills: boolean; home?: string; env?: Record<string, string | undefined> },
@@ -415,8 +415,7 @@ export function nativeSkillFolders(
}
}
if (engine.driverKind === "codex") {
- // A ChatGPT-plan instance runs on a CODEX_HOME of its own.
- if ((engine.config as { authMode?: unknown } | undefined)?.authMode === "chatgpt-plan") return [];
+ // A ChatGPT-plan instance signs in on a CODEX_HOME of its own, with the person's skills folder linked into it.
return [join(absolute(env.CODEX_HOME) ?? join(home, ".codex"), "skills")];
}
return [];
diff --git a/server/testing/setup.ts b/server/testing/setup.ts
index f2172eaac5..de6141e27b 100644
--- a/server/testing/setup.ts
+++ b/server/testing/setup.ts
@@ -14,6 +14,8 @@ process.env.USERPROFILE = home;
delete process.env.OMB_DATA_DIR;
// Do not let a developer's Hermes global config path leak into per-test homes.
delete process.env.HERMES_HOME;
+// A ChatGPT-plan turn links the person's Codex home ($CODEX_HOME or ~/.codex) into its own: keep it in the throwaway home.
+delete process.env.CODEX_HOME;
// Named explicitly although homedir() already covers it: the device tests delete this directory wholesale.
process.env.OMB_COMPANION_DIR = join(home, ".openmausbot-companion");