A desktop coding agent with free access to frontier models.
TypeScript
import { readdir, readFile, writeFile, mkdir, rm } from "node:fs/promises";
import type { Dirent } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { homedir } from "node:os";
import { globalOpencodeConfigDir } from "@omnirush/paths";
import type { SkillItem } from "./types.js";
import { parseFrontmatter, buildFrontmatter } from "./frontmatter.js";
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
* default, `.opencode/skills/` is what the desktop writes), so the GUI must
* list both or it hides skills the model can already use.
*/
const OPENCODE_SKILL_DIR_NAMES = ["skills", "skill"] as const;
/**
* Global OpenCode config directory as the engine resolves it (honours
* OPENCODE_CONFIG_DIR and XDG_CONFIG_HOME before falling back to ~/.config).
*/
function globalSkillConfigDir(): string {
return globalOpencodeConfigDir({ env: process.env });
}
/** Home directory with the same env precedence @omnirush/paths uses (HOME / USERPROFILE first). */
function resolveHomeDir(): string {
const fromEnv = process.platform === "win32"
? process.env.USERPROFILE?.trim() || process.env.HOME?.trim()
: process.env.HOME?.trim();
return fromEnv || homedir();
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function summarizeError(message: string): string {
return message.split(/\r?\n/, 1)[0] ?? "Unknown error";
}
export function renderSkillContentForResponse(item: SkillItem, content: string): string {
if (!item.error) return content;
return [
"ERROR: This skill has invalid YAML frontmatter and may not load correctly.",
"",
item.error,
"",
"Original SKILL.md:",
"",
content,
].join("\n");
}
async function findWorkspaceRoots(workspaceRoot: string): Promise<string[]> {
const roots: string[] = [];
let current = resolve(workspaceRoot);
while (true) {
roots.push(current);
const gitPath = join(current, ".git");
if (await exists(gitPath)) break;
const parent = resolve(current, "..");
if (parent === current) break;
current = parent;
}
return roots;
}
const extractTriggerFromBody = (body: string) => {
const lines = body.split(/\r?\n/);
let inWhenSection = false;
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
if (/^#{1,6}\s+/.test(trimmed)) {
const heading = trimmed.replace(/^#{1,6}\s+/, "").trim();
inWhenSection = /^when to use$/i.test(heading);
continue;
}
if (!inWhenSection) continue;
const cleaned = trimmed
.replace(/^[-*+]\s+/, "")
.replace(/^\d+[.)]\s+/, "")
.trim();
if (cleaned) return cleaned;
}
return "";
};
async function parseSkillEntry(
skillPath: string,
entryName: string,
scope: "project" | "global",
): Promise<SkillItem | null> {
let content: string;
try {
content = await readFile(skillPath, "utf8");
} catch (error) {
console.warn("[omnirush:skills] Skipping unreadable skill file", {
path: skillPath,
entryName,
scope,
error: errorMessage(error),
});
return null;
}
let data: Record<string, unknown>;
let body: string;
try {
const parsed = parseFrontmatter(content);
data = parsed.data;
body = parsed.body;
} catch (error) {
const message = errorMessage(error);
try {
validateSkillName(entryName);
} catch {
return null;
}
console.warn("[omnirush:skills] Found invalid skill frontmatter", {
path: skillPath,
entryName,
scope,
error: message,
});
return {
name: entryName,
description: `${INVALID_SKILL_DESCRIPTION}: ${summarizeError(message)}`,
path: skillPath,
scope,
error: message,
};
}
// The engine registers a skill under its frontmatter `name`, not its folder
// name, so a folder/frontmatter mismatch is still a live skill for the model
// and must stay visible (and deletable) in the GUI under that name.
const name = typeof data.name === "string" && data.name.trim() ? data.name.trim() : entryName;
const description = typeof data.description === "string" ? data.description : "";
const trigger =
typeof data.trigger === "string"
? data.trigger
: typeof data.when === "string"
? data.when
: extractTriggerFromBody(body);
try {
validateSkillName(name);
validateDescription(description);
} catch {
return null;
}
return {
name,
description,
path: skillPath,
scope,
trigger: trigger.trim() || undefined,
};
}
async function listSkillsInDir(dir: string, scope: "project" | "global"): Promise<SkillItem[]> {
if (!(await exists(dir))) return [];
const entries = await readdir(dir, { withFileTypes: true });
const groups = await Promise.all(
entries.map(async (entry) => {
if (!entry.isDirectory()) return [];
const skillPath = join(dir, entry.name, "SKILL.md");
if (await exists(skillPath)) {
// Direct skill: <dir>/<name>/SKILL.md
const item = await parseSkillEntry(skillPath, entry.name, scope);
return item ? [item] : [];
}
// Domain/category folder: <dir>/<domain>/<name>/SKILL.md – scan one level deeper.
// This supports the convention where global skills are organised as
// skills/<domain>/<skill-name>/SKILL.md
// in addition to the flat skills/<skill-name>/SKILL.md layout.
const domainDir = join(dir, entry.name);
let subEntries: Dirent[];
try {
subEntries = await readdir(domainDir, { withFileTypes: true });
} catch {
return [];
}
const subGroups = await Promise.all(
subEntries.map(async (subEntry) => {
if (!subEntry.isDirectory()) return [];
const subSkillPath = join(domainDir, subEntry.name, "SKILL.md");
if (!(await exists(subSkillPath))) return [];
const item = await parseSkillEntry(subSkillPath, subEntry.name, scope);
return item ? [item] : [];
}),
);
return subGroups.flat();
}),
);
return groups.flat();
}
export async function listSkills(workspaceRoot: string, includeGlobal: boolean): Promise<SkillItem[]> {
const roots = await findWorkspaceRoots(workspaceRoot);
const dirs: { dir: string; scope: "project" | "global" }[] = [];
for (const root of roots) {
for (const dirName of OPENCODE_SKILL_DIR_NAMES) {
dirs.push({ dir: join(root, ".opencode", dirName), scope: "project" });
}
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");
const globalAgentLegacy = join(home, ".agent", "skills");
dirs.push({ dir: globalClaude, scope: "global" });
dirs.push({ dir: globalAgents, scope: "global" });
dirs.push({ dir: globalAgentLegacy, scope: "global" });
}
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>();
return items.filter((item) => {
if (seen.has(item.name)) return false;
seen.add(item.name);
return true;
});
}
export type UpsertSkillPayload = {
name: string;
content: string;
description?: string;
};
export function buildSkillContent(payload: UpsertSkillPayload): { name: string; content: string } {
const name = payload.name.trim();
validateSkillName(name);
if (!payload.content) {
throw new ApiError(400, "invalid_skill_content", "Skill content is required");
}
let content = payload.content;
const { data, body } = parseFrontmatter(payload.content);
if (Object.keys(data).length > 0) {
const frontmatterName = typeof data.name === "string" ? data.name : "";
const frontmatterDescription = typeof data.description === "string" ? data.description : "";
if (frontmatterName && frontmatterName !== name) {
throw new ApiError(400, "invalid_skill_name", "Skill frontmatter name must match payload name");
}
validateDescription(frontmatterDescription || payload.description);
const nextDescription = frontmatterDescription || payload.description || "";
const frontmatter = buildFrontmatter({
...data,
name,
description: nextDescription,
});
content = frontmatter + body.replace(/^\n/, "");
} else {
validateDescription(payload.description);
const frontmatter = buildFrontmatter({ name, description: payload.description });
content = frontmatter + payload.content.replace(/^\n/, "");
}
return {
name,
content: content.endsWith("\n") ? content : content + "\n",
};
}
export async function upsertSkill(
workspaceRoot: string,
payload: UpsertSkillPayload,
): Promise<{ path: string; action: "added" | "updated" }> {
const skill = buildSkillContent(payload);
const baseDir = projectSkillsDir(workspaceRoot);
const skillDir = join(baseDir, skill.name);
await mkdir(skillDir, { recursive: true });
const skillPath = join(skillDir, "SKILL.md");
const existed = await exists(skillPath);
await writeFile(skillPath, skill.content, "utf8");
return { path: skillPath, action: existed ? "updated" : "added" };
}
export async function deleteSkill(workspaceRoot: string, name: string): Promise<{ path: string }> {
const trimmed = name.trim();
validateSkillName(trimmed);
const baseDir = projectSkillsDir(workspaceRoot);
const flatDir = join(baseDir, trimmed);
if (await exists(join(flatDir, "SKILL.md"))) {
await rm(flatDir, { recursive: true, force: true });
return { path: flatDir };
}
// Nested layout: skills/<domain>/<name>/SKILL.md (e.g. skills installed by
// marketplace plugin bundles are namespaced under a plugin folder). Listing
// supports this layout, so deletion must resolve it the same way.
const items = await listSkills(workspaceRoot, false);
const item = items.find((skill) => skill.name === trimmed && skill.scope === "project");
if (!item) {
throw new ApiError(404, "skill_not_found", `Skill not found: ${trimmed}`);
}
const skillDir = dirname(item.path);
await rm(skillDir, { recursive: true, force: true });
return { path: skillDir };
}