Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Codex native skill switch selects SKILL.md paths, covers ~/.agents/skills, and refuses to guess from unreadable switches
Plateau Nguyen18cb757c0a06
diff --git a/docs/custom-mcp-servers.md b/docs/custom-mcp-servers.mdindex cfd753fbdb..1d2b03a5a0 100644--- a/docs/custom-mcp-servers.md+++ b/docs/custom-mcp-servers.md@@ -276,9 +276,23 @@ and out of the tools' own folders outside their skills. A copy whose fileschange afterwards is left out until it is brought in again. A turn whoseengine already loads the folder a skill came from leaves the copy out, sonothing is listed twice: Claude Code with **Also use my Claude Code skills**-on, and Codex on the person's own `CODEX_HOME`. The copies travel with-backups and Copy to My Cloud. The step never opens credential, session or-history files, and it is skipped when there is nothing new.+on, and Codex on the person's own `CODEX_HOME` (a ChatGPT plan's linked one+included). The copies travel with backups and Copy to My Cloud. The step never+opens credential, session or history files, and it is skipped when there is+nothing new.++Skills an engine loads by itself show in **Bot Settings → Skills** with a+switch for that bot: for Codex, `$CODEX_HOME/skills`, `~/.agents/skills` and+`/etc/codex/skills`. Switching one off passes Codex that skill's `SKILL.md`+path for the bot's turns, so a same-named skill in the turn's own+`.agents/skills` stays on, and `[[skills.config]]` entries in `config.toml`+keep applying. A skill brought in from this computer and switched off is kept+out the same way, from the folder it came from. If the bot's saved switches+(`<data>/skill-state/<bot id>/native-skills.json`) are there but can't be read,+the page shows every such skill off, switches can't be changed, and the bot's+Claude and Codex turns don't start, saying which file to fix or delete;+deleting it resets those switches to on (skills from this computer switched+off for the bot stay off).Open a bot’s **Tools → Access → MCP servers** to narrow the enabled globalservers offered to it. Existing bots keep all enabled global servers until youdiff --git a/server/drivers/codex-guest.ts b/server/drivers/codex-guest.tsindex fe12e703b2..0cc51fe28d 100644--- a/server/drivers/codex-guest.ts+++ b/server/drivers/codex-guest.ts@@ -1,4 +1,9 @@-import { disabledNativeSkillNames } from "../native-skill-choices.ts";+import { statSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++import { codexSkillRoots } from "../imported-skills.ts";+import { deniedNativeSkills } from "../native-skill-choices.ts";const plainRecord = (value: unknown): Record<string, unknown> | null =>value && typeof value === "object" && !Array.isArray(value)@@ -16,19 +21,32 @@ export function codexShellDisabled(config: unknown): boolean {return features?.shell_tool === false && features?.unified_exec === false && features?.view_image === false;}-/** `-c skills.config=[…]` so Codex skips native skills this bot switched off, without touching ~/.codex/skills.- * It replaces any skills.config in ~/.codex/config.toml for that turn; the Skills page hint says so. */-export function codexDisabledNativeSkillArgs(botId: string | undefined): string[] {- const names = disabledNativeSkillNames(botId ?? "");- if (!names.length) return [];- const tables = names.map((name) => `{name=${JSON.stringify(name)},enabled=false}`).join(",");+const isFile = (path: string) => {+ try {+ return statSync(path).isFile();+ } catch {+ return false;+ }+};++/** `-c skills.config=[…]` selecting each SKILL.md this bot switched off by absolute path: a `name` selector would also+ * match the same-named skills linked into the turn's `.agents/skills`. codex-cli (0.163.0–0.167.0) keeps+ * `[[skills.config]]` from config.toml in effect alongside it and reads the list once per turn. Throws+ * NativeSkillChoicesUnreadable. */+export function codexDisabledNativeSkillArgs(botId: string | undefined, env: Record<string, string | undefined>): string[] {+ if (!botId) return [];+ const denied = deniedNativeSkills(botId);+ const inRoots = codexSkillRoots(env.HOME ?? homedir(), env.CODEX_HOME).flatMap((root) => denied.names.map((name) => join(root, name, "SKILL.md")));+ const files = [...new Set([...inRoots, ...denied.origins])].filter(isFile);+ if (!files.length) return [];+ const tables = files.map((file) => `{path=${JSON.stringify(file)},enabled=false}`).join(",");return ["-c", `skills.config=[${tables}]`];}/** Guest confinement and per-bot native skill disables for one Codex turn. */-export function codexTurnConfigArgs(turn: { guestConfined?: boolean; botId?: string }): string[] {+export function codexTurnConfigArgs(turn: { guestConfined?: boolean; botId?: string }, env: Record<string, string | undefined>): string[] {return [...(turn.guestConfined ? GUEST_CONFINED_CODEX_ARGS : []),- ...codexDisabledNativeSkillArgs(turn.botId),+ ...codexDisabledNativeSkillArgs(turn.botId, env),];}diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.tsindex 517916e8a5..3214545bf3 100644--- a/server/drivers/codex.test.ts+++ b/server/drivers/codex.test.ts@@ -255,6 +255,51 @@ describe("CodexDriver turns (fake app-server)", () => {expect(existsSync(dump)).toBe(false);});+ it("switches a bot's native skills off by path, and refuses its turn while its switches can't be read", async () => {+ const dump = join(scratch, "skills-off.json"); process.env.FAKE_CODEX_DUMP = dump;+ const skill = join(scratch, ".agents", "skills", "pdf", "SKILL.md");+ mkdirSync(dirname(skill), { recursive: true }); writeFileSync(skill, "---\nname: pdf\ndescription: PDFs.\n---\nSteps.\n");+ const choices = join(DATA_DIR, "skill-state", "codex-skills-off", "native-skills.json");+ mkdirSync(dirname(choices), { recursive: true }); writeFileSync(choices, JSON.stringify({ off: ["pdf"] }));+ await create({ environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex") } });+ await instance.adapter.sendTurn({ threadId: "skills-off", botId: "codex-skills-off", text: "hi" });+ await recorder.until((e) => e.type === "turn.completed");+ const skillsConfig = (file: string) => (JSON.parse(readFileSync(file, "utf8")) as { argv: string[] }).argv.find((arg) => arg.startsWith("skills.config=")) ?? "";+ expect(skillsConfig(dump)).toContain(`{path=${JSON.stringify(skill)},enabled=false}`);+ expect(skillsConfig(dump)).not.toContain("name=");++ writeFileSync(choices, "{\"off\": [");+ const refused = join(scratch, "skills-unreadable.json"); process.env.FAKE_CODEX_DUMP = refused;+ await expect(instance.adapter.sendTurn({ threadId: "skills-unreadable", botId: "codex-skills-off", text: "hi" })).rejects.toThrow(/can't be read/);+ expect(existsSync(refused)).toBe(false);+ });++ it("rebuilds a bot's native skill switches for each relaunch, and ends the turn if they turn unreadable", async () => {+ const skill = join(scratch, ".agents", "skills", "pdf", "SKILL.md");+ const choices = join(DATA_DIR, "skill-state", "codex-skills-retry", "native-skills.json");+ mkdirSync(dirname(choices), { recursive: true }); writeFileSync(choices, JSON.stringify({ off: ["pdf"] }));+ Object.assign(process.env, { FAKE_CODEX_TRANSIENTS: "1", FAKE_CODEX_RETRY_SCALE: "0.001", FAKE_CODEX_STATE: join(scratch, "skills-retry-launches"), FAKE_CODEX_DUMP: join(scratch, "skills-retry.json") });+ await create({ environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex") } });+ const unsubscribe = instance.adapter.onEvent((event) => {+ if (event.type !== "turn.retrying") return;+ mkdirSync(dirname(skill), { recursive: true }); writeFileSync(skill, "---\nname: pdf\ndescription: PDFs.\n---\nSteps.\n");+ });+ await instance.adapter.sendTurn({ threadId: "skills-retry", botId: "codex-skills-retry", text: "hi" });+ await expect(recorder.until((e) => e.type === "turn.completed", 15_000)).resolves.toMatchObject({ ok: true });+ unsubscribe();+ expect(readFileSync(join(scratch, "skills-retry-launches"), "utf8")).toBe("2");+ expect((JSON.parse(readFileSync(join(scratch, "skills-retry.json"), "utf8")) as { argv: string[] }).argv.join(" ")).toContain(JSON.stringify(skill));++ recorder.events.length = 0;+ process.env.FAKE_CODEX_STATE = join(scratch, "skills-retry-damaged");+ const damage = instance.adapter.onEvent((event) => { if (event.type === "turn.retrying") writeFileSync(choices, "{"); });+ await instance.adapter.sendTurn({ threadId: "skills-retry-damaged", botId: "codex-skills-retry", text: "hi" });+ await expect(recorder.until((e) => e.type === "turn.completed", 15_000)).resolves.toMatchObject({ ok: false });+ damage();+ expect(recorder.events.some((e) => e.type === "runtime.error" && /can't be read/.test((e as { message: string }).message))).toBe(true);+ expect(readFileSync(join(scratch, "skills-retry-damaged"), "utf8")).toBe("1");+ }, 30_000);+it("gates raw custom identities before mount renaming and disables ambient MCP servers", async () => {const dump = join(scratch, "scope-mcp.json"); process.env.FAKE_CODEX_DUMP = dump;mkdirSync(join(scratch, ".codex")); writeFileSync(join(scratch, ".codex/config.toml"), '[mcp_servers.notes]\nurl="https://example.test/ambient"\n');diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 6d2a410274..0aafa92b01 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -517,7 +517,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {const hideRefusedModel = (raw: string) => hidePlanRefusedModel(turn.model, raw, route);const signedOut = chatgptTurn && await loginCheck.check(childEnv()) === "missing";const authBridge = planAuth && await planRenewal.supported() ? await startPlanTokenBridge(() => planAuth.accessToken(), () => { assertPlanCurrent(); if (stopRequested) throw new Error("This task has ended."); }) : null;- try { assertPlanCurrent(); if (active.has(threadId)) throw new Error("a turn is already running on this thread"); } catch (error) { authBridge?.close(); throw error; }+ let turnConfigArgs: string[]; try { assertPlanCurrent(); if (active.has(threadId)) throw new Error("a turn is already running on this thread"); turnConfigArgs = codexTurnConfigArgs(turn, childEnv()); } catch (error) { authBridge?.close(); throw error; }const turnId = newId();if (signedOut) {emit({ ...base(threadId, turnId), type: "turn.started" });@@ -550,7 +550,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {// Native shell snapshots can restore variables the shell policy removed....(turn.toolScope === undefined && !authBridge ? [] : ["-c", "features.shell_snapshot=false"]),// A guest-driven turn: no shell, no file reads (-c wins over config files).- ...codexTurnConfigArgs(turn)];+ ...turnConfigArgs];const codexConfig = codexConfigMcp(env), declaredInCodexConfig = codexConfig.names;if (turn.toolScope !== undefined) appServerArgs.push(...codexMcpDisableArgs(declaredInCodexConfig));const baseEnv = new Map(Object.entries(env).filter(([, value]) => value !== undefined));@@ -806,7 +806,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {return settle(false, failedStop);}await interruptibleDelay(Math.max(1, Math.round(delayMs * retryScale)), stopSignal.signal).promise;- if (!stopRequested) void launchAttempt(attempt).catch(() => authBridge?.close());+ if (!stopRequested) { try { turnConfigArgs = codexTurnConfigArgs(turn, childEnv()); } catch (error) { emit({ ...base(threadId, turnId), type: "runtime.error", message: error instanceof Error ? error.message : String(error) }); return settle(false, "rpc_error"); } void launchAttempt(attempt).catch(() => authBridge?.close()); }else await settle(false, "interrupted");};diff --git a/server/host/skills-library.ts b/server/host/skills-library.tsindex 5ca46e3929..75b598c643 100644--- a/server/host/skills-library.ts+++ b/server/host/skills-library.ts@@ -11,7 +11,7 @@ import {importedSkillListings, importedSkillsFor, importedSkillsPrompt, listedImportedSkills, nativeSkillFolders, readImportedSkillFile,readImportedSkills, type ImportedSkillView, type SkillTurnEngine,} from "../imported-skills.ts";-import { disabledNativeSkillNames, isNativeSkillEnabled } from "../native-skill-choices.ts";+import { isNativeSkillEnabled } from "../native-skill-choices.ts";import { nativeSkillListing, nativeSkills, readNativeSkillFile } from "../native-skills.ts";import { redactSecretsInText } from "../redact.ts";import { readSectionContext } from "../section-context.ts";@@ -282,12 +282,9 @@ export function createSkillsLibraryHost(deps: SkillsLibraryHostDeps) {if (files.size < mentioned.length) add(importsFor(bot, assigned, instance));if (files.size < mentioned.length) {// A skill switched off on the Skills page stays off, even when the engine holds one of the same name.- const switched = new Set([- ...[...resolveBotSkills(bot.id, assigned), ...importedSkillListings(bot.id, new Set())]- .filter((skill) => !skill.enabled).map((skill) => skill.name),- ...disabledNativeSkillNames(bot.id),- ]);- add(nativesFor(bot, threadId, instance).filter((skill) => !switched.has(skill.name)));+ const switched = new Set([...resolveBotSkills(bot.id, assigned), ...importedSkillListings(bot.id, new Set())]+ .filter((skill) => !skill.enabled).map((skill) => skill.name));+ add(nativesFor(bot, threadId, instance).filter((skill) => !switched.has(skill.name) && isNativeSkillEnabled(bot.id, skill.name)));}return skillCommandTurnText(text, files, typed, ownStart);},diff --git a/server/imported-skills.ts b/server/imported-skills.tsindex c394ab4641..24b2194fa3 100644--- a/server/imported-skills.ts+++ b/server/imported-skills.ts@@ -10,7 +10,7 @@// skills", Codex with the person's own CODEX_HOME) leaves the copy out, so no engine sees a skill twice.import { createHash, randomUUID } from "node:crypto";import {- closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, renameSync, rmSync,+ closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync,statSync, symlinkSync, unlinkSync, writeFileSync,} from "node:fs";import { homedir } from "node:os";@@ -299,11 +299,16 @@ function enabledFor(name: string, entry: ImportedSkillEntry, choices: Choices):}const comparable = (path: string) => {- const resolved = resolve(path).replace(/^\\\\\?\\/, "");+ let real = resolve(path);+ try {+ real = realpathSync(real);+ } catch {}+ const resolved = real.replace(/^\\\\\?\\/, "");return process.platform === "win32" ? resolved.toLowerCase() : resolved;};-/** Whether the turn's engine loads this skill from where it came from: its folder there still exists. */+/** Whether the turn's engine loads this skill from where it came from: its folder there still exists. A ChatGPT-plan+ * CODEX_HOME links its `skills` to the person's, so folders compare by where they really are. */function loadedInPlace(entry: ImportedSkillEntry, native: readonly string[]): boolean {if (!native.some((folder) => comparable(folder) === comparable(entry.root))) return false;return entryExistsWithoutFollowing(entry.origin);@@ -387,6 +392,20 @@ export function setImportedSkillEnabled(botId: string, name: string, enabled: boreturn importedSkillListings(botId, new Set()).find((skill) => skill.name === name)!;}+export function importedSkillsSwitchedOff(botId: string): string[] {+ return readChoices(botId).off.filter(isSkillName);+}++/** Takes `name` off this bot's switched-off list without approving anything: a flagged skill's copy still needs a+ * read before it is listed. */+export function switchImportedSkillBackOn(botId: string, name: string): void {+ const choices = readChoices(botId);+ if (!choices.off.includes(name)) return;+ const next: Choices = { ...choices, off: choices.off.filter((other) => other !== name) };+ mkdirSync(dirname(choicesPath(botId)), { recursive: true, mode: 0o700 });+ writeFileAtomic(choicesPath(botId), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });+}+/** The engine of one turn, as far as which skill folders it loads by itself. */export interface SkillTurnEngine {driverKind: string;@@ -395,15 +414,15 @@ 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 the person's own $CODEX_HOME/skills for Codex, ChatGPT plan included. */+ * skills" (or OMB_CLAUDE_INHERIT_USER_CONFIG); for Codex, its user and admin scopes. */export function nativeSkillFolders(engine: SkillTurnEngine | undefined,options: { claudeUserSkills: boolean; home?: string; env?: Record<string, string | undefined> },): string[] {if (!engine) return [];- const home = options.home ?? homedir();const env = { ...(options.env ?? process.env), ...engine.environment };const absolute = (value: string | undefined) => (value && isAbsolute(value) ? value : null);+ const home = absolute(engine.environment?.HOME) ?? options.home ?? homedir();if (engine.driverKind === "claudeAgent") {if (env.OMB_CLAUDE_INHERIT_USER_CONFIG === "1") return [join(absolute(env.CLAUDE_CONFIG_DIR) ?? join(home, ".claude"), "skills")];if (!options.claudeUserSkills) return [];@@ -414,13 +433,18 @@ export function nativeSkillFolders(return [];}}- if (engine.driverKind === "codex") {- // 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")];- }+ if (engine.driverKind === "codex") return codexSkillRoots(home, env.CODEX_HOME);return [];}+/** The folders codex-cli (0.163.0–0.167.0) loads user and admin skills from, in its own order: $CODEX_HOME/skills (a+ * ChatGPT-plan instance links the person's into its own home), ~/.agents/skills and /etc/codex/skills. It also reads+ * `.agents/skills` from the turn's folder up to the repository root, where OpenMausBot links a bot's granted skills. */+export function codexSkillRoots(home: string, codexHome: string | undefined): string[] {+ const own = codexHome && isAbsolute(codexHome) ? codexHome : join(home, ".codex");+ return [join(own, "skills"), join(home, ".agents", "skills"), ...(process.platform === "win32" ? [] : ["/etc/codex/skills"])];+}+/** After the bot's own skills, with a budget of its own, so bringing many in never pushes the bot's own out. `unlisted`* counts the ones on for the bot that are left out of its list: it searches for them. */export function importedSkillsPrompt(skills: readonly ImportedSkillView[], unlisted = 0): string {diff --git a/server/native-skill-choices.test.ts b/server/native-skill-choices.test.tsindex 4a65973699..8207dd3be0 100644--- a/server/native-skill-choices.test.ts+++ b/server/native-skill-choices.test.ts@@ -1,22 +1,47 @@-import { rmSync } from "node:fs";+import { createHash } from "node:crypto";+import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { DATA_DIR } from "./config.ts";+import { claudeDisabledNativeSkillRules } from "./drivers/claude-unusable-tools.ts";import { codexDisabledNativeSkillArgs, codexTurnConfigArgs, GUEST_CONFINED_CODEX_ARGS } from "./drivers/codex-guest.ts";-import { disabledNativeSkillNames, isNativeSkillEnabled, setNativeSkillEnabled } from "./native-skill-choices.ts";-import { nativeSkillListing } from "./native-skills.ts";+import { setImportedSkillEnabled, storeImportedSkills } from "./imported-skills.ts";+import { deniedNativeSkills, isNativeSkillEnabled, NativeSkillChoicesUnreadable, setNativeSkillEnabled } from "./native-skill-choices.ts";++// HOME and the data folder are this test file's own temporary ones (server/testing/setup.ts).+const HOME = join(DATA_DIR, "..");+const CODEX_HOME = join(HOME, "codex-home");+const env = { HOME, CODEX_HOME };+const choicesFile = (botId: string) => join(DATA_DIR, "skill-state", botId, "native-skills.json");afterEach(() => {if (!DATA_DIR.startsWith(join(tmpdir(), "omb-test-home-"))) throw new Error(`refusing to clean ${DATA_DIR}: not this test's home`);- rmSync(join(DATA_DIR, "skill-state"), { recursive: true, force: true });+ for (const dir of [join(DATA_DIR, "skill-state"), join(DATA_DIR, "imported-skills"), join(HOME, ".agents"), CODEX_HOME, join(HOME, "repo"), join(HOME, "brought")]) {+ rmSync(dir, { recursive: true, force: true });+ }});+const skillMd = (name: string) => `---\nname: ${name}\ndescription: Works with ${name}.\n---\n\nSteps.\n`;+function plant(root: string, name: string): string {+ mkdirSync(join(root, name), { recursive: true });+ writeFileSync(join(root, name, "SKILL.md"), skillMd(name));+ return join(root, name, "SKILL.md");+}+/** The path tables of a skills.config override, limited to this test's home: /etc/codex/skills belongs to the machine. */+const paths = (args: string[]) => (args[1] ?? "").replace(/^skills\.config=\[|\]$/g, "").split("},{")+ .map((table) => /path=("(?:[^"\\]|\\.)*")/.exec(table)?.[1]).filter((path): path is string => path !== undefined)+ .map((path) => JSON.parse(path) as string).filter((path) => path.startsWith(HOME)).sort();+function damage(botId: string) {+ mkdirSync(join(DATA_DIR, "skill-state", botId), { recursive: true });+ writeFileSync(choicesFile(botId), "{\"off\": [");+}+describe("per-bot native skill switches", () => {it("defaults every native skill to on", () => {expect(isNativeSkillEnabled("bot-a", "pdf")).toBe(true);- expect(disabledNativeSkillNames("bot-a")).toEqual([]);+ expect(deniedNativeSkills("bot-a")).toEqual({ names: [], origins: [] });});it("persists off across reads and leaves other bots alone", () => {@@ -28,31 +53,54 @@ describe("per-bot native skill switches", () => {expect(isNativeSkillEnabled("bot-a", "pdf")).toBe(true);});- it("lists a native skill as disabled when this bot switched it off", () => {- setNativeSkillEnabled("bot-a", "pdf", false);- const listing = nativeSkillListing({- name: "pdf",- description: "Works with PDFs.",- folder: "/tmp/pdf",- file: "/tmp/pdf/SKILL.md",- source: "/tmp",- sha256: "a".repeat(64),- }, isNativeSkillEnabled("bot-a", "pdf"));- expect(listing).toMatchObject({ origin: "native", enabled: false, editable: false });+ it("refuses to guess when the bot's saved switches can't be read, and never writes over them", () => {+ damage("bot-a");+ expect(isNativeSkillEnabled("bot-a", "pdf")).toBe(false);+ expect(() => deniedNativeSkills("bot-a")).toThrow(NativeSkillChoicesUnreadable);+ expect(setNativeSkillEnabled("bot-a", "pdf", true)).toEqual({ error: expect.stringContaining("Fix or delete that file") });+ expect(readFileSync(choicesFile("bot-a"), "utf8")).toBe("{\"off\": [");+ expect(() => claudeDisabledNativeSkillRules("bot-a")).toThrow(NativeSkillChoicesUnreadable);+ expect(() => codexTurnConfigArgs({ botId: "bot-a" }, env)).toThrow(NativeSkillChoicesUnreadable);+ rmSync(choicesFile("bot-a"));+ expect(isNativeSkillEnabled("bot-a", "pdf")).toBe(true);});+});- it("builds Codex skills.config overrides for disabled names only", () => {+describe("Codex skills.config overrides for a bot's switched-off skills", () => {+ it("selects each switched-off user skill by its SKILL.md path, leaving same-named repository skills alone", () => {+ const agents = plant(join(HOME, ".agents", "skills"), "pdf");+ const legacy = plant(join(CODEX_HOME, "skills"), "pdf");+ plant(join(HOME, "repo", ".agents", "skills"), "pdf");+ plant(join(HOME, ".agents", "skills"), "rex");setNativeSkillEnabled("bot-a", "pdf", false);- setNativeSkillEnabled("bot-a", "rex", false);- expect(codexDisabledNativeSkillArgs("bot-a")).toEqual([- "-c",- 'skills.config=[{name="pdf",enabled=false},{name="rex",enabled=false}]',- ]);- expect(codexDisabledNativeSkillArgs("bot-b")).toEqual([]);- expect(codexTurnConfigArgs({ botId: "bot-a", guestConfined: true })).toEqual([- ...GUEST_CONFINED_CODEX_ARGS,- ...codexDisabledNativeSkillArgs("bot-a"),- ]);- expect(codexTurnConfigArgs({ botId: "bot-a" })).toEqual(codexDisabledNativeSkillArgs("bot-a"));++ const args = codexDisabledNativeSkillArgs("bot-a", env);+ expect(args[0]).toBe("-c");+ expect(paths(args)).toEqual([agents, legacy].sort());+ expect(args[1]).not.toContain("name=");+ expect(codexDisabledNativeSkillArgs("bot-b", env)).toEqual([]);+ expect(codexTurnConfigArgs({ botId: "bot-a", guestConfined: true }, env)).toEqual([...GUEST_CONFINED_CODEX_ARGS, ...args]);+ expect(codexTurnConfigArgs({ botId: "bot-a" }, env)).toEqual(args);+ });++ it("keeps a skill from this computer that the bot switched off out of Codex, from the folder it was brought in from", () => {+ const origin = plant(join(HOME, "brought"), "renamed-folder");+ const stored = storeImportedSkills([{+ name: "rex",+ entry: {+ description: "Works with rex.", source: "codex", root: join(HOME, "brought"), origin: join(HOME, "brought", "renamed-folder"),+ label: "rex", sha256: createHash("sha256").update(skillMd("rex")).digest("hex"), warnings: [],+ },+ skillMd: skillMd("rex"),+ files: [],+ }]);+ expect(stored.map((entry) => entry.name)).toEqual(["rex"]);+ expect(setImportedSkillEnabled("bot-a", "rex", false)).not.toHaveProperty("error");+ expect(isNativeSkillEnabled("bot-a", "rex")).toBe(false);+ expect(paths(codexDisabledNativeSkillArgs("bot-a", env))).toEqual([origin]);++ setNativeSkillEnabled("bot-a", "rex", true);+ expect(isNativeSkillEnabled("bot-a", "rex")).toBe(true);+ expect(paths(codexDisabledNativeSkillArgs("bot-a", env))).toEqual([]);});});diff --git a/server/native-skill-choices.ts b/server/native-skill-choices.tsindex 3e960e10dd..39984f0e71 100644--- a/server/native-skill-choices.ts+++ b/server/native-skill-choices.ts@@ -1,4 +1,4 @@-// Per-bot switches for skills the engine loads by itself (Codex ~/.codex/skills, Claude project+// Per-bot switches for skills the engine loads by itself (Codex ~/.codex/skills and ~/.agents/skills, Claude project// skills, …). Off stays off across restarts; personal skill folders are never deleted.import { mkdirSync, readFileSync } from "node:fs";import { dirname, join } from "node:path";@@ -6,40 +6,74 @@ import { z } from "zod";import { writeFileAtomic } from "./atomic.ts";import { DATA_DIR } from "./config.ts";+import { importedSkillsSwitchedOff, readImportedSkills, switchImportedSkillBackOn } from "./imported-skills.ts";import { isSkillName } from "../shared/skill-md.ts";const choicesPath = (botId: string) => join(DATA_DIR, "skill-state", botId, "native-skills.json");const choicesSchema = z.object({ off: z.array(z.string()) });-function readChoices(botId: string): { off: string[] } {+/** The bot's switches exist but cannot be read. Nothing can tell which skills were off, so a turn on an engine that+ * loads skills by itself does not start, and no switch is written over the file, until the person fixes or deletes it. */+export class NativeSkillChoicesUnreadable extends Error {+ constructor(path: string) {+ super(`This bot's switches for the skills its AI loads by itself can't be read (${path}). Fix or delete that file, then try again.`);+ }+}++function readChoices(botId: string): string[] {+ const path = choicesPath(botId);+ let text: string;try {- const parsed = choicesSchema.safeParse(JSON.parse(readFileSync(choicesPath(botId), "utf8")));- if (parsed.success) {- return { off: parsed.data.off.filter(isSkillName).sort() };- }- } catch { /* missing or unreadable → every native skill stays on */ }- return { off: [] };+ text = readFileSync(path, "utf8");+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw new NativeSkillChoicesUnreadable(path);+ }+ try {+ const parsed = choicesSchema.safeParse(JSON.parse(text));+ if (parsed.success) return parsed.data.off.filter(isSkillName).sort();+ } catch {}+ throw new NativeSkillChoicesUnreadable(path);}-function writeChoices(botId: string, off: string[]): void {- mkdirSync(dirname(choicesPath(botId)), { recursive: true, mode: 0o700 });- writeFileAtomic(choicesPath(botId), `${JSON.stringify({ off }, null, 2)}\n`, { mode: 0o600 });+/** Native skills this bot has off: its own switches, plus each skill from this computer it switched off, with the+ * SKILL.md it was brought in from, which an engine loading that folder would still read. Throws+ * NativeSkillChoicesUnreadable. */+export function deniedNativeSkills(botId: string): { names: string[]; origins: string[] } {+ const own = readChoices(botId);+ const imported = importedSkillsSwitchedOff(botId);+ const index = readImportedSkills();+ const origins = imported.flatMap((name) => (index[name] ? [join(index[name].origin, "SKILL.md")] : []));+ return { names: [...new Set([...own, ...imported])].sort(), origins };}-/** Names this bot has switched off; sorted, skill-name filtered. */+/** Names of the native skills this bot has off. Throws NativeSkillChoicesUnreadable. */export function disabledNativeSkillNames(botId: string): string[] {- return readChoices(botId).off;+ return deniedNativeSkills(botId).names;}export function isNativeSkillEnabled(botId: string, name: string): boolean {- return !readChoices(botId).off.includes(name);+ try {+ return !deniedNativeSkills(botId).names.includes(name);+ } catch (error) {+ if (error instanceof NativeSkillChoicesUnreadable) return false;+ throw error;+ }}/** Persist one bot's native-skill switch. Does not create or delete skill files. */export function setNativeSkillEnabled(botId: string, name: string, enabled: boolean): { off: string[] } | { error: string } {if (!isSkillName(name)) return { error: `invalid skill name "${name}"` };- const off = readChoices(botId).off.filter((other) => other !== name);+ let off: string[];+ try {+ off = readChoices(botId).filter((other) => other !== name);+ } catch (error) {+ if (error instanceof NativeSkillChoicesUnreadable) return { error: error.message };+ throw error;+ }const next = enabled ? off : [...off, name].sort();- writeChoices(botId, next);+ mkdirSync(dirname(choicesPath(botId)), { recursive: true, mode: 0o700 });+ writeFileAtomic(choicesPath(botId), `${JSON.stringify({ off: next }, null, 2)}\n`, { mode: 0o600 });+ if (enabled) switchImportedSkillBackOn(botId, name);return { off: next };}diff --git a/server/native-skills.test.ts b/server/native-skills.test.tsindex 0fb4ec9ea9..f58ec57da8 100644--- a/server/native-skills.test.ts+++ b/server/native-skills.test.ts@@ -6,6 +6,7 @@ import { afterEach, describe, expect, it } from "vitest";import { DATA_DIR, type AppConfig } from "./config.ts";import { createSkillsLibraryHost } from "./host/skills-library.ts";+import { setNativeSkillEnabled } from "./native-skill-choices.ts";import { skillExport } from "./skill-export.ts";import { installSkill, setSkillEnabled } from "./skills.ts";import type { BotRecord, Store } from "./store.ts";@@ -16,11 +17,12 @@ import { TASK_WORKSPACES_DIR } from "./workspace.ts";const HOME = join(DATA_DIR, "..");const USER_SKILLS = join(HOME, ".claude", "skills");const CODEX_SKILLS = join(HOME, ".codex", "skills");+const AGENTS_SKILLS = join(HOME, ".agents", "skills");const SHARED = join(TASK_WORKSPACES_DIR, ".claude", "skills");const PROJECTS = join(HOME, "projects");afterEach(() => {if (!DATA_DIR.startsWith(join(tmpdir(), "omb-test-home-"))) throw new Error(`refusing to clean ${DATA_DIR}: not this test's home`);- for (const dir of [TASK_WORKSPACES_DIR, USER_SKILLS, CODEX_SKILLS, PROJECTS, join(DATA_DIR, "skill-state")]) {+ for (const dir of [TASK_WORKSPACES_DIR, USER_SKILLS, CODEX_SKILLS, AGENTS_SKILLS, PROJECTS, join(DATA_DIR, "skill-state")]) {rmSync(dir, { recursive: true, force: true });}});@@ -161,8 +163,7 @@ describe("skills the engine loads by itself", () => {});describe("switching a native skill off for one bot", () => {- it("shows enabled false on the Skills page and keeps /name from expanding it", async () => {- const { setNativeSkillEnabled } = await import("./native-skill-choices.ts");+ it("shows enabled false on the Skills page and keeps /name from expanding it", () => {const { host, bot } = hostFor("codex");plant(join(HOME, ".codex", "skills"), "pdf");expect(host.listBotSkills(bot).find((skill) => skill.name === "pdf")).toMatchObject({ origin: "native", enabled: true });@@ -170,5 +171,26 @@ describe("switching a native skill off for one bot", () => {expect(host.listBotSkills(bot).find((skill) => skill.name === "pdf")).toMatchObject({ origin: "native", enabled: false });expect(host.expandSkillCommand(bot, "main", "/pdf summarise", undefined, [], true)).toBe("/pdf summarise");});++ it("lists Codex skills from ~/.agents/skills with a switch, as Codex loads them", () => {+ const { host, bot } = hostFor("codex");+ plant(AGENTS_SKILLS, "release-notes");+ expect(host.listBotSkills(bot).find((skill) => skill.name === "release-notes")).toMatchObject({ origin: "native", enabled: true });+ setNativeSkillEnabled(bot.id, "release-notes", false);+ expect(host.listBotSkills(bot).find((skill) => skill.name === "release-notes")).toMatchObject({ origin: "native", enabled: false });+ expect(listed(hostFor("claudeAgent").host.listBotSkills(bot))).not.toContain("release-notes:native");+ });++ it("shows every native skill off and keeps /name from expanding one while the bot's saved switches can't be read", () => {+ const { host, bot } = hostFor("codex");+ plant(CODEX_SKILLS, "pdf");+ plant(AGENTS_SKILLS, "deploy");+ mkdirSync(join(DATA_DIR, "skill-state", bot.id), { recursive: true });+ writeFileSync(join(DATA_DIR, "skill-state", bot.id, "native-skills.json"), "{\"off\": [\"pd");+ const natives = host.listBotSkills(bot).filter((skill) => "origin" in skill && skill.origin === "native")+ .map((skill) => [skill.name, skill.enabled] as const).sort();+ expect(natives).toEqual([["deploy", false], ["pdf", false]]);+ expect(host.expandSkillCommand(bot, "main", "/pdf now", undefined, [], true)).toBe("/pdf now");+ });});diff --git a/server/routes/bot-skills.ts b/server/routes/bot-skills.tsindex 99b09cc8b0..4866aa2900 100644--- a/server/routes/bot-skills.ts+++ b/server/routes/bot-skills.ts@@ -96,7 +96,7 @@ export function createBotSkillsRoutes(deps: BotSkillsRouteDeps): RouteHandler {if ("error" in result) return json(res, 409, { error: result.error });return json(res, 200, { skill: result });}- if (bot && listBotSkills(bot).some((skill) => skill.name === m![2] && (skill as { origin?: string }).origin === "native")) {+ if (bot && listBotSkills(bot).some((skill) => skill.name === m![2] && "origin" in skill && skill.origin === "native")) {const result = setNativeSkillEnabled(bot.id, m[2]!, parsed.data.enabled);if ("error" in result) return json(res, 409, { error: result.error });const skill = listBotSkills(bot).find((entry) => entry.name === m![2]);