Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

31.0 KB
Raw Blame
/**
 * Adelie plugin library: the built-in plugins and the loader that reads them (part
 * of core — hooks, skills and their loading all live in one SDK).
 *
 * The library has two sources, loaded the same way and distinguished only by
 * `LibraryPlugin.source`: the built-ins (a plugin is its own npm package,
 * `@adelie/<name>`, `plugins/<name>/` in the repo; resolved through Node from the host
 * package's dependency list — see pluginRoots) and the user plugin directory
 * (`<data root>/plugins`, see userPluginDirs), where a remote download or a local upload lands.
 * A user plugin of the same name as a built-in is not loaded — the built-in wins — and a user
 * directory the loader cannot read (no plugin.json, a malformed one, a version in the wrong
 * shape) is skipped rather than thrown, so one bad directory left on disk cannot take the whole
 * library down; the directory listing still shows it, so it can be deleted again.
 *
 * Either way a plugin is a directory carrying a `plugin.json` manifest, an `icon.svg` beside it
 * (every built-in plugin ships one; it is the icon of everything the plugin ships), and any of
 * two kinds of content:
 * skills (`skills/<name>/SKILL.md`, installed into an Agent's `agent_state/skills/`) and a
 * hook package (`hooks/*.mjs`, installed into `agent_state/hooks/<plugin>/` together with a
 * generated `hooks.json`). The files are the runtime source of truth — read and parsed on
 * every call, no caching (files are small, calls are infrequent) — so editing a file takes
 * effect immediately. They are committed content reached through declared dependencies, so
 * anything that fails to load is a broken install or a broken plugin and throws with the
 * path — never a silently smaller library. Only the category manifest (id and titles) is
 * code; install / uninstall / scan live in core's state layer.
 *
 * Versions are dates with a sequence number, `YYYY.MM.DD.N` (see PLUGIN_VERSION_PATTERN,
 * parsePluginVersion and comparePluginVersions). plugin.json is the single metadata holder: a library SKILL.md's frontmatter
 * carries only `name` and `description`, and the loader stamps the plugin's version and UI short
 * descriptions into each skill's metadata and installable content (the installed copy carries the
 * full frontmatter, generated — the way hooks.json is).
 *
 * Docs: packages/docs/content/skills.{zh,en}.md (site path /docs/skills) documents the plugin
 * format, the versions and the built-in library.
 */
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";
import { resolveRoot, userPluginsDir } from "../state/paths.js";

/** A skill's metadata. A library SKILL.md's frontmatter carries only `name` and `description`; the short descriptions and `version` are stamped from plugin.json by the loader (installed copies then carry the full generated frontmatter, which is what the installed-side readers parse). */
export interface SkillMetadata {
  /** Skill name (matches its containing directory name). */
  name: string;
  /** One-line description; injected into the model prompt via `{{SKILL_METADATA}}`. */
  description: string;
  /** UI short description (frontmatter `short_description`, optional): preferred in compact spots like cards, falls back to the full description if missing; not injected into the prompt. */
  shortDescription?: string;
  /** Chinese short description (frontmatter `short_description_zh`, optional). */
  shortDescriptionZh?: string;
  /** Version, `YYYY.MM.DD.N` (an installed copy may still carry the legacy `YYYY-MM-DD.N`); an absent or malformed frontmatter version reads as "" (older than any real version). */
  version: string;
}

/** A skill in the library: metadata + full SKILL.md content (including frontmatter, written as-is on install). */
export interface LibrarySkill extends SkillMetadata {
  content: string;
  /** The plugin's raw `icon.svg`, stamped onto every skill by the loader — a skill has no icon of its own — and written as `icon.svg` beside SKILL.md on install, so the installed copy carries it; absent when the plugin ships none. */
  icon?: string;
  /**
   * Optional auxiliary files the SKILL.md references (e.g. `reference/API.md`), keyed by
   * POSIX-relative path within the skill directory; every entry except the top-level SKILL.md
   * (its own field) and a top-level icon.svg (reserved: the plugin's icon is what installs
   * there). Written alongside SKILL.md on install (subdirectories preserved). Read as UTF-8
   * text — library content is committed text; the field is omitted when a skill has no extra
   * files.
   */
  files?: Record<string, string>;
}

/**
 * When a `user_prompt` command runs: `prompt` on every Prompt the user submits, `host` only
 * when the host starts the package's flow by name (`Session.runUserPromptHook` — goal mode's
 * start). Meaningless at the other hook points.
 */
