A desktop coding agent with free access to frontier models.
TypeScript
fix: keep skills across updates
ogsamrat39bc26c9473f
diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.tsindex cd126d89..1d2934bb 100644--- a/apps/server/src/omnirush-runtime-config.ts+++ b/apps/server/src/omnirush-runtime-config.ts@@ -17,6 +17,7 @@ import { managedPolicyPluginPath } from "./managed-policy-plugin.js";*/import { mkdir, readFile } from "node:fs/promises";import { join } from "node:path";+import { mergeSkillPaths, userGlobalSkillPaths } from "./user-skill-paths.js";import {omnirushExtensionsPreviewPluginPath,omnirushCapabilitiesKnowledgePluginPath,@@ -149,6 +150,8 @@ export async function buildOmniRushRuntimeConfigObject(config ? omnirushBestPracticesSkillsDir(config) : undefined,// The model's own web search: the server's switch as last seen (web-search.ts).config ? webSearchSetting({ env: process.env, stateDir: runtimeStorageDir(config) }) : null,+ // The user's own skill folders from the engine's global config (user-skill-paths.ts).+ config ? await userGlobalSkillPaths(process.env) : [],);// The Linux sandbox (box/): the engine's shell is the box shell and the box plugin is// loaded once any workspace may use a box; every other project's commands run natively@@ -227,6 +230,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(skillsDir?: string,bestPracticesDir?: string,webSearch: WebSearchSwitch | null = null,+ userSkillPaths: string[] = [],): Record<string, unknown> {const disabledProviders = runtimeDisabledProviderList(runtimeConfig);// OMNIRUSH_APPROVALS in the server environment wins over the persisted setting.@@ -241,10 +245,12 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(// Code diagnostics: the main languages' servers on, the rest off; the engine default (none) while off.const lsp = agentAssistFlags(runtimeConfig, env).diagnostics ? agentAssistLspConfig() : undefined;const enabled = bestPracticesEnabled(runtimeConfig);- const skillPaths = [+ // The app's skill folders, then the user's from the engine's global config:+ // the engine replaces that file's list with this file's (user-skill-paths.ts).+ const skillPaths = mergeSkillPaths([...(skillsDir ? [skillsDir] : []),...(enabled && bestPracticesDir ? [bestPracticesDir] : []),- ];+ ], userSkillPaths);const provider = {...runtimeProviderMap(runtimeConfig),...(internalGateway@@ -274,7 +280,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(// ours, which all stay in force. The main agent's own block below leaves// it out, or it would come after (and override) the user's grants.permission: { ...(catchAll ? { "*": catchAll } : {}), ...engineConfig.permission, ...topLevelPermissions },- // omnirush.ai's own on-demand skills (the swarm procedure).+ // omnirush.ai's own on-demand skills (the swarm procedure), then the user's skill folders....(skillPaths.length ? { skills: { paths: skillPaths } } : {}),default_agent: runtimeConfig.default_agent ?? "omnirush",// Sub-agent swarms: sub-agents may delegate again, up to this many layersdiff --git a/apps/server/src/skills.ts b/apps/server/src/skills.tsindex b4ac1fc4..f7ac2be3 100644--- a/apps/server/src/skills.ts+++ b/apps/server/src/skills.ts@@ -9,9 +9,14 @@ import { exists } from "./utils.js";import { validateDescription, validateSkillName } from "./validators.js";import { ApiError } from "./errors.js";import { projectSkillsDir } from "./workspace-files.js";+import { engineGlobalConfigDir, userGlobalSkillPaths } from "./user-skill-paths.js";+import { LEGACY_SWARM_SKILL_NAME, OMNIRUSH_SWARM_SKILL_NAME } from "./omnirush-swarm.js";const INVALID_SKILL_DESCRIPTION = "ERROR: Invalid skill frontmatter";+/** Skills the app writes into the engine's global folder (the swarm procedure, now and before 3.6). */+const APP_WRITTEN_SKILL_NAMES = new Set<string>([OMNIRUSH_SWARM_SKILL_NAME, LEGACY_SWARM_SKILL_NAME]);+/*** Directory names the engine scans for `<name>/SKILL.md` under a config root.* OpenCode accepts both spellings (`.opencode/skill/` is its documented@@ -222,11 +227,26 @@ export async function listSkills(workspaceRoot: string, includeGlobal: boolean):dirs.push({ dir: join(root, ".claude", "skills"), scope: "project" });}+ /** Folders the app writes its own skills into as well: their app skills are not listed. */+ const sharedDirs = new Set<string>();if (includeGlobal) {const globalConfigDir = globalSkillConfigDir();for (const dirName of OPENCODE_SKILL_DIR_NAMES) {dirs.push({ dir: join(globalConfigDir, dirName), scope: "global" });}+ // The engine's own global folder (~/.config/omnirush/skills, also the+ // OmniRush CLI's) and the user's `skills.paths` from its config: the+ // engine loads these too, so the list shows them.+ const engineConfigDir = engineGlobalConfigDir(process.env);+ for (const dirName of OPENCODE_SKILL_DIR_NAMES) {+ const dir = join(engineConfigDir, dirName);+ sharedDirs.add(resolve(dir));+ dirs.push({ dir, scope: "global" });+ }+ for (const entry of await userGlobalSkillPaths(process.env)) {+ const expanded = entry.startsWith("~/") ? join(resolveHomeDir(), entry.slice(2)) : entry;+ dirs.push({ dir: resolve(workspaceRoot, expanded), scope: "global" });+ }const home = resolveHomeDir();const globalClaude = join(home, ".claude", "skills");const globalAgents = join(home, ".agents", "skills");@@ -236,7 +256,10 @@ export async function listSkills(workspaceRoot: string, includeGlobal: boolean):dirs.push({ dir: globalAgentLegacy, scope: "global" });}- const groups = await Promise.all(dirs.map(({ dir, scope }) => listSkillsInDir(dir, scope)));+ const groups = await Promise.all(dirs.map(async ({ dir, scope }) => {+ const items = await listSkillsInDir(dir, scope);+ return sharedDirs.has(resolve(dir)) ? items.filter((item) => !APP_WRITTEN_SKILL_NAMES.has(item.name)) : items;+ }));const items = groups.flat();const seen = new Set<string>();diff --git a/apps/server/src/user-skill-paths.test.ts b/apps/server/src/user-skill-paths.test.tsnew file mode 100644index 00000000..8fb5004e--- /dev/null+++ b/apps/server/src/user-skill-paths.test.ts@@ -0,0 +1,132 @@+import { afterEach, describe, expect, test } from "bun:test";+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ buildOmniRushRuntimeConfigObject,+ buildOmniRushRuntimeConfigObjectFromSnapshot,+ omnirushRuntimeSkillsDir,+ writeOmniRushRuntimeConfigFile,+} from "./omnirush-runtime-config.js";+import { omnirushBestPracticesSkillsDir } from "./best-practices.js";+import { listSkills } from "./skills.js";+import { OMNIRUSH_SWARM_SKILL_NAME } from "./omnirush-swarm.js";+import { engineGlobalConfigDir, mergeSkillPaths, userGlobalSkillPaths } from "./user-skill-paths.js";+import type { ServerConfig } from "./types.js";++const roots: string[] = [];+const saved: Record<string, string | undefined> = {};++function setEnv(key: string, value: string | undefined) {+ if (!(key in saved)) saved[key] = process.env[key];+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+}++afterEach(async () => {+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ delete saved[key];+ }+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});++async function setup() {+ const root = await mkdtemp(join(tmpdir(), "omnirush-user-skills-"));+ roots.push(root);+ const home = join(root, "home");+ await mkdir(home, { recursive: true });+ setEnv("HOME", home);+ setEnv("USERPROFILE", home);+ setEnv("XDG_CONFIG_HOME", join(home, ".config"));+ setEnv("OPENCODE_CONFIG_DIR", undefined);+ setEnv("OMNIRUSH_RUNTIME_DB", join(home, ".config", "omnirush", "runtime.sqlite"));+ const workspace = join(root, "project");+ await mkdir(workspace, { recursive: true });+ const config = {+ host: "127.0.0.1",+ port: 0,+ token: "owt_test_token",+ hostToken: "owt_host_token",+ approval: { mode: "auto", timeoutMs: 1000 },+ corsOrigins: ["*"],+ workspaces: [{ id: "ws_1", name: "Workspace", path: workspace, preset: "starter", workspaceType: "local" }],+ authorizedRoots: [workspace],+ readOnly: false,+ startedAt: Date.now(),+ tokenSource: "cli",+ hostTokenSource: "cli",+ logFormat: "pretty",+ } as unknown as ServerConfig;+ return { root, home, workspace, config };+}++async function skill(dir: string, name: string) {+ await mkdir(join(dir, name), { recursive: true });+ await writeFile(join(dir, name, "SKILL.md"), `---\nname: ${name}\ndescription: test ${name}\n---\nbody\n`);+}++describe("user skill folders", () => {+ test("the global config's skills.paths are read as the engine takes them, never written", async () => {+ const { home } = await setup();+ const dir = engineGlobalConfigDir(process.env);+ expect(dir).toBe(join(home, ".config", "omnirush"));+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, "config.json"), JSON.stringify({ skills: { paths: ["/older"] } }));+ const file = join(dir, "opencode.jsonc");+ const bytes = '{\n // mine\n "skills": { "paths": ["~/my-skills", "/abs/team",], "urls": ["https://example.invalid/skills/"] },\n}\n';+ await writeFile(file, bytes);+ expect(await userGlobalSkillPaths(process.env)).toEqual(["~/my-skills", "/abs/team"]);+ expect(await readFile(file, "utf8")).toBe(bytes);+ expect(mergeSkillPaths(["/app"], ["/app", "/a"], undefined, ["/b"])).toEqual(["/app", "/a", "/b"]);+ });++ test("the app's engine config keeps the user's folders after its own; without them it is unchanged", () => {+ const own = ["/state/skills", "/state/best-practices"];+ const plain = buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, process.env, undefined, own[0], own[1], null);+ expect(plain.skills).toEqual({ paths: own });+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, process.env, undefined, own[0], own[1], null, [])).toEqual(plain);+ const withUser = buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, process.env, undefined, own[0], own[1], null, ["~/my-skills", own[0]]);+ expect(withUser.skills).toEqual({ paths: [...own, "~/my-skills"] });+ // Best practices off: the user's folders stay.+ const off = buildOmniRushRuntimeConfigObjectFromSnapshot({ bestPractices: false }, undefined, process.env, undefined, own[0], own[1], null, ["~/my-skills"]);+ expect(off.skills).toEqual({ paths: [own[0], "~/my-skills"] });+ // No app folders (specs, previews) and no user folders: still no skills key.+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}).skills).toBeUndefined();+ });++ test("an app update keeps the user's skills: same folders before and after, user files untouched", async () => {+ const { home, workspace, config } = await setup();+ const globalDir = engineGlobalConfigDir(process.env);+ await mkdir(globalDir, { recursive: true });+ const userConfig = join(globalDir, "opencode.json");+ const userBytes = `${JSON.stringify({ skills: { paths: [join(home, "team-skills")] } }, null, 2)}\n`;+ await writeFile(userConfig, userBytes);+ await skill(join(home, "team-skills"), "team-review");+ await skill(join(globalDir, "skills"), "cli-made");+ await skill(join(home, ".config", "opencode", "skills"), "desktop-global");+ await skill(join(workspace, ".opencode", "skills"), "workspace-skill");++ // Start of the old version, then of the new one (the same user files; the app regenerates its own file).+ const before = await writeOmniRushRuntimeConfigFile(config);+ const first = JSON.parse(await readFile(before.path, "utf8")) as { skills: { paths: string[] } };+ await rm(before.path);+ const after = await writeOmniRushRuntimeConfigFile(config);+ const second = JSON.parse(await readFile(after.path, "utf8")) as { skills: { paths: string[] } };+ expect(second).toEqual(first);+ expect(second.skills.paths).toEqual([+ omnirushRuntimeSkillsDir(config),+ omnirushBestPracticesSkillsDir(config),+ join(home, "team-skills"),+ ]);+ expect((await buildOmniRushRuntimeConfigObject(config)).skills).toEqual(second.skills);+ expect(await readFile(userConfig, "utf8")).toBe(userBytes);++ // The Library lists every folder the engine reads, but not the app's own swarm skill.+ const names = (await listSkills(workspace, true)).map((item) => item.name).sort();+ expect(names).toEqual(["cli-made", "desktop-global", "team-review", "workspace-skill"]);+ expect(names).not.toContain(OMNIRUSH_SWARM_SKILL_NAME);+ });+});diff --git a/apps/server/src/user-skill-paths.ts b/apps/server/src/user-skill-paths.tsnew file mode 100644index 00000000..6e516712--- /dev/null+++ b/apps/server/src/user-skill-paths.ts@@ -0,0 +1,53 @@+/**+ * The user's own skill folders (`skills.paths`), kept in the engine config the+ * app writes.+ *+ * The engine merges its config files in order (its global config folder+ * ~/.config/omnirush, then OPENCODE_CONFIG, the file this app writes, then+ * project files and OPENCODE_CONFIG_DIR) and a later file's `skills.paths`+ * replaces an earlier list instead of adding to it. The app's file lists its+ * own skills (the swarm procedure, the Best practices guides), so the folders+ * a user listed in ~/.config/omnirush/opencode.json (the OmniRush CLI's+ * global config too) were dropped. The app's list now carries them after its+ * own.+ * The user's files are only read, never written.+ */+import { homedir } from "node:os";+import { join } from "node:path";+import { readJsoncFile } from "./jsonc.js";++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/** The string entries of a config's `skills.paths`, or undefined when it does not set the key. */+export function configSkillPaths(config: unknown): string[] | undefined {+ if (!isRecord(config) || !isRecord(config.skills) || !Array.isArray(config.skills.paths)) return undefined;+ return config.skills.paths.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0);+}++/** The engine's own global config folder: <XDG config home>/omnirush (~/.config on every system, as the engine resolves it). */+export function engineGlobalConfigDir(env: NodeJS.ProcessEnv = process.env): string {+ return join(env.XDG_CONFIG_HOME?.trim() || join(homedir(), ".config"), "omnirush");+}++/**+ * The `skills.paths` of the engine's global config, as the engine takes it:+ * config.json, opencode.json, opencode.jsonc; the last file that sets the key+ * wins. Missing or unreadable files are skipped.+ */+export async function userGlobalSkillPaths(env: NodeJS.ProcessEnv = process.env): Promise<string[]> {+ const dir = engineGlobalConfigDir(env);+ let paths: string[] = [];+ for (const name of ["config.json", "opencode.json", "opencode.jsonc"]) {+ const read = await readJsoncFile<unknown>(join(dir, name), undefined, { allowInvalid: true, regularFileOnly: true }).catch(() => null);+ const listed = configSkillPaths(read?.data);+ if (listed) paths = listed;+ }+ return paths;+}++/** The app's folders first, then the user's, each once. */+export function mergeSkillPaths(own: string[], ...user: (string[] | undefined)[]): string[] {+ return [...new Set([...own, ...user.flatMap((list) => list ?? [])])];+}