Skip to content

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

feat(core,server,web): the library takes a plugin from a zip or a URL, exports it, and deletes it

lmliheng18d7c137a1f1
diff --git a/changelog/unreleased/2026-10-01-plugin-directory.md b/changelog/unreleased/2026-10-01-plugin-directory.md
new file mode 100644
index 00000000..7c51ba08
--- /dev/null
+++ b/changelog/unreleased/2026-10-01-plugin-directory.md
@@ -0,0 +1,28 @@
+# Plugins: the library takes a plugin from a zip or a URL, gives it back as a zip and removes it, and both dialogs state the rules for importing and for writing one
+
+- **Date:** 2026-10-01
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#943](https://github.com/Prism-Shadow/penguin-harness/pull/943)
+
+[中文版](2026-10-01-plugin-directory.zh.md)
+
+The Plugins page gained a plugin directory beside the packages the build ships: an admin installs a plugin into it from a local zip or a URL, the library lists it like any other, and its card exports it back out as a zip or deletes it. Both import dialogs state what an import accepts and what a plugin has to be.
+
+## Importing into the directory
+
+The routes are `POST /api/plugins/upload` (a zip carried in the request) and `POST /api/plugins/download` (a URL the server fetches), both admin-only — the directory belongs to the installation rather than to a Project, and an installed plugin's hook scripts run with the server's own rights, so the capability is the one that installs to a machine. `GET /api/plugins/directory` reads the directory line, `GET /api/plugins/:plugin/archive` exports a user plugin as a zip for any logged-in user, and `DELETE /api/plugins/:plugin` removes one.
+
+An archive is read in two passes, because an archive is not necessarily a plugin: the central directory is scanned for every entry name — nothing inflated — to locate the plugin root, and only that root's files are inflated afterwards. The root is the shallowest directory holding a `plugin.json`, and two of them at the same depth are refused rather than guessed at; everything outside the root is ignored, so a checkout that wraps a plugin in a repository installs the plugin and not the repository. A GitHub tree URL (`…/tree/<ref>/<subdir>`) narrows the search to that subdirectory, matched on the tail of the path because the archive's own top-level `<repo>-<ref>/` directory is whatever the host wrapped it in. The caps bound the plugin rather than the archive it arrived in: 200 files, 5 MB each and 20 MB in total under the plugin root, on top of 14 MB for an uploaded zip and 32 MB for a download.
+
+The name is taken from what the admin typed, else from the URL (a directory URL's last segment, a repository URL's repository name, a zip link's file name), else from the plugin root's directory name, and it has to match `^[A-Za-z0-9_-]+$` because it is the directory the plugin lands in. A name a built-in plugin already holds is refused — the loader would go on serving the built-in — while a user plugin of the same name answers `409 plugin_exists` until the request carries `overwrite: true`, which the dialog asks for in a confirmation instead of making the admin choose the file a second time. Every entry path is checked against zip-slip before a byte is written, and the manifest is validated by the library's own reader.
+
+Installing is a staged swap, the same shape as a Skill install: the files land in a dot-prefixed staging directory that the loader's scan skips, are read back through the library's reader — a directory that would not load is rejected before it is committed rather than installed and silently skipped afterwards — and only then replace the real directory in one rename. The staging directory is cleared first, so a leftover from an interrupted install is never merged into the next one. The library is read from disk on every request and caches nothing, so an imported plugin is in the listing and installable the moment the request returns: no restart and no invalidation.
+
+## The user plugin directory on the page
+
+`<root>/plugins` holds one directory per plugin, laid out exactly like a plugin package — `plugin.json`, `icon.svg`, `skills/`, `hooks/` — so the loader needs no second format and a plugin from here is installed, updated and uninstalled like a built-in one. The page names the directory under its title with a copy button and a count of what is in it, and a card from it carries a **User** badge beside **built in**. Such a card can be exported as a zip; deleting it removes its directory from disk after a confirmation and cannot be undone. Import and delete are what an admin sees and a member does not, and the page's help text says so.
+
+## The rules, beside the controls they govern
+
+Both dialogs end with the same two lists, because they describe the shape a plugin has to arrive in rather than one source's mechanics, and an admin who opened the wrong dialog should still meet them. **Plugin import rules** gives the sources, where the plugin root is found, the precedence the name is decided by, the size caps and what a name collision does — ordered, because the name precedence is what a GitHub repository URL traps. **Plugin authoring rules** states what a plugin has to be for whoever is about to publish one: one directory per plugin named after it, `plugin.json` and `skills/<skill>/SKILL.md` inside it, no account details in a plugin (the AppID, keys, mail addresses and phone numbers belong to whoever installs it — read them from memory or the environment, and pass them to scripts as arguments rather than defaulting to your own), and no credentials in the directory. They are written in the product rather than in any one plugin repository's README, because a plugin outlives the repository it was published in.
diff --git a/changelog/unreleased/2026-10-01-plugin-directory.zh.md b/changelog/unreleased/2026-10-01-plugin-directory.zh.md
new file mode 100644
index 00000000..14441df9
--- /dev/null
+++ b/changelog/unreleased/2026-10-01-plugin-directory.zh.md
@@ -0,0 +1,28 @@
+# 插件:插件库可以从 zip 或地址装入一个插件,也能把它导出为 zip、删除,两个对话框同时写明导入与编写规则
+
+- **Date:** 2026-10-01
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#943](https://github.com/Prism-Shadow/penguin-harness/pull/943)
+
+[English](2026-10-01-plugin-directory.md)
+
+插件市场页在构建自带的包之外多了一个插件目录:管理员可以从本地 zip 或一个地址把插件装进去,插件库像对待其他插件一样列出它,它的卡片可以再导出成 zip 或删除。两个导入对话框都写明导入接受什么,以及一个插件必须是什么样。
+
+## 装入插件目录
+
+路由是 `POST /api/plugins/upload`(zip 随请求提交)与 `POST /api/plugins/download`(由服务端抓取一个地址),两者都仅限管理员——这个目录属于整个安装而不是某个 Project,而且装进来的插件,其钩子脚本会以服务端自己的权限运行,因此这是「给机器装东西」那一档的能力。`GET /api/plugins/directory` 读取目录那一行,`GET /api/plugins/:plugin/archive` 供任何已登录用户把用户插件导出为 zip,`DELETE /api/plugins/:plugin` 删除一个。
+
+压缩包分两遍读,因为压缩包不一定是插件:先在中央目录里扫出全部条目名——不解压任何内容——定位插件根,之后才只解压该根之下的文件。插件根是最浅一层含 `plugin.json` 的目录,同一层出现两个就拒绝而不是猜一个;根之外的内容一律忽略,因此一个把插件包在仓库里的 checkout 装进来的是插件,而不是仓库。GitHub 的 tree 地址(`…/tree/<ref>/<subdir>`)把搜索限制到该子目录,且按路径尾段匹配,因为压缩包自带的那层 `<repo>-<ref>/` 是托管方套上去的。上限卡的是插件而不是它所在的那个压缩包:插件根之下 200 个文件、单文件 5 MB、合计 20 MB,此外上传的 zip 不超过 14 MB,下载的归档不超过 32 MB。
+
+插件名依次取:管理员填的名字、地址自带的名字(目录地址取末段、仓库地址取仓库名、zip 链接取文件名)、插件根的目录名;必须匹配 `^[A-Za-z0-9_-]+$`,因为它就是插件落地的那层目录。内置插件已占用的名字会被拒绝——否则加载器会继续跑内置的那一份——而同名用户插件在请求带上 `overwrite: true` 之前一律答 `409 plugin_exists`,对话框用一个确认去取这个标志,而不是让管理员再选一次文件。写入任何一个字节之前,每个条目的路径都过一遍 zip-slip 检查,清单则由插件库自己的读取器校验。
+
+安装是一次带暂存的替换,形状与 Skill 安装相同:文件先落进一个以点开头的暂存目录(加载器的扫描会跳过它),再通过插件库自己的读取器读回——读不出来的目录在提交之前就被拒绝,而不是装完之后被静默跳过——最后用一次 rename 顶替真正的目录。暂存目录会先清空,因此中断的安装留下的残留不会被并进下一次。插件库每次都从磁盘读取、不做任何缓存,所以导入的插件在请求返回的那一刻就已经在列表里、可以安装:不重启,也不需要失效任何东西。
+
+## 页面上的用户插件目录
+
+`<root>/plugins` 下一个插件一个目录,布局与插件包完全一致——`plugin.json`、`icon.svg`、`skills/`、`hooks/`——因此加载器不需要第二种格式,这里来的插件与内置插件一样安装、更新、卸载。页面在标题下方标出该目录,带复制按钮与其中插件的数量;来自这里的卡片在**内置**旁边带一个**用户**标签。这样的卡片可以导出为 zip;删除会在确认之后把它的目录从磁盘移除,不可恢复。导入与删除是管理员能看见而普通成员看不见的操作,页面提示里写明了这一点。
+
+## 规则就放在它所约束的控件旁边
+
+两个对话框末尾是同样的两份清单,因为它们描述的是插件必须以什么形状到达,而不是某一种来源的机制,打开错对话框的管理员也应当看到它们。**插件导入规则**给出可用的来源、插件根在哪里、插件名的取值优先级、大小上限以及同名时的行为——按顺序排列,因为名字的优先级正是 GitHub 仓库地址会踩的坑。**插件编写规则**则写明一个插件对即将发布它的人意味着什么:一个插件一个目录、目录名即插件名,目录里有 `plugin.json` 和 `skills/<技能名>/SKILL.md`,插件里不写账号信息(AppID、密钥、邮箱、手机号都属于使用者——从记忆或环境变量读取,作为参数传给脚本,而不是默认成自己的),目录里不放凭据。它们写在产品里而不是某个插件仓库的 README 里,因为插件比发布它的那个仓库活得久。
diff --git a/packages/core/src/plugins/index.ts b/packages/core/src/plugins/index.ts
index 137031a4..bd5169bf 100644
--- a/packages/core/src/plugins/index.ts
+++ b/packages/core/src/plugins/index.ts
@@ -2,10 +2,19 @@
* PenguinHarness 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).
*
- * A plugin is its own npm package (`@penguinharness/<name>`, `plugins/<name>/` in the repo;
- * resolved through Node from the host package's dependency list — see pluginRoots): 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:
+ * 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,
+ * `@penguinharness/<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
@@ -28,6 +37,7 @@ 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 {
@@ -100,10 +110,15 @@ export interface LibraryHooks {
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). */
@@ -319,7 +334,7 @@ export function workspacePluginRoot(
* 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 pluginRoots(): Map<string, string> {
+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>;
@@ -343,6 +358,49 @@ function pluginRoots(): Map<string, string> {
return roots;
}
+/**
+ * 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.
@@ -436,8 +494,13 @@ interface PluginManifestFile {
};
}
-/** Reads one plugin directory. */
-function readPluginDir(name: string, dir: string): LibraryPlugin {
+/**
+ * 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)) {
@@ -484,6 +547,7 @@ function readPluginDir(name: string, dir: string): LibraryPlugin {
: undefined;
return {
name,
+ source,
description,
...(descriptionZh !== undefined ? { descriptionZh } : {}),
...(shortDescription !== undefined ? { shortDescription } : {}),
@@ -504,29 +568,54 @@ function readPluginDir(name: string, dir: string): LibraryPlugin {
};
}
-/** Reads every plugin in the library (one per plugin package, see pluginRoots), sorted by name. */
-export function loadLibraryPlugins(): LibraryPlugin[] {
- return [...pluginRoots()]
- .map(([name, dir]) => readPluginDir(name, dir))
- .sort((a, b) => a.name.localeCompare(b.name));
+/**
+ * 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(): LibraryPlugin[] {
- return loadLibraryPlugins().filter((plugin) => plugin.preinstall);
+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 (names are looked up, never joined into a path). */
-export function libraryPlugin(name: string): LibraryPlugin | undefined {
- const dir = pluginRoots().get(name);
- return dir !== undefined ? readPluginDir(name, dir) : undefined;
+/** 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()) {
+ for (const plugin of loadLibraryPlugins(root)) {
const skill = plugin.skills.find((s) => s.name === name);
if (skill) return { plugin, skill };
}
@@ -570,6 +659,6 @@ export function groupPlugins(all: LibraryPlugin[]): ResolvedPluginGroup[] {
}
/** Reads the library and groups it (see groupPlugins). */
-export function loadPluginGroups(): ResolvedPluginGroup[] {
- return groupPlugins(loadLibraryPlugins());
+export function loadPluginGroups(root: string = resolveRoot()): ResolvedPluginGroup[] {
+ return groupPlugins(loadLibraryPlugins(root));
}
diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.ts
index 0397ce2e..fe631abc 100644
--- a/packages/core/src/state/agent-state.ts
+++ b/packages/core/src/state/agent-state.ts
@@ -238,7 +238,7 @@ export async function loadAgentState(opts?: {
// reads SKILL.md with shell and follows it. Hook packages run at the loop's hook points.
const plugins =
preset === undefined && agentId === DEFAULT_AGENT_ID
- ? loadPreinstalledPlugins()
+ ? loadPreinstalledPlugins(root)
: (preset?.plugins ?? []);
await Promise.all([
atomicWriteFile(agentsMdPath(root, projectId, agentId), agentsMd, { followSymlinks: true }),
@@ -271,7 +271,7 @@ export async function provisionProjectAgents(opts?: {
projectId?: string;
}): Promise<string[]> {
const agentIds: string[] = [];
- for (const { agentId, preset } of builtinProjectAgentPresets()) {
+ for (const { agentId, preset } of builtinProjectAgentPresets(opts?.root)) {
await loadAgentState({
...(opts?.root !== undefined ? { root: opts.root } : {}),
...(opts?.projectId !== undefined ? { projectId: opts.projectId } : {}),
diff --git a/packages/core/src/state/builtin-agents.ts b/packages/core/src/state/builtin-agents.ts
index fedd7c26..5e46e4c3 100644
--- a/packages/core/src/state/builtin-agents.ts
+++ b/packages/core/src/state/builtin-agents.ts
@@ -35,14 +35,16 @@ export interface AgentPreset {
* created; an existing Agent is never overwritten). The only builtin Agent is default_agent:
* installs the library's preinstalled plugins, with no preset AGENTS.md.
*/
-export function builtinProjectAgentPresets(): Array<{ agentId: string; preset: AgentPreset }> {
+export function builtinProjectAgentPresets(
+ root?: string,
+): Array<{ agentId: string; preset: AgentPreset }> {
return [
{
agentId: DEFAULT_AGENT_ID,
preset: {
name: "General Agent",
description: "General-purpose agent that completes the user's requests with its tools.",
- plugins: loadPreinstalledPlugins(),
+ plugins: loadPreinstalledPlugins(root),
},
},
];
diff --git a/packages/core/src/state/index.ts b/packages/core/src/state/index.ts
index 5d0b3e50..72ec8836 100644
--- a/packages/core/src/state/index.ts
+++ b/packages/core/src/state/index.ts
@@ -14,6 +14,7 @@ export * from "./model-catalog.js";
export * from "./command-policy-defaults.js";
export * from "./project-config.js";
export * from "./agent-state.js";
+export * from "./plugin-store.js";
export * from "./agent-vault.js";
export * from "./memory.js";
export * from "./example-benchmark.js";
diff --git a/packages/core/src/state/paths.ts b/packages/core/src/state/paths.ts
index bc31ab0b..16e4211f 100644
--- a/packages/core/src/state/paths.ts
+++ b/packages/core/src/state/paths.ts
@@ -29,6 +29,20 @@ export function projectDir(root: string, projectId: string): string {
return path.join(root, projectId);
}
+/**
+ * `<root>/plugins`: the user plugin directory — the library's second source, beside the
+ * `@penguinharness/*` packages the build ships (see plugins/index.ts). One directory per
+ * plugin, laid out exactly like a library plugin package (`plugin.json`, `icon.svg`, `skills/`,
+ * `hooks/`), put there by a remote download or a local upload rather than by the installer. It
+ * is a peer of the Project directories rather than something inside one: a plugin is part of
+ * the installation, shared by every Project on the machine, so anything in it is read by every
+ * Project's library and installed on an Agent the same way a built-in is. Doesn't exist until
+ * the first import.
+ */
+export function userPluginsDir(root: string): string {
+ return path.join(root, "plugins");
+}
+
/**
* `<projectDir>/agents` from an already-resolved Project directory path — the single
* definition point of the agents-container layout.
diff --git a/packages/core/src/state/plugin-store.ts b/packages/core/src/state/plugin-store.ts
new file mode 100644
index 00000000..9110c5d9
--- /dev/null
+++ b/packages/core/src/state/plugin-store.ts
@@ -0,0 +1,101 @@
+/**
+ * The user plugin directory (`<root>/plugins`): the library's second source beside the
+ * `@penguinharness/*` packages the build ships (see plugins/index.ts). One directory per
+ * plugin, laid out exactly like a plugin package — `plugin.json`, `icon.svg`, `skills/`,
+ * `hooks/` — so the loader needs no second format: these are the writers a remote download and
+ * a local upload go through, and the remover the management UI's delete calls.
+ *
+ * Installing is a staged swap, the same shape as a Skill install: the files land in a
+ * dot-prefixed staging directory (never a valid plugin name, so the loader's scan skips it),
+ * are read back through the library's own reader — a directory that would not load is rejected
+ * before it is committed rather than installed and silently skipped afterwards — and only then
+ * replace the real directory in one rename. The staging directory is cleared first, so a
+ * leftover from an interrupted install is never merged into this one. The window between
+ * removing the old directory and the rename is the one case this cannot make atomic; it is
+ * bounded by a single rm and leaves the plugin absent rather than half-written.
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { PLUGIN_NAME_PATTERN, readPluginDir } from "../plugins/index.js";
+import type { LibraryPlugin } from "../plugins/index.js";
+import { userPluginsDir } from "./paths.js";
+
+/** Rejects anything that is not a plugin name — the same rule the library's scan applies, restated where a write happens (a name is joined into a path, never trusted). */
+function assertPluginName(name: string): void {
+ if (!PLUGIN_NAME_PATTERN.test(name)) {
+ throw new Error(`Invalid plugin name: ${JSON.stringify(name)}`);
+ }
+}
+
+/** Rejects a file path that would land outside the plugin directory (a zip's entry path arrives here as given). */
+function assertRelativePath(rel: string): void {
+ if (
+ rel === "" ||
+ rel.includes("\\") ||
+ rel.startsWith("/") ||
+ /^[A-Za-z]:/.test(rel) ||
+ rel.split("/").some((segment) => segment === "" || segment === "." || segment === "..")
+ ) {
+ throw new Error(`Invalid plugin file path: ${JSON.stringify(rel)}`);
+ }
+}
+
+/** Whether a user plugin of this name is installed there (its directory exists). */
+export async function userPluginInstalled(root: string, name: string): Promise<boolean> {
+ assertPluginName(name);
+ try {
+ return (await fs.stat(path.join(userPluginsDir(root), name))).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Installs (or replaces) one user plugin from `files` (path relative to the plugin directory →
+ * content). Returns the plugin as the library reads it back; throws when the files are not a
+ * plugin (no `plugin.json`, an unreadable manifest, a version that is not `YYYY.MM.DD.N`) or a
+ * path escapes the directory, and leaves nothing behind in either case.
+ *
+ * Replacement is unconditional: whether an import may overwrite an existing plugin is the
+ * caller's rule (the API answers 409 unless the request asks for it), not the store's.
+ */
+export async function installUserPlugin(
+ root: string,
+ name: string,
+ files: Record<string, string | Uint8Array>,
+): Promise<LibraryPlugin> {
+ assertPluginName(name);
+ const dir = path.join(userPluginsDir(root), name);
+ const staging = path.join(userPluginsDir(root), `.${name}.incoming`);
+ await fs.mkdir(userPluginsDir(root), { recursive: true });
+ await fs.rm(staging, { recursive: true, force: true });
+ await fs.mkdir(staging, { recursive: true });
+ try {
+ for (const [rel, data] of Object.entries(files)) {
+ assertRelativePath(rel);
+ const file = path.join(staging, rel);
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ await fs.writeFile(file, data);
+ }
+ const plugin = readPluginDir(name, staging, "user");
+ await fs.rm(dir, { recursive: true, force: true });
+ await fs.rename(staging, dir);
+ return plugin;
+ } catch (err) {
+ await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined);
+ throw err;
+ }
+}
+
+/** Removes one user plugin's directory; false when there was nothing to remove (an uninstall is idempotent). */
+export async function removeUserPlugin(root: string, name: string): Promise<boolean> {
+ assertPluginName(name);
+ const dir = path.join(userPluginsDir(root), name);
+ try {
+ if (!(await fs.stat(dir)).isDirectory()) return false;
+ } catch {
+ return false;
+ }
+ await fs.rm(dir, { recursive: true, force: true });
+ return true;
+}
diff --git a/packages/core/test/plugin-store.test.ts b/packages/core/test/plugin-store.test.ts
new file mode 100644
index 00000000..e0ce046f
--- /dev/null
+++ b/packages/core/test/plugin-store.test.ts
@@ -0,0 +1,158 @@
+/**
+ * The user plugin directory (`<data root>/plugins`): the library's second source — what an
+ * import writes, what the loader reads back from it (source "user"), what a bad directory does
+ * (skipped, never fatal) and how a name that collides with a built-in is resolved.
+ */
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { libraryPlugin, loadLibraryPlugins, userPluginRoots } from "../src/plugins/index.js";
+import {
+ installUserPlugin,
+ removeUserPlugin,
+ userPluginInstalled,
+ userPluginsDir,
+} from "../src/state/index.js";
+
+let tmpRoot: string;
+let prevHome: string | undefined;
+
+beforeEach(async () => {
+ prevHome = process.env.PENGUIN_HOME;
+ tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-plugin-store-"));
+ process.env.PENGUIN_HOME = tmpRoot;
+});
+
+afterEach(async () => {
+ if (prevHome === undefined) {
+ delete process.env.PENGUIN_HOME;
+ } else {
+ process.env.PENGUIN_HOME = prevHome;
+ }
+ await fs.rm(tmpRoot, { recursive: true, force: true });
+});
+
+/** A minimal but complete plugin: manifest, icon and one skill (the reader requires the SKILL.md frontmatter name). */
+function pluginFiles(version = "2026.09.01.1"): Record<string, string> {
+ return {
+ "plugin.json": `${JSON.stringify(
+ {
+ description: "A plugin installed from outside the build.",
+ short_description: "Imported plugin.",
+ version,
+ category: "software-development",
+ },
+ null,
+ 2,
+ )}\n`,
+ "icon.svg": '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"></svg>\n',
+ "skills/imported-skill/SKILL.md":
+ "---\nname: imported-skill\ndescription: A skill the plugin ships.\n---\n\nBody.\n",
+ };
+}
+
+const installedDir = (name: string): string => path.join(userPluginsDir(tmpRoot), name);
+
+describe("installUserPlugin", () => {
+ it("writes the plugin directory and reads it back as a library plugin of the user source", async () => {
+ const plugin = await installUserPlugin(tmpRoot, "imported", pluginFiles());
+ expect(plugin).toMatchObject({
+ name: "imported",
+ source: "user",
+ version: "2026.09.01.1",
+ category: "software-development",
+ preinstall: true,
+ });
+ // The manifest's UI fields are stamped onto the skill the way a built-in's are.
+ expect(plugin.skills.map((s) => s.name)).toEqual(["imported-skill"]);
+ expect(plugin.skills[0]?.shortDescription).toBe("Imported plugin.");
+ expect(plugin.skills[0]?.content).toContain("description: A skill the plugin ships.");
+ expect(plugin.icon).toContain("<svg");
+ // On disk: the archive's paths, verbatim, under <root>/plugins/<name>/.
+ await expect(fs.readFile(installedDir("imported") + "/plugin.json", "utf8")).resolves.toContain(
+ "2026.09.01.1",
+ );
+ // And the library every other surface reads now carries it.
+ expect(libraryPlugin("imported")?.source).toBe("user");
+ expect(loadLibraryPlugins().map((p) => p.name)).toContain("imported");
+ await expect(userPluginInstalled(tmpRoot, "imported")).resolves.toBe(true);
+ });
+
+ it("replaces an existing install whole: a file the new copy does not ship is gone", async () => {
+ await installUserPlugin(tmpRoot, "imported", {
+ ...pluginFiles(),
+ "skills/stale/SKILL.md": "---\nname: stale\ndescription: Not shipped any more.\n---\n",
+ });
+ await installUserPlugin(tmpRoot, "imported", pluginFiles("2026.09.02.1"));
+ await expect(
+ fs.access(path.join(installedDir("imported"), "skills", "stale", "SKILL.md")),
+ ).rejects.toThrow();
+ expect(libraryPlugin("imported")?.version).toBe("2026.09.02.1");
+ });
+
+ it("rejects files that are not a plugin, leaving neither the directory nor its staging behind", async () => {
+ const noManifest = { ...pluginFiles() } as Record<string, string>;
+ delete noManifest["plugin.json"];
+ await expect(installUserPlugin(tmpRoot, "broken", noManifest)).rejects.toThrow();
+ // A version the library does not accept is the manifest's only hard rule.
+ await expect(installUserPlugin(tmpRoot, "broken", pluginFiles("1"))).rejects.toThrow(
+ /YYYY\.MM\.DD\.N/,
+ );
+ await expect(fs.stat(installedDir("broken"))).rejects.toThrow();
+ await expect(fs.stat(path.join(userPluginsDir(tmpRoot), ".broken.incoming"))).rejects.toThrow();
+ });
+
+ it("refuses a file path that would land outside the plugin directory", async () => {
+ await expect(
+ installUserPlugin(tmpRoot, "escapee", {
+ ...pluginFiles(),
+ "../outside.txt": "not inside",
+ }),
+ ).rejects.toThrow(/Invalid plugin file path/);
+ await expect(fs.stat(path.join(userPluginsDir(tmpRoot), "outside.txt"))).rejects.toThrow();
+ });
+
+ it("refuses a name that is not a plugin name", async () => {
+ await expect(installUserPlugin(tmpRoot, "../evil", pluginFiles())).rejects.toThrow(
+ /Invalid plugin name/,
+ );
+ });
+});
+
+describe("the loader over the user plugin directory", () => {
+ it("keeps a broken user directory out of the library without breaking it, and still lists it as installed", async () => {
+ await installUserPlugin(tmpRoot, "imported", pluginFiles());
+ // A directory left there by hand (an interrupted copy, a hand-edited manifest) must not
+ // take the whole library down with it.
+ const broken = path.join(userPluginsDir(tmpRoot), "handmade");
+ await fs.mkdir(broken, { recursive: true });
+ await fs.writeFile(path.join(broken, "plugin.json"), "{ not json", "utf8");
+ expect(loadLibraryPlugins().map((p) => p.name)).toContain("imported");
+ expect(libraryPlugin("handmade")).toBeUndefined();
+ // The scan still sees it — the management listing is how its owner gets rid of it.
+ expect([...userPluginRoots(tmpRoot).keys()]).toEqual(["handmade", "imported"]);
+ });
+
+ it("never lets a user plugin shadow a built-in of the same name", async () => {
+ await installUserPlugin(tmpRoot, "goal", {
+ ...pluginFiles(),
+ "plugin.json": JSON.stringify({
+ description: "Not the built-in goal.",
+ version: "2099.01.01.1",
+ }),
+ });
+ expect(libraryPlugin("goal")?.source).toBe("builtin");
+ expect(libraryPlugin("goal")?.description).not.toBe("Not the built-in goal.");
+ });
+});
+
+describe("removeUserPlugin", () => {
+ it("deletes the directory and is idempotent", async () => {
+ await installUserPlugin(tmpRoot, "imported", pluginFiles());
+ await expect(removeUserPlugin(tmpRoot, "imported")).resolves.toBe(true);
+ await expect(fs.stat(installedDir("imported"))).rejects.toThrow();
+ expect(libraryPlugin("imported")).toBeUndefined();
+ await expect(removeUserPlugin(tmpRoot, "imported")).resolves.toBe(false);
+ });
+});
diff --git a/packages/core/test/plugins.test.ts b/packages/core/test/plugins.test.ts
index dce8d444..6415ff0a 100644
--- a/packages/core/test/plugins.test.ts
+++ b/packages/core/test/plugins.test.ts
@@ -8,7 +8,7 @@ import { existsSync } from "node:fs";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import { describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
PLUGIN_CATEGORIES,
PLUGIN_VERSION_PATTERN,
@@ -27,9 +27,33 @@ import {
const pluginsRoot = path.resolve(import.meta.dirname, "../../../plugins");
+/**
+ * The library also reads the user plugin directory at `resolveRoot()/plugins`, so every test
+ * here points the data root at an empty temp directory: what loads is the repo's own library,
+ * never whatever this machine has imported (see test/plugin-store.test.ts for those).
+ */
+let tmpRoot: string;
+let prevHome: string | undefined;
+
+beforeEach(async () => {
+ prevHome = process.env.PENGUIN_HOME;
+ tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-plugins-"));
+ process.env.PENGUIN_HOME = tmpRoot;
+});
+
+afterEach(async () => {
+ if (prevHome === undefined) {
+ delete process.env.PENGUIN_HOME;
+ } else {
+ process.env.PENGUIN_HOME = prevHome;
+ }
+ await fs.rm(tmpRoot, { recursive: true, force: true });
+});
+
/** Minimal LibraryPlugin for groupPlugins unit tests. */
const fakePlugin = (name: string, category?: string): LibraryPlugin => ({
name,
+ source: "builtin",
description: `Do ${name}.`,
version: "2026.08.29.1",
preinstall: true,
diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.md
index 8ad01171..d697e755 100644
--- a/packages/docs/content/skills.en.md
+++ b/packages/docs/content/skills.en.md
@@ -7,6 +7,7 @@ A **Skill** is a set of reusable instructions that an agent reads when a task ca
- **Looking for new abilities?** See [Browse plugins](#browse-plugins) and [Install a plugin on an agent](#install-a-plugin-on-an-agent).
- **An update is waiting?** See [Update installed plugins](#update-installed-plugins).
+- **Adding a plugin of your own to the library?** See [Import, export and delete library plugins](#import-export-and-delete-library-plugins).
- **Want the agent to use a specific Skill?** See [Use a Skill in a chat](#use-a-skill-in-a-chat).
- **Managing one agent's Skills and hooks?** See [Manage an agent's Skills](#manage-an-agents-skills) and [Hook packages](#hook-packages).
- **Adding a sandbox backend or another server plugin?** See [Server plugins](#server-plugins).
@@ -70,6 +71,25 @@ To update:
**Dismiss** hides the notice and the sidebar dot until the library version changes again. The update buttons on the cards stay.
+## Import, export and delete library plugins
+
+Beside the plugins PenguinHarness ships, the library lists the plugins in the **user plugin directory**, `<data root>/plugins`. An admin fills it by importing — from a zip file on this machine, or from a URL the server downloads — and an agent can then install those plugins exactly like a built-in one. A plugin from there carries a **User** badge.
+
+To import a plugin, select **Upload plugin** or **Download from URL** in the page header and fill in the dialog:
+
+- **Upload plugin** takes a zip file of at most 14 MB. **Download from URL** takes a direct zip link, a GitHub repository URL (its default branch), or a directory inside one (`…/tree/<ref>/<subdir>`), of at most 32 MB.
+- **Plugin name** is optional. Leave it empty and the plugin is named after the directory inside the archive that holds `plugin.json`; the server refuses the request rather than inventing a name when `plugin.json` sits at the very root of the zip, where there is no directory to take one from.
+- The archive has to be a zip carrying a `plugin.json`. The plugin root is the shallowest directory holding one and everything outside it is ignored, so a whole repository can be handed over and only the plugin inside it is installed. Under the plugin root the caps are 200 files, 5 MB each and 20 MB in total.
+- Both dialogs end with **Plugin import rules**, which state the accepted sources, the order the name is decided in, the size caps and what happens when the name is taken.
+
+Importing a name a built-in plugin already holds is refused — pick another. Importing a name a user plugin already holds asks you to confirm first, and overwriting replaces every one of its files, local edits included.
+
+The directory belongs to the installation rather than to a Project, and an installed plugin's hook scripts run with the server's own rights, so importing and deleting are an admin's. Exporting is not: **Export plugin** on a user plugin's card downloads the plugin as a zip, which is also how you take a backup of one.
+
+**Delete plugin** on the card removes the plugin's directory from disk after a confirmation, and it cannot be recovered. The Skills and hook packages an agent already installed from it are that agent's own copies and stay where they are; uninstall those from **Manage installs** if you want them gone too.
+
+Writing a plugin of your own? Both dialogs also carry **Plugin authoring rules**: one directory per plugin named after it, `plugin.json` and `skills/<skill>/SKILL.md` inside it, no account details in the plugin, and no credentials in the directory. See [Write a Skill](#write-a-skill) and [Plugin file format](#plugin-file-format).
+
## Use a Skill in a chat
An agent sees the name and description of every installed Skill, and reads a Skill's full instructions when a task calls for it. To make sure it uses a particular Skill:
@@ -307,4 +327,5 @@ Installed Skills live under `agent_state/skills/<name>/`, and hook packages unde
- Each install replaces the whole directory, so reinstalling drops files a newer version no longer ships. Reinstalling is how an installed copy is updated.
- Uninstalling deletes the whole `skills/<name>/` or `hooks/<name>/` directory.
- A running Session keeps the hook packages its current model context opened with; the next context, after a compaction or on resume, reads them again. After a hook package is installed, imported or removed through the Web App or the API, or the **Enable hooks** switch changes, the server rebuilds the agent's cached runtimes the next time they are idle, so open conversations pick up the change from their next turn.
+- A user plugin is stored at `<data root>/plugins/<name>/`, laid out like a library plugin package and read on the same terms as one; the library caches nothing, so an imported plugin is in the listing and installable as soon as the import returns. Importing replaces the whole directory in one rename, and deleting removes it, leaving the copies agents already installed untouched.
- Besides the Web App, plugins can be installed through the SDK.
diff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.md
index b9394e67..48b954a3 100644
--- a/packages/docs/content/skills.zh.md
+++ b/packages/docs/content/skills.zh.md
@@ -7,6 +7,7 @@ description: 浏览插件,为 Agent 安装 Skill 和钩子包,为 Project
- **想给 Agent 添加新能力?** 见[浏览插件](#浏览插件)和[在 Agent 上安装插件](#在-agent-上安装插件)。
- **有更新可装?** 见[更新已安装的插件](#更新已安装的插件)。
+- **想把自己的插件加进插件库?** 见[导入、导出与删除插件库中的插件](#导入导出与删除插件库中的插件)。
- **想让 Agent 用上指定的 Skill?** 见[在对话中使用 Skill](#在对话中使用-skill)。
- **要管理某个 Agent 的 Skill 和钩子?** 见[管理 Agent 的 Skill](#管理-agent-的-skill) 和[钩子包](#钩子包)。
- **要添加沙箱后端或其他服务端插件?** 见[服务端插件](#服务端插件)。
@@ -70,6 +71,25 @@ description: 浏览插件,为 Agent 安装 Skill 和钩子包,为 Project
**忽略**会隐藏提示和侧边栏红点,直到插件库版本再次变化。卡片上的更新按钮仍然保留。
+## 导入、导出与删除插件库中的插件
+
+除了 PenguinHarness 自带的插件,插件库还会列出**用户插件目录**(`<数据根>/plugins`)里的插件。管理员通过导入来填充它——导入本机的一个 zip 文件,或导入一个由服务端下载的地址——之后 Agent 就能像安装内置插件一样安装它们。来自这个目录的插件带**用户**标签。
+
+导入插件时,点击页面头部的**上传插件**或**远程下载**,然后在对话框里填写:
+
+- **上传插件**接受不超过 14 MB 的 zip 文件。**远程下载**接受 zip 直链、GitHub 仓库地址(取默认分支)或仓库内目录地址(`…/tree/<ref>/<subdir>`),归档不超过 32 MB。
+- **插件名称**是可选的。留空时,插件名取压缩包内含 `plugin.json` 的那层目录名;如果 `plugin.json` 就放在 zip 根目录、没有目录可供取名,服务端会直接拒绝这次请求,而不是自己编一个名字。
+- 压缩包必须是含 `plugin.json` 的 zip。插件根取其中含 `plugin.json` 的最浅一层目录,根之外的内容一律忽略,因此可以整个仓库交上来、只安装仓库里的那个插件。插件根之下还有上限:200 个文件、单文件 5 MB、合计 20 MB。
+- 两个对话框末尾都是**插件导入规则**,写明可用的来源、插件名的取值顺序、大小上限,以及名字被占用时的行为。
+
+导入一个内置插件已占用的名字会被拒绝,换个名字即可。导入一个用户插件已占用的名字会先要求确认,覆盖会替换它的全部文件,含本地改动。
+
+这个目录属于整个安装而不是某个 Project,而且装进来的插件,其钩子脚本会以服务端自己的权限运行,因此导入与删除都是管理员的操作;导出不是:用户插件卡片上的**导出插件**会把插件下载成 zip,这也是备份它的方式。
+
+卡片上的**删除插件**在确认之后把该插件的目录从磁盘移除,不可恢复。Agent 已经从这个插件安装的 Skill 与钩子包是 Agent 自己的副本,会留在原处;要一并清掉,请在**管理安装**里卸载。
+
+想自己写插件?两个对话框里还有**插件编写规则**:一个插件一个目录、目录名即插件名,目录里有 `plugin.json` 和 `skills/<技能名>/SKILL.md`,插件里不写账号信息,目录里不放凭据。见[编写 Skill](#编写-skill)和[插件文件格式](#插件文件格式)。
+
## 在对话中使用 Skill
Agent 能看到每个已安装 Skill 的名称和描述,任务需要时才读取 Skill 的完整指令。要确保 Agent 使用某个指定 Skill:
@@ -307,4 +327,5 @@ Skill 分两步加载:先加载索引,正文按需读取。
- 每次安装都会整体替换目录,所以重新安装会清掉新版本不再包含的文件。已安装的副本就是靠重新安装来更新的。
- 卸载会删除整个 `skills/<name>/` 或 `hooks/<name>/` 目录。
- 运行中的 Session 沿用当前模型上下文开启时读到的钩子包;下一个上下文(压缩之后或恢复时)会重新读取。经 Web App 或 API 安装、导入或卸载钩子包,或者**启用钩子**开关变动之后,服务端会在 Agent 缓存的运行时下次空闲时重建它们,因此已经打开的对话从下一轮起生效。
+- 用户插件存放在 `<数据根>/plugins/<name>/`,布局与插件库的插件包一致,读取方式也相同;插件库不做任何缓存,因此导入一返回,插件就已经在列表里、可以安装。导入用一次 rename 整体替换该目录,删除则移除它,Agent 已安装的副本不受影响。
- 除 Web App 外,插件也可以通过 SDK 安装。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 3adf42bb..04f59d29 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -3772,8 +3772,18 @@ export interface HookItem {
icon?: string;
}
+/**
+ * Where a library plugin comes from: `builtin` = shipped with the build (the
+ * `@penguinharness/*` packages under the repo's `plugins/`), `user` = installed by an operator
+ * into the user plugin directory (a remote download or a local upload), which is the only kind
+ * the library can also delete again.
+ */
+export type PluginSource = "builtin" | "user";
+
/** One library plugin as the listing describes it: the manifest fields plus what it ships (skill bodies and scripts are never sent). */
export interface PluginItem {
+ /** Where the plugin comes from (see PluginSource); a user plugin of the same name as a built-in is never loaded — the built-in wins. */
+ source: PluginSource;
name: string;
description: string;
descriptionZh?: string;
@@ -3827,6 +3837,64 @@ export interface AgentPluginsInstallResponse {
hooks: HookItem[];
}
+/**
+ * GET /api/plugins/directory: the user plugin directory — where a remote download and a local
+ * upload land, and what "delete" removes from. `plugins` lists the names found there (each one
+ * a directory carrying plugin.json), sorted; a name that collides with a built-in is listed
+ * here but never loaded (the built-in wins).
+ */
+export interface PluginDirectoryResponse {
+ /** Absolute path of the directory (a plain directory of plugin directories; it may not exist yet). */
+ path: string;
+ /** Names of the plugin directories inside it, sorted. */
+ plugins: string[];
+}
+
+/** What an import (upload or download) put into the library: the plugin as the listing describes it, plus where it landed. */
+export interface PluginImportResponse {
+ plugin: PluginItem;
+ /** Absolute path of the installed plugin directory. */
+ path: string;
+}
+
+/**
+ * POST /api/plugins/upload: install a plugin from an uploaded zip archive. Layout: plugin.json
+ * at the archive root, or anywhere inside it (the shallowest directory carrying plugin.json is
+ * the plugin root — one, unambiguous). `name` overrides the name the installer would pick (the
+ * plugin root's directory name) and is required when plugin.json sits at the archive root;
+ * `overwrite` replaces an existing user plugin of that name. Admin-only.
+ *
+ * Errors, shared with the download route below: 403 `admin_required`, 404 `unknown_plugin`
+ * (delete only), 409 `plugin_exists` (`overwrite` was not set) and `plugin_builtin` (the name is
+ * one the build ships), 413 `plugin_too_large`, 400 `invalid_plugin` (the name is not a plugin
+ * name, or the manifest does not read as one) and 400 `bad_request` for everything else the
+ * archive can be wrong about (not a zip, no plugin.json, two plugins, name required, an entry
+ * path that would escape the directory).
+ */
+export interface PluginUploadRequest {
+ dataBase64: string;
+ name?: string;
+ overwrite?: boolean;
+}
+
+/**
+ * POST /api/plugins/download: the same import, fetched server-side from a URL. Accepts a zip
+ * archive, a GitHub repository URL (`https://github.com/<owner>/<repo>`, the default branch) or
+ * a GitHub tree URL (`…/tree/<ref>/<subdir>` — `subdir` picks the plugin root inside the
+ * archive), and answers the same errors as the upload route above, plus 400 `unsupported_url`
+ * (not an http(s) URL, or a GitHub page that is not a repository or tree), 400 `blocked_url`
+ * (a loopback, private or link-local host) and 400 `download_failed` (the request or its
+ * status). Admin-only.
+ */
+export interface PluginDownloadRequest {
+ url: string;
+ /** Overrides the derived plugin name. */
+ name?: string;
+ /** Path inside the archive the plugin root must live under (a `/tree/<ref>/<subdir>` URL fills it in). */
+ subdir?: string;
+ overwrite?: boolean;
+}
+
/** GET /api/projects/:p/agents/:a/skills: Skills installed on this Agent. */
export interface AgentSkillsResponse {
skills: SkillMetadataItem[];
diff --git a/packages/server/src/http/routes/plugins.ts b/packages/server/src/http/routes/plugins.ts
index d543579e..b55d4daa 100644
--- a/packages/server/src/http/routes/plugins.ts
+++ b/packages/server/src/http/routes/plugins.ts
@@ -1,11 +1,26 @@
/**
- * Plugins: the library this build ships, the registry a deployment lists, and what an
- * Agent has installed.
+ * Plugins: the library this build ships, the user plugin directory an operator installs into,
+ * the registry a deployment lists, and what an Agent has installed.
* GET /api/plugins # the built-in library by category (any logged-in user)
+ * GET /api/plugins/directory # the user plugin directory (any logged-in user)
+ * POST /api/plugins/upload # install a plugin from an uploaded zip (admin)
+ * POST /api/plugins/download # install a plugin fetched from a URL (admin)
* GET /api/plugins/:plugin/files # the files a library plugin ships, for the detail view's browser
+ * GET /api/plugins/:plugin/archive # export a plugin as a zip (any logged-in user)
+ * DELETE /api/plugins/:plugin # uninstall a user plugin (admin)
* GET /api/plugins/registry # the merged plugin index: the builtin entries and the published ones
* GET /api/plugins/registry/readme?name=… # one indexed entry's long-form readme
* POST /api/projects/:p/agents/:a/plugins # install plugins from the library (any member)
+ *
+ * The import and delete routes write inside the user plugin directory, which is part of the
+ * installation rather than of a Project — that is what makes them admin-only (machines.ts is
+ * the same call) and what makes them take no projectId. They need no restart and no
+ * invalidation of anything: the library is read from disk on every request (core's plugin
+ * loader caches nothing), so an imported plugin is in the listing and installable the moment
+ * the request returns. A name the build already ships is refused rather than shadowed — the
+ * loader would go on serving the built-in — and `overwrite` is what says a same-named *user*
+ * plugin may be replaced.
+ *
* Installing a plugin writes each of its skills to agent_state/skills/<name>/ and its hook
* package to agent_state/hooks/<plugin>/ (hooks.json + scripts); reinstalling overwrites with
* library content (i.e. an update). Installed skills and hook packages keep their own routes
@@ -15,17 +30,28 @@
* hooks. The library is what this build carries; the registry is what the deployment can
* fetch. Both are deployment-global (no Project check); only installing touches an Agent.
*/
+import path from "node:path";
+import { strToU8, unzipSync, zipSync } from "fflate";
import { Hono } from "hono";
+import type { Context } from "hono";
import {
+ PLUGIN_NAME_PATTERN,
installPlugin,
+ installUserPlugin,
+ libraryPlugin,
listInstalledHooks,
listInstalledSkills,
- libraryPlugin,
loadPluginGroups,
+ removeUserPlugin,
+ userPluginInstalled,
+ userPluginRoots,
+ userPluginsDir,
} from "@prismshadow/penguin-core";
import type {
AgentPluginsInstallResponse,
+ PluginDirectoryResponse,
PluginFilesResponse,
+ PluginImportResponse,
PluginIndexResponse,
PluginLibraryResponse,
PluginReadmeResponse,
@@ -50,19 +76,35 @@ export interface PluginsRouteDeps {
manager: ManagerIface;
}
import { HttpError } from "../errors.js";
-import { badRequest, optionalStringArray, readJson, requireValidId } from "../validate.js";
import {
+ badRequest,
+ optionalBoolean,
+ optionalString,
+ optionalStringArray,
+ readJson,
+ requireString,
+ requireValidId,
+} from "../validate.js";
+import {
+ pluginArchiveFiles,
pluginFiles,
resolveLibraryPlugins,
toHookItem,
toPluginItem,
toSkillItem,
} from "../../services/plugin-library.js";
+import {
+ fetchPluginArchive,
+ normalizePluginUrl,
+ pluginArchiveTooLarge,
+} from "../../services/plugin-download.js";
+import { assertSafeEntryPath, MAX_ARCHIVE_BYTES } from "./skills.js";
+import { unzipBounded } from "../../services/skill-import-limits.js";
/** Library listing: the files are the source of truth — read fresh on every request (small files, infrequent requests, no caching). */
-function libraryResponse(): PluginLibraryResponse {
+function libraryResponse(root: string): PluginLibraryResponse {
return {
- groups: loadPluginGroups().map((group) => ({
+ groups: loadPluginGroups(root).map((group) => ({
id: group.id,
title: group.title,
...(group.titleZh !== undefined ? { titleZh: group.titleZh } : {}),
@@ -71,20 +113,306 @@ function libraryResponse(): PluginLibraryResponse {
};
}
+/**
+ * The guard on everything that writes the user plugin directory. It is an installation-level
+ * resource — every Project reads it, and an installed plugin's hook scripts run with the
+ * server's own rights once an Agent runs them — so the capability is the admin's rather than a
+ * Project owner's, the way installing to a machine is.
+ */
+function requireAdmin(c: Context<AppEnv>): void {
+ if (!c.var.user.isAdmin) {
+ throw new HttpError(403, "admin_required", "Only an admin can manage the plugin directory.");
+ }
+}
+
+/** A plugin archive decoded and located: the name it installs under, and every file of the plugin root keyed by path relative to it. */
+export interface ParsedPluginArchive {
+ name: string;
+ files: Record<string, Uint8Array>;
+}
+
+/**
+ * Every entry name in an archive, in central-directory order, without inflating a byte: the
+ * filter refuses each entry as it is offered, and fflate stops there. That is what makes the
+ * two-pass read above cheap — locating the plugin root costs a directory scan, not an unpack.
+ */
+function entryNames(archive: Uint8Array): string[] {
+ const names: string[] = [];
+ unzipSync(archive, {
+ filter: (entry) => {
+ names.push(entry.name);
+ return false;
+ },
+ });
+ return names;
+}
+
+/** How deep a plugin root path is ("" is the archive root, i.e. depth 0). */
+function pathDepth(dir: string): number {
+ return dir === "" ? 0 : dir.split("/").length;
+}
+
+/**
+ * The plugin root inside an archive: the shallowest directory carrying `plugin.json`, which has
+ * to be the only directory at that depth — an archive holding two plugins is ambiguous and
+ * refused rather than guessed at. `plugin.json` at the archive root is depth 0 and therefore
+ * always wins, and everything outside the root is ignored (an archive may carry a README, a
+ * LICENSE or a whole monorepo beside the plugin).
+ *
+ * `subdir` narrows the search to a directory at the end of that path, the way a GitHub tree URL
+ * (`…/tree/<ref>/plugins/x`) names one: the archive's own top-level `<repo>-<ref>/` directory is
+ * whatever the host wrapped it in, so the match is on the tail, not on the whole path.
+ */
+function pluginRootIn(paths: readonly string[], subdir: string): string {
+ const dirs = new Set<string>();
+ for (const filePath of paths) {
+ if (filePath !== "plugin.json" && !filePath.endsWith("/plugin.json")) continue;
+ const dir = filePath.slice(0, filePath.length - "plugin.json".length).replace(/\/$/, "");
+ if (subdir !== "" && dir !== subdir && !dir.endsWith(`/${subdir}`)) continue;
+ dirs.add(dir);
+ }
+ if (dirs.size === 0) {
+ throw badRequest(
+ subdir === ""
+ ? "The archive carries no plugin.json — it is not a plugin."
+ : `The archive carries no plugin.json under ${subdir}.`,
+ );
+ }
+ const sorted = [...dirs].sort((a, b) => pathDepth(a) - pathDepth(b) || a.localeCompare(b));
+ const root = sorted[0]!;
+ if (sorted.length > 1 && pathDepth(sorted[1]!) === pathDepth(root)) {
+ throw badRequest(
+ `The archive carries more than one plugin (${sorted.filter((d) => pathDepth(d) === pathDepth(root)).join(", ")}).`,
+ );
+ }
+ return root;
+}
+
+/**
+ * Decodes an uploaded or downloaded archive into the files of one plugin. Everything a client
+ * supplies is checked here, before a byte is written: the zip's declared sizes through
+ * `unzipBounded` (which is where the caps have to be enforced — see that module), every entry
+ * path against zip-slip, the plugin root's ambiguity, and the name against the plugin-name
+ * rule. Directories the archive declares are skipped: the paths of the files recreate them.
+ */
+export function parsePluginArchive(
+ archive: Buffer,
+ options: { name?: string; subdir?: string } = {},
+): ParsedPluginArchive {
+ // Two passes, because an archive is not necessarily a plugin: a GitHub tree download is a
+ // whole repository with one plugin somewhere inside it. The first pass reads the central
+ // directory alone — every entry name, nothing inflated — to find the plugin root; the second
+ // inflates that root's files only. So the caps bound the PLUGIN (200 files, 5MB each, 20MB
+ // total, the same numbers an upload of a single plugin gets) instead of failing on the
+ // repository that happens to be wrapped around it, and a hundred-megabyte checkout is never
+ // expanded to serve a thirty-file plugin.
+ const bytes = new Uint8Array(archive);
+ let names: string[];
+ try {
+ names = entryNames(bytes);
+ } catch {
+ throw badRequest("The archive is not a valid zip file.");
+ }
+ if (names.length === 0) throw badRequest("The archive contains no files.");
+ const root = pluginRootIn(names, options.subdir ?? "");
+ const prefix = root === "" ? "" : `${root}/`;
+ let entries: Record<string, Uint8Array>;
+ try {
+ entries = unzipBounded(bytes, (name) => prefix === "" || name.startsWith(prefix));
+ } catch (err) {
+ // The caps arrive as 400s of their own; anything else means the bytes are not a zip.
+ if (err instanceof HttpError) throw err;
+ throw badRequest("The archive is not a valid zip file.");
+ }
+ const rootFiles: Record<string, Uint8Array> = {};
+ for (const [entry, data] of Object.entries(entries)) {
+ if (entry.endsWith("/")) continue;
+ assertSafeEntryPath(entry);
+ rootFiles[entry.slice(prefix.length)] = data;
+ }
+ // The archive's own layout names the plugin unless the request says otherwise; an archive
+ // with plugin.json at its root has no directory to take a name from.
+ const name = options.name ?? (root === "" ? undefined : path.basename(root));
+ if (name === undefined) {
+ throw badRequest("name is required when the archive carries plugin.json at its root.");
+ }
+ if (!PLUGIN_NAME_PATTERN.test(name)) {
+ throw new HttpError(400, "invalid_plugin", `Not a valid plugin name: ${name}`);
+ }
+ return { name, files: rootFiles };
+}
+
+/**
+ * Installs a parsed archive into the user plugin directory and answers what the library now
+ * carries. The two refusals come first, before anything is written: a built-in name (the loader
+ * would go on serving the built-in, so the import would be invisible), and an existing user
+ * plugin without `overwrite` (409 — replacing is an explicit decision, the user's copy may
+ * carry local edits).
+ *
+ * The directory is `<config.root>/plugins`, the same one the library reads: the server's data
+ * root and the library's user plugin root are one directory, both defined by PENGUIN_HOME.
+ */
+async function importPlugin(
+ deps: PluginsRouteDeps,
+ parsed: ParsedPluginArchive,
+ overwrite: boolean,
+): Promise<PluginImportResponse> {
+ const root = deps.config.root;
+ if (libraryPlugin(parsed.name, deps.config.root)?.source === "builtin") {
+ throw new HttpError(
+ 409,
+ "plugin_builtin",
+ `${parsed.name} is a built-in plugin; it cannot be replaced (import it under another name).`,
+ );
+ }
+ if (!overwrite && (await userPluginInstalled(root, parsed.name))) {
+ throw new HttpError(
+ 409,
+ "plugin_exists",
+ `A user plugin named ${parsed.name} is already installed.`,
+ );
+ }
+ let plugin;
+ try {
+ plugin = await installUserPlugin(root, parsed.name, parsed.files);
+ } catch (err) {
+ throw new HttpError(
+ 400,
+ "invalid_plugin",
+ `The plugin could not be installed: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ return {
+ plugin: toPluginItem(plugin),
+ path: path.join(userPluginsDir(root), parsed.name),
+ };
+}
+
/** GET /api/plugins (any logged-in user; no Project check). */
-export function pluginLibraryRoutes(): Hono<AppEnv> {
+export function pluginLibraryRoutes(deps: PluginsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
- app.get("/", (c) => c.json(libraryResponse()));
+ app.get("/", (c) => c.json(libraryResponse(deps.config.root)));
+
+ // The user plugin directory itself: its absolute path and what is in it. Readable by anyone
+ // logged in — the library listing shows the same plugins, and this only adds where they live
+ // — because the management line on the plugins page is not an admin's screen.
+ app.get("/directory", (c) =>
+ c.json({
+ path: userPluginsDir(deps.config.root),
+ plugins: [...userPluginRoots(deps.config.root).keys()],
+ } satisfies PluginDirectoryResponse),
+ );
+
+ // Install one plugin from an uploaded zip (admin). The body carries the archive base64 —
+ // the same shape the skill and hook archive routes take — so the request stays JSON
+ // throughout and needs no multipart handling.
+ app.post("/upload", async (c) => {
+ requireAdmin(c);
+ const body = await readJson(c);
+ const dataBase64 = requireString(body, "dataBase64", { minLen: 1, label: "dataBase64" });
+ const archive = Buffer.from(dataBase64, "base64");
+ if (archive.byteLength === 0) throw badRequest("The zip archive is empty.");
+ // The same answer the download path gives (413 `plugin_too_large`), at the cap the transport
+ // allows: this one arrives as base64 inside a JSON body, so it is the skill/hook archive
+ // limit — which is exactly what keeps the encoded request inside the body cap.
+ if (archive.byteLength > MAX_ARCHIVE_BYTES) {
+ throw pluginArchiveTooLarge(MAX_ARCHIVE_BYTES);
+ }
+ const requestedName = optionalString(body, "name", { maxLen: 128 });
+ const parsed = parsePluginArchive(archive, {
+ ...(requestedName !== undefined ? { name: requestedName } : {}),
+ });
+ return c.json(
+ await importPlugin(deps, parsed, optionalBoolean(body, "overwrite") ?? false),
+ 201,
+ );
+ });
+
+ // Install one plugin from a URL the operator names (admin). The whole download runs
+ // server-side: the server is what has the network position to reach it, and the archive is
+ // validated by the same parser the upload route uses, whichever way the bytes arrived.
+ app.post("/download", async (c) => {
+ requireAdmin(c);
+ const body = await readJson(c);
+ const url = requireString(body, "url", { minLen: 1, maxLen: 2048 });
+ const requestedName = optionalString(body, "name", { maxLen: 128 });
+ const requestedSubdir = optionalString(body, "subdir", { maxLen: 512 });
+ const source = normalizePluginUrl(url);
+ const archive = await fetchPluginArchive(source);
+ if (archive.byteLength === 0) throw badRequest("The download is empty.");
+ // What the request says wins over what the URL suggests: a name is what the operator asked
+ // for, a suggestion is what the host happened to call it.
+ const name = requestedName ?? source.name;
+ const parsed = parsePluginArchive(archive, {
+ ...(name !== undefined ? { name } : {}),
+ subdir: requestedSubdir ?? source.subdir,
+ });
+ return c.json(
+ await importPlugin(deps, parsed, optionalBoolean(body, "overwrite") ?? false),
+ 201,
+ );
+ });
+
// Everything one plugin ships, as text keyed by path, for the library detail view's file
// browser (the listing never carries bodies or scripts).
app.get("/:plugin/files", (c) => {
const pluginName = c.req.param("plugin");
- const plugin = libraryPlugin(pluginName);
+ const plugin = libraryPlugin(pluginName, deps.config.root);
if (!plugin) {
throw new HttpError(404, "unknown_plugin", `Plugin is not in the library: ${pluginName}`);
}
return c.json({ files: pluginFiles(plugin) } satisfies PluginFilesResponse);
});
+
+ // Export one plugin as a zip (any logged-in user — it is the content the detail view already
+ // shows, packed for a round trip out). Built-in and user plugins export the same way: the
+ // archive is rebuilt from the library's own view of the plugin, so what comes back in is what
+ // went out.
+ app.get("/:plugin/archive", (c) => {
+ const plugin = libraryPlugin(c.req.param("plugin"), deps.config.root);
+ if (!plugin) {
+ throw new HttpError(
+ 404,
+ "unknown_plugin",
+ `Plugin is not in the library: ${c.req.param("plugin")}`,
+ );
+ }
+ const archiveFiles: Record<string, Uint8Array> = {};
+ for (const [rel, text] of Object.entries(pluginArchiveFiles(plugin))) {
+ archiveFiles[rel] = strToU8(text);
+ }
+ const zip = zipSync(archiveFiles);
+ // The name is the plugin name (validated on the way in, [A-Za-z0-9_-]+), so it is itself
+ // when encoded; scripts.ts reads the file name off Content-Disposition.
+ const fileName =
+ plugin.version === "" ? `${plugin.name}.zip` : `${plugin.name}-v${plugin.version}.zip`;
+ return new Response(new Uint8Array(zip), {
+ headers: {
+ "Content-Type": "application/zip",
+ "Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`,
+ "X-Content-Type-Options": "nosniff",
+ },
+ });
+ });
+
+ // Uninstall one user plugin (admin): the directory is deleted from disk, so the library stops
+ // listing it. A built-in is refused (409) — its files belong to the installation — and a name
+ // that is not there at all is a 404 rather than a silent no-op.
+ app.delete("/:plugin", async (c) => {
+ requireAdmin(c);
+ const pluginName = c.req.param("plugin");
+ if (!PLUGIN_NAME_PATTERN.test(pluginName)) {
+ throw new HttpError(404, "unknown_plugin", `No such plugin: ${pluginName}`);
+ }
+ if (libraryPlugin(pluginName, deps.config.root)?.source === "builtin") {
+ throw new HttpError(409, "plugin_builtin", `${pluginName} is a built-in plugin.`);
+ }
+ if (!(await removeUserPlugin(deps.config.root, pluginName))) {
+ throw new HttpError(404, "unknown_plugin", `No user plugin named ${pluginName}`);
+ }
+ return c.body(null, 204);
+ });
+
return app;
}
@@ -101,7 +429,7 @@ export function agentPluginsRoutes(deps: PluginsRouteDeps): Hono<AppEnv> {
if (names.length === 0) throw badRequest("names must be a non-empty array.");
// Verify every name up front before writing anything: an unknown name rejects the whole
// request rather than leaving a half-installed state.
- const plugins = resolveLibraryPlugins(names);
+ const plugins = resolveLibraryPlugins(names, deps.config.root);
for (const plugin of plugins) {
await installPlugin(deps.config.root, projectId, agentId, plugin);
}
@@ -160,7 +488,7 @@ export class PluginRoutes {
agentConfigService: this.agentConfig,
manager: this.manager,
};
- this.libraryRoutes = pluginLibraryRoutes();
+ this.libraryRoutes = pluginLibraryRoutes(deps);
this.pluginRoutes = agentPluginsRoutes(deps);
this.hookRoutes = agentHooksRoutes(deps);
}
diff --git a/packages/server/src/services/agent-service.ts b/packages/server/src/services/agent-service.ts
index a8c377e0..5e63bb2c 100644
--- a/packages/server/src/services/agent-service.ts
+++ b/packages/server/src/services/agent-service.ts
@@ -132,7 +132,7 @@ export class AgentService implements AgentLifecycle {
// The plugin library is read once for the whole list (every Agent is checked against the
// same files). Meta reads and mtime stats for each Agent run in parallel (Promise.all
// preserves the sorted order).
- const library = loadLibraryPlugins();
+ const library = loadLibraryPlugins(this.root);
const sorted = [...known.values()].sort((a, b) =>
a.createdAt === b.createdAt
? a.agentId.localeCompare(b.agentId)
@@ -291,7 +291,7 @@ export class AgentService implements AgentLifecycle {
agentId: string,
pluginName: string,
): Promise<{ installed: string | null; library: string | null }> {
- const plugin = libraryPlugin(pluginName);
+ const plugin = libraryPlugin(pluginName, this.root);
if (!plugin) return { installed: null, library: null };
const base = skillsDir(this.root, projectId, agentId);
const versions: string[] = [];
@@ -324,7 +324,7 @@ export class AgentService implements AgentLifecycle {
* Session is built, unlike skills, which are read from disk on demand.
*/
async updatePlugin(projectId: string, agentId: string, pluginName: string): Promise<void> {
- for (const plugin of resolveLibraryPlugins([pluginName])) {
+ for (const plugin of resolveLibraryPlugins([pluginName], this.root)) {
await installPlugin(this.root, projectId, agentId, plugin);
}
}
@@ -447,7 +447,7 @@ export class AgentService implements AgentLifecycle {
// installed after the library plugins and so win a name collision: the user picked that
// directory for this Agent specifically, which is a narrower intent than "install the
// built-in one".
- const librarySeed = resolveLibraryPlugins(pluginNames ?? []);
+ const librarySeed = resolveLibraryPlugins(pluginNames ?? [], this.root);
const directorySeed = directory
? await resolveDirectorySkills(directory.path, directory.names)
: [];
@@ -498,7 +498,11 @@ export class AgentService implements AgentLifecycle {
const meta = await this.agentConfig.readCardMeta(projectId, agentId);
const cardName = archive !== undefined ? (meta.name ?? agentId) : displayName;
const cardDescription = archive !== undefined ? meta.description : description;
- const installed = await this.installedPlugins(projectId, agentId, loadLibraryPlugins());
+ const installed = await this.installedPlugins(
+ projectId,
+ agentId,
+ loadLibraryPlugins(this.root),
+ );
return {
agentId,
name: cardName,
diff --git a/packages/server/src/services/plugin-download.ts b/packages/server/src/services/plugin-download.ts
new file mode 100644
index 00000000..15f8af12
--- /dev/null
+++ b/packages/server/src/services/plugin-download.ts
@@ -0,0 +1,230 @@
+/**
+ * Remote plugin download: turns a URL an operator typed into the archive to install. Two
+ * separate concerns, in one place because the route needs both and neither is a route:
+ * `normalizePluginUrl` reads the URL (and rewrites the two GitHub shapes into the archive URL
+ * they stand for), `fetchPluginArchive` performs the one outbound request and bounds it.
+ *
+ * A plugin archive is a zip whose contents carry `plugin.json` somewhere; where exactly is the
+ * installer's question (http/routes/plugins.ts), not this module's — a plain zip URL is passed
+ * through untouched.
+ *
+ * Safety: the URL is a server-side request an administrator controls, so it is not a
+ * user-supplied fetch — but a redirect or a typo could still aim the server at its own network.
+ * `isBlockedHost` refuses the obvious cases (loopback, private and link-local literals, the
+ * `.local`/`.internal` names) before the request and again on the URL that answered. It is a
+ * literal-host guard, not a DNS guard: a public name resolving to an internal address is not
+ * caught here, which is the right trade for an admin-only endpoint on a self-hosted server and
+ * would not be for one reachable by every user.
+ */
+import { isIP } from "node:net";
+import { HttpError } from "../http/errors.js";
+import { badRequest } from "../http/validate.js";
+
+/**
+ * Cap for a downloaded archive. Larger than the upload routes' 14MB on purpose: that number
+ * exists to keep a base64 body inside the request limit, and nothing is base64 here. What is
+ * fetched is often a whole repository — a GitHub tree URL downloads the checkout the plugin
+ * lives in — so 32MB is what "a plugin archive" means over the network, while the plugin that
+ * comes out of it is capped by the same content limits either way (see unzipBounded).
+ */
+export const MAX_PLUGIN_ARCHIVE_BYTES = 32 * 1024 * 1024;
+
+/**
+ * How long one download may take. Generous compared with a balance query — this pulls a file,
+ * not a status — but bounded, so an unresponsive host cannot pin a request handler.
+ */
+const DOWNLOAD_TIMEOUT_MS = 60_000;
+
+/** A URL, read: what to fetch, which subdirectory inside the archive is the plugin, and the name the URL itself suggests. */
+export interface PluginArchiveSource {
+ /** The URL to fetch (the GitHub archive URL when the input was a repository page). */
+ fetchUrl: string;
+ /** Path inside the archive under which the plugin root must live ("" = anywhere, the shallowest plugin root wins). */
+ subdir: string;
+ /** The name the URL suggests (a GitHub repository, a tree URL's directory); undefined when only the archive's own layout can say. */
+ name?: string;
+}
+
+/**
+ * Reads an operator-typed URL into the fetch it stands for. Accepted:
+ * - a zip URL (anything http/https ending in `.zip`, or any URL whose response turns out to be
+ * an archive — the extension is not required, only used to suggest a name);
+ * - `https://github.com/<owner>/<repo>` → that repository's default branch (`…/archive/HEAD.zip`);
+ * - `https://github.com/<owner>/<repo>/tree/<ref>[/<sub…>]` → that ref, with `sub` as the
+ * subdirectory to look in (this is the shape a "copy the URL of the folder" gesture yields).
+ * Anything else on github.com is not an archive (a `blob` page, a user page) → 400.
+ */
+export function normalizePluginUrl(raw: string): PluginArchiveSource {
+ const trimmed = raw.trim();
+ if (trimmed === "") throw badRequest("url must not be empty.");
+ let url: URL;
+ try {
+ url = new URL(trimmed);
+ } catch {
+ throw new HttpError(400, "unsupported_url", "url must be an absolute http(s) URL.");
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
+ throw new HttpError(400, "unsupported_url", "url must be an http(s) URL.");
+ }
+ assertHostAllowed(url);
+
+ const host = url.hostname.toLowerCase().replace(/^www\./, "");
+ if (host !== "github.com") {
+ // A plain link: fetched as given. The file name suggests a name only when it is a zip.
+ const file = url.pathname.split("/").filter(Boolean).pop() ?? "";
+ const suggested = file.toLowerCase().endsWith(".zip") ? file.slice(0, -4) : undefined;
+ return { fetchUrl: url.toString(), subdir: "", ...(suggested ? { name: suggested } : {}) };
+ }
+
+ const segments = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
+ const [owner, repo, kind, ...rest] = segments;
+ if (!owner || !repo) {
+ throw new HttpError(
+ 400,
+ "unsupported_url",
+ "Not a GitHub repository URL: expected /<owner>/<repo>.",
+ );
+ }
+ const repoUrl = `https://github.com/${owner}/${repo}`;
+ if (kind === undefined) {
+ // The repository page: its default branch. `HEAD` needs no API call to resolve.
+ return { fetchUrl: `${repoUrl}/archive/HEAD.zip`, subdir: "", name: repo };
+ }
+ // `/archive/…`, `/releases/download/…`, `/raw/…`: already a download link, passed through.
+ if (kind !== "tree") {
+ return { fetchUrl: url.toString(), subdir: "", name: repo };
+ }
+ const [ref, ...sub] = rest;
+ if (!ref) throw new HttpError(400, "unsupported_url", "A GitHub tree URL needs a branch or tag.");
+ const subdir = sub.join("/");
+ return {
+ fetchUrl: `${repoUrl}/archive/${encodeURIComponent(ref)}.zip`,
+ subdir,
+ // The plugin directory is the last segment of the subdirectory — that is its name.
+ name: sub.length > 0 ? sub[sub.length - 1]! : repo,
+ };
+}
+
+/** Refuses a host that can only be the server's own network (see the module header). */
+export function isBlockedHost(hostname: string): boolean {
+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, "");
+ if (host === "localhost" || host.endsWith(".localhost")) return true;
+ if (host.endsWith(".local") || host.endsWith(".internal")) return true;
+ const version = isIP(host);
+ if (version === 4) {
+ const octets = host.split(".").map(Number);
+ const [a, b] = octets as [number, number];
+ return (
+ a === 0 ||
+ a === 10 ||
+ a === 127 ||
+ (a === 100 && b >= 64 && b <= 127) ||
+ (a === 169 && b === 254) ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 168) ||
+ a >= 224
+ );
+ }
+ if (version === 6) {
+ // ::1 and :: (loopback, unspecified), fe80::/10 (link-local), fc00::/7 (unique-local).
+ return (
+ /^(0*:)*0*1$/.test(host) ||
+ host.startsWith("fe8") ||
+ host.startsWith("fe9") ||
+ host.startsWith("fea") ||
+ host.startsWith("feb") ||
+ host.startsWith("fc") ||
+ host.startsWith("fd")
+ );
+ }
+ return false;
+}
+
+function assertHostAllowed(url: URL): void {
+ if (isBlockedHost(url.hostname)) {
+ throw new HttpError(
+ 400,
+ "blocked_url",
+ `Refusing to fetch from a local or private host: ${url.hostname}`,
+ );
+ }
+}
+
+/**
+ * Fetches one plugin archive. Bounded three ways — a deadline, a decoded-size cap enforced
+ * while streaming (a `content-length` is a claim, and a chunked response makes no claim at
+ * all), and a re-check of the host that actually answered (a redirect may leave the network
+ * the URL declared). Every failure is an HttpError the route returns as-is: `download_failed`
+ * for a transport error or a non-2xx answer, `plugin_too_large` past the cap.
+ */
+export async function fetchPluginArchive(
+ source: PluginArchiveSource,
+ options: { fetchImpl?: typeof fetch; timeoutMs?: number } = {},
+): Promise<Buffer> {
+ const doFetch = options.fetchImpl ?? fetch;
+ let res: Response;
+ try {
+ res = await doFetch(source.fetchUrl, {
+ method: "GET",
+ redirect: "follow",
+ headers: { accept: "application/zip, application/octet-stream, */*" },
+ signal: AbortSignal.timeout(options.timeoutMs ?? DOWNLOAD_TIMEOUT_MS),
+ });
+ } catch (err) {
+ throw new HttpError(400, "download_failed", `Could not download: ${message(err)}`);
+ }
+ if (res.url) {
+ try {
+ assertHostAllowed(new URL(res.url));
+ } catch (err) {
+ if (err instanceof HttpError) throw err;
+ throw new HttpError(400, "download_failed", "Could not read the URL that answered.");
+ }
+ }
+ if (!res.ok) {
+ await res.body?.cancel().catch(() => undefined);
+ throw new HttpError(400, "download_failed", `Download failed with HTTP ${res.status}.`);
+ }
+ const declared = Number(res.headers.get("content-length") ?? "");
+ if (Number.isFinite(declared) && declared > MAX_PLUGIN_ARCHIVE_BYTES) {
+ await res.body?.cancel().catch(() => undefined);
+ throw pluginArchiveTooLarge(MAX_PLUGIN_ARCHIVE_BYTES);
+ }
+ return readBounded(res);
+}
+
+/** Reads the body, refusing the moment it passes the cap rather than after buffering it all. */
+async function readBounded(res: Response): Promise<Buffer> {
+ const reader = res.body?.getReader();
+ if (!reader) return Buffer.from(await res.arrayBuffer());
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > MAX_PLUGIN_ARCHIVE_BYTES) {
+ await reader.cancel().catch(() => undefined);
+ throw pluginArchiveTooLarge(MAX_PLUGIN_ARCHIVE_BYTES);
+ }
+ chunks.push(value);
+ }
+ return Buffer.concat(chunks);
+}
+
+/**
+ * The one "too large" answer, shared by both import routes so an over-size archive reads the
+ * same whether it was uploaded or downloaded — each quoting its own cap (the transport decides
+ * that number: a base64 request body for an upload, server memory for a download).
+ */
+export function pluginArchiveTooLarge(limitBytes: number): HttpError {
+ return new HttpError(
+ 413,
+ "plugin_too_large",
+ `The archive exceeds the ${Math.floor(limitBytes / (1024 * 1024))}MB limit.`,
+ );
+}
+
+function message(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
diff --git a/packages/server/src/services/plugin-library.ts b/packages/server/src/services/plugin-library.ts
index 6525acfc..c69d3a83 100644
--- a/packages/server/src/services/plugin-library.ts
+++ b/packages/server/src/services/plugin-library.ts
@@ -18,9 +18,9 @@ import { HttpError } from "../http/errors.js";
* `unknown_plugin` on the first name the library does not carry — the caller is expected to
* run this before it creates or writes anything.
*/
-export function resolveLibraryPlugins(names: readonly string[]): LibraryPlugin[] {
+export function resolveLibraryPlugins(names: readonly string[], root: string): LibraryPlugin[] {
return names.map((name) => {
- const plugin = libraryPlugin(name);
+ const plugin = libraryPlugin(name, root);
if (!plugin) {
throw new HttpError(404, "unknown_plugin", `Plugin is not in the library: ${name}`);
}
@@ -83,10 +83,52 @@ export function pluginFiles(plugin: LibraryPlugin): Record<string, string> {
return files;
}
+/**
+ * Everything a plugin ships as the files of an installable archive, keyed by path relative to
+ * the plugin directory — the export side of the import routes, and the inverse of
+ * readPluginDir: `plugin.json` regenerated from the loaded manifest (the library is what knows
+ * the plugin's identity — description, version, category, preinstall, and the hook command
+ * lists that plugin.json declares), the icon, then the same skill and hook files the file
+ * browser shows. So an export round-trips through an import, whichever source the plugin came
+ * from, and a file the library does not read (a README beside the manifest, the npm
+ * `package.json` a built-in carries) is not part of the archive: it is not part of the plugin
+ * as this installation holds it.
+ */
+export function pluginArchiveFiles(plugin: LibraryPlugin): Record<string, string> {
+ const manifest: Record<string, unknown> = {
+ description: plugin.description,
+ ...(plugin.descriptionZh !== undefined ? { description_zh: plugin.descriptionZh } : {}),
+ ...(plugin.shortDescription !== undefined
+ ? { short_description: plugin.shortDescription }
+ : {}),
+ ...(plugin.shortDescriptionZh !== undefined
+ ? { short_description_zh: plugin.shortDescriptionZh }
+ : {}),
+ version: plugin.version,
+ ...(plugin.category !== undefined ? { category: plugin.category } : {}),
+ preinstall: plugin.preinstall,
+ ...(plugin.hooks !== undefined
+ ? {
+ hooks: {
+ stop: plugin.hooks.manifest.stop,
+ pre_tool_use: plugin.hooks.manifest.pre_tool_use,
+ user_prompt: plugin.hooks.manifest.user_prompt,
+ },
+ }
+ : {}),
+ };
+ return {
+ "plugin.json": `${JSON.stringify(manifest, null, 2)}\n`,
+ ...(plugin.icon !== undefined ? { "icon.svg": plugin.icon } : {}),
+ ...pluginFiles(plugin),
+ };
+}
+
/** A library plugin as the listing describes it. Its skills go without their icon: it is the plugin's, sent once on the plugin itself. */
export function toPluginItem(plugin: LibraryPlugin): PluginItem {
return {
name: plugin.name,
+ source: plugin.source,
description: plugin.description,
...(plugin.descriptionZh !== undefined ? { descriptionZh: plugin.descriptionZh } : {}),
...(plugin.shortDescription !== undefined ? { shortDescription: plugin.shortDescription } : {}),
diff --git a/packages/server/src/services/skill-import-limits.ts b/packages/server/src/services/skill-import-limits.ts
index 35f5cb11..4a393fa8 100644
--- a/packages/server/src/services/skill-import-limits.ts
+++ b/packages/server/src/services/skill-import-limits.ts
@@ -29,12 +29,24 @@ export const MAX_TOTAL_BYTES = 20 * 1024 * 1024;
* Throws the caps as 400s, matching the archive route this was factored out of; a corrupt
* archive still throws whatever fflate throws, for the caller to translate.
*/
-export function unzipBounded(archive: Uint8Array): Record<string, Uint8Array> {
+export function unzipBounded(
+ archive: Uint8Array,
+ /**
+ * Which entries this caller wants, asked before counting and before inflation. A caller that
+ * already knows — the plugin import, which reads ONE plugin out of an archive that may hold a
+ * whole repository beside it — passes the plugin root's prefix here, and the caps then bound
+ * that plugin rather than everything around it. It is not an escape hatch from the caps: the
+ * entries it accepts are counted and capped exactly as before, and the ones it refuses are
+ * never inflated, so they cannot allocate anything either.
+ */
+ wanted: (name: string) => boolean = () => true,
+): Record<string, Uint8Array> {
let files = 0;
let declared = 0;
return unzipSync(archive, {
filter: ({ name, originalSize }) => {
- if (name.endsWith("/")) return true;
+ if (name.endsWith("/")) return wanted(name);
+ if (!wanted(name)) return false;
files += 1;
if (files > MAX_ARCHIVE_FILES) {
throw badRequest(`The zip archive exceeds the ${MAX_ARCHIVE_FILES}-file limit.`);
diff --git a/packages/server/test/plugin-import.test.ts b/packages/server/test/plugin-import.test.ts
new file mode 100644
index 00000000..67e9cced
--- /dev/null
+++ b/packages/server/test/plugin-import.test.ts
@@ -0,0 +1,408 @@
+/**
+ * The plugin directory routes — local upload, remote download, the directory listing, export
+ * and delete — and the two pure readers behind them (the archive parser and the URL reader).
+ *
+ * Two things are the point here. First, what an import must refuse: an archive with no plugin
+ * in it, one carrying two, an entry path that would land outside the plugin directory, and a
+ * name the build already ships (which the loader would go on serving). Second, who may do it:
+ * the user plugin directory is installation-level — every Project reads it and its hook scripts
+ * run with the server's rights — so these routes are the admin's, like installing to a machine,
+ * not a Project owner's.
+ *
+ * The tests pin PENGUIN_HOME at the app's temp root, because that is the production invariant
+ * being relied on: the server's data root and the library's plugin root are one directory.
+ */
+import path from "node:path";
+import { strToU8, zipSync } from "fflate";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type {
+ PluginDirectoryResponse,
+ PluginImportResponse,
+ PluginLibraryResponse,
+} from "../src/api/types.js";
+import { parsePluginArchive } from "../src/http/routes/plugins.js";
+import { isBlockedHost, normalizePluginUrl } from "../src/services/plugin-download.js";
+import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+/** A minimal valid plugin: manifest, icon and one skill (the loader requires the SKILL.md frontmatter name). */
+function pluginFiles(version = "2026.09.01.1"): Record<string, string> {
+ return {
+ "plugin.json": `${JSON.stringify(
+ {
+ description: "A plugin that arrived from outside the build.",
+ short_description: "Imported plugin.",
+ version,
+ category: "software-development",
+ },
+ null,
+ 2,
+ )}\n`,
+ "icon.svg": '<svg xmlns="http://www.w3.org/2000/svg"></svg>\n',
+ "skills/imported-skill/SKILL.md":
+ "---\nname: imported-skill\ndescription: A skill the plugin ships.\n---\n\nBody.\n",
+ };
+}
+
+function zip(files: Record<string, string>): Buffer {
+ const entries: Record<string, Uint8Array> = {};
+ for (const [rel, text] of Object.entries(files)) entries[rel] = strToU8(text);
+ return Buffer.from(zipSync(entries));
+}
+
+const readErrorCode = async (res: Response): Promise<string> =>
+ ((await res.json()) as { error: { code: string } }).error.code;
+
+describe("parsePluginArchive", () => {
+ it("takes the archive's own directory as the plugin root and its name", () => {
+ const inner: Record<string, string> = {};
+ for (const [rel, text] of Object.entries(pluginFiles())) inner[`imported/${rel}`] = text;
+ const parsed = parsePluginArchive(zip(inner));
+ expect(parsed.name).toBe("imported");
+ expect(Object.keys(parsed.files).sort()).toEqual([
+ "icon.svg",
+ "plugin.json",
+ "skills/imported-skill/SKILL.md",
+ ]);
+ });
+
+ it("needs a name when plugin.json sits at the archive root, and takes the one it is given", () => {
+ expect(() => parsePluginArchive(zip(pluginFiles()))).toThrow(/name is required/);
+ const parsed = parsePluginArchive(zip(pluginFiles()), { name: "named-by-request" });
+ expect(parsed.name).toBe("named-by-request");
+ });
+
+ it("locates the plugin under the subdirectory a tree URL names, ignoring the host's wrapper directory", () => {
+ // The shape a GitHub tree archive has: everything wrapped in `<repo>-<ref>/`, with the
+ // plugin (and other plugins, and everything else) below it.
+ const inner: Record<string, string> = {};
+ for (const [rel, text] of Object.entries(pluginFiles())) {
+ inner[`penguin-harness-local/plugins/imported/${rel}`] = text;
+ }
+ for (const [rel, text] of Object.entries(pluginFiles())) {
+ inner[`penguin-harness-local/plugins/other/${rel}`] = text;
+ }
+ const parsed = parsePluginArchive(zip(inner), { subdir: "plugins/imported" });
+ expect(parsed.name).toBe("imported");
+ expect(Object.keys(parsed.files).sort()).toEqual([
+ "icon.svg",
+ "plugin.json",
+ "skills/imported-skill/SKILL.md",
+ ]);
+ });
+
+ it("reads one plugin out of a repository archive, without the repository's own limits applying", () => {
+ // A checkout is not a plugin: 400 unrelated files around a 3-file plugin must neither fail
+ // the 200-file cap nor be inflated — the caps bound the plugin that comes out (`wanted`).
+ const inner: Record<string, string> = {};
+ for (const [rel, text] of Object.entries(pluginFiles())) {
+ inner[`penguin-harness-main/plugins/wanted/${rel}`] = text;
+ }
+ for (let i = 0; i < 400; i += 1) {
+ inner[`penguin-harness-main/docs/page-${i}.md`] = `# page ${i}\n`;
+ }
+ const parsed = parsePluginArchive(zip(inner), { subdir: "plugins/wanted" });
+ expect(parsed.name).toBe("wanted");
+ expect(Object.keys(parsed.files).sort()).toEqual([
+ "icon.svg",
+ "plugin.json",
+ "skills/imported-skill/SKILL.md",
+ ]);
+ // The same archive read as a whole still refuses: two directories carry plugin.json only
+ // in the plugin case above, so here it is the plugin's own file count that has to fail.
+ const crowded: Record<string, string> = {};
+ for (const [rel, text] of Object.entries(pluginFiles())) crowded[`crowded/${rel}`] = text;
+ for (let i = 0; i < 200; i += 1) {
+ crowded[`crowded/skills/extra-${i}/SKILL.md`] =
+ `---\nname: extra-${i}\ndescription: Filler.\n---\n`;
+ }
+ expect(() => parsePluginArchive(zip(crowded))).toThrow(/200-file limit/);
+ });
+
+ it("refuses an archive that carries two plugins side by side", () => {
+ const inner: Record<string, string> = {};
+ for (const [rel, text] of Object.entries(pluginFiles())) {
+ inner[`one/${rel}`] = text;
+ inner[`two/${rel}`] = text;
+ }
+ expect(() => parsePluginArchive(zip(inner))).toThrow(/more than one plugin/);
+ });
+
+ it("refuses an archive with no plugin, an empty archive, and a zip-slip entry path", () => {
+ expect(() => parsePluginArchive(zip({ "readme.md": "nothing here" }))).toThrow(
+ /no plugin.json/,
+ );
+ expect(() => parsePluginArchive(zip({}))).toThrow(/no files/);
+ const escaping = { ...pluginFiles(), "../outside.txt": "not inside" };
+ expect(() => parsePluginArchive(zip({ ...escaping }))).toThrow(/Invalid zip entry path/);
+ });
+
+ it("refuses bytes that are not a zip at all", () => {
+ expect(() => parsePluginArchive(Buffer.from("not a zip"))).toThrow(/not a valid zip/);
+ });
+
+ it("refuses a plugin name the loader would never accept", () => {
+ const inner: Record<string, string> = {};
+ for (const [rel, text] of Object.entries(pluginFiles())) inner[`../evil/${rel}`] = text;
+ // The entry path is checked first (zip-slip) — a name check is what the request's own
+ // `name` field goes through.
+ expect(() => parsePluginArchive(zip(pluginFiles()), { name: "../evil" })).toThrow(
+ /Not a valid plugin name/,
+ );
+ });
+});
+
+describe("normalizePluginUrl", () => {
+ it("turns a GitHub repository page into its default-branch archive", () => {
+ expect(normalizePluginUrl("https://github.com/Prism-Shadow/penguin-harness")).toEqual({
+ fetchUrl: "https://github.com/Prism-Shadow/penguin-harness/archive/HEAD.zip",
+ subdir: "",
+ name: "penguin-harness",
+ });
+ });
+
+ it("turns a GitHub tree URL into that ref's archive plus the subdirectory to look in", () => {
+ expect(normalizePluginUrl("https://github.com/o/r/tree/main/plugins/humanizer")).toEqual({
+ fetchUrl: "https://github.com/o/r/archive/main.zip",
+ subdir: "plugins/humanizer",
+ name: "humanizer",
+ });
+ expect(normalizePluginUrl("https://github.com/o/r/tree/v1.2.3")).toEqual({
+ fetchUrl: "https://github.com/o/r/archive/v1.2.3.zip",
+ subdir: "",
+ name: "r",
+ });
+ });
+
+ it("passes a plain download link through, suggesting a name only when it is a zip", () => {
+ expect(normalizePluginUrl("https://example.com/plugins/thing.zip")).toEqual({
+ fetchUrl: "https://example.com/plugins/thing.zip",
+ subdir: "",
+ name: "thing",
+ });
+ expect(normalizePluginUrl("https://example.com/download?id=7")).toEqual({
+ fetchUrl: "https://example.com/download?id=7",
+ subdir: "",
+ });
+ });
+
+ it("refuses a protocol or a host that is the server's own network", () => {
+ expect(() => normalizePluginUrl("ftp://example.com/thing.zip")).toThrow(/http\(s\)/);
+ expect(() => normalizePluginUrl("not a url")).toThrow(/absolute http\(s\) URL/);
+ for (const url of [
+ "http://localhost:8080/thing.zip",
+ "http://127.0.0.1/thing.zip",
+ "http://10.0.0.5/thing.zip",
+ "http://192.168.1.7/thing.zip",
+ "http://169.254.169.254/latest/meta-data",
+ "http://[::1]/thing.zip",
+ "http://box.internal/thing.zip",
+ ]) {
+ expect(() => normalizePluginUrl(url), url).toThrow(/local or private host/);
+ }
+ // The literal-host guard, stated as a table: public addresses and names pass.
+ expect(isBlockedHost("github.com")).toBe(false);
+ expect(isBlockedHost("8.8.8.8")).toBe(false);
+ });
+});
+
+describe("the plugin directory routes", () => {
+ let t: TestApp;
+ let admin: ReturnType<typeof apiClient>;
+ let member: ReturnType<typeof apiClient>;
+ let prevHome: string | undefined;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ prevHome = process.env.PENGUIN_HOME;
+ process.env.PENGUIN_HOME = t.root;
+ admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ member = apiClient(t.app, (await provisionUser(t.app, "plain_member")).cookie);
+ });
+ afterEach(async () => {
+ vi.unstubAllGlobals();
+ if (prevHome === undefined) delete process.env.PENGUIN_HOME;
+ else process.env.PENGUIN_HOME = prevHome;
+ await t.cleanup();
+ });
+
+ const upload = (files: Record<string, string>, body: Record<string, unknown> = {}) =>
+ admin.post("/api/plugins/upload", {
+ dataBase64: zip(files).toString("base64"),
+ ...body,
+ });
+
+ const libraryNames = async (client = admin): Promise<string[]> => {
+ const res = await client.get("/api/plugins");
+ const body = (await res.json()) as PluginLibraryResponse;
+ return body.groups.flatMap((g) => g.plugins.map((p) => p.name)).sort();
+ };
+
+ it("installs an uploaded plugin into the library, lists the directory and deletes it again", async () => {
+ const res = await upload(pluginFiles(), { name: "imported" });
+ expect(res.status).toBe(201);
+ const body = (await res.json()) as PluginImportResponse;
+ expect(body.plugin).toMatchObject({
+ name: "imported",
+ source: "user",
+ version: "2026.09.01.1",
+ });
+ expect(body.path).toBe(path.join(t.root, "plugins", "imported"));
+ // On disk under the data root, and in the library every other surface reads.
+ expect(await libraryNames()).toContain("imported");
+ const dir = (await (
+ await admin.get("/api/plugins/directory")
+ ).json()) as PluginDirectoryResponse;
+ expect(dir).toEqual({ path: path.join(t.root, "plugins"), plugins: ["imported"] });
+ const files = (await (await admin.get("/api/plugins/imported/files")).json()) as {
+ files: Record<string, string>;
+ };
+ expect(Object.keys(files.files)).toContain("skills/imported-skill/SKILL.md");
+
+ expect((await admin.delete("/api/plugins/imported")).status).toBe(204);
+ expect(await libraryNames()).not.toContain("imported");
+ // Gone from disk too — the delete is the directory, not a tombstone.
+ expect((await admin.get("/api/plugins/imported/files")).status).toBe(404);
+ expect((await admin.delete("/api/plugins/imported")).status).toBe(404);
+ });
+
+ it("answers one code for an archive past the cap, uploaded or downloaded alike", async () => {
+ const res = await admin.post("/api/plugins/upload", {
+ dataBase64: Buffer.alloc(15 * 1024 * 1024).toString("base64"),
+ name: "oversize",
+ });
+ expect(res.status).toBe(413);
+ expect(await readErrorCode(res)).toBe("plugin_too_large");
+ // Nothing was written on the way to the refusal.
+ const dir = (await (
+ await admin.get("/api/plugins/directory")
+ ).json()) as PluginDirectoryResponse;
+ expect(dir.plugins).toEqual([]);
+ });
+
+ it("keeps the import to admins", async () => {
+ const res = await upload(pluginFiles(), { name: "imported" });
+ expect(res.status).toBe(201);
+ expect(
+ (
+ await member.post("/api/plugins/upload", {
+ dataBase64: zip(pluginFiles()).toString("base64"),
+ name: "by-member",
+ })
+ ).status,
+ ).toBe(403);
+ expect((await member.delete("/api/plugins/imported")).status).toBe(403);
+ // Reading stays open: the library listing and the directory line are not an admin's screen.
+ expect((await member.get("/api/plugins")).status).toBe(200);
+ expect((await member.get("/api/plugins/directory")).status).toBe(200);
+ });
+
+ it("refuses a name the build already ships, and asks before overwriting a user plugin", async () => {
+ const builtin = await upload(pluginFiles(), { name: "goal" });
+ expect(builtin.status).toBe(409);
+ expect(await readErrorCode(builtin)).toBe("plugin_builtin");
+
+ expect((await upload(pluginFiles(), { name: "imported" })).status).toBe(201);
+ const again = await upload(pluginFiles("2026.09.02.1"), { name: "imported" });
+ expect(again.status).toBe(409);
+ expect(await readErrorCode(again)).toBe("plugin_exists");
+ const overwritten = await upload(pluginFiles("2026.09.02.1"), {
+ name: "imported",
+ overwrite: true,
+ });
+ expect(overwritten.status).toBe(201);
+ expect(((await overwritten.json()) as PluginImportResponse).plugin.version).toBe(
+ "2026.09.02.1",
+ );
+ });
+
+ it("exports a plugin as an archive that imports back", async () => {
+ await upload(pluginFiles(), { name: "imported" });
+ const res = await admin.get("/api/plugins/imported/archive");
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-type")).toBe("application/zip");
+ expect(res.headers.get("content-disposition")).toContain("imported-v2026.09.01.1.zip");
+ const archive = Buffer.from(await res.arrayBuffer());
+ // The archive carries the plugin as the library holds it, so it re-imports under a new name.
+ const parsed = parsePluginArchive(archive, { name: "imported-again" });
+ expect(Object.keys(parsed.files).sort()).toEqual([
+ "icon.svg",
+ "plugin.json",
+ "skills/imported-skill/SKILL.md",
+ ]);
+ const again = await admin.post("/api/plugins/upload", {
+ dataBase64: archive.toString("base64"),
+ name: "imported-again",
+ });
+ expect(again.status).toBe(201);
+ expect(await libraryNames()).toEqual(expect.arrayContaining(["imported", "imported-again"]));
+ });
+
+ it("downloads an archive from a URL, and refuses one the host will not serve", async () => {
+ const calls: string[] = [];
+ // What that archive really looks like: the repository wrapped in `<repo>-<ref>/`.
+ const fromGitHub: Record<string, string> = {};
+ for (const [rel, text] of Object.entries(pluginFiles())) {
+ fromGitHub[`penguin-harness-main/plugins/from-github/${rel}`] = text;
+ }
+ vi.stubGlobal("fetch", async (input: Parameters<typeof fetch>[0]) => {
+ calls.push(String(input));
+ return new Response(new Uint8Array(zip(fromGitHub)), { status: 200 });
+ });
+ const res = await admin.post("/api/plugins/download", {
+ url: "https://github.com/Prism-Shadow/penguin-harness/tree/main/plugins/from-github",
+ });
+ expect(res.status).toBe(201);
+ // The GitHub page became the archive it stands for, and the tree's directory named the plugin.
+ expect(calls).toEqual(["https://github.com/Prism-Shadow/penguin-harness/archive/main.zip"]);
+ expect(((await res.json()) as PluginImportResponse).plugin.name).toBe("from-github");
+
+ vi.stubGlobal("fetch", async () => new Response("nope", { status: 404 }));
+ const failed = await admin.post("/api/plugins/download", { url: "https://example.com/x.zip" });
+ expect(failed.status).toBe(400);
+ expect(await readErrorCode(failed)).toBe("download_failed");
+
+ vi.stubGlobal("fetch", async () => {
+ throw new Error("getaddrinfo ENOTFOUND");
+ });
+ const unreachable = await admin.post("/api/plugins/download", {
+ url: "https://example.com/x.zip",
+ });
+ expect(unreachable.status).toBe(400);
+ expect(await readErrorCode(unreachable)).toBe("download_failed");
+
+ // Past the cap, refused while streaming rather than after buffering it whole.
+ vi.stubGlobal(
+ "fetch",
+ async () =>
+ new Response("x", { status: 200, headers: { "content-length": String(64 * 1024 * 1024) } }),
+ );
+ const tooBig = await admin.post("/api/plugins/download", {
+ url: "https://example.com/big.zip",
+ });
+ expect(tooBig.status).toBe(413);
+ expect(await readErrorCode(tooBig)).toBe("plugin_too_large");
+
+ // What is fetched whole is often a repository, so the download cap is larger than the upload
+ // one: 20MB is past the base64 body limit and inside this one, and what the route says about
+ // it is "not a zip" — the body is a zip's problem, not its size.
+ vi.stubGlobal(
+ "fetch",
+ async () => new Response(Buffer.alloc(20 * 1024 * 1024, 0x7a), { status: 200 }),
+ );
+ const repositorySized = await admin.post("/api/plugins/download", {
+ url: "https://example.com/repo.zip",
+ });
+ expect(repositorySized.status).toBe(400);
+ expect(await readErrorCode(repositorySized)).toBe("bad_request");
+ });
+
+ it("refuses a URL aimed at the server's own network before fetching anything", async () => {
+ const fetchSpy = vi.fn();
+ vi.stubGlobal("fetch", fetchSpy);
+ const res = await admin.post("/api/plugins/download", { url: "http://127.0.0.1:7364/x.zip" });
+ expect(res.status).toBe(400);
+ expect(await readErrorCode(res)).toBe("blocked_url");
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/ui-gallery/src/app/mock/fixtures.ts b/packages/ui-gallery/src/app/mock/fixtures.ts
index f3f544f5..81e9027d 100644
--- a/packages/ui-gallery/src/app/mock/fixtures.ts
+++ b/packages/ui-gallery/src/app/mock/fixtures.ts
@@ -610,6 +610,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
titleZh: "开发",
plugins: [
{
+ source: "builtin",
name: IDS.plugins.registry,
description:
"Answer questions about Claude Code from its documentation, with citations.",
@@ -629,6 +630,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
hooks: [],
},
{
+ source: "builtin",
name: "penguin-sdk",
description:
"Build with the PenguinHarness SDK: the Session, Agent State and OmniMessage APIs.",
@@ -641,6 +643,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
hooks: [],
},
{
+ source: "builtin",
name: "web-design",
description: "Design and build web pages that do not read as templated defaults.",
descriptionZh: "设计并实现不像模板默认值的网页。",
@@ -656,6 +659,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
titleZh: "办公效率",
plugins: [
{
+ source: "builtin",
name: "goal",
description:
"Run a Session round after round until an objective is met, within a token budget.",
@@ -665,6 +669,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
hooks: ["stop"],
},
{
+ source: "builtin",
name: "continual-learning",
description: "Write what a Session learned into the Agent's memory when it ends.",
descriptionZh: "会话结束时把学到的东西写进智能体记忆。",
@@ -679,6 +684,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
hooks: ["stop"],
},
{
+ source: "builtin",
name: "report-writer",
description:
"Turn findings into a structured report with a summary, sections and an appendix.",
@@ -689,6 +695,27 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
},
],
},
+ // The plugin directory's own plugin: from the operator's import rather than from the
+ // build, so its card carries the User badge, its export is offered and it is the one
+ // delete can remove (see routes.ts). A plugin without a category lands in "Other".
+ {
+ id: "other",
+ title: "Other",
+ titleZh: "其他",
+ plugins: [
+ {
+ source: "user",
+ name: "release-notes",
+ description: "Draft the release notes for one version from its merged changes.",
+ descriptionZh: "根据一个版本已合并的改动起草发布说明。",
+ shortDescription: "Release notes from merged changes",
+ shortDescriptionZh: "由已合并的改动生成发布说明",
+ version: "2026.09.28.1",
+ skills: [skill("release-notes", "起草发布说明", "Draft release notes")],
+ hooks: [],
+ },
+ ],
+ },
],
};
const pluginFiles: Record<string, Record<string, string>> = {
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index ca47f95a..3996cc04 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -63,6 +63,7 @@ import type {
OrganizationsResponse,
PluginConfigActionResponse,
PluginConfigResponse,
+ PluginDirectoryResponse,
PluginFilesResponse,
PluginIndexResponse,
PluginLibraryResponse,
@@ -1654,6 +1655,13 @@ const libraryPlugins = (store: DemoStore) => store.f.library.groups.flatMap((g)
router
.get("/api/plugins", ({ store }): PluginLibraryResponse => store.f.library)
+ .get("/api/plugins/directory", ({ store }): PluginDirectoryResponse => ({
+ path: "/home/demo/.penguin/data/plugins",
+ plugins: libraryPlugins(store)
+ .filter((plugin) => plugin.source === "user")
+ .map((plugin) => plugin.name)
+ .sort(),
+ }))
.get("/api/plugins/registry", ({ store }): PluginIndexResponse => store.f.pluginIndex)
.get("/api/plugins/registry/readme", ({ store, query }): PluginReadmeResponse => {
const name = query.get("name") ?? "";
@@ -1667,6 +1675,26 @@ router
}
return { files };
})
+ // An import needs a server: the upload's zip would have to be unpacked and validated, and the
+ // download fetched — the demo has neither, the same as the two archive installs (see
+ // skills/hooks above). The directory line and the delete below are the demo's own state, so
+ // they answer for real.
+ .post("/api/plugins/upload", () => readOnly("import a plugin archive"))
+ .post("/api/plugins/download", () => readOnly("download a plugin from a URL"))
+ .get("/api/plugins/:plugin/archive", ({ params }) =>
+ raw("PK\u0003\u0004 demo archive", {
+ "content-type": "application/zip",
+ "content-disposition": `attachment; filename="${params.plugin}.zip"`,
+ }),
+ )
+ .delete("/api/plugins/:plugin", ({ store, params }) => {
+ const group = store.f.library.groups.find((g) =>
+ g.plugins.some((p) => p.name === params.plugin && p.source === "user"),
+ );
+ if (!group) notFound("Plugin");
+ group.plugins = group.plugins.filter((p) => !(p.name === params.plugin && p.source === "user"));
+ return empty();
+ })
.post("/api/projects/:projectId/agents/:agentId/plugins", (ctx): unknown => {
const installed = installedOf(ctx);
const agent = agentOf(ctx);
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 1fb24cee..7740dd19 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -128,9 +128,13 @@ import type {
OrgTicketStartResponse,
OrgTicketUpdateRequest,
PasswordChangeRequest,
+ PluginDirectoryResponse,
+ PluginDownloadRequest,
PluginFilesResponse,
+ PluginImportResponse,
PluginInstallRequest,
PluginLibraryResponse,
+ PluginUploadRequest,
PrefsResponse,
ProjectCreateRequest,
ProjectCreateResponse,
@@ -1528,6 +1532,39 @@ export const getPluginLibrary = () => apiFetch<PluginLibraryResponse>("/api/plug
export const getPluginFiles = (plugin: string) =>
apiFetch<PluginFilesResponse>(`/api/plugins/${encodeURIComponent(plugin)}/files`);
+/**
+ * The user plugin directory: its absolute path and the names of the plugins currently inside
+ * it — where an import lands and what a delete removes from, and therefore the one line the
+ * page shows about it. Answers whether or not the directory exists yet.
+ */
+export const getPluginDirectory = () => apiFetch<PluginDirectoryResponse>("/api/plugins/directory");
+
+/**
+ * Imports one plugin from an uploaded zip (base64), admin-only like every write into the
+ * directory. The archive carries `plugin.json` plus its `skills/`, `hooks/` and `icon.svg`;
+ * 409 `plugin_exists` when a user plugin of that name is already installed and `overwrite` is
+ * not set. 201 answers with the plugin as the library now lists it, plus where it landed.
+ */
+export const importPluginArchive = (body: PluginUploadRequest) =>
+ apiFetch<PluginImportResponse>("/api/plugins/upload", { method: "POST", body });
+
+/**
+ * The same import, fetched server-side from a URL: a zip link, a GitHub repository
+ * (`https://github.com/<owner>/<repo>`, default branch) or a GitHub tree URL
+ * (`…/tree/<ref>/<subdir>`, whose subdirectory is the plugin root). Same 409 `plugin_exists`
+ * as the upload, and the same admin-only gate.
+ */
+export const importPluginFromUrl = (body: PluginDownloadRequest) =>
+ apiFetch<PluginImportResponse>("/api/plugins/download", { method: "POST", body });
+
+/** Deletes one user plugin from the library and from disk (admin-only); 409 `plugin_builtin` for a built-in name, 404 `unknown_plugin` for one the library does not hold. */
+export const deletePlugin = (plugin: string) =>
+ apiFetch<void>(`/api/plugins/${encodeURIComponent(plugin)}`, { method: "DELETE" });
+
+/** Zip download URL for one library plugin (server sets Content-Disposition attachment): the card's export, which round-trips through importPluginArchive. */
+export const pluginArchiveUrl = (plugin: string): string =>
+ `/api/plugins/${encodeURIComponent(plugin)}/archive`;
+
/**
* Installs whole library plugins — each one's skills and hook package; an already-installed
* plugin is overwritten with the library content (i.e. updated). 201 returns the Agent's
diff --git a/packages/web/src/features/plugins/plugin-import-dialog.tsx b/packages/web/src/features/plugins/plugin-import-dialog.tsx
new file mode 100644
index 00000000..b0da3e14
--- /dev/null
+++ b/packages/web/src/features/plugins/plugin-import-dialog.tsx
@@ -0,0 +1,413 @@
+/**
+ * The plugin library's two import actions — a local zip upload and a remote download — with the
+ * Modal and the overwrite confirmation they need, kept out of plugins-page.tsx so the page
+ * keeps describing the library rather than the dialogs.
+ *
+ * Both are the same import twice: one carries the archive in the request, the other a URL the
+ * server fetches, and everything after the POST is shared — a 409 `plugin_exists` opens the
+ * overwrite confirmation, whose confirm resends THAT request with `overwrite: true` (so the
+ * user never picks the file twice, nor retypes the name), and any other failure rolls back to a
+ * toast. The library list and the directory line are re-read on success, which is how the new
+ * card appears.
+ *
+ * Each dialog carries the same optional name field, for the one case the archive cannot answer
+ * itself: plugin.json at the very root of the zip has no directory to take a name from. Left
+ * empty — the normal case — nothing is sent, and the server names the plugin after the
+ * directory inside the archive that carries plugin.json. The field is held to the server's own
+ * name rule while it is typed, so a name the route would answer 400 for cannot reach the
+ * submit button.
+ *
+ * Both dialogs end with the same panel of rules (see PluginRules), in two lists: what the import
+ * takes — which sources, where the plugin root is found, the precedence the plugin NAME is
+ * decided by, the size caps, and what happens on a name collision — and what a plugin has to be,
+ * for whoever is about to publish one. It sits at the foot so the reader meets each rule just
+ * after the control it governs, and it is identical in both dialogs because it describes the
+ * shape a plugin has to arrive in rather than one source's mechanics.
+ *
+ * Admin-only by the server's own rule: the plugin directory is a server-level resource shared
+ * by every Project, so a member cannot write into it — the caller (plugins-page) renders this
+ * component only for an admin, and the routes answer 403 `admin_required` regardless.
+ */
+import { useState } from "react";
+import type { ChangeEvent } from "react";
+import {
+ Button,
+ ConfirmModal,
+ HiddenFileInput,
+ Input,
+ Modal,
+ toastError,
+ toastSuccess,
+} from "@prismshadow/penguin-ui";
+import * as api from "../../api/endpoints";
+import { ApiError } from "../../api/client";
+import { S } from "../../lib/strings";
+import { UPLOAD_LABEL_CLASS } from "../agents/skills-tab";
+import {
+ PLUGIN_ZIP_LIMIT_MB,
+ pluginImportErrorText,
+ pluginNameBody,
+ pluginNameFromError,
+ pluginNameFromUrl,
+ pluginNameInvalid,
+ pluginZipTooLarge,
+} from "./plugin-import";
+
+/**
+ * One import request, in the shape the retry needs: repeatable exactly as it was sent, `name`
+ * included — the confirmation resends it, so what the user typed goes out once and once only.
+ * Two variants because the two flows carry different things — the uploaded bytes cannot be
+ * recovered from anywhere else once the POST is gone, while a download re-fetches from its URL.
+ * `name` is empty whenever the user left the field alone; pluginNameBody is what decides
+ * whether it travels.
+ */
+type ImportRequest =
+ | { source: "upload"; dataBase64: string; name: string }
+ | { source: "download"; url: string; name: string };
+
+/** An import that answered 409 `plugin_exists`: its request, plus the plugin name the overwrite confirmation's copy names. */
+type PendingOverwrite = ImportRequest & { pluginName: string };
+
+/** Which import is in flight; the header label and the dialog's confirm button both read it. */
+type Busy = "upload" | "download" | null;
+
+/** A picked zip already read into the request body, with the names the flow needs: the file as the user sees it, and the stem a nameless import falls back to. */
+interface PickedArchive {
+ dataBase64: string;
+ fileName: string;
+ stem: string;
+}
+
+/**
+ * The plugin rules, the same two numbered blocks at the foot of both dialogs: what an import
+ * takes (importRules), then what a plugin has to be (authoringRules). Read from the strings
+ * rather than written into the JSX, so they follow the locale like every other line on this
+ * surface.
+ *
+ * The import list is ORDERED because its last two entries are a precedence rather than a set of
+ * facts: the plugin name is typed name first, then the name the source carries, then the
+ * archive's own layout — and a GitHub REPOSITORY url is a source that carries the repository's
+ * name, which is how a plugin can install under a name nobody asked for. That is the rule this
+ * panel exists to put in front of the reader, at the moment they are about to name the thing.
+ *
+ * The authoring list is here for the same reason the panel is not in any one plugin repository:
+ * a plugin outlives the repository it was published in, and the rules it states — no account
+ * details, no credentials inside a plugin — are the ones its own author breaks, while looking at
+ * this surface rather than at that repository's README.
+ *
+ * Exported for its own test (test/plugin-import-rules.test.ts): the dialogs around it render
+ * through a portal and cannot be mounted in the suite's node environment, while this panel can.
+ */
+export function PluginRules() {
+ return (
+ <div className="rounded-lg border border-gray-200 bg-gray-50/60 p-3 dark:border-gray-800 dark:bg-gray-900/40">
+ <RuleList title={S.plugins.importRulesTitle} rules={S.plugins.importRules} />
+ <RuleList title={S.plugins.authoringRulesTitle} rules={S.plugins.authoringRules} />
+ </div>
+ );
+}
+
+/** One titled numbered list of the panel above. */
+function RuleList({ title, rules }: { title: string; rules: readonly string[] }) {
+ return (
+ <div className="mt-3 first:mt-0">
+ <p className="text-xs font-medium text-gray-700 dark:text-gray-300">{title}</p>
+ <ol className="mt-1.5 list-decimal space-y-1 pl-4 text-xs leading-relaxed text-gray-500 dark:text-gray-400">
+ {rules.map((rule) => (
+ <li key={rule}>{rule}</li>
+ ))}
+ </ol>
+ </div>
+ );
+}
+
+export function PluginImportActions({
+ onImported,
+}: {
+ /** Called once an import landed and was toasted: re-read the library listing and the directory line, so the new plugin's card is on screen. */
+ onImported: () => Promise<void> | void;
+}) {
+ const [busy, setBusy] = useState<Busy>(null);
+ const [uploadOpen, setUploadOpen] = useState(false);
+ // The picked archive is held rather than posted from the picker's own callback: the dialog
+ // collects the file and the name together, and the confirm sends both in one request.
+ const [picked, setPicked] = useState<PickedArchive | null>(null);
+ const [uploadName, setUploadName] = useState("");
+ const [downloadOpen, setDownloadOpen] = useState(false);
+ const [url, setUrl] = useState("");
+ const [downloadName, setDownloadName] = useState("");
+ // The 409 confirmation, and the only state both flows share.
+ const [pending, setPending] = useState<PendingOverwrite | null>(null);
+
+ const uploadNameInvalid = pluginNameInvalid(uploadName);
+ const downloadNameInvalid = pluginNameInvalid(downloadName);
+
+ /** Success path, shared by both flows: close what was open, toast, re-read the library. */
+ const imported = async (name: string) => {
+ setPending(null);
+ setUploadOpen(false);
+ setPicked(null);
+ setUploadName("");
+ setDownloadOpen(false);
+ setUrl("");
+ setDownloadName("");
+ toastSuccess(S.plugins.importDoneToast(name));
+ await onImported();
+ };
+
+ /**
+ * Closing the upload dialog drops what was picked with it — unlike the download dialog's URL,
+ * which survives a cancel (it is one pasted string the user would have to find again), the
+ * archive is a base64 body held in memory, and a dialog opened to start over has no use for it.
+ */
+ const closeUpload = () => {
+ setUploadOpen(false);
+ setPicked(null);
+ setUploadName("");
+ };
+
+ /**
+ * A 409 lands in the overwrite confirmation instead of a toast — it is a question, not a
+ * failure — and every other refusal (or a missing admin right) rolls back to one.
+ */
+ const failed = (e: unknown, request: ImportRequest, fallbackName: string) => {
+ if (e instanceof ApiError && e.status === 409 && e.code === "plugin_exists") {
+ setPending({ ...request, pluginName: pluginNameFromError(e, fallbackName) });
+ } else {
+ setPending(null);
+ toastError(pluginImportErrorText(e));
+ }
+ };
+
+ /** POST the archive body; `overwrite` only ever set by the confirmation's retry. */
+ const upload = async (
+ dataBase64: string,
+ name: string,
+ fallbackName: string,
+ overwrite: boolean,
+ ) => {
+ setBusy("upload");
+ try {
+ const res = await api.importPluginArchive({
+ dataBase64,
+ // Absent, not empty, when the field was left alone: see pluginNameBody.
+ ...pluginNameBody(name),
+ ...(overwrite ? { overwrite: true } : {}),
+ });
+ await imported(res.plugin.name);
+ } catch (e) {
+ failed(e, { source: "upload", dataBase64, name }, fallbackName);
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ /** POST the URL; the server derives the name from it (and `subdir` from a tree URL). */
+ const download = async (target: string, name: string, overwrite: boolean) => {
+ setBusy("download");
+ try {
+ const res = await api.importPluginFromUrl({
+ url: target,
+ ...pluginNameBody(name),
+ ...(overwrite ? { overwrite: true } : {}),
+ });
+ await imported(res.plugin.name);
+ } catch (e) {
+ failed(e, { source: "download", url: target, name }, pluginNameFromUrl(target));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ /**
+ * Read the picked zip now, post it later: the dialog's confirm is what sends it, so the name
+ * gets its say first. The fallback name is the picked file's stem, used only if the server's
+ * 409 message does not name the plugin (see pluginNameFromError).
+ */
+ const onPickFile = (e: ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ // Clear the picker's value so picking the SAME file again after a refusal still fires a
+ // change event (the Skills tab's import does the same, for the same reason).
+ e.target.value = "";
+ if (!file) return;
+ // Refused before reading: see pluginZipTooLarge.
+ if (pluginZipTooLarge(file.size)) {
+ toastError(S.plugins.importTooLarge(PLUGIN_ZIP_LIMIT_MB));
+ return;
+ }
+ const reader = new FileReader();
+ reader.onload = () => {
+ const dataUrl = reader.result as string;
+ // Strip the `data:…;base64,` prefix the FileReader adds.
+ setPicked({
+ dataBase64: dataUrl.slice(dataUrl.indexOf(",") + 1),
+ fileName: file.name,
+ stem: file.name.replace(/\.zip$/i, ""),
+ });
+ };
+ reader.onerror = () => toastError(S.common.unknownError);
+ reader.readAsDataURL(file);
+ };
+
+ const submitUpload = () => {
+ if (picked === null) return;
+ void upload(picked.dataBase64, uploadName, picked.stem, false);
+ };
+
+ const confirmOverwrite = () => {
+ if (pending === null) return;
+ if (pending.source === "upload") {
+ void upload(pending.dataBase64, pending.name, pending.pluginName, true);
+ } else {
+ void download(pending.url, pending.name, true);
+ }
+ };
+
+ return (
+ <>
+ {/* Right-aligned in the title row, next to the page title. Each action opens its own
+ dialog (both are a source plus the optional name), and both are disabled while either
+ import runs, since one import at a time is what the confirmation's single pending slot
+ can carry. */}
+ <div className="ml-auto flex shrink-0 items-center gap-2">
+ <Button size="sm" disabled={busy !== null} onClick={() => setUploadOpen(true)}>
+ {busy === "upload" ? S.plugins.importUploading : S.plugins.importUpload}
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy !== null}
+ onClick={() => setDownloadOpen(true)}
+ >
+ {busy === "download" ? S.plugins.importDownloading : S.plugins.importDownload}
+ </Button>
+ </div>
+
+ {/* Local zip upload: the picker, and the name field that only matters when plugin.json
+ sits at the archive's root. */}
+ <Modal
+ open={uploadOpen}
+ title={S.plugins.importUpload}
+ onClose={closeUpload}
+ widthClass="sm:max-w-lg"
+ footer={
+ <>
+ <Button size="sm" onClick={closeUpload}>
+ {S.common.cancel}
+ </Button>
+ {/* Disabled until a file is picked, and while the typed name breaks the server's
+ own rule (the field carries the message that says so). */}
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy !== null || picked === null || uploadNameInvalid}
+ onClick={submitUpload}
+ >
+ {busy === "upload" ? S.plugins.importUploading : S.plugins.uploadAction}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <p className="text-xs text-gray-500 dark:text-gray-400">{S.plugins.uploadDesc}</p>
+ <div className="flex items-center gap-2">
+ <label
+ className={`${UPLOAD_LABEL_CLASS} ${busy !== null ? "pointer-events-none opacity-60" : ""}`}
+ >
+ <HiddenFileInput accept=".zip" disabled={busy !== null} onChange={onPickFile} />
+ {S.plugins.uploadPickFile}
+ </label>
+ {/* Which file the next confirm will send: without it, picking one shows nothing. */}
+ {picked !== null && (
+ <span className="truncate text-xs text-gray-500 dark:text-gray-400">
+ {S.plugins.uploadPicked(picked.fileName)}
+ </span>
+ )}
+ </div>
+ <Input
+ size="sm"
+ label={S.plugins.pluginNameLabel}
+ hint={S.plugins.pluginNameHint}
+ placeholder={S.plugins.pluginNamePlaceholder}
+ value={uploadName}
+ onChange={(e) => setUploadName(e.target.value)}
+ error={uploadNameInvalid ? S.plugins.pluginNameInvalid : undefined}
+ autoComplete="off"
+ />
+ <PluginRules />
+ </div>
+ </Modal>
+
+ <Modal
+ open={downloadOpen}
+ title={S.plugins.downloadTitle}
+ onClose={() => setDownloadOpen(false)}
+ widthClass="sm:max-w-lg"
+ footer={
+ <>
+ {/* Cancel stays live while the download runs (as in the Skills tab's import
+ modal): the request is already on its way, and it still reports itself — a
+ success through the toast and the refreshed list, a 409 through the overwrite
+ confirmation, which is a dialog of its own. */}
+ <Button size="sm" onClick={() => setDownloadOpen(false)}>
+ {S.common.cancel}
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy !== null || url.trim() === "" || downloadNameInvalid}
+ onClick={() => void download(url.trim(), downloadName, false)}
+ >
+ {busy === "download" ? S.plugins.importDownloading : S.plugins.downloadAction}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <p className="text-xs text-gray-500 dark:text-gray-400">{S.plugins.downloadDesc}</p>
+ <Input
+ size="sm"
+ label={S.plugins.downloadUrlLabel}
+ hint={S.plugins.downloadUrlHint}
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ placeholder={S.plugins.downloadUrlPlaceholder}
+ autoComplete="off"
+ autoFocus
+ />
+ <Input
+ size="sm"
+ label={S.plugins.pluginNameLabel}
+ hint={S.plugins.pluginNameHint}
+ placeholder={S.plugins.pluginNamePlaceholder}
+ value={downloadName}
+ onChange={(e) => setDownloadName(e.target.value)}
+ error={downloadNameInvalid ? S.plugins.pluginNameInvalid : undefined}
+ autoComplete="off"
+ />
+ <PluginRules />
+ </div>
+ </Modal>
+
+ {/* Overwrite confirmation: the dialog that asked stays underneath (its Cancel returns to
+ it, file and name both intact), and confirm resends the same request with
+ overwrite: true. */}
+ {pending !== null && (
+ <ConfirmModal
+ open
+ title={S.plugins.importOverwriteTitle}
+ tone="primary"
+ confirmLabel={S.plugins.importOverwriteAction}
+ cancelLabel={S.common.cancel}
+ busy={busy !== null}
+ onClose={() => setPending(null)}
+ onConfirm={confirmOverwrite}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.plugins.importOverwriteBody(pending.pluginName)}
+ </p>
+ </ConfirmModal>
+ )}
+ </>
+ );
+}
diff --git a/packages/web/src/features/plugins/plugin-import.ts b/packages/web/src/features/plugins/plugin-import.ts
new file mode 100644
index 00000000..cd1a9865
--- /dev/null
+++ b/packages/web/src/features/plugins/plugin-import.ts
@@ -0,0 +1,133 @@
+/**
+ * The plugin import flows' DOM-free half: the client-side size guard, the name a failed import
+ * is about, and the code → copy mapping for the failures the upload and download routes raise.
+ *
+ * Split out of plugin-import-dialog.tsx so each piece can be unit-tested on its own — the
+ * dialog only wires them to state, and nothing here touches the DOM. The same split as
+ * lib/upload-limits.ts, and for the same reason: a client that draws a line (a size ceiling, a
+ * name, a message) must draw it exactly where the server does, and that agreement is only
+ * checkable without a browser.
+ */
+import { ApiError } from "../../api/client";
+import { apiErrorText } from "../../lib/api-error";
+import { S } from "../../lib/strings";
+import { MB_BYTES } from "../../lib/upload-limits";
+
+/**
+ * The decoded-zip ceiling both plugin routes enforce, in whole MB — the same 14MB cap the skill
+ * and hook archive routes use (`MAX_ARCHIVE_BYTES`), which the server keeps in one place and
+ * the web cannot import (it resolves the server's wire types only). Named here rather than
+ * inlined so the copy that quotes it and the check that applies it cannot drift apart.
+ */
+export const PLUGIN_ZIP_LIMIT_MB = 14;
+
+/**
+ * Whether a picked zip is over the ceiling and must be refused BEFORE it is read.
+ *
+ * `>` and not `>=`, matching the server's `bytes.length > limit`: an off-by-one here would
+ * reject exactly the file a user just resized to fit. Reading first would cost the wait and
+ * then a base64 request a third larger than the file — to earn a 413 that this check can
+ * answer instantly, in the file picker's own language.
+ */
+export function pluginZipTooLarge(bytes: number): boolean {
+ return bytes > PLUGIN_ZIP_LIMIT_MB * MB_BYTES;
+}
+
+/**
+ * The rule a plugin name has to satisfy, as a client copy of the server's own
+ * (`PLUGIN_NAME_PATTERN` in core): the name IS the directory the plugin is installed under, so it
+ * has to be one safe path segment. Copied rather than imported for the same reason as the ceiling
+ * above — the web resolves the server's wire types, never its source — which is exactly why the
+ * dialog checks with it before submitting: the server's 400 would be the first thing a user learns
+ * about a typo otherwise.
+ */
+export const PLUGIN_NAME_PATTERN = /^[A-Za-z0-9_-]+$/;
+
+/**
+ * Whether the name field must hold the submit back. The field is OPTIONAL: empty means "let the
+ * archive name the plugin" (see pluginNameBody), so only a non-empty value is held to the rule —
+ * and the surrounding blanks of a value the user did type are not their problem.
+ */
+export function pluginNameInvalid(name: string): boolean {
+ const trimmed = name.trim();
+ return trimmed !== "" && !PLUGIN_NAME_PATTERN.test(trimmed);
+}
+
+/**
+ * The name field of an import request: the typed name trimmed, or NO field at all when the box is
+ * empty — never `name: ""`.
+ *
+ * An absent name is what tells the server to name the plugin after the archive (the directory
+ * inside it that carries plugin.json); an empty one is a name that fails the rule above and earns
+ * a 400, which would turn the optional field into a trap. The blanks-only case goes out absent for
+ * the same reason: nobody typed a name.
+ */
+export function pluginNameBody(name: string): { name?: string } {
+ const trimmed = name.trim();
+ return trimmed === "" ? {} : { name: trimmed };
+}
+
+/**
+ * The plugin name a URL names, for the overwrite confirmation's copy — the name the server
+ * would derive, read off the address the user pasted.
+ *
+ * - `https://github.com/<owner>/<repo>` names the repo (a trailing `.git` included: the address
+ * bar hands one back when it was copied from the clone button);
+ * - `…/tree/<ref>/<subdir…>` names the plugin root, i.e. the LAST segment of the subdirectory —
+ * the subdirectory IS the plugin (see the route's shallowest-plugin.json rule), and the ref
+ * in front of it names a commit rather than anything the user will recognize;
+ * - anything else names its last segment with a `.zip` suffix dropped: a direct link to the
+ * archive.
+ *
+ * Query and fragment are stripped first: neither names anything, and a pasted address usually
+ * ends in a trailing slash, which would otherwise leave an empty last segment.
+ */
+export function pluginNameFromUrl(url: string): string {
+ const segments = url
+ .trim()
+ .replace(/[?#].*$/, "")
+ .split("/")
+ .filter((segment) => segment.length > 0);
+ const tree = segments.indexOf("tree");
+ // `…/tree/<ref>` alone: the last segment is the ref, so the repo before it is the only name
+ // the address carries.
+ if (tree !== -1 && segments.length <= tree + 2) return segments[tree - 1] ?? "";
+ const last = segments[segments.length - 1] ?? "";
+ // A tree URL points at a directory, so its last segment is already the name; everywhere else
+ // the last segment is a file (`plugin.zip`) or a repo (`plugin.git`).
+ return tree === -1 ? last.replace(/\.(zip|git)$/i, "") : last;
+}
+
+/** The name inside the 409 the plugin routes answer with: "A user plugin named <name> is already installed." */
+const NAMED_IN_MESSAGE = /\bnamed\s+([A-Za-z0-9_-]+)\b/;
+/** The tail form ("…: <name>") the skill and hook imports already parse, read too in case the wording converges on that one. */
+const TAILED_IN_MESSAGE = /:\s*([A-Za-z0-9_-]+)$/;
+
+/**
+ * The plugin name a 409 is about, for the overwrite confirmation's copy; `fallback` (the picked
+ * file's stem, or the name the URL spells) covers a rewording on the server side.
+ *
+ * The message is not a contract — the CODE is, and that is what the caller branches on — so a
+ * miss here only costs the confirmation a less exact name. What must never happen is a nameless
+ * confirmation over a question ("overwrite which plugin?"), which the fallback rules out.
+ */
+export function pluginNameFromError(err: unknown, fallback: string): string {
+ if (!(err instanceof ApiError)) return fallback;
+ return (
+ NAMED_IN_MESSAGE.exec(err.message)?.[1] ?? TAILED_IN_MESSAGE.exec(err.message)?.[1] ?? fallback
+ );
+}
+
+/**
+ * The text of a failed import or delete: the plugin codes the routes answer with get their own
+ * copy (the server's message is English-only, the UI language may not be), everything else
+ * goes through the shared error mapping.
+ */
+export function pluginImportErrorText(err: unknown): string {
+ if (err instanceof ApiError) {
+ const byCode = S.plugins.importErrors as Record<string, string | undefined>;
+ const text = byCode[err.code];
+ if (text !== undefined) return text;
+ }
+ return apiErrorText(err);
+}
diff --git a/packages/web/src/features/plugins/plugins-page.tsx b/packages/web/src/features/plugins/plugins-page.tsx
index b1541130..1f38efca 100644
--- a/packages/web/src/features/plugins/plugins-page.tsx
+++ b/packages/web/src/features/plugins/plugins-page.tsx
@@ -42,6 +42,7 @@ import type {
AgentSummary,
HookItem,
InstalledPluginsResponse,
+ PluginDirectoryResponse,
PluginGroupItem,
PluginIndexEntry,
PluginItem,
@@ -49,9 +50,12 @@ import type {
} from "@prismshadow/penguin-server/api";
import {
AgentAvatar,
+ Badge,
Button,
CollapsibleSection,
ConfirmModal,
+ CopyButton,
+ DownloadIcon,
GlyphIcon,
ICONS,
ICON_SIZE,
@@ -87,7 +91,10 @@ import { DRAFT_SESSION_ID } from "../chat/chat-page";
import { draftKey, loadDraft, saveDraft } from "../chat/draft-cache";
import { prepareNewChatDraft } from "../chat/new-chat";
import { localizedShortText, localizedText } from "../chat/skill-use";
+import { downloadArchive } from "../agents/archive-download";
import { PluginDetailModal } from "./plugin-detail";
+import { PluginImportActions } from "./plugin-import-dialog";
+import { pluginImportErrorText } from "./plugin-import";
import { SettingsDialog } from "../settings/settings-dialog";
import { formatRelativeDate } from "../../lib/format";
import { SkillTile } from "../skills/skill-icon-view";
@@ -222,6 +229,9 @@ export function PluginsPage() {
const [groups, setGroups] = useState<PluginGroupItem[] | null>(null);
const [error, setError] = useState<string | null>(null);
+ /** GET /api/plugins/directory: the directory line's data (null until it answers, or when the read failed). */
+ const [directory, setDirectory] = useState<PluginDirectoryResponse | null>(null);
+ const [directoryError, setDirectoryError] = useState<string | null>(null);
const [installed, setInstalled] = useState<InstalledMap>(new Map());
/** What this Project asks for of the module plugins, and which of those the process runs. */
const [deployment, setDeployment] = useState<InstalledPluginsResponse | null>(null);
@@ -348,23 +358,46 @@ export function PluginsPage() {
}
};
- // Library list: readable once logged in, fetched once on page entry.
- useEffect(() => {
- let cancelled = false;
- setError(null);
- api
- .getPluginLibrary()
- .then((res) => {
- if (!cancelled) setGroups(res.groups);
- })
- .catch((e: unknown) => {
- if (!cancelled) setError(apiErrorText(e));
- });
- return () => {
- cancelled = true;
- };
+ /**
+ * The directory line alone — what a delete moves. The listing is updated in place there, so
+ * re-fetching it too would only flash a skeleton over a card the user just removed.
+ */
+ const reloadDirectory = useCallback(async () => {
+ try {
+ setDirectory(await api.getPluginDirectory());
+ setDirectoryError(null);
+ } catch (e) {
+ setDirectoryError(apiErrorText(e));
+ }
}, []);
+ /**
+ * The page's two reads in one call — the library listing and the directory line. Every import
+ * wants both (it adds a card AND moves the count behind it), and neither half may take the
+ * other down with it: a read that fails still leaves the other half on screen, and only the
+ * listing has a page-level error state (it is the page's content; the directory's own line
+ * carries its failure).
+ */
+ const reloadLibrary = useCallback(async () => {
+ await Promise.all([
+ api.getPluginLibrary().then(
+ (res) => {
+ setGroups(res.groups);
+ setError(null);
+ },
+ (e: unknown) => setError(apiErrorText(e)),
+ ),
+ reloadDirectory(),
+ ]);
+ }, [reloadDirectory]);
+
+ // Library list and directory line: readable once logged in, read once on page entry and again
+ // after every import (reloadLibrary above). Both writes are whole-state replacements, so an
+ // answer that arrives after the page unmounted is discarded rather than guarded against.
+ useEffect(() => {
+ void reloadLibrary();
+ }, [reloadLibrary]);
+
// Installed skills and hook packages for every Agent in the current Project (fetched in
// parallel, same convention as the sessions context): a single Agent's failure is silently
// treated as "nothing installed" and doesn't break the whole page.
@@ -579,6 +612,50 @@ export function PluginsPage() {
navigate(`/chat/${DRAFT_SESSION_ID}`, { state: { agentId } });
};
+ /**
+ * "Export" on a user plugin's card: the shared archive download (archive-download.ts, the same
+ * one the Skills and Hooks tabs export with). Open to any member — GET
+ * /api/plugins/:plugin/archive is a plain read of a directory everyone can already browse —
+ * and the way to keep a copy of a plugin an admin may delete off the machine.
+ */
+ const exportPlugin = async (name: string) => {
+ try {
+ await downloadArchive(api.pluginArchiveUrl(name), name);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ }
+ };
+
+ /**
+ * Delete one user plugin (admin-only server-side): optimistic on the local listing — the card
+ * goes at once, the way install/uninstall move the install snapshot — and rolled back with a
+ * toast when the server refuses (a built-in name, or a right the account no longer has). The
+ * directory line is re-read afterwards, since the on-disk directory is what it reports.
+ */
+ const removePlugin = async (plugin: PluginItem) => {
+ const prev = groups;
+ setGroups(
+ (current) =>
+ current
+ ?.map((group) => ({
+ ...group,
+ plugins: group.plugins.filter((p) => p.name !== plugin.name),
+ }))
+ // A category the deleted plugin was the only member of goes with it: the grouping is
+ // the server's, and an empty section would stand under the title until the next load.
+ .filter((group) => group.plugins.length > 0) ?? current,
+ );
+ try {
+ await api.deletePlugin(plugin.name);
+ toastSuccess(S.plugins.deletedToast(plugin.name));
+ } catch (e) {
+ setGroups(prev);
+ toastError(pluginImportErrorText(e));
+ return;
+ }
+ await reloadDirectory();
+ };
+
const allInstalled = installedPluginRows(groups ?? [], locale, deployment, index ?? [], view);
const allAvailable = availablePluginRows(deployment, index ?? [], view);
const facets = pluginFacets([...allInstalled, ...allAvailable]);
@@ -611,6 +688,12 @@ export function PluginsPage() {
actions={
isAdmin ? (
<>
+ {/* Importing into the plugin directory, in the title row beside the gear: a
+ server-level resource, so both actions are the admin's and the routes answer
+ 403 without the right. Rendered only for an admin — a button that always
+ refuses is worse than no button — and disabled while either runs, since one
+ import at a time is what the overwrite confirmation's slot can carry. */}
+ <PluginImportActions onImported={reloadLibrary} />
{/* Which machine's plugins the rows show, and which table an install or a
removal edits: the shared one, or that machine's own. */}
{otherMachines.length > 0 && (
@@ -634,6 +717,10 @@ export function PluginsPage() {
) : undefined
}
>
+ {/* Where an import lands and what a delete removes from: the server's own plugin
+ directory, named under the title rather than left for the reader to find in a
+ settings page. A read, so every member sees it. */}
+ <PluginDirectoryLine directory={directory} failed={directoryError !== null} />
{/* Last stop on the plugins trail: what the sidebar's dot was pointing at, the control
that takes all of it in one press, and the way to clear it for someone who has looked
and decided to stay on the installed copies. A plugin is never NEW here — one nobody
@@ -712,9 +799,12 @@ export function PluginsPage() {
plugin={row.plugin}
category={row.category}
installed={installed}
+ canDelete={isAdmin}
onQuickInvoke={quickInvoke}
onToggleInstall={toggleInstall}
onUpdateOutdated={updateOutdated}
+ onExport={exportPlugin}
+ onDelete={removePlugin}
/>
) : (
<ModuleRow
@@ -1211,22 +1301,73 @@ function Tag({
);
}
+/**
+ * The user plugin directory line under the title: the absolute path in monospace with the
+ * shared copy button, and how many user plugins are inside it — the answer to where an import
+ * landed, which is also the directory a delete removes from.
+ *
+ * Deliberately quiet (one line of small gray text) and worded rather than counted at zero:
+ * "0 user plugins" reads like a fault where the directory is simply still empty. Nothing is
+ * rendered until the read answers, so the list below never jumps for a line that is not there
+ * yet; a failed read states itself in the same line instead of hiding, since silence under the
+ * title would leave the count missing for no visible reason.
+ */
+function PluginDirectoryLine({
+ directory,
+ failed,
+}: {
+ directory: PluginDirectoryResponse | null;
+ /** The read failed: say so in words (there is no path to show then). */
+ failed: boolean;
+}) {
+ if (directory === null && !failed) return null;
+ return (
+ <div className="mt-2 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs text-gray-400 dark:text-gray-500">
+ <span className="shrink-0">{S.plugins.dirLabel}</span>
+ {directory === null ? (
+ <span>{S.plugins.dirUnavailable}</span>
+ ) : (
+ <>
+ {/* The path is the one value here worth taking away, so it is selectable, truncating
+ with the full path in the tooltip, and carries the app's copy button beside it. */}
+ <span className="min-w-0 truncate font-mono" data-tooltip={directory.path}>
+ {directory.path}
+ </span>
+ <CopyButton text={directory.path} label={S.plugins.dirPathCopy} size="sm" />
+ <span className="shrink-0">
+ {directory.plugins.length === 0
+ ? S.plugins.dirEmpty
+ : S.plugins.dirCount(directory.plugins.length)}
+ </span>
+ </>
+ )}
+ </div>
+ );
+}
+
/** A single plugin card: metadata display (contents badges + a semantic metadata line) + update reminder + quick start + "manage installs" Modal. */
function PluginCard({
plugin,
category,
installed,
+ canDelete,
onQuickInvoke,
onToggleInstall,
onUpdateOutdated,
+ onExport,
+ onDelete,
}: {
plugin: PluginItem;
/** The library's category, shown as the row's first tag (the page has no groups). */
category: string;
installed: InstalledMap;
+ /** Whether this account may delete, which is the account's admin right and not a Project role (see the page header). */
+ canDelete: boolean;
onQuickInvoke: (skillName: string) => void;
onToggleInstall: (agentId: string, plugin: PluginItem, on: boolean) => Promise<void>;
onUpdateOutdated: (name: string, agentIds: string[]) => Promise<void>;
+ onExport: (name: string) => Promise<void>;
+ onDelete: (plugin: PluginItem) => Promise<void>;
}) {
const { locale } = useLocale();
const { agents, currentAgent } = useProject();
@@ -1236,6 +1377,10 @@ function PluginCard({
const [updating, setUpdating] = useState(false);
// Agent pending an uninstall confirmation (null = none): uninstalling deletes the installed files, local edits included.
const [pendingUninstall, setPendingUninstall] = useState<string | null>(null);
+ // Whether this card's delete confirmation is open: deleting a user plugin removes its directory from disk, so it confirms first, like the uninstall above.
+ const [deleteOpen, setDeleteOpen] = useState(false);
+ /** A user plugin, i.e. one from the server's plugin directory: the only kind the library can delete, and the only kind that carries a "user" mark. */
+ const isUser = plugin.source === "user";
const confirmUpdate = async () => {
if (!pendingUpdate) return;
@@ -1330,10 +1475,16 @@ function PluginCard({
>
{meta}
</p>
- {/* Tag line: the category, "built in" (the library ships with the build), what it carries. */}
+ {/* Tag line: the category, where the plugin came from (the build, or the server's plugin
+ directory — the two kinds carry different actions, so this is what says which a card
+ is), and what it carries. */}
<div className="mt-2 flex flex-wrap items-center gap-1.5 text-xs">
<Tag>{category}</Tag>
- <Tag title={S.plugins.libraryBuiltinHint}>{S.plugins.builtin}</Tag>
+ {isUser ? (
+ <Tag title={S.plugins.userBadgeHint}>{S.plugins.userBadge}</Tag>
+ ) : (
+ <Tag title={S.plugins.libraryBuiltinHint}>{S.plugins.builtin}</Tag>
+ )}
{plugin.skills.length > 0 && <Tag mono>{S.skills.skillCount(plugin.skills.length)}</Tag>}
{plugin.hooks.length > 0 && <Tag mono>{S.hooks.hookCount(plugin.hooks.length)}</Tag>}
</div>
@@ -1388,6 +1539,35 @@ function PluginCard({
>
<GlyphIcon d={INSTALL_ICON} size={ICON_SIZE.iconButton} />
</Button>
+ {/* Export, for a user plugin only (a built-in is in the build, so there is nothing to take
+ a copy of): the archive download the Skills and Hooks rows export with, open to every
+ member — the route is a read. */}
+ {isUser && (
+ <Button
+ size="sm"
+ variant="secondary"
+ className="h-8 w-8 shrink-0 justify-center p-0"
+ aria-label={`${S.plugins.exportPlugin} ${plugin.name}`}
+ title={S.plugins.exportPlugin}
+ onClick={() => void onExport(plugin.name)}
+ >
+ <DownloadIcon size={ICON_SIZE.iconButton} />
+ </Button>
+ )}
+ {/* Delete, for a user plugin and an admin: the one action that removes files from the
+ machine, so it takes the danger variant and confirms first. */}
+ {isUser && canDelete && (
+ <Button
+ size="sm"
+ variant="danger"
+ className="h-8 w-8 shrink-0 justify-center p-0"
+ aria-label={`${S.plugins.deletePluginAction} ${plugin.name}`}
+ title={S.plugins.deletePluginAction}
+ onClick={() => setDeleteOpen(true)}
+ >
+ <GlyphIcon d={ICONS.trash} size={ICON_SIZE.iconButton} />
+ </Button>
+ )}
</div>
{installOpen && (
<Modal
@@ -1473,6 +1653,25 @@ function PluginCard({
</p>
</ConfirmModal>
)}
+ {/* Delete confirmation: unlike an uninstall, this takes the plugin's directory — and with
+ it every skill and hook it ships — off the machine, so it asks first and says so. */}
+ {deleteOpen && (
+ <ConfirmModal
+ open
+ title={S.plugins.deleteConfirmTitle(plugin.name)}
+ confirmLabel={S.plugins.deletePluginAction}
+ cancelLabel={S.common.cancel}
+ onClose={() => setDeleteOpen(false)}
+ onConfirm={() => {
+ setDeleteOpen(false);
+ void onDelete(plugin);
+ }}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.plugins.deleteConfirmBody(plugin.name)}
+ </p>
+ </ConfirmModal>
+ )}
</div>
);
}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 04cca137..a668e13f 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -2125,6 +2125,116 @@ export const en: Strings = {
uninstallConfirmTitle: (name: string): string => `Uninstall ${name}`,
uninstallConfirmBody: (plugin: string, agent: string): string =>
`Uninstall ${plugin} from ${agent}? Its installed skill and hook files (local edits included) will be deleted.`,
+ /** Import actions in the page header (admin only — the plugin directory belongs to the server, not to a Project). */
+ importUpload: "Upload plugin",
+ importDownload: "Download from URL",
+ /** Busy states: the upload one replaces the file-picker label, the download one its dialog's confirm button. */
+ importUploading: "Uploading\u2026",
+ importDownloading: "Downloading\u2026",
+ /** Client-side refusal of a picked zip over the decoded-archive cap; the file is dropped unread, so the server's own 413 never has to be earned. */
+ importTooLarge: (mb: number): string =>
+ `A plugin archive cannot exceed ${mb} MB \u2014 compress it and try again`,
+ /**
+ * The import rules, shown as one numbered block at the foot of BOTH dialogs: they are the
+ * shape a plugin has to arrive in, not the property of one source, and a reader who opened
+ * the wrong dialog should still learn them. Ordered, because the name is decided by a
+ * precedence the reader has to walk (typed \u2192 URL \u2192 the archive's own layout), and that order
+ * is the trap a repository URL sets: it carries the repository's name.
+ */
+ importRulesTitle: "Plugin import rules",
+ importRules: [
+ "The source is a local zip, or a URL: a direct zip link, a GitHub repository (its default branch), or a directory inside one (\u2026/tree/<ref>/<subdir>).",
+ "The archive must be a zip carrying plugin.json; the plugin root is the shallowest directory holding one, and two of them at the same depth are refused.",
+ "The name is taken in this order: what you type here \u2192 the name the URL carries (a directory URL's last segment, a repository URL's repository name, a zip link's file name) \u2192 the plugin root's directory name; letters, digits, underscores and hyphens only. Importing from a repository URL therefore installs it under the repository's name.",
+ "Caps: an uploaded zip is at most 14 MB and a downloaded archive 32 MB; after unpacking, only the plugin root counts \u2014 200 files, 5 MB each, 20 MB in total.",
+ "A name a built-in plugin already holds cannot be imported (pick another); a user plugin of the same name is confirmed first, and overwriting replaces every one of its files.",
+ ],
+ /**
+ * The other half, under it: what a plugin has to BE, rather than what the import does with
+ * it. Written here rather than in any one plugin repository for the reason the rules exist
+ * at all \u2014 a plugin outlives the repository it was published in, and the two rules that keep
+ * being broken (account details and credentials inside the plugin) are broken by whoever is
+ * writing one, who is looking at this surface and not at that repository's README.
+ */
+ authoringRulesTitle: "Plugin authoring rules",
+ authoringRules: [
+ "One directory per plugin, named after it; plugins share no files \u2014 copy what you need rather than reaching across.",
+ "The directory carries plugin.json (description, version) and skills/<skill>/SKILL.md; to hand it to someone, zip it with the plugin name as the top-level directory.",
+ "No account details inside a plugin: the AppID, keys, mail addresses and phone numbers belong to whoever installs it \u2014 read them from their memory or the environment, and make every script take them as an argument instead of defaulting to yours.",
+ "No credentials in the plugin directory: private keys, tokens and cookies stay out.",
+ ],
+ /**
+ * Local upload dialog: what the archive has to be, the picker that is its source field, the
+ * file it will send, and the confirm. The dialog's title reuses importUpload.
+ */
+ uploadDesc:
+ "A zip archive carrying plugin.json: at its root, or inside any one of its directories (the shallowest directory holding plugin.json becomes the plugin root).",
+ uploadPickFile: "Choose a zip file",
+ uploadPicked: (file: string): string => `Selected ${file}`,
+ uploadAction: "Upload and import",
+ /** Success toast of both imports; the library list and the directory line are re-read with it, which is how the new plugin appears. */
+ importDoneToast: (name: string): string => `Imported the plugin ${name}`,
+ /** Overwrite confirmation both imports raise on the 409 plugin_exists they answer with (the confirm resends the same request with overwrite: true). */
+ importOverwriteTitle: "Overwrite the user plugin of that name",
+ importOverwriteBody: (name: string): string =>
+ `The user plugin \u201c${name}\u201d already exists. Overwriting replaces every one of its files (local edits included) and cannot be undone. Continue?`,
+ importOverwriteAction: "Overwrite",
+ /**
+ * The name field both import dialogs carry. The label stays bare on purpose \u2014 the app's
+ * marker rule is that a field with no red "*" is the optional one, and never that a label
+ * says so (test/required-mark.test.ts) \u2014 while the hint says what leaving it empty does
+ * and names the ONE case that needs a value: plugin.json at the very root of the zip, where
+ * there is no directory to take a name from and the server refuses the request rather than
+ * guessing one.
+ */
+ pluginNameLabel: "Plugin name",
+ pluginNameHint:
+ "When left empty, the plugin is named after the directory inside the archive that holds plugin.json; it is needed only when plugin.json sits at the very root of the zip, where there is no directory to name it after (the server refuses that request instead of inventing a name).",
+ pluginNamePlaceholder: "my-plugin",
+ /** Sits under the field, and holds the submit back, while the typed name breaks the rule the server applies to the directory a plugin is installed into. */
+ pluginNameInvalid: "Letters, digits, underscores and hyphens only (^[A-Za-z0-9_-]+$).",
+ /** Remote download dialog. */
+ downloadTitle: "Download a plugin from a URL",
+ downloadUrlLabel: "Plugin URL",
+ downloadUrlHint:
+ "A direct zip link, or a GitHub repository URL (https://github.com/<owner>/<repo>, default branch) or a directory inside one (\u2026/tree/<ref>/<subdir>)",
+ downloadUrlPlaceholder: "https://github.com/<owner>/<repo> or https://\u2026/plugin.zip",
+ downloadDesc:
+ "The archive must carry plugin.json; for a GitHub repository or directory URL the shallowest directory containing plugin.json becomes the plugin root.",
+ downloadAction: "Download and import",
+ /** "User" badge on a card whose plugin comes from the user plugin directory rather than the build. */
+ userBadge: "User",
+ userBadgeHint:
+ "From the user plugin directory: exportable as a backup, imported and deleted by an admin",
+ /** Card actions of a user plugin (a built-in plugin keeps today's actions only). */
+ exportPlugin: "Export plugin",
+ deletePluginAction: "Delete plugin",
+ deleteConfirmTitle: (name: string): string => `Delete ${name}`,
+ deleteConfirmBody: (name: string): string =>
+ `Delete the user plugin ${name}? Its directory is removed from disk and cannot be recovered.`,
+ deletedToast: (name: string): string => `Deleted the plugin ${name}`,
+ /** User plugin directory line under the title (path + copy button + count). */
+ dirLabel: "User plugin directory",
+ dirPathCopy: "Copy the directory path",
+ dirCount: (n: number): string => (n === 1 ? "1 user plugin" : `${n} user plugins`),
+ /** Count line at zero: worded rather than "0 user plugins", which reads like a fault. */
+ dirEmpty: "No user plugins in it yet",
+ /** The directory read failed: the line says so in words, since there is no path to show. */
+ dirUnavailable: "Could not read the user plugin directory",
+ /** Appended to the page's "?" for a non-admin, who sees no import or delete action. */
+ adminOnly: "Only an admin can import or delete plugins.",
+ /** Import and delete failures, keyed by the code the route answers with (pluginImportErrorText falls back to the server's own message for anything not named here). */
+ importErrors: {
+ plugin_exists: "A user plugin of that name already exists.",
+ plugin_builtin:
+ "A built-in plugin cannot be overwritten or deleted (import it under another name).",
+ unsupported_url:
+ "That URL is not supported: use a direct zip link, or a GitHub repository or directory URL.",
+ blocked_url: "That URL was refused (an internal address, or one that is not allowed).",
+ download_failed: "The download failed \u2014 check that the URL is reachable.",
+ invalid_plugin: "The archive carries no valid plugin.json.",
+ plugin_too_large: "The plugin archive exceeds the server's size limit.",
+ },
},
/** Agent settings "Hooks" tab (features/agents/hooks-tab.tsx): the hook packages installed on one agent — the list with its enable switch, the import modal (chat import / zip upload) and the export. The hook-point chips carry the bare point name (`stop`, `user_prompt`) and need no string. */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 637f8c8c..b6c9f9d1 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -2166,6 +2166,112 @@ export const zh = {
uninstallConfirmTitle: (name: string): string => `卸载 ${name}`,
uninstallConfirmBody: (plugin: string, agent: string): string =>
`确定从 ${agent} 卸载 ${plugin} 吗?其已安装的技能与钩子文件(含本地改动)将被删除。`,
+ /** Import actions in the page header (admin only — the plugin directory belongs to the server, not to a Project). */
+ importUpload: "上传插件",
+ importDownload: "远程下载",
+ /** Busy states: the upload one replaces the file-picker label, the download one its dialog's confirm button. */
+ importUploading: "上传中…",
+ importDownloading: "下载中…",
+ /** Client-side refusal of a picked zip over the decoded-archive cap; the file is dropped unread, so the server's own 413 never has to be earned. */
+ importTooLarge: (mb: number): string => `插件包不能超过 ${mb} MB,请压缩后重试`,
+ /**
+ * The import rules, shown as one numbered block at the foot of BOTH dialogs: they are the
+ * shape a plugin has to arrive in, not the property of one source, and a reader who opened
+ * the wrong dialog should still learn them. Ordered, because the name is decided by a
+ * precedence the reader has to walk (typed → URL → the archive's own layout), and that order
+ * is the trap a repository URL sets: it carries the repository's name.
+ */
+ importRulesTitle: "插件导入规则",
+ importRules: [
+ "来源是本地 zip,或一个地址——zip 直链、GitHub 仓库地址(取默认分支)、仓库内目录地址(…/tree/<分支>/<子目录>)。",
+ "压缩包必须是含 plugin.json 的 zip;插件根取归档里最浅一层含 plugin.json 的目录,同一层出现多个则拒绝。",
+ "插件名依次取:你填的名字 → 地址自带的名字(目录地址取末段目录名、仓库地址取仓库名、zip 链接取文件名)→ 插件根的目录名;只能用字母、数字、下划线和中划线。所以从仓库地址导入会装成仓库名。",
+ "上传的 zip 不超过 14 MB,远程归档不超过 32 MB;解包后只统计插件根之下:200 个文件、单文件 5 MB、合计 20 MB。",
+ "内置插件占用的名字不能导入(换个名字);同名用户插件会先问一次是否覆盖,覆盖即替换其全部文件。",
+ ],
+ /**
+ * The other half, under it: what a plugin has to BE, rather than what the import does with
+ * it. Written here rather than in any one plugin repository for the reason the rules exist
+ * at all — a plugin outlives the repository it was published in, and the two rules that keep
+ * being broken (account details and credentials inside the plugin) are broken by whoever is
+ * writing one, who is looking at this surface and not at that repository's README.
+ */
+ authoringRulesTitle: "插件编写规则",
+ authoringRules: [
+ "一个插件一个目录,目录名即插件名;插件之间不共享文件,要复用就复制一份。",
+ "目录里要有 plugin.json(描述、版本)和 skills/<技能名>/SKILL.md;给别人时打成 zip,顶层目录名就是插件名。",
+ "不要把账号信息写进插件——AppID、密钥、邮箱、手机号都属于使用者:从记忆或环境变量里读,脚本一律做成参数,不要写死默认值。",
+ "不提交密钥:私钥、token、cookie 都不进插件目录。",
+ ],
+ /**
+ * Local upload dialog: what the archive has to be, the picker that is its source field, the
+ * file it will send, and the confirm. The dialog's title reuses importUpload.
+ */
+ uploadDesc:
+ "zip 压缩包,需带有 plugin.json:放在压缩包根目录,或放在其中任意一层目录里(取最浅一层含 plugin.json 的目录作为插件根)。",
+ uploadPickFile: "选择 zip 文件",
+ uploadPicked: (file: string): string => `已选择 ${file}`,
+ uploadAction: "上传并导入",
+ /** Success toast of both imports; the library list and the directory line are re-read with it, which is how the new plugin appears. */
+ importDoneToast: (name: string): string => `已导入插件 ${name}`,
+ /** Overwrite confirmation both imports raise on the 409 plugin_exists they answer with (the confirm resends the same request with overwrite: true). */
+ importOverwriteTitle: "覆盖同名用户插件",
+ importOverwriteBody: (name: string): string =>
+ `用户插件「${name}」已存在,覆盖导入会替换其全部文件(含本地改动),不可恢复。确认继续?`,
+ importOverwriteAction: "覆盖导入",
+ /**
+ * The name field both import dialogs carry. The label stays bare on purpose — the app's
+ * marker rule is that a field with no red "*" is the optional one, and never that a label
+ * says so (test/required-mark.test.ts) — while the hint says what leaving it empty does and
+ * names the ONE case that needs a value: plugin.json at the very root of the zip, where there
+ * is no directory to take a name from and the server refuses the request rather than guessing
+ * one.
+ */
+ pluginNameLabel: "插件名称",
+ pluginNameHint:
+ "留空时,取压缩包内含 plugin.json 的那层目录名作为插件名;仅当 plugin.json 就放在 zip 根目录、没有目录可供取名时才需要填写(此时留空会被服务端拒绝,不会自动取名)。",
+ pluginNamePlaceholder: "my-plugin",
+ /** Sits under the field, and holds the submit back, while the typed name breaks the rule the server applies to the directory a plugin is installed into. */
+ pluginNameInvalid: "只能用字母、数字、下划线和中划线(^[A-Za-z0-9_-]+$)。",
+ /** Remote download dialog. */
+ downloadTitle: "远程下载插件",
+ downloadUrlLabel: "插件地址",
+ downloadUrlHint:
+ "zip 直链,或 GitHub 仓库地址(https://github.com/<owner>/<repo>,取默认分支)与仓库内目录地址(…/tree/<ref>/<subdir>)",
+ downloadUrlPlaceholder: "https://github.com/<owner>/<repo> 或 https://…/plugin.zip",
+ downloadDesc:
+ "压缩包需带有 plugin.json;GitHub 仓库或目录地址会自动选取最浅一层含 plugin.json 的目录作为插件根。",
+ downloadAction: "下载并导入",
+ /** "User" badge on a card whose plugin comes from the user plugin directory rather than the build. */
+ userBadge: "用户",
+ userBadgeHint: "来自用户插件目录:可导出备份,由管理员导入或删除",
+ /** Card actions of a user plugin (a built-in plugin keeps today's actions only). */
+ exportPlugin: "导出插件",
+ deletePluginAction: "删除插件",
+ deleteConfirmTitle: (name: string): string => `删除 ${name}`,
+ deleteConfirmBody: (name: string): string =>
+ `确定删除用户插件 ${name} 吗?其目录会从磁盘删除,不可恢复。`,
+ deletedToast: (name: string): string => `已删除插件 ${name}`,
+ /** User plugin directory line under the title (path + copy button + count). */
+ dirLabel: "用户插件目录",
+ dirPathCopy: "复制目录路径",
+ dirCount: (n: number): string => `${n} 个用户插件`,
+ /** Count line at zero: worded rather than "0 个用户插件", which reads like a fault. */
+ dirEmpty: "目录中还没有用户插件",
+ /** The directory read failed: the line says so in words, since there is no path to show. */
+ dirUnavailable: "无法读取用户插件目录",
+ /** Appended to the page's "?" for a non-admin, who sees no import or delete action. */
+ adminOnly: "只有管理员可以导入或删除插件。",
+ /** Import and delete failures, keyed by the code the route answers with (pluginImportErrorText falls back to the server's own message for anything not named here). */
+ importErrors: {
+ plugin_exists: "已存在同名用户插件。",
+ plugin_builtin: "内置插件不能被覆盖或删除(导入同名插件请另起一个名字)。",
+ unsupported_url: "该地址不受支持:请填 zip 直链,或 GitHub 仓库/目录地址。",
+ blocked_url: "该地址被拒绝(内网或其他不允许的地址)。",
+ download_failed: "下载失败,请确认该地址可以访问。",
+ invalid_plugin: "压缩包里没有合法的 plugin.json。",
+ plugin_too_large: "插件包超过了服务端的大小上限。",
+ },
},
/** Agent settings "Hooks" tab (features/agents/hooks-tab.tsx): the hook packages installed on one Agent — the list with its enable switch, the import modal (chat import / zip upload) and the export. The hook-point chips carry the bare point name (`stop`, `user_prompt`) and need no string. */
diff --git a/packages/web/test/plugin-import-rules.test.ts b/packages/web/test/plugin-import-rules.test.ts
new file mode 100644
index 00000000..421f6188
--- /dev/null
+++ b/packages/web/test/plugin-import-rules.test.ts
@@ -0,0 +1,77 @@
+/**
+ * The plugin rules panel (src/features/plugins/plugin-import-dialog.tsx).
+ *
+ * It states, at the point where an operator is naming a plugin, the rules the form cannot show.
+ * Two of them carry the weight: leave the name empty and it comes from the SOURCE — and a GitHub
+ * repository URL carries the repository's name, which is how a plugin installs under a name
+ * nobody asked for; and a plugin must not carry its author's account details or credentials, a
+ * rule whose home is this surface rather than any one plugin repository.
+ *
+ * The dialogs themselves cannot be rendered here (Modal portals to document.body, this suite is
+ * `environment: "node"`), so the panel is rendered on its own and the two dialogs are checked
+ * against the source, the way modal-focus.test.ts checks its portal-bound wiring.
+ */
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { PluginRules } from "../src/features/plugins/plugin-import-dialog";
+import { S } from "../src/lib/strings";
+
+const source = readFileSync(
+ fileURLToPath(new URL("../src/features/plugins/plugin-import-dialog.tsx", import.meta.url)),
+ "utf8",
+);
+
+/** React escapes `&`, `<` and `>` in text children; the rules quote URL shapes, so the markup holds the escaped form. */
+const asMarkup = (text: string): string =>
+ text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+
+describe("PluginRules", () => {
+ const html = renderToStaticMarkup(createElement(PluginRules));
+
+ it("carries both titles: importing a plugin, and writing one", () => {
+ expect(html).toContain(S.plugins.importRulesTitle);
+ expect(html).toContain(S.plugins.authoringRulesTitle);
+ expect(S.plugins.importRules.length).toBeGreaterThan(0);
+ expect(S.plugins.authoringRules.length).toBeGreaterThan(0);
+ });
+
+ it("lists every rule of both lists, in order, as numbered lists", () => {
+ // Ordered and not bulleted on purpose: the name rule is a precedence the reader walks.
+ const lists = html.match(/<ol[^>]*>.*?<\/ol>/g) ?? [];
+ expect(lists).toHaveLength(2);
+ expect(html.match(/<li>/g) ?? []).toHaveLength(
+ S.plugins.importRules.length + S.plugins.authoringRules.length,
+ );
+ for (const [i, rules] of [S.plugins.importRules, S.plugins.authoringRules].entries()) {
+ const positions = rules.map((rule) => lists[i]!.indexOf(asMarkup(rule)));
+ expect(positions).not.toContain(-1);
+ expect(positions).toEqual([...positions].sort((a, b) => a - b));
+ }
+ });
+
+ it("spells out the rule the form cannot show: the name comes from the source", () => {
+ // The precedence itself — typed name, then the source's own name, then the archive's layout.
+ expect(html).toContain("你填的名字");
+ expect(html).toContain("仓库地址取仓库名");
+ // …and the caps and the collision rule, which no control on the dialog states either.
+ expect(html).toContain("14 MB");
+ expect(html).toContain("32 MB");
+ expect(html).toContain("覆盖");
+ });
+
+ it("keeps a plugin's author from baking in account details or credentials", () => {
+ const authoring = S.plugins.authoringRules.join("\n");
+ expect(authoring).toContain("目录名即插件名");
+ expect(authoring).toContain("不要把账号信息写进插件");
+ expect(authoring).toContain("不提交密钥");
+ // Stated as the reader's own values being the wrong default, which is how they get in.
+ expect(authoring).toContain("不要写死默认值");
+ });
+
+ it("is rendered by both import dialogs, upload and download", () => {
+ expect(source.match(/<PluginRules \/>/g) ?? []).toHaveLength(2);
+ });
+});
diff --git a/packages/web/test/plugin-import.test.ts b/packages/web/test/plugin-import.test.ts
new file mode 100644
index 00000000..2e376691
--- /dev/null
+++ b/packages/web/test/plugin-import.test.ts
@@ -0,0 +1,186 @@
+/**
+ * The plugin import flows' pure half (features/plugins/plugin-import): the client-side size
+ * guard, the optional plugin-name field, the name a failed import is about, and the code → copy
+ * mapping.
+ *
+ * What matters is agreement with the SERVER rather than these functions' own arithmetic. The
+ * size guard exists only to save a user a pointless upload, so it must draw the line exactly
+ * where the server does (`>` the cap, not `>=`) — a stricter client silently blocks a legal
+ * file, a looser one replaces a clear refusal with a 413 after a long base64 upload. The name
+ * field is the same kind of agreement on a different rule: what it holds back is a request the
+ * server would answer 400 for, and what it must NOT hold back is the empty field, which is how
+ * the archive gets to name the plugin. The name and the message both feed a confirmation the
+ * user reads before overwriting a plugin directory, so a miss there either names the wrong
+ * plugin or asks in English.
+ */
+import { describe, expect, it } from "vitest";
+import { ApiError } from "../src/api/client";
+import { MB_BYTES } from "../src/lib/upload-limits";
+import { S } from "../src/lib/strings";
+import {
+ PLUGIN_NAME_PATTERN,
+ PLUGIN_ZIP_LIMIT_MB,
+ pluginImportErrorText,
+ pluginNameBody,
+ pluginNameFromError,
+ pluginNameFromUrl,
+ pluginNameInvalid,
+ pluginZipTooLarge,
+} from "../src/features/plugins/plugin-import";
+
+describe("pluginZipTooLarge", () => {
+ it("refuses one byte over the cap and accepts a zip of exactly the cap", () => {
+ // The server's check is `bytes.length > limit`, so the boundary file is legal; pinning both
+ // sides is the point, since an off-by-one here would be invisible in normal use and would
+ // reject exactly the archive a user just repacked to fit.
+ expect(pluginZipTooLarge(PLUGIN_ZIP_LIMIT_MB * MB_BYTES)).toBe(false);
+ expect(pluginZipTooLarge(PLUGIN_ZIP_LIMIT_MB * MB_BYTES + 1)).toBe(true);
+ expect(pluginZipTooLarge(0)).toBe(false);
+ });
+});
+
+describe("pluginNameFromUrl", () => {
+ it("names the repository of a GitHub repo URL, a trailing .git included", () => {
+ expect(pluginNameFromUrl("https://github.com/acme/my-plugin")).toBe("my-plugin");
+ expect(pluginNameFromUrl("https://github.com/acme/my-plugin.git")).toBe("my-plugin");
+ });
+
+ it("names the plugin root a tree URL points at, not the ref in front of it", () => {
+ // The plugin is the SUBDIRECTORY (the shallowest one carrying plugin.json), and the ref
+ // names a commit: the confirmation used to name the commit whenever the paste was of a
+ // directory rather than a whole repo.
+ expect(pluginNameFromUrl("https://github.com/acme/mono/tree/main/plugins/review")).toBe(
+ "review",
+ );
+ expect(pluginNameFromUrl("https://github.com/acme/mono/tree/main/skills/a/b/c")).toBe("c");
+ // No subdirectory at all: the URL still has to name something, and the repo is what it
+ // carries.
+ expect(pluginNameFromUrl("https://github.com/acme/mono/tree/main")).toBe("mono");
+ });
+
+ it("names the file a plain link points at, and is unmoved by a query, a fragment or a trailing slash", () => {
+ expect(pluginNameFromUrl("https://example.com/downloads/web-design.zip")).toBe("web-design");
+ // What a browser address bar hands back: a token, an anchor, or the slash copy-paste adds.
+ expect(pluginNameFromUrl("https://example.com/x.zip?token=abc#frag")).toBe("x");
+ expect(pluginNameFromUrl("https://github.com/acme/my-plugin/")).toBe("my-plugin");
+ });
+});
+
+describe("pluginNameInvalid", () => {
+ it("accepts the empty field — the name is optional — and every name the rule allows", () => {
+ // Empty is the normal case (the archive names the plugin), so holding it to the rule would
+ // block precisely the import that never needed a name.
+ expect(pluginNameInvalid("")).toBe(false);
+ expect(pluginNameInvalid(" ")).toBe(false);
+ expect(pluginNameInvalid("web-design")).toBe(false);
+ expect(pluginNameInvalid("web_design2")).toBe(false);
+ // The surrounding blanks are the user's typing, not a name: they are trimmed before the check
+ // rather than reported as a broken one.
+ expect(pluginNameInvalid(" web-design ")).toBe(false);
+ });
+
+ it("rejects what the server would answer 400 for, so the submit never earns that 400", () => {
+ // The name IS the directory the plugin is installed into, so a space, a dot, a slash or a
+ // non-ASCII character is a 400 on the route — and has to be an inline message here instead.
+ for (const name of ["web design", "web.design", "a/b", "a\\b", "插件", "web-design!"]) {
+ expect(pluginNameInvalid(name), name).toBe(true);
+ }
+ });
+
+ it("pins the pattern the inline message quotes", () => {
+ // The copy spells the rule out (^[A-Za-z0-9_-]+$) for a user who wants to see it; this keeps
+ // the quotation honest.
+ expect(PLUGIN_NAME_PATTERN.source).toBe("^[A-Za-z0-9_-]+$");
+ });
+});
+
+describe("pluginNameBody", () => {
+ it("omits the field entirely when the box is empty, so the server names the plugin itself", () => {
+ // Never `name: ""`: the server reads an absent name as "name it after the archive" and an
+ // empty one as a name that breaks the rule — the exact 400 this field exists to keep away.
+ expect(pluginNameBody("")).toEqual({});
+ expect("name" in pluginNameBody(" ")).toBe(false);
+ });
+
+ it("sends the typed name, trimmed", () => {
+ expect(pluginNameBody(" web-design ")).toEqual({ name: "web-design" });
+ });
+});
+
+describe("pluginNameFromError", () => {
+ it("reads the name out of the 409's own sentence", () => {
+ // The wording the plugin routes answer with today, quoted from the route itself rather than
+ // invented: the confirmation names a plugin the user is about to overwrite, and a wrong
+ // name there is worse than no confirmation at all.
+ const err = new ApiError(
+ 409,
+ "plugin_exists",
+ "A user plugin named web-design is already installed.",
+ );
+ expect(pluginNameFromError(err, "fallback")).toBe("web-design");
+ });
+
+ it("also reads the tail form the skill and hook imports parse", () => {
+ const err = new ApiError(409, "plugin_exists", "Plugin is already installed: web-design");
+ expect(pluginNameFromError(err, "fallback")).toBe("web-design");
+ });
+
+ it("falls back to the caller's own name when the message names nothing", () => {
+ // A reworded server message must not leave the confirmation nameless; the picked file's
+ // stem (or the name the URL spells) is what the caller passes.
+ expect(pluginNameFromError(new ApiError(409, "plugin_exists", "conflict"), "picked")).toBe(
+ "picked",
+ );
+ expect(pluginNameFromError(new Error("boom"), "picked")).toBe("picked");
+ });
+});
+
+describe("pluginImportErrorText", () => {
+ /** The codes the upload, download and delete routes answer with for anything a user can fix. */
+ const CODES = [
+ "plugin_exists",
+ "plugin_builtin",
+ "unsupported_url",
+ "blocked_url",
+ "download_failed",
+ "invalid_plugin",
+ "plugin_too_large",
+ ];
+
+ it("localizes every code the routes answer with, instead of showing the server's English message", () => {
+ for (const code of CODES) {
+ const text = pluginImportErrorText(new ApiError(400, code, "An English server message."));
+ expect(text, code).toBe((S.plugins.importErrors as Record<string, string>)[code]);
+ expect(text, code).not.toBe("An English server message.");
+ expect(text.length, code).toBeGreaterThan(0);
+ }
+ });
+
+ it("leaves codes it does not name to the shared mapping, and unknown failures to the generic text", () => {
+ expect(pluginImportErrorText(new ApiError(403, "admin_required", "Admin only."))).toBe(
+ (S.errors.byCode as Record<string, string>).admin_required,
+ );
+ expect(pluginImportErrorText(new Error("boom"))).toBe(S.common.unknownError);
+ });
+
+ it("maps the 413 the upload route answers for an over-size zip just as it maps the download one", () => {
+ // Both import routes answer `plugin_too_large` from the same cap, so the one code → copy row
+ // covers both — this pins the UPLOAD flow, whose over-size refusal used to arrive as
+ // `bad_request` (a code with no copy of its own, so it showed the server's English sentence).
+ // The mapping is keyed by code rather than by route or status, which is what makes that hold.
+ const text = pluginImportErrorText(
+ new ApiError(413, "plugin_too_large", "The archive exceeds the 14MB limit."),
+ );
+ expect(text).toBe((S.plugins.importErrors as Record<string, string>).plugin_too_large);
+ expect(text).not.toBe("The archive exceeds the 14MB limit.");
+ });
+
+ it("leaves bad_request to the server's own sentence", () => {
+ // The upload route's remaining refusals are bad_requests whose sentence is about the request
+ // in hand ("The zip archive is empty."), which says more than any generic line could — so the
+ // code deliberately stays out of both tables.
+ expect(
+ pluginImportErrorText(new ApiError(400, "bad_request", "The zip archive is empty.")),
+ ).toBe("The zip archive is empty.");
+ });
+});