export type UserPromptTrigger = "prompt" | "host";

/** One hook script entry: `command` is a path relative to the plugin's `hooks/` directory, run with Node; `timeout` in seconds (core's default applies when absent); `trigger` says when a `user_prompt` command runs (see {@link userPromptTrigger} for the default). */
export interface HookCommand {
  command: string;
  timeout?: number;
  trigger?: UserPromptTrigger;
}

/**
 * The manifest an installed hook package carries (`agent_state/hooks/<plugin>/hooks.json`),
 * generated by the installer from plugin.json: identity and display fields plus one script
 * list per hook point (`stop`, `pre_tool_use`, `user_prompt`). Whether a Session runs hooks
 * at all is an Agent-level decision (`hooks.enabled` in system_config.yaml), not a per-package
 * one. The plugin's icon is not part of it: the installer writes `icon.svg` beside the
 * manifest instead. Unknown keys are ignored rather than rejected.
 */
export interface HookManifest {
  name: string;
  description: string;
  description_zh?: string;
  version: string;
  /** Stop commands, consulted after every Task of a run. */
  stop: HookCommand[];
  /** Pre-tool-use commands, consulted before each tool call's approval. */
  pre_tool_use: HookCommand[];
  /** User-prompt expansion commands: run on every Prompt the user submits, or — `trigger: "host"` — only when the host starts the flow the package owns (goal mode's start). */
  user_prompt: HookCommand[];
}

/** A plugin's hook package as read from the library: the manifest to install and the `hooks/` files (relative path → text). */
export interface LibraryHooks {
  manifest: HookManifest;
  files: Record<string, string>;
}

/** Where a plugin in the library comes from (see the module header). */
export type PluginSource = "builtin" | "user";

/** A plugin in the library: the manifest fields plus the content it ships. */
export interface LibraryPlugin {
  /** Plugin name (its directory name). */
  name: string;
  /** Which of the two sources it was read from. */
  source: PluginSource;
  /** English one-line description (plugin.json `description`). */
  description: string;
  /** Chinese description (plugin.json `description_zh`, optional). */
  descriptionZh?: string;
  /** UI short descriptions (plugin.json `short_description(_zh)`, optional). */
  shortDescription?: string;
  shortDescriptionZh?: string;
  /** `YYYY.MM.DD.N`. */
  version: string;
  /** Category id (see PLUGIN_CATEGORIES); absent or unknown → the "other" group. */
  category?: string;
  /** Whether default_agent gets this plugin at creation (plugin.json `preinstall`, default true). */
  preinstall: boolean;
  /** Raw `icon.svg` beside plugin.json — every built-in plugin ships one. It is the icon of everything the plugin ships: stamped onto each skill and written beside an installed hook package. */
  icon?: string;
  skills: LibrarySkill[];
  hooks?: LibraryHooks;
}

/** Category manifest entry: id and titles (Chinese optional, displayed per UI language). */
export interface PluginCategory {
  id: string;
  title: string;
  titleZh?: string;
}

/** Grouping result: category metadata + member plugins read from library files. */
export interface ResolvedPluginGroup extends PluginCategory {
  plugins: LibraryPlugin[];
}

/** Character rule for plugin, skill and hook names (directory names): prevents path traversal (exported for the server's archive-install validation). */
export const PLUGIN_NAME_PATTERN = /^[A-Za-z0-9_-]+$/;

/** Version format: a dotted date and a sequence number, e.g. `2026.08.29.1`. What a library manifest must carry. */
export const PLUGIN_VERSION_PATTERN = /^\d{4}\.\d{2}\.\d{2}\.\d+$/;

/** The spelling used before this format, `2026-08-29.1`: still read wherever an installed copy carries it (see parsePluginVersion). */
const LEGACY_PLUGIN_VERSION_PATTERN = /^\d{4}-\d{2}-\d{2}\.\d+$/;

/**
 * Reads either spelling of a version — the current `YYYY.MM.DD.N` and the legacy
 * `YYYY-MM-DD.N` — into the date and sequence number both denote, or null when the string is
 * not a version at all. The two spellings of one version parse to the same key, so a copy
 * installed before the rename compares equal to the library's copy of that same version:
 * installed copies predate the rename, and reinstalling every one of them over a spelling
 * would put noise in the update badges instead of information.
 */
export function parsePluginVersion(version: string): { date: string; seq: number } | null {
  if (!PLUGIN_VERSION_PATTERN.test(version) && !LEGACY_PLUGIN_VERSION_PATTERN.test(version)) {
    return null;
  }
  const dot = version.lastIndexOf(".");
  return { date: version.slice(0, dot).replace(/-/g, "."), seq: Number(version.slice(dot + 1)) };
}

/**
 * Orders two versions: by date, then by sequence number (numeric, so `.10` follows `.9`). Both
 * spellings are read (see parsePluginVersion), so the legacy and current spellings of one
 * version compare equal. A string that is not a version (the empty string an unversioned
 * install reads as, a legacy natural number) sorts before every real version, so anything in
 * the library counts as newer.
 */
export function comparePluginVersions(a: string, b: string): number {
  const va = parsePluginVersion(a);
  const vb = parsePluginVersion(b);
  if (!va || !vb) return Number(va !== null) - Number(vb !== null);
  if (va.date !== vb.date) return va.date < vb.date ? -1 : 1;
  return va.seq - vb.seq;
}

/**
 * The first manifest version written for a harness that runs `user_prompt` commands on every
 * Prompt. See {@link userPromptTrigger}.
 */
export const USER_PROMPT_EVERY_PROMPT_SINCE = "2026.09.29.1";

/**
 * When one `user_prompt` command of a manifest runs. A command that says so decides; one
 * that does not runs on every Prompt.
 *
 * COMPAT (remove at 0.3.0 release preparation; the release notes must first require
 * updating the goal plugin): the point used to be reached by name only, and the goal
 * package installed before this version starts an unbudgeted goal whenever its `start.mjs`
 * runs without a budget. A manifest carrying a real plugin version older than
 * {@link USER_PROMPT_EVERY_PROMPT_SINCE} therefore keeps the by-name reading for the
 * commands that name no trigger. A manifest with no version, or one that is not a plugin
 * version (a hand-written package), is not affected.
 */
export function userPromptTrigger(
  manifestVersion: string,
  command: HookCommand,
): UserPromptTrigger {
  if (command.trigger !== undefined) return command.trigger;
  return predatesEveryPromptHooks(manifestVersion) ? "host" : "prompt";
}

/** Whether a manifest version is a real plugin version from before `user_prompt` commands ran on every Prompt (the compatibility rule of {@link userPromptTrigger}). */
export function predatesEveryPromptHooks(manifestVersion: string): boolean {
  return (
    parsePluginVersion(manifestVersion) !== null &&
    comparePluginVersions(manifestVersion, USER_PROMPT_EVERY_PROMPT_SINCE) < 0
  );
}

/**
 * Parses the frontmatter at the start of SKILL.md: only recognizes `key: value` lines inside the
 * first `---` block (split on the first colon, value trimmed, values may themselves contain colons);
 * all fields are scalars, no YAML dependency needed.
 * Error tolerance: returns null if the `---` block or name is missing; a version in neither the
 * current `YYYY.MM.DD.N` nor the legacy `YYYY-MM-DD.N` spelling reads as "".
 */
export function parseSkillFrontmatter(content: string): SkillMetadata | null {
  // Strip a possible UTF-8 BOM (may be introduced by editors when manually editing an installed SKILL.md); CRLF is handled by \r?\n.
  const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(content.replace(/^/, ""));
  if (!match) return null;
  const fields: Record<string, string> = {};
  for (const line of match[1]!.split(/\r?\n/)) {
    const idx = line.indexOf(":");
    if (idx <= 0) continue;
    const key = line.slice(0, idx).trim();
    if (key) fields[key] = line.slice(idx + 1).trim();
  }
  const name = fields["name"];
  if (!name) return null;
  const version = fields["version"] ?? "";
  const shortDescription = fields["short_description"];
  const shortDescriptionZh = fields["short_description_zh"];
  return {
    name,
    description: fields["description"] ?? "",
    // short_description(_zh) is optional: omitted when absent (undefined keys aren't set).
    ...(shortDescription !== undefined ? { shortDescription } : {}),
    ...(shortDescriptionZh !== undefined ? { shortDescriptionZh } : {}),
    // An installed copy may carry either spelling; both are real versions (see parsePluginVersion).
    version: parsePluginVersion(version) !== null ? version : "",
  };
}

/**
 * The nearest package root above this module: `packages/core` from source or dist, and the
 * bundling package's own root wherever core is inlined (the CLI bundle, the desktop server
 * bundle) — which is exactly whose package.json lists the plugin packages to resolve.
 */
function packageRoot(): string {
  const start = path.dirname(fileURLToPath(import.meta.url));
  let dir = start;
  for (;;) {
    if (fs.existsSync(path.join(dir, "package.json"))) return dir;
    const parent = path.dirname(dir);
    if (parent === dir) throw new Error(`No package.json above the plugin loader at ${start}`);
    dir = parent;
  }
}
const PKG_ROOT = packageRoot();
/** npm-name prefix of the per-plugin packages (the host package's dependencies name them). */
const PLUGIN_PKG_PREFIX = "@adelie/";

/**
 * The pnpm workspace root above `from`, or null outside a workspace checkout: the directory
 * holding `pnpm-workspace.yaml`. An npm install and the packed desktop app have none above
 * them, which is what keeps the workspace preference below out of their way.
 */
function workspaceRootAbove(from: string): string | null {
  let dir = from;
  for (;;) {
    if (fs.existsSync(path.join(dir, "pnpm-workspace.yaml"))) return dir;
    const parent = path.dirname(dir);
    if (parent === dir) return null;
    dir = parent;
  }
}

/**
 * The directory a plugin is read from, given where Node resolved its package: in a workspace
 * checkout, the repo's own `plugins/<name>/` whenever it holds that package; the resolved
 * directory otherwise.
 *
 * The workspace installs every `workspace:*` package as an injected copy (a snapshot pnpm
 * takes at install time and refreshes only after the package's `build` script runs — which
 * plugins have none of), so `require.resolve` lands on a copy that misses every file added
 * since the last install, and an edited `plugin.json` version stays invisible to a running
 * `pnpm dev`. The plugin directory itself is the source of truth in a checkout, so that is
 * what a checkout reads; nothing changes for an npm install or the packed desktop app,
 * which have no workspace file above them and keep resolving their own copy.
 */
export function workspacePluginRoot(
  name: string,
  resolvedDir: string,
  packageRoot: string = PKG_ROOT,
): string {
  const workspace = workspaceRootAbove(packageRoot);
  if (workspace === null) return resolvedDir;
  const candidate = path.join(workspace, "plugins", name);
  try {
    const manifest = JSON.parse(fs.readFileSync(path.join(candidate, "package.json"), "utf8")) as {
      name?: unknown;
    };
    return manifest.name === `${PLUGIN_PKG_PREFIX}${name}` ? candidate : resolvedDir;
  } catch {
    return resolvedDir;
  }
}

/**
 * Where the plugin directories live, name → absolute root. Each plugin is its own npm package
 * (`@adelie/<name>`, `plugins/<name>/` in the repo): the host package's `dependencies`
 * name them (core, the CLI, and the desktop app — whose packaged manifest keeps that field
 * and nothing else, so `devDependencies` would not survive into an installer), and each is
 * resolved through Node from this module's own location, so the lookup walks the same
 * `node_modules` chain a `require` from here would: an npm install and the packed desktop
 * app (electron-builder collects the declared packages into its node_modules) each land on
 * their own copy, and a workspace checkout is redirected to its `plugins/<name>/` directory
 * (see workspacePluginRoot). Read fresh on every call, like the plugin files themselves.
 */
function builtinRoots(): Map<string, string> {
  const roots = new Map<string, string>();
  const pkg = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, "package.json"), "utf8")) as {
    dependencies?: Record<string, string>;
  };
  const require = createRequire(import.meta.url);
  for (const dep of Object.keys(pkg.dependencies ?? {})) {
    if (!dep.startsWith(PLUGIN_PKG_PREFIX)) continue;
    let manifest: string;
    try {
      manifest = require.resolve(`${dep}/package.json`);
    } catch (err) {
      // A declared plugin that Node cannot find is a broken install (the deployment did not
      // carry the package), not a smaller library.
      throw new Error(
        `Plugin package ${dep} is declared in ${PKG_ROOT}/package.json but cannot be resolved: ${err instanceof Error ? err.message : String(err)}`,
      );
    }
    const name = dep.slice(PLUGIN_PKG_PREFIX.length);
    roots.set(name, workspacePluginRoot(name, path.dirname(manifest)));
  }
  return roots;
}

/**
 * One built-in plugin package's directory, by the bare name the library files it under
 * (`csu-mail`, not `@adelie/csu-mail`), or undefined when this build carries no such plugin.
 *
 * For a reader of the PACKAGE rather than of its parsed plugin: the market builds an entry for
 * each package it ships out of the package's own manifests, and resolving them the way the
 * library reader does keeps an entry and a card describing the same copy of one package —
 * including a workspace checkout, where that is the repo's `plugins/<name>/` and not the copy
 * Node's `node_modules` still holds.
 */
export function builtinPluginDir(name: string): string | undefined {
  return builtinRoots().get(name);
}

/**
 * Where every plugin is read from, name → its directory and which source it came from: the
 * built-ins first, then the user plugin directory, and only for names no built-in claimed — an
 * import that collides with a plugin the build ships must not be able to shadow it (the API
 * refuses such an import up front; this is what makes a directory left there by hand harmless).
 */
function pluginRoots(
  root: string = resolveRoot(),
): Map<string, { dir: string; source: PluginSource }> {
  const roots = new Map<string, { dir: string; source: PluginSource }>();
  for (const [name, dir] of builtinRoots()) roots.set(name, { dir, source: "builtin" });
  for (const [name, dir] of userPluginRoots(root)) {
    if (!roots.has(name)) roots.set(name, { dir, source: "user" });
  }
  return roots;
}

/**
 * The user plugin directories, name → absolute path: `<data root>/plugins/<name>` for every
 * entry of the user plugin directory that could be a plugin — a directory, named like a plugin
 * (PLUGIN_NAME_PATTERN, which also excludes the dot-prefixed staging directory an install
 * writes through). Read fresh on every call, like everything else here. Whether the entry is a
 * *valid* plugin is the reader's question (see readPluginDir), not this scan's: the directory
 * listing must show a broken one too, so its owner can delete it.
 */
export function userPluginRoots(root: string = resolveRoot()): Map<string, string> {
  const dir = userPluginsDir(root);
  const roots = new Map<string, string>();
  let entries: fs.Dirent[];
  try {
    entries = fs.readdirSync(dir, { withFileTypes: true });
  } catch {
    // No user plugin directory: nothing has ever been imported here.
    return roots;
  }
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
    if (entry.isDirectory() && PLUGIN_NAME_PATTERN.test(entry.name)) {
      roots.set(entry.name, path.join(dir, entry.name));
    }
  }
  return roots;
}

/**
 * Recursively collects a directory's files as text keyed by POSIX-relative path, skipping the
 * names in `except` at the top level. Symlinks and other non-regular entries are skipped.
 * Returns undefined when the directory has no such files.
 */
function readDirFiles(dir: string, except: readonly string[]): Record<string, string> | undefined {
  const files: Record<string, string> = {};
  const walk = (abs: string, rel: string): void => {
    for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
      const childRel = rel ? `${rel}/${entry.name}` : entry.name;
      if (entry.isDirectory()) {
        walk(path.join(abs, entry.name), childRel);
      } else if (entry.isFile()) {
        if (rel === "" && except.includes(entry.name)) continue;
        files[childRel] = fs.readFileSync(path.join(abs, entry.name), "utf8");
      }
    }
  };
  walk(dir, "");
  return Object.keys(files).length > 0 ? files : undefined;
}

/**
 * Reads one skill directory: name from the directory (overriding frontmatter), SKILL.md verbatim,
 * and every other file as auxiliary content. The icon is not read here: a skill has none of
 * its own, and stampSkill gives it the plugin's.
 */
function readSkillDir(dir: string, name: string): LibrarySkill {
  const file = path.join(dir, "SKILL.md");
  const content = fs.readFileSync(file, "utf8");
  const meta = parseSkillFrontmatter(content);
  if (!meta) throw new Error(`Library skill ${file} has no frontmatter with a name`);
  const files = readDirFiles(dir, ["SKILL.md", "icon.svg"]);
  return { ...meta, name, content, ...(files !== undefined ? { files } : {}) };
}

/**
 * Resolves a library skill against its plugin: the plugin's version and UI short descriptions
 * are the skill's (a library SKILL.md carries only `name` and `description`), its icon
 * becomes the skill's, and the installable `content` gets the full frontmatter regenerated in
 * canonical field order — the installed copy is self-describing (update checks read its
 * `version`, the UI its short descriptions and icon) the same way an installed hook package's
 * hooks.json is generated.
 */
function stampSkill(
  skill: LibrarySkill,
  plugin: {
    shortDescription?: string;
    shortDescriptionZh?: string;
    version: string;
    icon?: string;
  },
): LibrarySkill {
  const { shortDescription, shortDescriptionZh } = plugin;
  const front = [
    "---",
    `name: ${skill.name}`,
    `description: ${skill.description}`,
    ...(shortDescription !== undefined ? [`short_description: ${shortDescription}`] : []),
    ...(shortDescriptionZh !== undefined ? [`short_description_zh: ${shortDescriptionZh}`] : []),
    `version: ${plugin.version}`,
    "---",
  ].join("\n");
  const body = skill.content.replace(/^\ufeff?---\r?\n[\s\S]*?\r?\n---/, "");
  return {
    ...skill,
    ...(shortDescription !== undefined ? { shortDescription } : {}),
    ...(shortDescriptionZh !== undefined ? { shortDescriptionZh } : {}),
    version: plugin.version,
    ...(plugin.icon !== undefined ? { icon: plugin.icon } : {}),
    content: `${front}${body}`,
  };
}

/** The plugin.json shape: the single metadata holder of a plugin (see the module header). */
interface PluginManifestFile {
  description: string;
  description_zh?: string;
  short_description?: string;
  short_description_zh?: string;
  /** `YYYY.MM.DD.N` — the library's manifests carry the current spelling only. */
  version: string;
  category?: string;
  /** Default true. */
  preinstall?: boolean;
  /** One command list per hook point the plugin's hook package answers at. */
  hooks?: {
    stop?: HookCommand[];
    pre_tool_use?: HookCommand[];
    user_prompt?: HookCommand[];
  };
}

/**
 * Reads one plugin directory. Throws on anything that makes it not a plugin — the manifest is
 * missing or unparseable, or its version is not `YYYY.MM.DD.N` — which is the check an import
 * runs against the files it is about to install, and the reason a built-in that fails to read
 * is a broken install rather than a smaller library.
 */
export function readPluginDir(name: string, dir: string, source: PluginSource): LibraryPlugin {
  const manifestFile = path.join(dir, "plugin.json");
  const manifest = JSON.parse(fs.readFileSync(manifestFile, "utf8")) as PluginManifestFile;
  if (!PLUGIN_VERSION_PATTERN.test(manifest.version)) {
    throw new Error(`${manifestFile}: version must be YYYY.MM.DD.N, got ${manifest.version}`);
  }
  const {
    description,
    description_zh: descriptionZh,
    short_description: shortDescription,
    short_description_zh: shortDescriptionZh,
    version,
  } = manifest;
  const skills: LibrarySkill[] = [];
  const skillsDir = path.join(dir, "skills");
  if (fs.existsSync(skillsDir)) {
    for (const entry of fs.readdirSync(skillsDir, { withFileTypes: true })) {
      if (entry.isDirectory())
        skills.push(readSkillDir(path.join(skillsDir, entry.name), entry.name));
    }
    skills.sort((a, b) => a.name.localeCompare(b.name));
  }
  let icon: string | undefined;
  try {
    icon = fs.readFileSync(path.join(dir, "icon.svg"), "utf8");
  } catch {
    // Built-in plugins all ship one; a plugin without it falls back to the kind's glyph in the UI.
  }
  const hooksDir = path.join(dir, "hooks");
  const hookFiles = fs.existsSync(hooksDir) ? readDirFiles(hooksDir, []) : undefined;
  const hooks: LibraryHooks | undefined =
    hookFiles !== undefined
      ? {
          manifest: {
            name,
            description,
            ...(descriptionZh !== undefined ? { description_zh: descriptionZh } : {}),
            version,
            stop: manifest.hooks?.stop ?? [],
            pre_tool_use: manifest.hooks?.pre_tool_use ?? [],
            user_prompt: manifest.hooks?.user_prompt ?? [],
          },
          files: hookFiles,
        }
      : undefined;
  return {
    name,
    source,
    description,
    ...(descriptionZh !== undefined ? { descriptionZh } : {}),
    ...(shortDescription !== undefined ? { shortDescription } : {}),
    ...(shortDescriptionZh !== undefined ? { shortDescriptionZh } : {}),
    version,
    ...(manifest.category !== undefined ? { category: manifest.category } : {}),
    preinstall: manifest.preinstall !== false,
    ...(icon !== undefined ? { icon } : {}),
    skills: skills.map((skill) =>
      stampSkill(skill, {
        ...(shortDescription !== undefined ? { shortDescription } : {}),
        ...(shortDescriptionZh !== undefined ? { shortDescriptionZh } : {}),
        version,
        ...(icon !== undefined ? { icon } : {}),
      }),
    ),
    ...(hooks !== undefined ? { hooks } : {}),
  };
}

/**
 * Reads one plugin from where pluginRoots found it. A built-in that fails to read throws; a
 * user plugin that fails to read is skipped (see the module header) — the library stays usable
 * and the directory listing still shows the directory, so its owner can delete it.
 */
function readLibraryPlugin(
  name: string,
  dir: string,
  source: PluginSource,
): LibraryPlugin | undefined {
  if (source === "builtin") return readPluginDir(name, dir, source);
  try {
    return readPluginDir(name, dir, source);
  } catch {
    return undefined;
  }
}

/** Reads every plugin in the library (one per plugin package and one per user plugin directory, see pluginRoots), sorted by name. */
export function loadLibraryPlugins(root: string = resolveRoot()): LibraryPlugin[] {
  const plugins: LibraryPlugin[] = [];
  for (const [name, { dir, source }] of pluginRoots(root)) {
    const plugin = readLibraryPlugin(name, dir, source);
    if (plugin) plugins.push(plugin);
  }
  return plugins.sort((a, b) => a.name.localeCompare(b.name));
}

/** The plugins default_agent installs at initialization: every library plugin except those whose manifest sets `preinstall: false`. */
export function loadPreinstalledPlugins(root: string = resolveRoot()): LibraryPlugin[] {
  return loadLibraryPlugins(root).filter((plugin) => plugin.preinstall);
}

/** Reads a single library plugin by name; undefined when the library has no such plugin, or when the user plugin of that name cannot be read (names are looked up, never joined into a path). */
export function libraryPlugin(
  name: string,
  dataRoot: string = resolveRoot(),
): LibraryPlugin | undefined {
  const root = pluginRoots(dataRoot).get(name);
  return root !== undefined ? readLibraryPlugin(name, root.dir, root.source) : undefined;
}

/** Finds a library skill by its own name (across every plugin), with the plugin that ships it. */
export function librarySkill(
  name: string,
  root: string = resolveRoot(),
): { plugin: LibraryPlugin; skill: LibrarySkill } | undefined {
  for (const plugin of loadLibraryPlugins(root)) {
    const skill = plugin.skills.find((s) => s.name === name);
    if (skill) return { plugin, skill };
  }
  return undefined;
}

/**
 * Category manifest, in display order. Categories group by audience, not by technology: a
 * hook-only plugin sits with the skills it serves the same audience as (goal mode and
 * continual learning are office productivity), and agent tuning is AI app development.
 * Docs: /docs/skills § "Built-in library".
 */
export const PLUGIN_CATEGORIES: PluginCategory[] = [
  { id: "office-productivity", title: "Office Productivity", titleZh: "办公效率" },
  { id: "software-development", title: "Software Development", titleZh: "软件开发" },
  { id: "ai-app-development", title: "AI App Development", titleZh: "AI 应用开发" },
  { id: "agent-company", title: "Agent Company", titleZh: "Agent 公司" },
];

/**
 * Groups plugins by category in PLUGIN_CATEGORIES order (members sorted by name; an empty
 * category is omitted); plugins with no or an unknown category land in an Other group appended
 * at the end (only when non-empty). A pure function, the testable core of loadPluginGroups.
 */
export function groupPlugins(all: LibraryPlugin[]): ResolvedPluginGroup[] {
  const groups: ResolvedPluginGroup[] = [];
  const known = new Set(PLUGIN_CATEGORIES.map((c) => c.id));
  for (const category of PLUGIN_CATEGORIES) {
    const members = all
      .filter((p) => p.category === category.id)
      .sort((a, b) => a.name.localeCompare(b.name));
    if (members.length > 0) groups.push({ ...category, plugins: members });
  }
  const others = all
    .filter((p) => p.category === undefined || !known.has(p.category))
    .sort((a, b) => a.name.localeCompare(b.name));
  if (others.length > 0) {
    groups.push({ id: "other", title: "Other", titleZh: "其他", plugins: others });
  }
  return groups;
}

/** Reads the library and groups it (see groupPlugins). */
export function loadPluginGroups(root: string = resolveRoot()): ResolvedPluginGroup[] {
  return groupPlugins(loadLibraryPlugins(root));
}