A local-first multi-agent app development platform, built on PenguinHarness
feat(plugins): list, install, and manage plugins (#383)
Myriad-Dreamine77cef3cc2a2
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex f98cdcf5..c19f22b5 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -118,7 +118,7 @@ single data directory (`~/.penguin/data`) and a single message protocol (OmniMes| [`plugins/*`](../plugins) | `@penguinharness/<name>` | The built-in plugins, one npm package each: skills (software development, model development, agent development/tuning, …) and session hooks (goal mode, skill summaries); the loader lives in `packages/core` || [`packages/landing`](../packages/landing) | — | Product landing page (this repo's website) || [`packages/docs`](../packages/docs) | — | Documentation site (bilingual, deployed under `/docs/`) |-| [`plugins/*`](../plugins) | `@prismshadow/penguin-plugin-*` | Plugin packages a deployment installs and lists in `plugins.json` — a directory of their own because nothing else in the harness depends on one |+| [`plugins/*`](../plugins) | `@prismshadow/penguin-plugin-*` | Plugin packages a Project asks for on the Plugins page (its `[plugins]` table) — a directory of their own because nothing else in the harness depends on one |Responsibilities split by source of truth: the **SDK** owns protocol and execution(message parsing, the agent loop, tools), the **Server** owns the multi-user runtimediff --git a/changelog/unreleased/2026-08-20-plugin-platform.md b/changelog/unreleased/2026-08-20-plugin-platform.mdnew file mode 100644index 00000000..153c9a9d--- /dev/null+++ b/changelog/unreleased/2026-08-20-plugin-platform.md@@ -0,0 +1,54 @@+# Plugins: a catalogue, packages shipped with every build, and a per-Project list the platform applies++- **Date:** 2026-08-20+- **Type:** feature+- **Scope:** `core`, `server`, `web`, `desktop`, `tooling`, `docs`+- **PR:** [#383](https://github.com/Prism-Shadow/penguin-harness/pull/383)+- **Breaking:** yes — the data root's `plugins.json` is no longer read; each Project asks for its plugins again on the Plugins page++[中文版](2026-08-20-plugin-platform.zh.md)++The harness gains plugins end to end: a registry abstraction and a shared index format on the server, the plugins this repository builds shipped as part of every deployment, a Plugins page that lists what a Project has and what it could have, a plugin list that belongs to the Project and takes effect without a restart, and the same list kept on the machines the Project uses. Plugins are loaded by the platform, so all of it reaches a running deployment by a push.++## Registries and the index format++- A **plugin registry** is one source of plugin index entries. Two implementations ship — a **builtin registry** serving an index embedded in the server package, and an **HTTP registry** fetching an `index.json` URL. Both run their document through the same validator, so a remote index is trusted no further than the embedded one.+- All registries share one **plugin index format**, modeled on typst/packages' `index.json` schema: a flat array of per-version entries with `name`, `version`, `description`, `authors`, `license`, and optional `repository` / `homepage` / `keywords` / `categories` / `updatedAt`. An entry's `name` is the package specifier a Project's plugin list names.+- `GET /api/plugins/registry` (any logged-in user) serves the merged index of the configured registries. The builtin one lists the packages this build ships: the four sandbox backends — bubblewrap (Linux), Seatbelt (macOS), MXC (Windows) and the DSH adaptor — and the language floor.+- A readme is fetched per entry through `GET /api/plugins/registry/readme?name=…` rather than carried in the index: the listing is sent in full on every visit, while a readme is large and wanted only for the entry someone opened. The endpoint answers only for entries the deployment lists, so it cannot be used to probe what exists; a registry that has no readme for an entry answers null rather than a guessed URL. The readmes are the packages' own `README.md` files, read from the package on this machine, so the catalogue holds no second copy of the prose to drift from the first; a test pins every listed entry's name, version, description and license to what the package itself declares.++## Shipped as the npm packages they are++`scripts/build-plugins.mjs` takes every `plugins/*` package with a code entry, runs the package's own `build`, packs it with `pnpm pack` — exactly what `npm publish` would send, `files` honored — and installs the tarballs with `npm install` into a staging directory laid out as an npm prefix: `plugins/package.json`, whose `dependencies` name what was shipped, plus `plugins/node_modules/<name>/…`, each package's dependencies beside it the way npm installs them anywhere. Nothing about a package is rewritten: its `package.json`, its `exports`, its `dist/`, its generated `ifaces.json` and its `README.md` reach the target as its own build produced them. The SDK is not among the installed dependencies — a plugin compiles against `@prismshadow/penguin-core`'s types and shares the host's copy at run time. The staged prefix is cached under `node_modules/.cache/penguin-plugins/` by the hash of every plugin's sources, manifest, README and build config, so a push that touched nothing there builds, packs and installs nothing again.++A hot push ships the prefix among its assets (`plugins/…`); the desktop build stages it beside `skills/` (`scripts/build-assets.mjs`, `electron-builder.yml`). The loader resolves plugins from, in order: `<root>/plugins` (the data root's own prefix), the committed push's `plugins/` (read from `harness.json`, no host needed), the installation's `plugins/`, and the installation entry — looking a package up the way Node does and reading the entry an importer would, its `exports` import condition or `main`.++**Shipping one is not installing it.** `builtin` is a tag on where a package came from, never a second way of being installed: a plugin the build carries appears in the catalogue marked *built in* — installing it copies nothing over the network — and it is installed, loaded and removed exactly like any other, by a Project listing it. Only a plugin the build ships can be asked for; a name the build does not ship is refused rather than listed, so a Project never names a package that is not on the machine.++## The Plugins page++One list, one plugin per row, every kind in the same card, with a search box above it and the filters beside it. **Installed plugins (N)** comes first, folded by default: the library's skill and hook packages, which ship with the build and every Agent may use, and the module plugins the current Project asks for, each with what the running process makes of it — *Installed*, *Running*, or *Restart to load*. **Available** follows: the registry entries the Project does not ask for yet, and a shipped package the registry has no entry for. A row carries the plugin's name, description, version and update date, and its tags: the category (Office Productivity, sandbox, languages, …), *built in*, and the keywords. The filters are three controlled facets, each option with its count — **Categories**, **Contains** (skills, hooks, modules) and **Status** (installed, available, running, restart to load); options within a facet widen the match, facets narrow it. Each row carries its control, so a plugin is asked for where it is read about, and removed there too. An entry opens a detail page with its metadata and rendered readme, so choosing a sandbox backend does not mean reading its source.++## The list belongs to a Project; the process runs the closure++A Project's plugins live in its own config — the `[plugins]` table in `.project_config.toml`, package name → requirement in the shape of Cargo's `[dependencies]` (`"@scope/name" = "*"` for whatever the deployment ships, a version string, or `{ version = "…" }` where later fields go), beside its models — because machines are lent to Projects, so a Project's list is what says which machines a plugin has to reach (see PRFC-0010). Loading is per process, though: there is one module tree. So what a deployment runs is the **closure**, the union over its Projects, and what a plugin contributes is visible to all of them. A row on the Plugins page is therefore two facts joined: this Project asked for it, and the process has it.++The routes are `/api/projects/:projectId/plugins/installed`: `GET` (any member of the Project) reads the list with what the process makes of each entry, `PUT { plugins }` (admin) rewrites it, `POST { specifier }` (admin) asks for one plugin and `DELETE …?specifier=` drops it. Every name that enters the list passes the same gate, on `PUT` as on `POST`: a package name, never a path or a subpath, and one the build ships. Asking is consent, not a download; removing changes nothing on disk, and a package leaves the disk only once no Project asks for it. A listed plugin the process could not load — a specifier that does not resolve, a package whose table is missing, an import that threw, a module name another plugin already took — is reported with that reason rather than as a pending restart, and the page shows the row as failed with the reason. A Project whose config cannot be read contributes nothing to the closure and its own list view reports the fault; the other Projects' deployment comes up.++## Applied without a restart, by the platform++A write asks the App to re-assemble itself: the platform boots its inner tree again with the kernel's own `upgrade` — same bundle, same parked document, the swap a hot push already performs — so ptys and machine connections cross it exactly as they cross a push, and what a push stops, this stops too: the agent runs in progress, in every Project, since there is one tree. The page says so before an admin applies a change. No process restart, and nothing in the HMR layer is involved: the runtime keeps holding the same outer instance throughout, which is why this works on every runtime, old ones included. The edit travels with the re-assembly: it is written in the re-assembly's queue, so two admins' edits of one file never interleave, and a boot that fails undoes it before the previous App is restored — reported as "did not take", with the list as it was.++Reading the closure and importing it is the platform's, in its own boot, rather than the runtime's at process start. Which plugins a deployment runs, and how that list is read, is policy; a machine whose program predated a rule could otherwise never learn it from a push — a machine given a Project's list sat with every plugin inactive because its program still looked for the old `plugins.json`. Now any deployment that can take a push can take a plugin change. What stays in the registry across a swap is the imported objects, claimed by the next App and reused by specifier, never imported twice; an entry the closure no longer names is simply absent from the new host. The host in the registry is written only by a boot that succeeded, so a plugin can no longer read as active while nothing running contains it. The runtime keeps a load of its own as a shim, for a platform older than this move being rolled back onto it.++## The same list on a Project's machines++A Project's list is handed to the machines it uses, on the same trip its Model credentials already take and at the same moments: when the list changes, and again on connect. Parity is **strict** — the Project's list is the truth and what a machine has beyond it is removed.++That has a cost worth knowing: a platform-specific sandbox backend is not in the other platform's list and is therefore taken away. Keeping one means listing it fleet-wide; a machine that cannot resolve it shows an inert error row rather than losing the backend it can use. The sync reports per machine what it added, what it removed, what that machine lists but cannot resolve (most often a machine that needs updating first), and whether it still has to restart.++## Compatibility++**The data root's `plugins.json` is no longer read, and nothing migrates it.** A deployment that had one starts with **no plugins**: sandbox backends, languages and session surfaces are all absent from the tree until each Project asks again on the Plugins page. The old file is left on disk untouched, so rolling back to an earlier platform finds it exactly as it was.++The same holds for the list form this key briefly had before release (`plugins = ["…"]`): it is not read, and such a Project asks for no plugins until its table is written again from the Plugins page.diff --git a/changelog/unreleased/2026-08-20-plugin-platform.zh.md b/changelog/unreleased/2026-08-20-plugin-platform.zh.mdnew file mode 100644index 00000000..0d8d907b--- /dev/null+++ b/changelog/unreleased/2026-08-20-plugin-platform.zh.md@@ -0,0 +1,54 @@+# 插件:一个目录、随每个构建发布的包,以及由 platform 应用的 Project 级清单++- **Date:** 2026-08-20+- **Type:** feature+- **Scope:** `core`, `server`, `web`, `desktop`, `tooling`, `docs`+- **PR:** [#383](https://github.com/Prism-Shadow/penguin-harness/pull/383)+- **Breaking:** yes — 数据根的 `plugins.json` 不再被读取;各 Project 在插件页重新要求自己的插件++[English](2026-08-20-plugin-platform.md)++harness 从头到尾有了插件:服务端的注册表抽象与共享索引格式;本仓库构建出的插件成为每个部署自带的一部分;一个插件页,列出 Project 已有的和可以拥有的;一份属于 Project、不重启即生效的插件清单;以及在 Project 使用的机器上保持一致的同一份清单。插件由 platform 加载,因此这一切都能靠一次推送抵达运行中的部署。++## 注册表与索引格式++- **插件注册表(plugin registry)**是一个插件索引条目来源。本次实现两种——服务端包内嵌索引的**内置注册表(builtin registry)**,以及拉取 `index.json` URL 的 **HTTP 注册表**。两者共用同一个校验器,远端索引不会比内嵌索引获得更多信任。+- 所有注册表共享同一份**插件索引格式**,参考 typst/packages 的 `index.json` 模式:扁平数组,每个元素是插件的一个版本条目,含 `name`、`version`、`description`、`authors`、`license`,可选 `repository` / `homepage` / `keywords` / `categories` / `updatedAt`。条目的 `name` 就是 Project 插件清单里写的包名。+- `GET /api/plugins/registry`(任何已登录用户可访问)返回已配置注册表合并后的索引。内置注册表列出本构建自带的包:四个沙盒后端——bubblewrap(Linux)、Seatbelt(macOS)、MXC(Windows)与 DSH 适配器——以及语言楼层。+- 说明文档按条目单独通过 `GET /api/plugins/registry/readme?name=…` 获取,而不随索引下发:列表每次进入页面都要完整发送,而说明文档体积大,且只有被打开的那个条目才需要。该端点只对部署自己列出的条目作答,因此无法用来探测存在哪些插件;注册表没有某条目的说明文档时返回 null,而不是猜一个 URL。说明文档就是各包自己的 `README.md`,从本机的包里读取,因此目录里不存在第二份会与之漂移的副本;测试把每个条目的 name、version、description 与 license 钉在包自己声明的值上。++## 以 npm 包的本来面目发布++`scripts/build-plugins.mjs` 取 `plugins/*` 下每个带代码入口的包,先跑包自己的 `build`,再用 `pnpm pack` 打成 tarball——与 `npm publish` 送出的完全一样,`files` 照旧生效——然后用 `npm install` 把这些 tarball 装进一个按 npm 前缀布局的暂存目录:`plugins/package.json`(其 `dependencies` 记录发布了哪些包)加 `plugins/node_modules/<name>/…`,每个包的依赖像在任何地方一样由 npm 装在旁边。包的任何部分都不被改写:`package.json`、`exports`、`dist/`、生成的 `ifaces.json` 与 `README.md` 都以包自己的构建产出的样子到达目标。SDK 不在装入的依赖之列——插件只对 `@prismshadow/penguin-core` 的类型编译,运行时共用宿主那一份。暂存前缀按所有插件的源码、清单、README 与构建配置的哈希缓存在 `node_modules/.cache/penguin-plugins/` 下,没碰它们的推送不会再构建、打包或安装。++热推送把前缀放进资产(`plugins/…`);桌面构建把它暂存到 `skills/` 旁边(`scripts/build-assets.mjs`、`electron-builder.yml`)。加载器按顺序解析:`<root>/plugins`(数据根自己的前缀)、已提交推送的 `plugins/`(从 `harness.json` 读取,无需宿主)、安装目录的 `plugins/`、安装入口——按 Node 的方式查找包,读 import 方会读到的入口(`exports` 的 import 条件或 `main`)。++**随构建发布不等于已安装。** `builtin` 只是「这个包从哪来」的标签,绝不是第二种安装方式:构建带来的插件在目录里标为*内置*——安装它不会经过网络——但它的安装、加载与移除与其他插件完全一样,由 Project 把它列进清单。只有随构建发布的插件可以被要求;构建没有带的名字会被拒绝而不是写入清单,因此 Project 永远不会指名一个不在机器上的包。++## 插件页++一个列表,一行一个插件,各种插件都用同一种卡片,上方是搜索框,旁边是筛选器。**已安装的插件 (N)** 在前,默认折叠:插件库里的 skill 与 hook 包(随构建自带,每个 Agent 都可以用),以及当前 Project 要求的模块插件,各自带着运行中的进程对它的判定——*已安装*、*运行中*或*重启后加载*。其后是**可安装**:Project 尚未要求的市场条目,以及市场里还没有条目的自带包。每一行有插件的名字、描述、版本与更新日期,以及它的标签:分类(Office Productivity、sandbox、languages……)、*内置*、关键词。筛选器是三组受控的维度,每个选项带计数——**分类**、**包含**(skills、hooks、modules)与**状态**(已安装、可安装、运行中、重启后加载);同一维度内的选项取并集,维度之间取交集。每一行都带自己的控件,可以在读到它的地方直接要求,也在同一处移除。点开条目进入详情页,有元数据与渲染后的说明文档,因此选择一个沙盒后端不必再去读它的源码。++## 清单属于 Project,进程跑的是闭包++一个 Project 的插件写在它自己的配置里——`.project_config.toml` 的 `[plugins]` 表,包名 → 要求,形状同 Cargo 的 `[dependencies]`(`"@scope/name" = "*"` 表示部署自带的那个,或版本字符串,或 `{ version = "…" }`,后续字段就放在这里)——与它的模型并列——因为机器是按 Project 借出的,所以 Project 的清单才是「插件要抵达哪些机器」的依据(见 PRFC-0010)。但加载是按进程的:模块树只有一棵。所以部署跑的是**闭包**,即它各 Project 的并集,插件贡献的东西对所有 Project 可见。插件页上的一行因此是两个事实的合并:这个 Project 要了它,以及这个进程有它。++路由是 `/api/projects/:projectId/plugins/installed`:`GET`(该 Project 的成员即可)读取清单及进程对每一项的判定,`PUT { plugins }`(管理员)重写它,`POST { specifier }`(管理员)要求一个插件,`DELETE …?specifier=` 去掉它。进入清单的每个名字都过同一道闸,`PUT` 与 `POST` 一样:必须是包名——不是路径或子路径——且是随构建发布的包。要求是同意,不是下载;移除不改动磁盘上的任何东西,只有当没有任何 Project 还要它时,包才从磁盘上移除。已列出但进程加载不了的——specifier 无法解析、包缺少它的表、import 抛错、模块名已被另一个插件占用——会带着原因显示,而不是被算作「待重启」;插件页把这一行标为加载失败并给出原因。配置读不了的 Project 不向闭包贡献任何插件,它自己的列表视图会报告这个故障;其他 Project 的部署照常启动。++## 不重启即生效,由 platform 完成++写入之后会让 App 自行重组:platform 用 kernel 自带的 `upgrade` 把内层的树再启动一次——同一个 bundle、同一份寄存文档,热推送本来就在做的那次交换——所以 pty 与机器连接像跨越一次推送那样跨过去;推送会中止的,它同样中止:正在进行的 Agent 运行,所有 Project 的,因为树只有一棵。管理员应用改动之前,插件页会先说明这一点。不重启进程,HMR 层也一字未动:运行时自始至终握着同一个外层实例,因此在任何运行时上都生效,旧的也一样。改动随重组一起走:在重组的队列里写入,因此两个管理员对同一个文件的编辑不会交错;启动失败时先撤销改动再恢复上一棵树——报告「未生效」,清单保持原样。++读闭包并 import 是 platform 在自己的 boot 里做的事,而不是 runtime 在进程启动时做的。一个部署运行哪些插件、这份清单怎么读,是策略;否则程序比某条规则旧的机器永远学不会它——一台机器已经收到了 Project 的清单,却所有插件都不生效,因为它的程序仍在找旧的 `plugins.json`。现在凡是能接受推送的部署,就能接受插件变更。跨越一次 swap 留在注册表里的是已 import 的对象,由下一个 App claim 并按 specifier 复用,绝不重复 import;闭包不再提到的条目直接不在新的 host 里。注册表里的 host 只由成功的 boot 写入,于是不可能再出现「插件显示已启用、而运行中的树里根本没有它」。runtime 仍保留一份自己的加载作为垫片,供比这次改动更旧的 platform 回滚时使用。++## 一个 Project 的机器上保持同一份清单++Project 的清单会被交给它使用的机器,走的是它的模型凭据本来就在走的那趟,时机也一样:清单变动时,以及每次连接时。一致是**严格**的——以 Project 的清单为准,机器上多出来的被移除。++代价需要知道:分平台的沙盒后端不在另一平台的清单里,因此会被拿走。想保住就把它列进整支机队的清单;解析不到它的那台会显示一条惰性的错误行,而不是丢掉自己能用的那个。同步按机器汇报:加了什么、移除了什么、哪些它列了却解析不到(多半是那台需要先更新),以及它是否仍需重启。++## 兼容性++**数据根的 `plugins.json` 不再被读取,也不做任何迁移。** 原本装着插件的部署会以**没有任何插件**的状态启动:沙盒后端、语言、会话表面都不在树里,直到各 Project 在插件页重新要求。旧文件原样留在盘上,因此回滚到更早的平台时它还在。++这个键在发布前短暂有过的列表形式(`plugins = ["…"]`)同样不再读取:这样的 Project 视为不要求任何插件,直到在插件页重新写入它的表。diff --git a/packages/core/src/state/project-config.ts b/packages/core/src/state/project-config.tsindex 1cbe867e..be2e704f 100644--- a/packages/core/src/state/project-config.ts+++ b/packages/core/src/state/project-config.ts@@ -194,6 +194,23 @@ export interface ProjectConfig {* key, and dropping `enabled` falls back to on.*/command_policy?: CommandPolicyConfig;+ /**+ * The plugin packages this Project asks its deployment to run: the `[plugins]` table,+ * keyed by package name, in the shape of Cargo's `[dependencies]` —+ *+ * [plugins]+ * "@scope/name" = "*" # whatever the deployment ships+ * "@scope/other" = "1.2.3" # a version requirement+ * "@scope/third" = { version = "1.2" } # the table form, where later fields go+ *+ * A table rather than a list so an entry can grow fields without a format change.+ *+ * Project-scoped because machines are lent to Projects, so this is what says which+ * machines a plugin has to reach. LOADING is per process, though — there is one module+ * tree — so a deployment runs the CLOSURE: the union over its Projects. A plugin any+ * Project asks for is in the tree, and what it contributes is visible to all of them.+ */+ plugins?: PluginTable;models: ModelEntry[];}@@ -312,6 +329,51 @@ function parseDefaultChat(value: unknown): ProjectChatDefaults | undefined {* file — the same sharing rule as projectConfigFromTable, so the two paths can never* narrow the block differently.*/+/** What a Project asks of one plugin. `version` absent (or `"*"` in the file) means whatever the deployment ships. */+export interface PluginRequirement {+ version?: string;+}++/** The `[plugins]` table: package name → what is asked of it, in the file's order. */+export type PluginTable = Record<string, PluginRequirement>;++/**+ * Leniently parses the `[plugins]` table. An entry's value is a version requirement string+ * (`"*"` for any) or a table with an optional `version`; an entry of any other shape is+ * dropped rather than failing the load — a config whose plugin table is malformed still has+ * to open, or a typo there would take the Project's models with it. A value that is not a+ * table at all (the list form this key had before it was a table) reads as undefined:+ * such a Project asks for no plugins until it is written again.+ */+export function parsePluginTable(value: unknown): PluginTable | undefined {+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;+ const out: PluginTable = {};+ for (const [rawName, spec] of Object.entries(value as Record<string, unknown>)) {+ const name = rawName.trim();+ if (name === "") continue;+ if (typeof spec === "string") {+ const version = spec.trim();+ out[name] = version === "" || version === "*" ? {} : { version };+ continue;+ }+ if (spec === null || typeof spec !== "object" || Array.isArray(spec)) continue;+ const version = (spec as { version?: unknown }).version;+ if (version !== undefined && typeof version !== "string") continue;+ out[name] =+ version === undefined || version.trim() === "" || version.trim() === "*"+ ? {}+ : { version: version.trim() };+ }+ return out;+}++/** The `[plugins]` table as it is written: the string form wherever only a version is asked. */+export function pluginTableToToml(+ table: PluginTable,+): Record<string, string | { version?: string }> {+ return Object.fromEntries(Object.entries(table).map(([name, req]) => [name, req.version ?? "*"]));+}+export function parseCommandPolicy(value: unknown): CommandPolicyConfig | undefined {if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;const t = value as Record<string, unknown>;@@ -356,12 +418,14 @@ export function projectConfigFromTable(const visionModel = parseRefField(file, "vision_model", parsed.vision_model);const defaultChat = parseDefaultChat(parsed.default_chat);const commandPolicy = parseCommandPolicy(parsed.command_policy);+ const plugins = parsePluginTable(parsed.plugins);return {...(parsed.name !== undefined ? { name: parsed.name as string } : {}),...(defaultModel !== undefined ? { default_model: defaultModel } : {}),...(visionModel !== undefined ? { vision_model: visionModel } : {}),...(defaultChat !== undefined ? { default_chat: defaultChat } : {}),...(commandPolicy !== undefined ? { command_policy: commandPolicy } : {}),+ ...(plugins !== undefined ? { plugins } : {}),models: ((parsed.models as unknown[] | undefined) ?? []).map((m) => assertModelEntry(file, m)),};}diff --git a/packages/desktop/electron-builder.yml b/packages/desktop/electron-builder.ymlindex 81644a39..86cad6be 100644--- a/packages/desktop/electron-builder.yml+++ b/packages/desktop/electron-builder.yml@@ -45,6 +45,9 @@ files:# they arrive as collected dependencies, at the app root's node_modules.- dist/node_modules/**/*- bin/**/*+ # The builtin plugins (scripts/build-assets.mjs → build-plugins.mjs): a second node_modules+ # that must ship, named for the same reason dist/node_modules is above.+ - plugins/**/*- package.json- from: ../web/distto: web-distdiff --git a/packages/desktop/scripts/build-assets.mjs b/packages/desktop/scripts/build-assets.mjsindex 20db5a6f..13cb2203 100644--- a/packages/desktop/scripts/build-assets.mjs+++ b/packages/desktop/scripts/build-assets.mjs@@ -45,6 +45,16 @@ for (const required of [launcherModule, path.join(distDir, "pty-payload.js")]) {}}+// The builtin plugins, as the npm prefix the bundled server resolves from+// (`<app>/plugins/package.json` + `plugins/node_modules/<name>/…`; the server's+// plugin/loader.ts looks one directory above `dist/`). The packages as npm publishes+// them, installed by npm (scripts/build-plugins.mjs), from its content cache when unchanged.+const { buildBuiltinPlugins, stagePrefix } = await import(+ pathToFileURL(path.resolve(pkgDir, "..", "..", "scripts", "build-plugins.mjs")).href+);+const builtPlugins = await buildBuiltinPlugins({ log: (m) => console.log(`[build-assets] ${m}`) });+await stagePrefix(builtPlugins, path.join(pkgDir, "plugins"));+const repoRoot = path.resolve(pkgDir, "..", "..");for (const name of ["install.sh", "install.ps1"]) {const src = path.join(repoRoot, name);@@ -114,5 +124,5 @@ fs.chmodSync(path.join(binDir, "penguin"), 0o755);fs.writeFileSync(path.join(binDir, "penguin.cmd"), windowsLauncherScript());console.log(- `[build-assets] done: dist/icon.png, dist/tray/ (${trayIcons.length} icons), dist/install.{sh,ps1}, bin/, ${NODE_PTY_RELDIR.join("/")} (${ptyFiles.length} files, bindings: ${bindings.join(", ")})`,+ `[build-assets] done: plugins/ (${builtPlugins.plugins.length} builtin plugins), dist/icon.png, dist/tray/ (${trayIcons.length} icons), dist/install.{sh,ps1}, bin/, ${NODE_PTY_RELDIR.join("/")} (${ptyFiles.length} files, bindings: ${bindings.join(", ")})`,);diff --git a/packages/desktop/scripts/preflight.mjs b/packages/desktop/scripts/preflight.mjsindex 9679539c..cf6cf12e 100644--- a/packages/desktop/scripts/preflight.mjs+++ b/packages/desktop/scripts/preflight.mjs@@ -30,6 +30,7 @@ for (const [what, rel] of [...Object.keys(pkg.dependencies).filter((dep) => dep.startsWith("@penguinharness/")).map((dep) => [`the plugin package ${dep}`, `node_modules/${dep}/plugin.json`]),+ ["the builtin plugins", "plugins"],["the web frontend build", "../web/dist/index.html"],]) {if (!fs.existsSync(path.join(pkgDir, rel))) {diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex cb541706..70ad3c3e 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -200,6 +200,18 @@ The PKCE verifier is generated server-side, held in memory for ten minutes, andWhat that route may do is bounded a second time: it stores the code on the flow and nothing else. The exchange with the provider and the write into the Project's models both run on `GET /:flowId`, the owner's own poll, behind the session gate — so no key reaches a Project without its owner asking for its flow's status, and a failed exchange is reported there as `{status: error, error}` rather than on the redirect page. Nothing adjacent is exempt either: a longer path, any other method (`HEAD` on the literal path answers 405), and the three sibling routes all still require the session.`mode: manual` omits the callback so the authorization page shows a one-time code to carry back by hand, for deployments the redirect cannot reach. Whichever route redeems the code, a completed flow invalidates cached runtimes and publishes `credentials_updated`, exactly as `PUT /models` does.+### Plugin Registry++| Method | Path | Description |+| --- | --- | --- |+| GET | /api/plugins/registry | Plugin index for the Plugins page: `{plugins: PluginIndexEntry[]}` — the merged index of every configured registry (currently the builtin one) |+| GET | /api/plugins/registry/readme?name=… | One listed entry's readme: `{name, readme}` (`readme` null when the registry has none); 404 for a name the index does not list |+| GET | /api/projects/:projectId/plugins/installed | What this Project asks for, joined with what the process runs: `{plugins: [{specifier, active, builtin, modules, replaces, error?}], shipped, file, restartPending}` (any member) |+| POST | /api/projects/:projectId/plugins/installed | `{specifier}` — ask this Project for a plugin the build ships (400 `plugin_not_shipped` otherwise), applied without a restart — the App re-assembles itself, which stops the agent runs in progress in every Project; a change whose boot fails is undone (admin) |+| PUT | /api/projects/:projectId/plugins/installed | `{plugins}` — rewrite this Project's list and apply; a name new to the list must be a shipped package's (admin) |+| DELETE | /api/projects/:projectId/plugins/installed?specifier=… | Drop it from this Project's list and apply; nothing on disk changes (admin) |++The index format follows typst/packages' `index.json` schema: a flat array of per-version entries (`name`, `version`, `description`, `authors`, `license`, plus optional `repository` / `homepage` / `keywords` / `categories` / `updatedAt`). The registry is discovery only and never imports plugin code; a Project asks for an entry through the routes above, and its list lives in its own `.project_config.toml` as the `[plugins]` table — package name → requirement, in the shape of Cargo's `[dependencies]` (`"@scope/name" = "*"`, a version string, or `{ version = "…" }`). The process runs the union over every Project's table.### Agentsdiff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex b27fe5e5..8dcd0bbd 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -200,6 +200,18 @@ PKCE 的 verifier 在服务端生成、只在内存中保留十分钟,绝不这条路由能做的事还有第二重边界:它只把授权码存到流程上,此外什么都不做。与供应商的兑换、以及写入该 Project 模型的动作,都发生在 `GET /:flowId`——Owner 自己的轮询,仍在会话校验之内。因此没有 Owner 主动查询流程状态,就不会有 key 落进任何 Project;兑换失败也在那里以 `{status: error, error}` 报出,而不是显示在跳回页面上。周边的一切同样不在豁免之内:更长的路径、其它任何请求方法(该字面路径上的 `HEAD` 返回 405),以及另外三条同级路由,仍然都需要会话。`mode: manual` 不传回调地址,授权页改为显示一次性授权码供用户手动带回,适用于跳转回不来的部署。无论由哪条路由完成兑换,流程完成后同样会使缓存的运行时失效并发布 `credentials_updated`,与 `PUT /models` 一致。+### 插件注册表++| Method | Path | Description |+| --- | --- | --- |+| GET | /api/plugins/registry | 插件市场页的插件索引:`{plugins: PluginIndexEntry[]}`——所有已配置注册表(当前仅内置注册表)合并后的索引 |+| GET | /api/plugins/registry/readme?name=… | 某个已列出条目的说明文档:`{name, readme}`(注册表没有时 `readme` 为 null);索引未列出的名字返回 404 |+| GET | /api/projects/:projectId/plugins/installed | 该 Project 要求的插件,并联上进程实际在跑的状态:`{plugins: [{specifier, active, builtin, modules, replaces, error?}], shipped, file, restartPending}`(成员即可) |+| POST | /api/projects/:projectId/plugins/installed | `{specifier}`——为该 Project 要求一个随构建发布的插件(否则 400 `plugin_not_shipped`),无需重启即生效,App 自行重组——这会中止所有 Project 正在进行的 Agent 运行;启动失败的改动会被撤销(管理员) |+| PUT | /api/projects/:projectId/plugins/installed | `{plugins}`——重写该 Project 的列表并应用;新增的名字须是随构建发布的包(管理员) |+| DELETE | /api/projects/:projectId/plugins/installed?specifier=… | 从该 Project 的列表中去掉并应用;磁盘上什么都不变(管理员) |++索引格式沿用 typst/packages 的 `index.json` 模式:扁平数组,每个元素是插件的一个版本条目(`name`、`version`、`description`、`authors`、`license`,可选 `repository` / `homepage` / `keywords` / `categories` / `updatedAt`)。注册表仅用于发现,不会导入任何插件代码;Project 通过上面的路由要求某个条目,其列表存在自己的 `.project_config.toml` 的 `[plugins]` 表里——包名 → 要求,形状同 Cargo 的 `[dependencies]`(`"@scope/name" = "*"`、版本字符串,或 `{ version = "…" }`)。进程运行的是所有 Project 表的并集。### Agentdiff --git a/packages/docs/content/server-boot.en.md b/packages/docs/content/server-boot.en.mdindex c59b90ad..cdfc1526 100644--- a/packages/docs/content/server-boot.en.md+++ b/packages/docs/content/server-boot.en.md@@ -25,7 +25,7 @@ main() —— one PenguinServer method per line├─ ① loadEnv · installProxy dotenv first (.env may define HTTP_PROXY itself), then the proxy takes over fetch├─ ② readConfig env only: PENGUIN_HOME, PORT, HOST, PENGUIN_WEB_DB …├─ ③ ensureSoleInstance data root held by another live instance → exit code 3 (before the DB opens)-├─ ④ loadPlugins read <root>/plugins.json → import → fill this process's one PluginHost+├─ ④ loadPlugins a SHIM for a platform older than the move below: the platform loads its own plugins├─ ⑤ buildDeps = bootAppDeps open the DB → runtime core (auth, ChannelHub, HmrHost) → publish the│ capabilities (db/auth/channels/config/proxy/desktop/plugin host) →│ hmr.ensure() boots the platform: its create() assembles the WHOLE@@ -37,7 +37,7 @@ main() —— one PenguinServer method per line└─ ⑩ installProcessHandlers signals, the desktop quit path, the process-level error fallback```-The order is not arbitrary — four of its constraints are hard: the proxy takes over global `fetch` before any outbound request can happen; the instance lock is checked **before** the database opens, because `web.db` is single-writer; plugins finish loading **before** ⑤, and the host enters the registry with the other capabilities before the platform boots, so they are present for the very first App creation; and the platform — the whole business surface with it — finishes booting before `listen`, so **no request is ever served before business and plugins are in place**. `installProcessHandlers` comes last, after `listen`, so shutdown can never fire before there is a listener for it to close.+The order is not arbitrary — four of its constraints are hard: the proxy takes over global `fetch` before any outbound request can happen; the instance lock is checked **before** the database opens, because `web.db` is single-writer; the plugin host enters the registry with the other capabilities before the platform boots, so what an earlier App imported is there for the next one to reuse; and the platform — the whole business surface with it — finishes booting before `listen`, so **no request is ever served before business and plugins are in place**. `installProcessHandlers` comes last, after `listen`, so shutdown can never fire before there is a listener for it to close.Plugin loading sitting after `ensureSoleInstance` is deliberate too: a process about to exit with code 3 has no business importing third-party modules and running their top-level side effects first.@@ -51,7 +51,7 @@ Process-level (runtime mechanism, once) App-level (the business surface, re-ruSQLite · auth (AuthService) every business service and route (services + http/routes)ChannelHub (SSE survives swaps) SessionManager · SchedulerHmrHost · the resource registry TerminalManager (adopts parked ptys)-plugins.json load (⑤ pub.) plugin modules created as children of the tree+the plugin host (imported objects) plugin closure read + imported, modules created as children of the tree```**Swap semantics: unparked state HARD-STOPS** — pending approvals are denied, active runs abort, the scheduler dies with its App, and the next App rebuilds everything from the claimed capabilities. Only resources that implement park/adopt (terminal ptys) ride across.@@ -84,11 +84,11 @@ A plugin is a set of modules — the unit the harness itself is built from, writ| Moment | Frequency | What happens || --------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| Load | Once per process | Boot step ④ `loadPlugins`: resolve and import each specifier in `plugins.json`, read the `ifaces.json` beside its `package.json` (absent = no modules), check each class the default export names against its manifest there. A package that names classes without a table (never built), or one whose class and table disagree (a stale build), is skipped with its reason; an unreadable or malformed `plugins.json` fails the boot |+| Load | Once per App | The platform's `create()` reads the closure — the union of every Project's `[plugins]` table — and resolves and imports each specifier, reads the `ifaces.json` beside its `package.json` (absent = no modules), and checks each class the default export names against its manifest there. A package that names classes without a table (never built), or one whose class and table disagree (a stale build), is skipped with its reason; a Project whose config cannot be read or parsed contributes nothing and its list view says so. An entry the previous App imported from the same, unchanged file is reused rather than imported again || Check + create | Once per App | The platform adds the plugin modules to its tree; the whole tree is checked as data first (requirements resolved by signature, contributions validated against their slots), then created in dependency order — so a module is created fresh per boot and per hot swap || Dispose | Once per App | A module's `effect()` registrations run in reverse creation order when the App is disposed; nothing of a plugin survives into the next generation |-The plugin contract (`Plugin`, the decorators, plus the sandbox vocabulary) is declared in the SDK, at `@prismshadow/penguin-core/plugin`; `@prismshadow/penguin-server/plugin` re-exports the interfaces a plugin module may require (`Sandbox`, `Terminals`, `SessionManager`, `Agents`, …), types only. The decorators are the SDK's only runtime a plugin carries — they record on the class itself, so the copy in a plugin's bundle and the host's read the same thing. Which plugins exist is the deployment's `<root>/plugins.json`; the harness itself imports no plugin. A component's interface is its class's public surface; a module's provisions and a consumer's narrow requirements are abstract classes (`extends Interface<…>()`) declared beside the code that owns them. `pnpm gen:ifaces` projects both into `src/ifaces.json` (generated, not committed — `typecheck`, `build` and `test` regenerate it), the table the tree is checked against.+The plugin contract (`Plugin`, the decorators, plus the sandbox vocabulary) is declared in the SDK, at `@prismshadow/penguin-core/plugin`; `@prismshadow/penguin-server/plugin` re-exports the interfaces a plugin module may require (`Sandbox`, `Terminals`, `SessionManager`, `Agents`, …), types only. The decorators are the SDK's only runtime a plugin carries — they record on the class itself, so the copy in a plugin's bundle and the host's read the same thing. Which plugins run is the closure over the Projects' `[plugins]` tables (`.project_config.toml`), written from the Plugins page; the harness itself imports no plugin. A component's interface is its class's public surface; a module's provisions and a consumer's narrow requirements are abstract classes (`extends Interface<…>()`) declared beside the code that owns them. `pnpm gen:ifaces` projects both into `src/ifaces.json` (generated, not committed — `typecheck`, `build` and `test` regenerate it), the table the tree is checked against.## Subsystem inventory@@ -106,7 +106,7 @@ Each subsystem's construction site and external surface (step numbers refer to t| Scheduler | `runtime/scheduler.ts` — **App-level** (started/stopped by create)| The schedules routes; publishes results into the ChannelHub || HMR host / platform | `hmr/host.ts` (end of ⑤) | `PlatformApi` (`park` / `info` / `http` / `terminals` / `attachStream`); `POST /api/hmr/upgrade` is a runtime-owned route, never offered to the platform || Terminals | `terminal/` — **App-level** | `/api/terminals*` route group (registered into the platform's one Hono app), WS `GET /api/terminals/:id/stream`; ptys are parked and survive swaps |-| Plugin host | built by ④ `loadPlugins`, published to the registry in ⑤ | an npm package: its generated `ifaces.json` (the module payload), a default export `{ modules: [<class>, …] }`; the configuration surface is `<root>/plugins.json` |+| Plugin host | built by the platform's `create()`, published to the registry for the next App | an npm package: its generated `ifaces.json` (the module payload), a default export `{ modules: [<class>, …] }`; the configuration surface is the `[plugins]` table of each Project's `.project_config.toml` || Sandbox | `sandbox/service.ts` — **App-level** (a module; backends contribute to its `providers` slot) | a `SandboxModule.providers` contribution from a plugin module; enforcement reaches commands through core's spawn seam || Module tree | `src/platform.ts` — **App-level** (booted by create over the claimed capabilities) | `@Component()` on each service / repo class (a node is named by its class) with `@Use()` fields for its dependencies; `@Module({ children, exports })` groups (`IdentityModule`, `ProjectsModule`, …) whose exports are what their children offer the rest of the tree; `@Module({ … })` classes with `@Provide()` fields where one class builds several things; narrow consumer interfaces as abstract classes beside their consumer (`extends Interface<…>()`); no `modules/` directory — each node lives in the file of the thing it is; `src/ifaces.json` generated; `GET /api/contributions` lists what reached the web slots || Model catalog | No boot-time construction — static core data | `/api/projects/:projectId/models`; the catalog itself lives in `core/src/state/model-catalog.ts` |diff --git a/packages/docs/content/server-boot.zh.md b/packages/docs/content/server-boot.zh.mdindex 17068dd4..65d54d14 100644--- a/packages/docs/content/server-boot.zh.md+++ b/packages/docs/content/server-boot.zh.md@@ -25,7 +25,7 @@ main() —— 每行一个 PenguinServer 方法├─ ① loadEnv · installProxy dotenv 先行(.env 自己可能定义 HTTP_PROXY),随后全局代理接管 fetch├─ ② readConfig 仅环境变量:PENGUIN_HOME、PORT、HOST、PENGUIN_WEB_DB …├─ ③ ensureSoleInstance 数据根被另一存活实例持有 → 退出码 3(先于开库)-├─ ④ loadPlugins 读 <root>/plugins.json → import → 装进本进程唯一的 PluginHost+├─ ④ loadPlugins 给比下述改动更旧的平台留的垫片:平台在自己的 create() 里加载插件├─ ⑤ buildDeps = bootAppDeps 开库 → 运行时核心(auth、ChannelHub、HmrHost)→ 发布能力(db/auth/│ channels/config/proxy/desktop/插件 host)→ hmr.ensure() 启动平台:│ 其 create() 组装整个业务面(服务、路由、scheduler)并投递插件钩子@@ -36,7 +36,7 @@ main() —— 每行一个 PenguinServer 方法└─ ⑩ installProcessHandlers 信号、Desktop 退出路径、进程级错误兜底```-这个顺序不是随意排的,其中四条是硬约束:代理在任何出站请求可能发生之前接管全局 `fetch`;单实例锁在开库**之前**预检,因为 `web.db` 是单写者;插件在 ⑤ **之前**加载完毕,host 随其他能力一起在平台 boot 前进入注册表,因此首个 App 创建时它们已经在场;平台(连同整个业务面)在 `listen` 之前完成启动,因此**没有任何请求会在业务与插件就位之前被服务**。收尾的 `installProcessHandlers` 排在 `listen` 之后,这样关停流程不会在监听器存在之前被触发。+这个顺序不是随意排的,其中四条是硬约束:代理在任何出站请求可能发生之前接管全局 `fetch`;单实例锁在开库**之前**预检,因为 `web.db` 是单写者;插件 host 随其他能力一起在平台 boot 前进入注册表,因此上一个 App import 过的对象可供下一个复用;平台(连同整个业务面)在 `listen` 之前完成启动,因此**没有任何请求会在业务与插件就位之前被服务**。收尾的 `installProcessHandlers` 排在 `listen` 之后,这样关停流程不会在监听器存在之前被触发。插件加载排在 `ensureSoleInstance` 之后也是有意的:一个即将以退出码 3 退出的进程不应该先去 import 一堆第三方模块、执行它们的顶层副作用。@@ -50,7 +50,7 @@ main() —— 每行一个 PenguinServer 方法SQLite · 认证(AuthService) 全部业务服务与路由(services + http/routes)ChannelHub(SSE 跨 swap 存活) SessionManager · SchedulerHmrHost · 资源注册表 TerminalManager(接管寄存的 pty)-plugins.json 加载(⑤ 发布) 插件模块作为树的子节点创建+插件 host(已 import 的对象) 读插件闭包并 import,插件模块作为树的子节点创建```**swap 语义:未实现 park 的状态一律硬中止**——待审批全部拒绝、运行中任务中止、scheduler 随旧 App 死掉,新 App 从认领的能力重建一切。只有实现了 park/adopt 的资源(终端 pty)跨 swap 存活。@@ -82,11 +82,11 @@ platformImpl.create| 时机 | 频率 | 发生什么 || ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |-| 加载 | 每进程一次 | 启动步骤 ④ `loadPlugins`:解析 `plugins.json` 里的 specifier、import、读它 `package.json` 旁的 `ifaces.json`(没有即没有模块),把默认导出点名的每个类对照表中自己的 manifest 核对。点名了类却没有表的包(没构建过)、类与表不一致的包(构建陈旧)会带原因被跳过;`plugins.json` 不可读或格式错误则启动失败 |+| 加载 | 每 App 一次 | platform 的 `create()` 读闭包——所有 Project 的 `[plugins]` 表的并集——解析并 import 每个 specifier、读它 `package.json` 旁的 `ifaces.json`(没有即没有模块),把默认导出点名的每个类对照表中自己的 manifest 核对。点名了类却没有表的包(没构建过)、类与表不一致的包(构建陈旧)会带原因被跳过;配置读不了或解析不了的 Project 不贡献任何插件,其列表视图会说明。上一个 App 从同一个、未改动的文件 import 过的条目直接复用,不再 import || 校验 + 创建 | 每 App 一次 | platform 把插件模块加入它的树;整棵树先作为数据校验(requires 按签名解析、contribution 按槽位校验),再按依赖顺序创建——所以模块在每次启动、每次热替换时都是全新创建的 || 释放 | 每 App 一次 | 模块通过 `effect()` 登记的清理在 App 释放时按创建逆序执行;插件的任何东西都不会进入下一代 |-插件契约(`Plugin`、装饰器,加上沙箱词汇表)声明在 SDK 里,即 `@prismshadow/penguin-core/plugin`;`@prismshadow/penguin-server/plugin` 再导出插件模块可以 require 的接口(`Sandbox`、`Terminals`、`SessionManager`、`Agents`……),只有类型。装饰器是插件带走的唯一一段 SDK 运行时——它们把记录写在类自身上,所以插件 bundle 里的那份和宿主读的是同一样东西。哪些插件存在由部署的 `<root>/plugins.json` 决定,harness 自身不 import 任何插件。组件的接口是它 class 的公开表面;模块的 provides 与消费者的窄 requires 是声明在归属代码旁边的抽象类(`extends Interface<…>()`)。`pnpm gen:ifaces` 把两者投影进 `src/ifaces.json`(生成物,不进版本库——`typecheck`、`build`、`test` 都会重新生成),即模块树据以校验的表。+插件契约(`Plugin`、装饰器,加上沙箱词汇表)声明在 SDK 里,即 `@prismshadow/penguin-core/plugin`;`@prismshadow/penguin-server/plugin` 再导出插件模块可以 require 的接口(`Sandbox`、`Terminals`、`SessionManager`、`Agents`……),只有类型。装饰器是插件带走的唯一一段 SDK 运行时——它们把记录写在类自身上,所以插件 bundle 里的那份和宿主读的是同一样东西。哪些插件运行由各 Project 的 `[plugins]` 表(`.project_config.toml`,在插件页写入)的闭包决定,harness 自身不 import 任何插件。组件的接口是它 class 的公开表面;模块的 provides 与消费者的窄 requires 是声明在归属代码旁边的抽象类(`extends Interface<…>()`)。`pnpm gen:ifaces` 把两者投影进 `src/ifaces.json`(生成物,不进版本库——`typecheck`、`build`、`test` 都会重新生成),即模块树据以校验的表。## 子系统一览@@ -104,7 +104,7 @@ platformImpl.create| Scheduler | `runtime/scheduler.ts`——**App 级**(create 内启停)| schedules 路由;执行结果发布进 ChannelHub || HMR 宿主 / 平台 | `hmr/host.ts`(⑤ 末尾) | `PlatformApi`(`park` / `info` / `http` / `terminals` / `attachStream`);`POST /api/hmr/upgrade` 为运行时自留路由,不经平台 || 终端 | `terminal/`——**App 级** | `/api/terminals*` 路由组(注册进平台唯一的 Hono app)、WS `GET /api/terminals/:id/stream`;pty 寄存跨热更新存活 |-| 插件宿主 | ④ `loadPlugins` 构建,⑤ 发布进资源注册表 | 一个 npm 包:生成的 `ifaces.json`(模块载荷)、默认导出 `{ modules: [<class>, …] }`;配置面是 `<root>/plugins.json` |+| 插件宿主 | platform 的 `create()` 构建,发布进注册表供下一个 App 复用 | 一个 npm 包:生成的 `ifaces.json`(模块载荷)、默认导出 `{ modules: [<class>, …] }`;配置面是各 Project `.project_config.toml` 的 `[plugins]` 表 || 模块树 | `src/platform.ts`——**App 级**(create 在认领的能力之上启动) | 每个服务 / repo class 上 `@Component()`(节点以 class 命名),依赖是 `@Use()` 字段;`@Module({ children, exports })` 分组(`IdentityModule`、`ProjectsModule`……),exports 是组内 children 向树的其余部分提供的接口;一个 class 造出多个东西时用带 `@Provide()` 字段的 `@Module({ … })`;消费者的窄接口是紧挨消费者声明的抽象类(`extends Interface<…>()`);没有 `modules/` 目录——每个节点就住在它所是的那个东西的文件里;生成的 `src/ifaces.json`;`GET /api/contributions` 列出到达 web 槽位的内容 || 沙盒 | `sandbox/service.ts`——**App 级**(一个模块;后端向它的 `providers` 槽位投递) | 插件模块向 `SandboxModule.providers` 投递的一条 contribution;约束经 core 的 spawn seam 落到命令上 || 模型目录 | 无启动期构建——core 静态数据 | `/api/projects/:projectId/models`;目录本体在 `core/src/state/model-catalog.ts` |diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 016ed00c..38481cba 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -3563,6 +3563,49 @@ export interface SkillArchiveInstallRequest {overwrite?: boolean;}+// ---------------------------------------------------------------------------+// Plugin registry index+// ---------------------------------------------------------------------------++/**+ * One published version of a plugin — the index entry format every plugin registry+ * speaks (modeled on the typst/packages `index.json` schema: a flat array of+ * per-version entries; a plugin published at several versions appears once per+ * version). Installation is out of scope here: an entry's `name` is the package+ * specifier a Project's plugin list names.+ */+export interface PluginIndexEntry {+ /** Package specifier — the string a Project's plugin list names. */+ name: string;+ /** Semantic version of this entry. */+ version: string;+ description: string;+ authors: string[];+ /** SPDX license identifier. */+ license: string;+ /** Source repository URL. */+ repository?: string;+ homepage?: string;+ /** Free-form searchable terms; the Web App renders them as chips (e.g. the target OS). */+ keywords?: string[];+ /** Capability floor(s) the plugin provides on (e.g. "sandbox"). */+ categories?: string[];+ /** Unix timestamp (seconds) of the entry's last update. */+ updatedAt?: number;+}++/** GET /api/plugins/registry: the merged index of every configured registry (currently the builtin one). */+export interface PluginIndexResponse {+ plugins: PluginIndexEntry[];+}++/** GET /api/plugins/registry/readme — long-form docs for one entry; `readme` is null when none exists. */+export interface PluginReadmeResponse {+ name: string;+ /** Markdown, rendered by the Web App. Null when this entry has no readme. */+ readme: string | null;+}+// ---------------------------------------------------------------------------// Version and self-update// ---------------------------------------------------------------------------@@ -4666,3 +4709,39 @@ export interface ContributionsResponse {agentTabs: WebContribution[];sessionTabs: WebContribution[];}++/** One plugin a Project lists (GET /api/projects/:projectId/plugins/installed). */+export interface InstalledPlugin {+ /** The package specifier as written in the file. */+ specifier: string;+ /** Whether the running process holds this package — its modules are in the tree. */+ active: boolean;+ /**+ * Where the package came from: shipped with the build (a hot push's assets, or the+ * installation's own `plugins/`) rather than fetched from npm. A tag on an installed+ * plugin — being shipped is not being installed.+ */+ builtin: boolean;+ /** Module names the package declares it adds. */+ modules: string[];+ /** Node names the package declares it stands in for. */+ replaces: string[];+ /**+ * Why the package is not running: unresolvable, or a load that+ * failed (an import that threw, a module name another plugin already took).+ */+ error?: string;+}++export interface InstalledPluginsResponse {+ plugins: InstalledPlugin[];+ /**+ * Specifiers this build SHIPS (the hot push's assets, or the installation's own+ * `plugins/`): installable without a download, and not installed until listed.+ */+ shipped: string[];+ /** The file the list lives in, named for the page that explains where to edit it by hand. */+ file: string;+ /** A listed plugin neither runs nor failed to load: the App could not be re-assembled around it (the previous one was restored), so a restart is what applies it. */+ restartPending: boolean;+}diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 09ab9c4c..6fc5d292 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -38,6 +38,7 @@ import {HMR_HOST_RESOURCE_ID,HMR_CONTROL_RESOURCE_ID,HMR_OVERRIDES_RESOURCE_ID,+ HMR_TEST_PLUGINS_RESOURCE_ID,type Replacements,HMR_PROXY_RESOURCE_ID,HmrCapabilities,@@ -197,15 +198,22 @@ export interface ServerBoot {* the business surface — see app.ts), and return the merged view. Shared* by production and tests; tests pass dbPath=":memory:" and a temp root.*- * `plugins` is the host index.ts's loadPlugins step filled from plugins.json — handed in- * rather than registered by the caller because the platform boots inside this function,- * and everything it claims has to be in the registry first. Absent (tests), the platform- * falls back to an empty host (see plugin/index.ts's pluginHostFrom).+ * `plugins` is what index.ts's loadPlugins shim imported — handed in rather than registered+ * by the caller because the platform boots inside this function, and everything it claims has+ * to be in the registry first. The platform builds its own host from the Projects' closure+ * either way (plugin/loader.ts); this only lets it reuse objects already imported, and lets a+ * platform older than that move find a host at all.+ *+ * `testPlugins` is the other half of that: entries a TEST stands up in process, which no+ * closure could name because they were never on disk. Kept apart from the line above so the+ * production path stays "what the Projects ask for, imported", with no way for a fake to+ * enter it.*/export async function bootAppDeps(config: ServerConfig,replacements: Replacements = [],plugins?: PluginHost,+ testPlugins?: PluginHost,host?: ServerHmrHost,control?: Hmr<PlatformApi>,): Promise<ServerBoot> {@@ -296,6 +304,9 @@ export async function bootAppDeps(if (plugins !== undefined) {hmr.resources.register(PLUGINS_RESOURCE_ID, plugins, () => void plugins.dispose());}+ if (testPlugins !== undefined) {+ hmr.resources.register(HMR_TEST_PLUGINS_RESOURCE_ID, testPlugins);+ }// Boot the platform now rather than on the first request: the business surface —// services, routes, the scheduler — is assembled inside its create(). The check readsdiff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.tsindex 9eda47b9..581e2c79 100644--- a/packages/server/src/hmr/capabilities.ts+++ b/packages/server/src/hmr/capabilities.ts@@ -200,6 +200,13 @@ export const HMR_AUTH_STATE_RESOURCE_ID = "platform.authState";/** Test-only: the node Replacements bootAppDeps leaves for the platform boot to claim. */export const HMR_OVERRIDES_RESOURCE_ID = "platform.overrides";+/**+ * Test-only: plugin entries a test stands up in process, unioned into the host the platform+ * builds from the closure. Its own id, not the host's: the closure is read from disk, so a+ * plugin that exists only as an object in a test has no specifier anyone could import.+ */+export const HMR_TEST_PLUGINS_RESOURCE_ID = "platform.pluginsInjected";+/*** The {@link Interfaces} descriptor each App leaves for its successor, naming the* live-object contracts it parks by ID-prefix group (`terminal` covers every `terminal:*`@@ -513,6 +520,36 @@ export class RuntimeHmrControl {this.hmrControl = this.caps.hmrControl;}}++/**+ * The App re-assembling itself from the same bundle — how a plugin change applies without+ * a process restart. The PLATFORM's own, above the seam: it re-boots its inner tree with+ * the kernel's upgrade, and the runtime holds the same outer instance throughout (see+ * hmr/platform.ts). Nothing here is a runtime capability, so it works on every runtime.+ */+/**+ * A configuration change that a re-assembly applies: written just before the new tree+ * boots, in the same queue as every other re-assembly (so two edits of one file never+ * interleave), and undone before the previous tree is restored when that boot fails — the+ * restore boot reads the same configuration, and a change that broke the tree once would+ * break it again.+ */+export interface ReassemblyChange {+ write(): Promise<void>;+ undo(): Promise<void>;+}+export abstract class Reassembly extends Interface<{+ /** Whether the re-assembled tree is the one now running; false when its boot failed and the previous one was restored. */+ reassemble(change?: ReassemblyChange): Promise<boolean>;+}>() {}+@Module()+export class AppReassembly {+ @Provide() reassembly!: Reassembly;+ constructor(private readonly run: (change?: ReassemblyChange) => Promise<boolean>) {}+ setup() {+ this.reassembly = { reassemble: this.run };+ }+}@Module()export class RuntimeDesktop {@Provide() desktop!: Desktop;diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.tsindex 8efaf75b..23dc1eff 100644--- a/packages/server/src/hmr/platform.ts+++ b/packages/server/src/hmr/platform.ts@@ -28,6 +28,7 @@ import type {Json,Park,IfaceTable,+ Instance,ManifestTable,ModuleDef,ModuleTree,@@ -36,8 +37,11 @@ import {defineIface,schema,type,+ boot,bootModules,+ initialDoc,moduleDefOf,+ upgrade,} from "@prismshadow/penguin-core/kernel";import type { HmrHost, PlatformBundle } from "@prismshadow/penguin-hmr";import { TerminalManager } from "../terminal/manager.js";@@ -56,11 +60,14 @@ import { declined, seamHttp } from "./hono-seam.js";import {PENGUIN_FAMILY,RESOURCE_IFACES_RESOURCE_ID,+ HMR_TEST_PLUGINS_RESOURCE_ID,claimHmrCapabilities,Log,} from "./capabilities.js";-import type { Interfaces, MembersOf } from "./capabilities.js";-import { pluginHostFrom } from "../plugin/host.js";+import type { Interfaces, MembersOf, ReassemblyChange } from "./capabilities.js";+import { PLUGINS_RESOURCE_ID, pluginHostFrom } from "../plugin/host.js";+import type { PluginHost } from "../plugin/host.js";+import { loadPluginHost } from "../plugin/loader.js";import { migrate } from "../db/migrations.js";import type { Auth } from "../mechanisms/identity.js";@@ -224,194 +231,322 @@ export const DECLARED_RESOURCES: ParkedInterfaces = {*/const DRAIN_GRACE_MS = 5000;-export const platformImpl: Impl<PlatformApi, PlatformCtx> = {- async create(ctx, context) {- // The claim comes FIRST, before a single registry read is acted on, and "refused" is a- // throw — what each outcome means and why lives on HmrClaim (capabilities.ts).- // The check sits HERE, in the bundle, because the runtime that needs it is by- // definition too old to receive it; failing this early costs nothing — doUpgradeAll- // rolls the whole upgrade back, and a hot upgrade cannot land what a fresh start- // would refuse (bootAppDeps treats a business-less platform as fatal too).- const claim = claimHmrCapabilities(ctx.resources);- if (claim.kind === "refused") {- throw new Error(- `this runtime publishes no business capabilities this platform can claim ` +- `(${claim.reason}) — update the installation itself; a push replaces the ` +- `platform, never the runtime`,- );- }- const caps = claim.kind === "claimed" ? claim.caps : null;- // A pushed platform carries its own migrations, which is the only way the tables its- // business needs can reach a runtime older than they are — that runtime will never grow- // them by restarting, because it does not have them. swapPath: this boot can be rolled- // back, so a restart-only migration is refused here instead of being left behind. Before- // any node is created: every repo below prepares its statements against this schema.- if (caps !== null) migrate(caps.db, { swapPath: true });- // Resource-interface reconciliation, BEFORE anything is adopted: integrate the groups- // the predecessor declared at the version this build also declares, hard-stop the- // rest — a version bump or a dropped group means this create() does not speak the- // contract behind those handles, and adopting them anyway is how a swap turns into a- // TypeError. A predecessor from before the declaration existed reads as `{}`:- // nothing provable, nothing disposed on its behalf (pre-declaration behavior).- const inherited = ctx.resources.claim<Interfaces>(RESOURCE_IFACES_RESOURCE_ID);- const inheritable = inherited !== undefined && inherited.family === DECLARED_RESOURCES.family;- // DECIDE ONLY. Disposing a group kills live ptys and child processes, and nothing- // brings them back — so the decision is computed here and ACTED ON at the bottom,- // once this App is fully built. Everything between can still throw (a module's- // create, a workflow factory), and a boot that fails there is recovered by re-booting- // the previous bundle; that recovery is only honest if the resources it re-adopts are- // still alive.- const doomedGroups = Object.entries(inherited ?? {})- .filter(([group]) => group !== "family")- .filter(([group, offered]) => {- // Wrong family, wrong version, or a group this build no longer declares: this- // create() cannot speak the contract behind those handles.- const need = DECLARED_RESOURCES[group];- const offers =- Array.isArray(need) && Array.isArray(offered) && need.every((m) => offered.includes(m));- return !inheritable || !offers;- })- .map(([group]) => group);- const adoptable = (group: string) => !doomedGroups.includes(group);+type CreateCtx = Parameters<Impl<PlatformApi, PlatformCtx>["create"]>[0];++/**+ * The App proper: one module tree over the runtime's capabilities. Booted as the INNER+ * instance of `platformImpl` below, and booted again — by the kernel's own upgrade — when a+ * plugin change asks the App to re-assemble.+ */+async function createInner(+ ctx: CreateCtx,+ context: PlatformCtx,+ reassemble: (change?: ReassemblyChange) => Promise<boolean>,+): Promise<PlatformApi> {+ // The claim comes FIRST, before a single registry read is acted on, and "refused" is a+ // throw — what each outcome means and why lives on HmrClaim (capabilities.ts).+ // The check sits HERE, in the bundle, because the runtime that needs it is by+ // definition too old to receive it; failing this early costs nothing — doUpgradeAll+ // rolls the whole upgrade back, and a hot upgrade cannot land what a fresh start+ // would refuse (bootAppDeps treats a business-less platform as fatal too).+ const claim = claimHmrCapabilities(ctx.resources);+ if (claim.kind === "refused") {+ throw new Error(+ `this runtime publishes no business capabilities this platform can claim ` ++ `(${claim.reason}) — update the installation itself; a push replaces the ` ++ `platform, never the runtime`,+ );+ }+ const caps = claim.kind === "claimed" ? claim.caps : null;+ // A pushed platform carries its own migrations, which is the only way the tables its+ // business needs can reach a runtime older than they are — that runtime will never grow+ // them by restarting, because it does not have them. swapPath: this boot can be rolled+ // back, so a restart-only migration is refused here instead of being left behind. Before+ // any node is created: every repo below prepares its statements against this schema.+ if (caps !== null) migrate(caps.db, { swapPath: true });+ // Resource-interface reconciliation, BEFORE anything is adopted: integrate the groups+ // the predecessor declared at the version this build also declares, hard-stop the+ // rest — a version bump or a dropped group means this create() does not speak the+ // contract behind those handles, and adopting them anyway is how a swap turns into a+ // TypeError. A predecessor from before the declaration existed reads as `{}`:+ // nothing provable, nothing disposed on its behalf (pre-declaration behavior).+ const inherited = ctx.resources.claim<Interfaces>(RESOURCE_IFACES_RESOURCE_ID);+ const inheritable = inherited !== undefined && inherited.family === DECLARED_RESOURCES.family;+ // DECIDE ONLY. Disposing a group kills live ptys and child processes, and nothing+ // brings them back — so the decision is computed here and ACTED ON at the bottom,+ // once this App is fully built. Everything between can still throw (a module's+ // create, a workflow factory), and a boot that fails there is recovered by re-booting+ // the previous bundle; that recovery is only honest if the resources it re-adopts are+ // still alive.+ const doomedGroups = Object.entries(inherited ?? {})+ .filter(([group]) => group !== "family")+ .filter(([group, offered]) => {+ // Wrong family, wrong version, or a group this build no longer declares: this+ // create() cannot speak the contract behind those handles.+ const need = DECLARED_RESOURCES[group];+ const offers =+ Array.isArray(need) && Array.isArray(offered) && need.every((m) => offered.includes(m));+ return !inheritable || !offers;+ })+ .map(([group]) => group);+ const adoptable = (group: string) => !doomedGroups.includes(group);- // Plugins are modules (see ../plugin/): the host is CLAIMED from the registry,- // never imported (see pluginHostFrom), and its modules join the tree below.- const plugins = pluginHostFrom(ctx.resources);+ // Plugins are modules (see ../plugin/), and WHICH ones this App runs is configuration it+ // reads for ITSELF: the closure over the root's Projects, loaded here rather than handed+ // over by the runtime, so the rule for reading it ships by push like every other policy.+ // A bare kernel has no root to read and keeps whatever was already imported.+ const plugins =+ caps === null+ ? pluginHostFrom(ctx.resources)+ : await loadPluginHost(ctx.resources, caps.config.root, caps.hmr.assetsDir());+ // Plus whatever a test stood up in process, which no closure could name (see the id).+ const injected = ctx.resources.claim<PluginHost | null>(HMR_TEST_PLUGINS_RESOURCE_ID);+ if (injected != null && typeof injected.entries === "function") {+ for (const entry of injected.entries().values()) plugins.use(entry);+ }- let tree: ModuleTree;- let business: ModuleTree | null = null;- let terminals: TerminalManager;- if (caps === null) {- // A declared bare kernel: terminals only, no business surface. The module tree is- // reduced to what needs no runtime capability — the sandbox floor and the backends- // registered into it — so confinement settings still park and restore.- console.warn("[platform] bare kernel: terminals only, no business surface");- terminals = new TerminalManager(ctx.resources, { assets: () => null });- terminals.adopt(adoptable("TerminalModule") ? (context.terminals ?? []) : []);- tree = await bootModules(bareTree([...plugins.modules()], plugins.replacements()), {+ let tree: ModuleTree;+ let business: ModuleTree | null = null;+ let terminals: TerminalManager;+ if (caps === null) {+ // A declared bare kernel: terminals only, no business surface. The module tree is+ // reduced to what needs no runtime capability — the sandbox floor and the backends+ // registered into it — so confinement settings still park and restore.+ console.warn("[platform] bare kernel: terminals only, no business surface");+ terminals = new TerminalManager(ctx.resources, { assets: () => null });+ terminals.adopt(adoptable("TerminalModule") ? (context.terminals ?? []) : []);+ tree = await bootModules(bareTree([...plugins.modules()], plugins.replacements()), {+ ifaces: plugins.ifaces(ifaceTable as unknown as IfaceTable),+ resources: ctx.resources,+ parked: parkedModules(context),+ });+ } else {+ // THE MODULE TREE (see ../platform.ts): every business service, every route+ // group and the terminal manager are modules wired by their manifests — checked as+ // data before any create() runs, created in dependency order. Sandbox backends the+ // plugin host registered enter the same tree as one contributing module.+ tree = await bootModules(+ platformDef(caps, adoptable, [...plugins.modules()], plugins.replacements(), reassemble),+ {ifaces: plugins.ifaces(ifaceTable as unknown as IfaceTable),resources: ctx.resources,parked: parkedModules(context),+ },+ );+ business = tree;+ terminals = tree.api<TerminalManager>("TerminalModule", "terminals");+ }+ // Ordinary code over this App's own auth: the same object the business routes+ // authenticate with. A bare kernel has none — terminals stay fail-closed.+ const auth = business?.api<Auth>("IdentityModule", "Auth") ?? null;+ const identity = identityFrom(auth);+ const manager = business?.api<SessionManager>("SessionRuntimeModule", "Sessions") ?? null;+ // The runtime's one mid-request need of the CURRENT App is a hook installed over a+ // claimed capability — overwrite-only across swaps, so a dead generation's hook is+ // replaced and never removed: "is this session busy" for the channel sweep.+ if (caps !== null && manager !== null) {+ caps.channels.setActivityProbe((key) => manager.statusOf(key) !== "idle");+ }+ // PARK — the App's resource inventory, split by fate:+ //+ // DELIVERED (survives the swap; the successor adopts it at load):+ // - pty sessions registry `terminal:*` + the terminal module's parked ids+ // - machine tunnels ssh children + machines-connect.json (pid/port) → adopted by+ // the successor's tunnelPortFor, which checks the pid is alive+ // - runtime singletons db / auth-state / channels / config / proxy / desktop —+ // runtime-owned, re-claimed by every App+ // SUSPENDED (stopped here; the successor rebuilds it fresh at load):+ // - scheduler, messaging bridge, machine connections their modules' dispose effects+ // stop them; each successor's setup starts over from the record+ // - agent runs approvals → deny, drives → abort (manager.shutdown below)+ // - session environments dispose() after the drive settles+ // - reap timers the terminal module's effect quiesces them+ // DETACHED (the object survives, this App's grip on it does not):+ // - pty exit listeners unsubscribed, so a dead generation never releases a+ // registry id the successor owns+ // Known exceptions, accepted with reasons: an in-flight self-update child (rare,+ // bounded by its own 10-minute cap, and a successful update restarts the process+ // anyway); an in-flight machines install (same shape — its ssh children run to their+ // own timeouts, the far side's installer stages-and-swaps or rolls back on its own,+ // and the progress log is simply lost, which re-running recovers); and SSE subscriber+ // closures (they serve the old generation's stream until the client reloads on+ // web_updated — the channel hub itself is runtime-owned).+ // A module with state of its own (sandbox settings, workflow refs, ssh tunnels, an+ // in-flight job) belongs in the right list here — the list is the contract, not a+ // description of today's modules.+ // The tree's dispose runs every module's effects in reverse creation order; the+ // asynchronous tail (waiting for aborted runs to end) cannot run inside a sync+ // effect, so it is exposed as api.drained(), which the KERNEL awaits between dispose+ // and the successor's boot (kernel/upgrade.ts). Nothing about the handover touches+ // the registry.+ let drained: Promise<void> | undefined;+ ctx.effect(() => {+ // Forwards to machines are DELIVERED, not suspended: the ssh children are separate+ // processes that keep forwarding across the swap, and the successor adopts them by the+ // pid recorded in web.db (machines/service.ts).+ const drains: Promise<unknown>[] = [];+ if (manager !== null) drains.push(manager.shutdown(DRAIN_GRACE_MS));+ tree.dispose();+ if (business === null) terminals.quiesce();+ drained = Promise.allSettled(drains).then(() => undefined);+ });++ // COMMIT: from here the App is built and nothing below throws, so the irreversible+ // half of the resource reconciliation runs — the groups this build cannot speak for+ // are disposed, and the declaration is overwritten (never released — see the ID's+ // doc) so the NEXT App reads this build's.+ for (const group of doomedGroups) ctx.resources.disposeGroup?.(group);+ ctx.resources.register(RESOURCE_IFACES_RESOURCE_ID, DECLARED_RESOURCES);+ // The imported plugin objects, handed to whoever boots next — parked state, registered+ // at the commit so a create() that threw leaves the previous App's host in place.+ ctx.resources.register(PLUGINS_RESOURCE_ID, plugins);++ const httpApi = business?.api<{ fetch(request: Request): Promise<Response> }>(+ "HttpModule",+ "http",+ );+ const http = httpApi !== undefined ? seamHttp(httpApi) : seamHttp(bareApp(terminals, identity));+ const logNode = business?.api<Log>("RuntimeModule", "Log") ?? null;++ return {+ log: (line) => (logNode !== null ? logNode.line(line) : console.log(line)),+ park: () => {+ const modules = tree.park();+ // The top-level fields are written for every platform that reads them: a bare+ // kernel's own ptys, and the two parking modules' state in the form the first+ // platforms parked it — so a rollback to any of them keeps terminals and confinement.+ const terminalIds =+ business === null+ ? terminals.handleIds()+ : (parkedSelf(modules, "TerminalModule")?.terminals as string[] | undefined);+ const sandbox = parkedSelf(modules, "SandboxModule")?.settings;+ return {+ motd: context.motd,+ modules,+ ...(terminalIds !== undefined ? { terminals: terminalIds } : {}),+ ...(sandbox !== undefined ? { sandbox } : {}),+ };+ },+ info: () => ({+ impl: "packaged",+ ifaceVersion: PlatformIface.version,+ motd: context.motd,+ terminals: terminals.handleIds().length,+ }),+ http,+ terminals: () => terminals,+ attachStream: (ws, session, url, log) => bindTerminalStream(ws, session, url, log),+ business: () => business,+ // Process exit wants the manager's graceful ≤5s drain, which a synchronous dispose+ // effect cannot await — exposed for index.ts's shutdown to call before disposing.+ shutdown: async () => {+ if (manager !== null) await manager.shutdown(DRAIN_GRACE_MS);+ },+ drained: () => drained,+ };+}++/**+ * What the runtime boots: a shell around the inner App, so the App can re-assemble itself+ * while the runtime keeps holding the same instance.+ *+ * A plugin change is configuration, and configuration changes while the process runs; the+ * tree has to be built again for it to take. That rebuild is the platform's own business —+ * policy, shipped by push, working on every runtime — so it happens here, above the seam,+ * with the kernel's `upgrade` over the inner instance: same impl, same iface, same parked+ * document, the swap a hot push performs but without a new bundle. A boot that fails is+ * recovered onto the previous document, as a failed push is, and reported as false.+ *+ * Every member of the outer API forwards to the inner App of the moment. Re-assemblies are+ * serialized on `op`; a runtime-driven dispose (a push landing) disposes the inner App at+ * once, as the App's own dispose always did, unless a re-assembly is mid-swap — then the+ * dispose waits for it through `drained`, which the kernel awaits before booting the+ * successor. One window stays open by design: `park()` cannot wait, so a push+ * that parks exactly while a re-assembly is mid-swap parks the tree being replaced.+ */+export const platformImpl: Impl<PlatformApi, PlatformCtx> = {+ async create(ctx, context) {+ const innerImpl: Impl<PlatformApi, PlatformCtx> = {+ create: (innerCtx, innerContext) => createInner(innerCtx, innerContext, reassemble),+ };+ let inner: Instance<PlatformApi>;+ let op: Promise<unknown> = Promise.resolve();+ let closed = false;+ /** True while a re-assembly holds the inner instance mid-swap. */+ let swapping = false;+ async function reassemble(change?: ReassemblyChange): Promise<boolean> {+ const run = op.then(async () => {+ if (closed) return false;+ // The change is written HERE, in the queue: two edits of one Project's file never+ // interleave, and each re-assembly reads exactly what was written for it.+ await change?.write();+ swapping = true;+ try {+ const result = await upgrade({+ current: inner,+ impl: innerImpl,+ iface: PlatformIface,+ resources: ctx.resources,+ });+ if (result.status === "ok") {+ inner = result.instance;+ return true;+ }+ if (result.status === "failed") {+ // The kernel has disposed the previous tree; the restore boot reads the+ // configuration again, so the change is undone first — with it in place, a+ // plugin that broke the boot once would break the restore too and leave the+ // process forwarding to a disposed tree.+ const reason =+ result.error instanceof Error ? result.error.message : String(result.error);+ await change?.undo();+ inner = await boot(innerImpl, PlatformIface, result.doc, ctx.resources);+ console.warn(+ `[platform] the App failed to boot after a plugin change; the change was undone and the previous App restored: ${reason}`,+ );+ }+ return false;+ } finally {+ swapping = false;+ }});- } else {- // THE MODULE TREE (see ../platform.ts): every business service, every route- // group and the terminal manager are modules wired by their manifests — checked as- // data before any create() runs, created in dependency order. Sandbox backends the- // plugin host registered enter the same tree as one contributing module.- tree = await bootModules(- platformDef(caps, adoptable, [...plugins.modules()], plugins.replacements()),- {- ifaces: plugins.ifaces(ifaceTable as unknown as IfaceTable),- resources: ctx.resources,- parked: parkedModules(context),- },+ op = run.then(+ () => undefined,+ () => undefined,);- business = tree;- terminals = tree.api<TerminalManager>("TerminalModule", "terminals");- }- // Ordinary code over this App's own auth: the same object the business routes- // authenticate with. A bare kernel has none — terminals stay fail-closed.- const auth = business?.api<Auth>("IdentityModule", "Auth") ?? null;- const identity = identityFrom(auth);- const manager = business?.api<SessionManager>("SessionRuntimeModule", "Sessions") ?? null;- // The runtime's one mid-request need of the CURRENT App is a hook installed over a- // claimed capability — overwrite-only across swaps, so a dead generation's hook is- // replaced and never removed: "is this session busy" for the channel sweep.- if (caps !== null && manager !== null) {- caps.channels.setActivityProbe((key) => manager.statusOf(key) !== "idle");+ return run;}- // PARK — the App's resource inventory, split by fate:- //- // DELIVERED (survives the swap; the successor adopts it at load):- // - pty sessions registry `terminal:*` + the terminal module's parked ids- // - machine tunnels ssh children + machines-connect.json (pid/port) → adopted by- // the successor's tunnelPortFor, which checks the pid is alive- // - runtime singletons db / auth-state / channels / config / proxy / desktop —- // runtime-owned, re-claimed by every App- // SUSPENDED (stopped here; the successor rebuilds it fresh at load):- // - scheduler, messaging bridge, machine connections their modules' dispose effects- // stop them; each successor's setup starts over from the record- // - agent runs approvals → deny, drives → abort (manager.shutdown below)- // - session environments dispose() after the drive settles- // - reap timers the terminal module's effect quiesces them- // DETACHED (the object survives, this App's grip on it does not):- // - pty exit listeners unsubscribed, so a dead generation never releases a- // registry id the successor owns- // Known exceptions, accepted with reasons: an in-flight self-update child (rare,- // bounded by its own 10-minute cap, and a successful update restarts the process- // anyway); an in-flight machines install (same shape — its ssh children run to their- // own timeouts, the far side's installer stages-and-swaps or rolls back on its own,- // and the progress log is simply lost, which re-running recovers); and SSE subscriber- // closures (they serve the old generation's stream until the client reloads on- // web_updated — the channel hub itself is runtime-owned).- // A module with state of its own (sandbox settings, workflow refs, ssh tunnels, an- // in-flight job) belongs in the right list here — the list is the contract, not a- // description of today's modules.- // The tree's dispose runs every module's effects in reverse creation order; the- // asynchronous tail (waiting for aborted runs to end) cannot run inside a sync- // effect, so it is exposed as api.drained(), which the KERNEL awaits between dispose- // and the successor's boot (kernel/upgrade.ts). Nothing about the handover touches- // the registry.+ // The kernel hands create() its node's own document; the inner boot wants the tree's,+ // which for this platform (no kernel children — the module tree parks inside `modules`)+ // is that document wrapped once.+ inner = await boot(innerImpl, PlatformIface, initialDoc(PlatformIface, context), ctx.resources);+let drained: Promise<void> | undefined;ctx.effect(() => {- // Forwards to machines are DELIVERED, not suspended: the ssh children are separate- // processes that keep forwarding across the swap, and the successor adopts them by the- // pid recorded in web.db (machines/service.ts).- const drains: Promise<unknown>[] = [];- if (manager !== null) drains.push(manager.shutdown(DRAIN_GRACE_MS));- tree.dispose();- if (business === null) terminals.quiesce();- drained = Promise.allSettled(drains).then(() => undefined);+ closed = true;+ // Synchronous in the ordinary case, exactly as the App's own dispose is: the runtime+ // (and a test's cleanup) closes the database right after this returns, and every+ // module's dispose effect must have run by then. Only a re-assembly caught mid-swap+ // is let finish first — it holds the one handle on the tree it is booting.+ if (!swapping) {+ inner.dispose();+ drained = inner.api.drained();+ return;+ }+ drained = op.then(() => {+ inner.dispose();+ return inner.api.drained();+ });});-- // COMMIT: from here the App is built and nothing below throws, so the irreversible- // half of the resource reconciliation runs — the groups this build cannot speak for- // are disposed, and the declaration is overwritten (never released — see the ID's- // doc) so the NEXT App reads this build's.- for (const group of doomedGroups) ctx.resources.disposeGroup?.(group);- ctx.resources.register(RESOURCE_IFACES_RESOURCE_ID, DECLARED_RESOURCES);-- const httpApi = business?.api<{ fetch(request: Request): Promise<Response> }>(- "HttpModule",- "http",- );- const http = httpApi !== undefined ? seamHttp(httpApi) : seamHttp(bareApp(terminals, identity));- const logNode = business?.api<Log>("RuntimeModule", "Log") ?? null;-return {- log: (line) => (logNode !== null ? logNode.line(line) : console.log(line)),- park: () => {- const modules = tree.park();- // The top-level fields are written for every platform that reads them: a bare- // kernel's own ptys, and the two parking modules' state in the form the first- // platforms parked it — so a rollback to any of them keeps terminals and confinement.- const terminalIds =- business === null- ? terminals.handleIds()- : (parkedSelf(modules, "TerminalModule")?.terminals as string[] | undefined);- const sandbox = parkedSelf(modules, "SandboxModule")?.settings;- return {- motd: context.motd,- modules,- ...(terminalIds !== undefined ? { terminals: terminalIds } : {}),- ...(sandbox !== undefined ? { sandbox } : {}),- };- },- info: () => ({- impl: "packaged",- ifaceVersion: PlatformIface.version,- motd: context.motd,- terminals: terminals.handleIds().length,- }),- http,- terminals: () => terminals,- attachStream: (ws, session, url, log) => bindTerminalStream(ws, session, url, log),- business: () => business,- // Process exit wants the manager's graceful ≤5s drain, which a synchronous dispose- // effect cannot await — exposed for index.ts's shutdown to call before disposing.- shutdown: async () => {- if (manager !== null) await manager.shutdown(DRAIN_GRACE_MS);- },+ log: (line) => inner.api.log(line),+ park: () => inner.api.park(),+ info: () => inner.api.info(),+ http: (request) => inner.api.http(request),+ terminals: () => inner.api.terminals(),+ attachStream: (ws, session, url, log) => inner.api.attachStream(ws, session, url, log),+ business: () => inner.api.business(),+ shutdown: () => inner.api.shutdown(),drained: () => drained,};},diff --git a/packages/server/src/http/routes/plugins-installed.ts b/packages/server/src/http/routes/plugins-installed.tsnew file mode 100644index 00000000..575834d8--- /dev/null+++ b/packages/server/src/http/routes/plugins-installed.ts@@ -0,0 +1,274 @@+/**+ * The plugins a PROJECT asks for, and which of them this process is actually running:+ *+ * GET / this Project's list, joined with what the process runs,+ * plus which plugins the build ships (any member)+ * POST / { specifier } add a plugin the build ships to this Project's list, and+ * apply (admin); nothing is fetched from anywhere+ * PUT / { plugins } rewrite this Project's list, and apply (admin)+ * DELETE /?specifier=… drop it from this Project's list, and apply (admin)+ *+ * WHERE THE LIST LIVES. In the Project's own config (the `[plugins]` table of `.project_config.toml`,+ * package name → requirement, Cargo's `[dependencies]` shape),+ * beside its models — because machines are lent to Projects, so a Project's list is what+ * says which machines a plugin has to reach (PRFC-0010). The data root's old `plugins.json`+ * is not read any more, deliberately without a migration: a deployment that had one starts+ * with no plugins until each Project asks again.+ *+ * WHAT ACTUALLY RUNS is the CLOSURE — the union over this root's Projects — because loading+ * is per process: there is one module tree. So a plugin any Project asks for is in the tree,+ * and what it contributes is visible to all of them. A row here is therefore "this Project+ * asked for it" joined with "the process has it", which are two different facts.+ *+ * APPLYING. A write asks the App to re-assemble itself (the platform's own `Reassembly`,+ * hmr/platform.ts): the new create() reads the closure and imports what it names — no+ * process restart, ptys and connections delivered across it exactly as a push delivers+ * them. What a push does not deliver, this does not either: agent runs in flight are+ * stopped and pending approvals denied, in EVERY Project, because there is one tree. The+ * page says so before an admin applies a change. The edit itself travels with the+ * re-assembly (ReassemblyChange): written in its queue, so two admins' edits of one file+ * never interleave, and undone when the new tree fails to boot — the previous App is+ * restored on the previous list, and the answer is "did not take".+ */+import { Hono } from "hono";+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";+import type { AppEnv } from "../../auth/middleware.js";+import type { InstalledPlugin, InstalledPluginsResponse } from "../../api/types.js";+import { HttpError } from "../errors.js";+import { readJson, requireValidId } from "../validate.js";+import type { Config, Hmr, Reassembly, ReassemblyChange } from "../../hmr/capabilities.js";+import {+ discoverBuiltinPlugins,+ PACKAGE_NAME,+ PLUGINS_FILE,+ pluginBases,+ readPluginDeclaration,+} from "../../plugin/loader.js";+import { pluginHostFrom } from "../../plugin/host.js";+import { Access, ProjectConfigStore } from "../../mechanisms/projects.js";++export interface InstalledPluginsDeps {+ root: string;+ /** The current version's assets, where the builtin plugins a push carried live. */+ assetsDir: () => string | null;+ /** What the process's plugin host holds, by specifier, and what it could not load, with why. */+ running: () => { loaded: ReadonlySet<string>; skipped: ReadonlyMap<string, string> };+ projectConfig: ProjectConfigStore;+ access: Access;+ /**+ * Writes the change and re-assembles the App on it. Answers whether the running tree is+ * the new one; false when its boot failed (the change is then undone and the previous+ * App restored) or when the runtime cannot re-assemble at all (the change stays written,+ * for the restart that will read it).+ */+ apply: (change: ReassemblyChange) => Promise<boolean>;+}++export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ const scope = (c: {+ req: { param(n: string): string | undefined };+ var: AppEnv["Variables"];+ }) => {+ const projectId = requireValidId(c as never, "projectId");+ deps.access.requireProjectAccess(c.var.user.userId, projectId);+ return projectId;+ };++ const view = async (projectId: string): Promise<InstalledPluginsResponse> => {+ const listed = await deps.projectConfig.getPlugins(projectId).catch((err: unknown) => {+ // A Project whose config will not parse cannot be answered for — its models are just+ // as unreadable — and saying "no plugins" would read as a healthy empty deployment.+ throw new HttpError(+ 400,+ "invalid_plugins_file",+ `${projectId}: ${PLUGINS_FILE} could not be read: ${err instanceof Error ? err.message : String(err)}`,+ );+ });+ const { loaded, skipped } = deps.running();+ const bases = pluginBases(deps.root, deps.assetsDir());+ // Exactly what this Project lists: a plugin the build ships is not asked for until a+ // Project says so. `builtin` on a row is where the package CAME FROM, a tag, not a+ // second way of being asked for. What the package declares is read from its files;+ // whether the process holds it, and why not, is the host's — a load that failed says+ // so, rather than passing as a restart that would not help.+ const plugins: InstalledPlugin[] = [];+ for (const specifier of Object.keys(listed)) {+ const declared = await readPluginDeclaration(specifier, bases);+ if ("error" in declared) {+ plugins.push({+ specifier,+ active: false,+ builtin: false,+ modules: [],+ replaces: [],+ error: declared.error,+ });+ continue;+ }+ const active = loaded.has(specifier);+ const failure = skipped.get(specifier);+ plugins.push({+ specifier,+ active,+ builtin: declared.builtin,+ modules: declared.modules,+ replaces: declared.replaces,+ ...(!active && failure !== undefined ? { error: failure } : {}),+ });+ }+ return {+ plugins,+ // What the build ships, asked for or not: the catalogue marks these rows "built in",+ // and asking for one is a list edit rather than a download.+ shipped: await discoverBuiltinPlugins(bases),+ file: PLUGINS_FILE,+ // A listed plugin that neither runs nor failed is waiting for a runtime that can+ // re-assemble the App — otherwise applying already loaded it.+ restartPending: plugins.some((p) => !p.active && p.error === undefined),+ };+ };++ app.get("/", async (c) => c.json(await view(scope(c))));++ const requireAdmin = (c: { var: AppEnv["Variables"] }) => {+ if (!c.var.user.isAdmin) {+ throw new HttpError(403, "admin_required", "Only an admin can perform this operation.");+ }+ };++ /** A package name (scoped or not) — never a path, a URL or a version range. */+ const specifierOf = (value: unknown): string => {+ const s = typeof value === "string" ? value.trim() : "";+ if (!PACKAGE_NAME.test(s)) {+ throw new HttpError(400, "bad_request", "specifier must be a package name.");+ }+ return s;+ };++ /**+ * Only a plugin the build ships can be asked for: it is already on the machine, so asking+ * is consent, not a download. Nothing is fetched from a registry — a listed plugin that is+ * not on disk is exactly the state these routes exist to avoid. One gate for every verb+ * that adds a name, so a list rewrite cannot name what a single add could not.+ */+ const requireShipped = async (specifiers: readonly string[]) => {+ if (specifiers.length === 0) return;+ const shipped = await discoverBuiltinPlugins(pluginBases(deps.root, deps.assetsDir()));+ for (const specifier of specifiers) {+ if (!shipped.includes(specifier)) {+ throw new HttpError(+ 400,+ "plugin_not_shipped",+ `'${specifier}' does not ship with this build; only builtin plugins can be installed.`,+ );+ }+ }+ };++ type PluginTable = Awaited<ReturnType<ProjectConfigStore["getPlugins"]>>;+ /**+ * An edit of this Project's table as a re-assembly change: read and written inside the+ * re-assembly's queue, so two edits never interleave, and undone — the table as it was —+ * when the new tree fails to boot.+ */+ const edit = (projectId: string, next: (listed: PluginTable) => PluginTable) => {+ let previous: PluginTable | null = null;+ const change: ReassemblyChange = {+ write: async () => {+ previous = await deps.projectConfig.getPlugins(projectId);+ await deps.projectConfig.setPlugins(projectId, next(previous));+ },+ undo: async () => {+ if (previous !== null) await deps.projectConfig.setPlugins(projectId, previous);+ },+ };+ return change;+ };++ app.post("/", async (c) => {+ requireAdmin(c);+ const projectId = scope(c);+ const specifier = specifierOf((await readJson(c)).specifier);+ await requireShipped([specifier]);+ await deps.apply(+ edit(projectId, (listed) => (specifier in listed ? listed : { ...listed, [specifier]: {} })),+ );+ return c.json(await view(projectId));+ });++ app.delete("/", async (c) => {+ requireAdmin(c);+ const projectId = scope(c);+ const specifier = specifierOf(c.req.query("specifier"));+ await deps.apply(+ edit(projectId, (listed) => {+ const kept = { ...listed };+ delete kept[specifier];+ return kept;+ }),+ );+ return c.json(await view(projectId));+ });++ app.put("/", async (c) => {+ requireAdmin(c);+ const projectId = scope(c);+ const body = await readJson(c);+ const list = body.plugins;+ if (!Array.isArray(list)) {+ throw new HttpError(400, "bad_request", "plugins must be an array of package specifiers.");+ }+ // Names only, over the wire — the same names POST accepts. A name the list already+ // carries was consented to when it was written; a NEW one is gated exactly as POST+ // gates it. A name that stays keeps what the file asked of it.+ const names = list.map(specifierOf);+ const already = await deps.projectConfig.getPlugins(projectId).catch(() => ({}));+ await requireShipped(names.filter((s) => !(s in already)));+ await deps.apply(+ edit(projectId, (listed) => Object.fromEntries(names.map((s) => [s, listed[s] ?? {}]))),+ );+ return c.json(await view(projectId));+ });++ return app;+}++@Component({+ contributes: {+ "HttpModule.routes": [+ {+ id: "InstalledPluginRoutes.routes",+ prefix: "/api/projects/:projectId/plugins/installed",+ auth: "user",+ // Ahead of the catalogue group, whose "/" would otherwise answer here.+ order: 60,+ },+ ],+ },+})+export class InstalledPluginRoutes {+ @Use() private readonly config!: Config;+ @Use() private readonly hmr!: Hmr;+ @Use() private readonly reassembly!: Reassembly;+ @Use() private readonly projectConfig!: ProjectConfigStore;+ @Use() private readonly access!: Access;+ @Bind("InstalledPluginRoutes.routes") routes!: Hono<AppEnv>;+ setup() {+ const hmr = this.hmr;+ this.routes = installedPluginRoutes({+ root: this.config.root,+ assetsDir: () => hmr.assetsDir(),+ // Claimed per call rather than captured: the host belongs to the process, and a hot+ // swap hands the same one to the next platform.+ running: () => {+ const host = pluginHostFrom(hmr.resources);+ return { loaded: new Set(host.entries().keys()), skipped: host.skipped() };+ },+ projectConfig: this.projectConfig,+ access: this.access,+ apply: (change) => this.reassembly.reassemble(change),+ });+ }+}diff --git a/packages/server/src/http/routes/plugins.ts b/packages/server/src/http/routes/plugins.tsindex 9524c7bf..e2321eef 100644--- a/packages/server/src/http/routes/plugins.ts+++ b/packages/server/src/http/routes/plugins.ts@@ -1,12 +1,19 @@/**- * Plugin library & installing from it:- * GET /api/plugins # the library by category (any logged-in user)- * GET /api/plugins/:plugin/files # the files a plugin ships, for the detail view's browser (any logged-in user)+ * Plugins: the library this build ships, 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/:plugin/files # the files a library plugin ships, for the detail view's browser+ * 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)* 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* (skills.ts, hooks.ts).+ *+ * Library and registry are two views of one kind of thing — a package of skills and/or+ * 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 { Hono } from "hono";import {@@ -19,16 +26,21 @@ import {import type {AgentPluginsInstallResponse,PluginFilesResponse,+ PluginIndexResponse,PluginLibraryResponse,+ PluginReadmeResponse,} from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import type { ServerConfig } from "../../config.js";-import type { Config } from "../../hmr/capabilities.js";+import type { Config, Hmr } from "../../hmr/capabilities.js";import type { AgentConfig } from "../../mechanisms/agents.js";import type { Access } from "../../mechanisms/projects.js";import type { Sessions as ManagerIface } from "../../runtime/session-manager.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import { agentHooksRoutes } from "./hooks.js";+import { builtinPluginRegistry } from "../../plugin/registry.js";+import { pluginBases } from "../../plugin/loader.js";+import type { PluginBase } from "../../plugin/loader.js";/** What these route groups reach — bound by their component below. */export interface PluginsRouteDeps {@@ -153,3 +165,55 @@ export class PluginRoutes {this.hookRoutes = agentHooksRoutes(deps);}}++export function pluginRegistryRoutes(bases: () => readonly PluginBase[]): Hono<AppEnv> {+ const app = new Hono<AppEnv>();+ const registry = builtinPluginRegistry(bases);+ app.get("/", async (c) => {+ const body: PluginIndexResponse = { plugins: await registry.index() };+ return c.json(body);+ });+ app.get("/readme", async (c) => {+ const name = c.req.query("name");+ if (name === undefined || name === "") {+ return c.json({ error: { code: "bad_request", message: "name is required" } }, 400);+ }+ // Only entries this deployment actually lists: the readme map is keyed by specifier,+ // and answering for an unlisted name would make the endpoint a probe of what exists.+ const listed = (await registry.index()).some((e) => e.name === name);+ if (!listed) {+ return c.json({ error: { code: "not_found", message: "no such plugin" } }, 404);+ }+ const body: PluginReadmeResponse = { name, readme: await registry.readme(name) };+ return c.json(body);+ });+ return app;+}++/**+ * The registry the Plugins page reads beside the built-in library: deployment-global, and+ * nested under /api/plugins/registry so both views answer under one prefix. The specifier+ * is a query parameter on `readme`, not a path segment, because it is scoped+ * (`@scope/name`) and would otherwise have to survive two rounds of slash encoding.+ */+@Component({+ contributes: {+ "HttpModule.routes": [+ {+ id: "PluginRegistryRoutes.routes",+ prefix: "/api/plugins/registry",+ auth: "user",+ order: 69,+ },+ ],+ },+})+export class PluginRegistryRoutes {+ @Use() private readonly config!: Config;+ @Use() private readonly hmr!: Hmr;+ @Bind("PluginRegistryRoutes.routes") routes!: Hono<AppEnv>;+ setup() {+ // Read per request: a push moves the shipped prefix to a new assets directory.+ this.routes = pluginRegistryRoutes(() => pluginBases(this.config.root, this.hmr.assetsDir()));+ }+}diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex 8ec75e12..a466203d 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -150,10 +150,12 @@ class PenguinServer {}/**- * Plugins are configuration, and reading configuration is the runtime's job: take the- * specifiers plugins.json names, import them, and register each into this process's one- * PluginHost. Once per process — a hot swap re-delivers the hooks to these same plugin- * objects, which is the host's job, but must never import them again.+ * A SHIM, since the platform loads its own (plugin/loader.ts's loadPluginHost, called from+ * the platform's create()). Which plugins a deployment runs, and how that list is read, is+ * policy — it ships by push, and a machine whose program predates a new rule must still+ * learn it. What this keeps working is one case: a platform OLDER than that move, pushed+ * onto this runtime, which claims the host and never builds one. It goes when no such+ * platform is worth rolling back to.** A plugin that fails to load is skipped with a warning instead of taking the server* down: the capability it would have provided stays unavailable, which a deployment can@@ -192,7 +194,7 @@ class PenguinServer {}async buildDeps(hmr: Hmr<PlatformApi>): Promise<void> {- this.deps = await bootAppDeps(this.config, [], this.plugins, this.host, hmr);+ this.deps = await bootAppDeps(this.config, [], this.plugins, undefined, this.host, hmr);}/**diff --git a/packages/server/src/mechanisms/projects.ts b/packages/server/src/mechanisms/projects.tsindex ab8cc2e3..6e9edd86 100644--- a/packages/server/src/mechanisms/projects.ts+++ b/packages/server/src/mechanisms/projects.ts@@ -25,7 +25,12 @@ import type {} from "../api/types.js";import type { UserRow } from "../db/repos/users.js";import type { RawTable, UtilityCompletion } from "../services/project-config-service.js";-import type { ListEndpointModelsOptions, ModelRef, ProjectConfig } from "@prismshadow/penguin-core";+import type {+ ListEndpointModelsOptions,+ ModelRef,+ PluginTable,+ ProjectConfig,+} from "@prismshadow/penguin-core";import type { TieredRates } from "../services/usage-service.js";import type {ModelOAuthErrorCode,@@ -101,6 +106,10 @@ export abstract class ProjectConfigStore extends Interface<{setDefaultModelRef(projectId: string, ref: ModelRefDto): Promise<ModelRefDto>;getChatDefaults(projectId: string): Promise<ChatDefaultsDto>;setChatDefaults(projectId: string, req: ChatDefaultsDto): Promise<ChatDefaultsDto>;+ /** The `[plugins]` table this Project asks for: package name → requirement, in the file's order. */+ getPlugins(projectId: string): Promise<PluginTable>;+ /** Replaces the table (a declarative PUT); answers what was written. */+ setPlugins(projectId: string, plugins: PluginTable): Promise<PluginTable>;getCommandPolicy(projectId: string): Promise<CommandPolicyDto>;setCommandPolicy(projectId: string,diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex 67aa2866..068b0f42 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -1,7 +1,7 @@import { Component, Module, moduleDefOf, Use } from "@prismshadow/penguin-core/kernel";import type { ManifestTable, ModuleClass, ModuleDef } from "@prismshadow/penguin-core/kernel";import table from "./ifaces.json" with { type: "json" };-import type { HmrCapabilities } from "./hmr/capabilities.js";+import type { HmrCapabilities, ReassemblyChange } from "./hmr/capabilities.js";import {ConfigPaths,ConsoleLog,@@ -13,6 +13,7 @@ import {RuntimeDesktop,RuntimeHmr,RuntimeHmrControl,+ AppReassembly,RuntimeProxy,RuntimeResourceGroups,SystemClock,@@ -24,6 +25,7 @@ import {Desktop,Lifecycle,Hmr,+ Reassembly,HmrControl,Log,Paths,@@ -109,7 +111,8 @@ import { DesktopRoutes, DesktopTrayRoutes, DesktopUpdateRoutes } from "./http/roimport { InstallRoutes } from "./http/routes/install.js";import { HmrRoutes } from "./hmr/routes.js";import { EventsRoutes } from "./http/routes/events.js";-import { PluginRoutes } from "./http/routes/plugins.js";+import { PluginRegistryRoutes, PluginRoutes } from "./http/routes/plugins.js";+import { InstalledPluginRoutes } from "./http/routes/plugins-installed.js";import { TerminalModule } from "./terminal/manager.js";import { SessionApiRoutes } from "./http/routes/sessions.js";import { Admin, Auth, AuthSessions, Users } from "./mechanisms/identity.js";@@ -201,6 +204,7 @@ export class Startup {RuntimeProxy,RuntimeHmr,RuntimeHmrControl,+ AppReassembly,RuntimeDesktop,RuntimeAuthState,RuntimeLifecycle,@@ -216,6 +220,7 @@ export class Startup {Proxy,Hmr,HmrControl,+ Reassembly,Desktop,AuthState,Lifecycle,@@ -376,6 +381,8 @@ export class CompanyModule {}DesktopUpdateRoutes,DesktopTrayRoutes,PluginRoutes,+ PluginRegistryRoutes,+ InstalledPluginRoutes,],exports: [Http, WebShell, UpdateCheck],})@@ -414,6 +421,11 @@ export function platformDef(adoptable: (group: string) => boolean,plugins: ModuleDef[] = [],replace: ReadonlyMap<string, ModuleDef> = new Map(),+ /** The platform's own re-assembly (hmr/platform.ts); a test tree that never re-assembles writes the change and answers false. */+ reassemble: (change?: ReassemblyChange) => Promise<boolean> = async (change) => {+ await change?.write();+ return false;+ },): ModuleDef {const instances = new Map<ModuleClass, object>([[RuntimeConfig, new RuntimeConfig(caps)],@@ -422,6 +434,7 @@ export function platformDef([RuntimeProxy, new RuntimeProxy(caps)],[RuntimeHmr, new RuntimeHmr(caps)],[RuntimeHmrControl, new RuntimeHmrControl(caps)],+ [AppReassembly, new AppReassembly(reassemble)],[RuntimeDesktop, new RuntimeDesktop(caps)],[RuntimeAuthState, new RuntimeAuthState(caps)],[RuntimeLifecycle, new RuntimeLifecycle(caps)],diff --git a/packages/server/src/plugin/builtin-index.json b/packages/server/src/plugin/builtin-index.jsonnew file mode 100644index 00000000..6e92fc0e--- /dev/null+++ b/packages/server/src/plugin/builtin-index.json@@ -0,0 +1,42 @@+[+ {+ "name": "@prismshadow/penguin-plugin-sandbox-bwrap",+ "version": "0.2.2",+ "description": "Bubblewrap sandbox backend for PenguinHarness: filesystem confinement plus network isolation and path masking.",+ "authors": ["Prism Shadow"],+ "license": "Apache-2.0",+ "repository": "https://github.com/Prism-Shadow/penguin-harness",+ "keywords": ["linux", "bubblewrap", "network-isolation", "path-masking"],+ "categories": ["sandbox"]+ },+ {+ "name": "@prismshadow/penguin-plugin-sandbox-seatbelt",+ "version": "0.2.2",+ "description": "macOS Seatbelt sandbox backend for PenguinHarness: filesystem confinement plus network isolation and path masking.",+ "authors": ["Prism Shadow"],+ "license": "Apache-2.0",+ "repository": "https://github.com/Prism-Shadow/penguin-harness",+ "keywords": ["macos", "seatbelt", "network-isolation", "path-masking"],+ "categories": ["sandbox"]+ },+ {+ "name": "@prismshadow/penguin-plugin-sandbox-mxc",+ "version": "0.2.2",+ "description": "Windows sandbox backend for PenguinHarness over Microsoft MXC (Microsoft eXecution Containers): filesystem confinement, network isolation and path masking via the processcontainer backend.",+ "authors": ["Prism Shadow"],+ "license": "Apache-2.0",+ "repository": "https://github.com/Prism-Shadow/penguin-harness",+ "keywords": ["windows", "mxc", "network-isolation", "path-masking"],+ "categories": ["sandbox"]+ },+ {+ "name": "@prismshadow/penguin-plugin-sandbox-dsh",+ "version": "0.2.2",+ "description": "DeepSeek Harness sandbox adaptor for PenguinHarness: the DSH local backend chain behind the harness's own sandbox interface.",+ "authors": ["Prism Shadow"],+ "license": "Apache-2.0",+ "repository": "https://github.com/Prism-Shadow/penguin-harness",+ "keywords": ["linux", "macos", "windows", "dsh", "filesystem-only"],+ "categories": ["sandbox"]+ }+]diff --git a/packages/server/src/plugin/host.ts b/packages/server/src/plugin/host.tsindex ba8b6a00..0b6e14cc 100644--- a/packages/server/src/plugin/host.ts+++ b/packages/server/src/plugin/host.ts@@ -8,6 +8,21 @@ import type { IfaceTable, ModuleDef, Resources } from "@prismshadow/penguin-core/** One loaded plugin: the package, its modules and stand-ins with manifests paired to code, and its generated table. */export interface LoadedPlugin {specifier: string;+ /**+ * The entry file this was imported from, when there was one to resolve. It is what makes a+ * REUSE safe: the specifier alone does not say which bytes are behind it, and a hot push+ * moves the builtin plugins to a new assets directory — so an entry held from before the+ * push resolves to a different file, and must be imported again rather than kept. Absent on+ * an entry from a generation older than this field (re-imported, which is correct for it)+ * and on a bare specifier the installation itself resolves.+ */+ file?: string | null;+ /**+ * The entry file's modification time when it was imported. A file rewritten in place keeps+ * its path, so the path alone would reuse the old code; absent on an older generation's+ * entry, which is then imported again.+ */+ stamp?: number | null;/** Nodes the plugin adds under the root. */modules: ModuleDef[];/** Nodes the plugin stands in for, by the replaced node's name. */@@ -19,6 +34,8 @@ export interface LoadedPlugin {/** One host per server process; load order is the order the modules join the tree. */export class PluginHost {private readonly plugins: LoadedPlugin[] = [];+ /** specifier → why a listed plugin is not here; what a surface reports beside its row. */+ private readonly failures = new Map<string, string>();/** Registers a plugin; a module name already taken by an earlier plugin is refused. */use(plugin: LoadedPlugin): void {@@ -68,6 +85,21 @@ export class PluginHost {return { ifaces, types };}+ /** What is loaded, by specifier — how the next App reuses these objects instead of importing again. */+ entries(): ReadonlyMap<string, LoadedPlugin> {+ return new Map(this.plugins.map((e) => [e.specifier, e]));+ }++ /** Records why a listed plugin could not be loaded into this host. */+ skip(specifier: string, reason: string): void {+ this.failures.set(specifier, reason);+ }++ /** The listed plugins this host could not load, each with its reason. */+ skipped(): ReadonlyMap<string, string> {+ return this.failures;+ }+/** Nothing to release at process exit: modules dispose with the App that created them. */dispose(): void {}}@@ -81,9 +113,8 @@ export class PluginHost {* is parked only because the imported objects must survive a swap — a re-import would give* the successor different module instances.*- * That the runtime still LOADS it at process start (index.ts) is the misfiling this note- * exists to flag: it is why a machine whose program is older cannot learn a new loading rule- * from a push, and had to be restarted to pick up a plugin list.+ * The platform builds it, at its own boot (plugin/loader.ts's loadPluginHost). The runtime+ * keeps a load of its own only as a shim for platforms older than that move.*/export const PLUGINS_RESOURCE_ID = "platform.plugins";diff --git a/packages/server/src/plugin/loader.ts b/packages/server/src/plugin/loader.tsindex 3791abf2..ef8a73f0 100644--- a/packages/server/src/plugin/loader.ts+++ b/packages/server/src/plugin/loader.ts@@ -1,8 +1,15 @@/*** Plugin loading: WHICH plugins a deployment runs is CONFIGURATION, not capability- * baked into the platform. They do not ride the platform bundle and no hot push- * delivers one — `<root>/plugins.json` lists them and each entry resolves against the- * INSTALLATION, so installing or upgrading one is an install-side action.+ * baked into the platform.+ *+ * The configuration is per PROJECT (the `[plugins]` table in `.project_config.toml`), because machines+ * are lent to Projects and that is what says which machines a plugin has to reach. Loading+ * is per PROCESS, though — there is one module tree — so what a deployment runs is the+ * CLOSURE: the union over its Projects. A plugin any Project asks for is in the tree, and+ * what it contributes is visible to all of them.+ *+ * The closure is read from the FILES, without the database: this runs at boot, before the+ * platform exists, and a Project is a directory holding a `.project_config.toml`.** Resolution is anchored at `process.argv[1]`, for the same reason the packaged* bundle's own resolver is: a bundle running from `hmr/store` has no node_modules of@@ -14,7 +21,11 @@* default export, whose manifests the package's generated `ifaces.json` carries.*/import fs from "node:fs/promises";-import { createRequire } from "node:module";+import type { Dirent } from "node:fs";+import { parse as parseToml } from "smol-toml";+import { parsePluginTable, projectConfigPath } from "@prismshadow/penguin-core";+import { findPackageJSON } from "node:module";+import { existsSync, readFileSync, statSync } from "node:fs";import path from "node:path";import { pathToFileURL } from "node:url";import type {@@ -22,13 +33,21 @@ import type {ManifestTable,ModuleClass,ModuleDef,+ Resources,} from "@prismshadow/penguin-core/kernel";import { moduleDefOf, parseManifest } from "@prismshadow/penguin-core/kernel";+import { readManifest } from "../hmr/manifest.js";import type { Plugin } from "@prismshadow/penguin-core/plugin";import type { LoadedPlugin } from "./host.js";+import { PluginHost, pluginHostFrom } from "./host.js";-/** The config file's name inside the data root. */-export const PLUGINS_FILE = "plugins.json";+/**+ * Where a Project's list lives, for a surface that has to name the file. The data root's+ * old `plugins.json` is NOT read any more: the list moved into Project config, deliberately+ * without a migration (PRFC-0010), so a deployment that had one starts with no plugins+ * until each Project asks again.+ */+export const PLUGINS_FILE = ".project_config.toml";export type { LoadedPlugin } from "./host.js";@@ -37,55 +56,329 @@ export interface PluginLoadResult {/** specifier → why it was skipped. */failed: Map<string, string>;}-/**- * An ABSENT file means "no plugins" — the default deployment shape, not an error. Any- * other outcome is: a file that exists but cannot be read (a permission, a directory in- * its place, an I/O fault) is indistinguishable from a malformed one for the operator's- * purposes — something was configured and this process cannot honor it, so running- * unconfigured would misrepresent what was asked for.- */-export async function readPluginList(root: string): Promise<string[]> {+/** The Project ids of a data root: every directory holding a `.project_config.toml`. */+export async function listProjectIds(root: string): Promise<string[]> {+ let entries: Dirent[];+ try {+ entries = await fs.readdir(root, { withFileTypes: true });+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw err;+ }+ const ids: string[] = [];+ for (const entry of entries) {+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;+ try {+ await fs.access(projectConfigPath(root, entry.name));+ ids.push(entry.name);+ } catch {+ // Not a Project directory: `hmr`, `store`, whatever else lives beside them.+ }+ }+ return ids.sort();+}++/** One Project's list, in the order it wrote them; empty when it asks for none. */+export async function readProjectPluginList(root: string, projectId: string): Promise<string[]> {let text: string;try {- text = await fs.readFile(path.join(root, PLUGINS_FILE), "utf8");+ text = await fs.readFile(projectConfigPath(root, projectId), "utf8");} catch (err) {if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];- throw new Error(- `${PLUGINS_FILE} exists but could not be read: ${err instanceof Error ? err.message : String(err)}`,+ // A Project whose config cannot be read (permissions, a directory in its place) is a+ // configuration fault, but not this one's to fail the boot over: its models are just as+ // unreadable, and the deployment must still come up for every other Project. The list+ // view reports the fault on that Project (routes/plugins-installed.ts).+ console.warn(+ `[plugins] ${projectId}: .project_config.toml could not be read, its plugins are skipped: ${err instanceof Error ? err.message : String(err)}`,);+ return [];}let parsed: unknown;try {- parsed = JSON.parse(text);+ parsed = parseToml(text);} catch (err) {- throw new Error(- `${PLUGINS_FILE} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,+ // The same for one that does not parse.+ console.warn(+ `[plugins] ${projectId}: .project_config.toml is not valid TOML, its plugins are skipped: ${err instanceof Error ? err.message : String(err)}`,);+ return [];}- const list = (parsed as { plugins?: unknown }).plugins;- if (!Array.isArray(list) || list.some((entry) => typeof entry !== "string")) {- throw new Error(`${PLUGINS_FILE} must be { "plugins": ["<package specifier>", …] }`);+ return Object.keys(parsePluginTable((parsed as { plugins?: unknown }).plugins) ?? {});+}++/**+ * The closure this deployment runs: the union over its Projects, first-asked order. One+ * process, one module tree — so this is what `loadPlugins` loads, whoever asked for it.+ */+export async function readPluginClosure(root: string): Promise<string[]> {+ const out: string[] = [];+ for (const projectId of await listProjectIds(root)) {+ for (const specifier of await readProjectPluginList(root, projectId)) {+ if (!out.includes(specifier)) out.push(specifier);+ }}- return list as string[];+ return out;+}++/**+ * Where plugins are looked for, in order. Each is an npm prefix (`<dir>/package.json` ++ * `<dir>/node_modules/…`) except the installation entry, which resolves as the running+ * program does:+ *+ * 1. `<root>/plugins` — the data root's own npm prefix, for a package put there by hand+ * (nothing in the product writes it yet; a registry install would).+ * 2. `<assets>/plugins` — the BUILTIN plugins the committed hot push carried+ * (scripts/build-plugins.mjs), i.e. the plugins of the revision that is running.+ * 3. `<installation>/plugins` — the builtin plugins the build shipped (the desktop app+ * stages them beside `skills/`), for a deployment nothing was ever pushed to.+ * 4. the installation entry — a plugin installed globally beside the program.+ *+ * A prefix marked `builtin` is one the harness ships, not one the operator installed.+ */+export interface PluginBase {+ file: string;+ builtin: boolean;+ /**+ * The running program's entry rather than an npm prefix: a specifier resolves from it the+ * way the program's own imports do, `node_modules` upward. A prefix answers only for what+ * is under its OWN `node_modules` — the walk upward would otherwise find a package beside+ * the program from the builtin prefix and label it built in.+ */+ program?: true;+}++/** A bare package name, scoped or not — never a subpath, a path, a URL or a version range. */+export const PACKAGE_NAME = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;++/** Why a specifier cannot name a plugin, or null when it is a package name or a path. */+export function specifierFault(specifier: string): string | null {+ if (path.isAbsolute(specifier) || PACKAGE_NAME.test(specifier)) return null;+ return `'${specifier}' is not a package name: a plugin is named by its package, never by a subpath, a URL or a version range`;}-/** Resolved against the installation rather than the bundle's location. */-async function importPlugin(specifier: string): Promise<{ module: unknown; file: string | null }> {+/** `<root>/plugins`: the npm prefix of the data root itself. */+export function pluginsPrefix(root: string): string {+ return path.join(root, "plugins");+}++export function pluginBases(root: string | undefined, assetsDir: string | null): PluginBase[] {+ const bases: PluginBase[] = [];+ if (root !== undefined && root !== "") {+ bases.push({ file: path.join(pluginsPrefix(root), "package.json"), builtin: false });+ }+ if (assetsDir !== null) {+ bases.push({ file: path.join(assetsDir, "plugins", "package.json"), builtin: true });+ }const entry = process.argv[1];if (typeof entry === "string" && entry.length > 0) {+ bases.push({+ file: path.join(path.dirname(entry), "..", "plugins", "package.json"),+ builtin: true,+ });+ bases.push({ file: entry, builtin: false, program: true });+ }+ return bases;+}++/** The assets directory of the committed version, read from harness.json without a host. */+export async function committedAssetsDir(root: string): Promise<string | null> {+ const manifest = await readManifest(root);+ const dir = manifest?.assets?.dir;+ return typeof dir === "string" ? path.join(root, "hmr", dir) : null;+}++/**+ * The package a bare specifier names, looked up from a base the way Node looks up any+ * package (`node_modules` upward from the base): its directory, its manifest, and the base+ * that found it — or null. Nothing about the package is assumed: it is whatever npm put there.+ */+export function resolvePluginPackage(+ specifier: string,+ bases: readonly PluginBase[],+): { dir: string; manifest: string; base: PluginBase } | null {+ // A path names a file, not a package: the nearest package.json above it is the+ // package (a dev checkout's plugin, written beside its manifest). As a URL, so that a+ // Windows drive letter is not read as a URL scheme.+ const lookup = path.isAbsolute(specifier) ? pathToFileURL(specifier).href : specifier;+ for (const base of bases) {+ let manifest: string | undefined;try {- const resolved = createRequire(entry).resolve(specifier);- return { module: await import(pathToFileURL(resolved).href), file: resolved };+ manifest = findPackageJSON(lookup, base.file);} catch {- // Fall through: a dev checkout resolves the specifier directly.+ manifest = undefined;}+ if (manifest === undefined) continue;+ // findPackageJSON walks `node_modules` upward from the base; a prefix speaks only for+ // its own (see PluginBase.program).+ if (base.program !== true) {+ const own = path.join(path.dirname(base.file), "node_modules") + path.sep;+ if (!manifest.startsWith(own)) continue;+ }+ return { dir: path.dirname(manifest), manifest, base };}- return { module: await import(specifier), file: null };+ return null;+}++/**+ * The file an `import "<name>"` of the package would load: `exports["."]` — a string, or its+ * `import` / `node` / `default` condition — else `main` (with `.js` supplied when it is+ * written without one), else `index.js`. The packages are ESM and name one entry, which is+ * all this reads; anything richer is the package's own business once Node imports it.+ */+function packageEntry(dir: string, manifest: string): string | null {+ let pkg: { exports?: unknown; main?: unknown };+ try {+ pkg = JSON.parse(readFileSync(manifest, "utf8")) as typeof pkg;+ } catch {+ return null;+ }+ const condition = (value: unknown): string | null => {+ if (typeof value === "string") return value;+ if (value === null || typeof value !== "object") return null;+ const v = value as Record<string, unknown>;+ return condition(v.import) ?? condition(v.node) ?? condition(v.default) ?? null;+ };+ let rel: string | null = null;+ const exp = pkg.exports;+ if (typeof exp === "string") rel = exp;+ else if (exp !== null && typeof exp === "object") {+ const table = exp as Record<string, unknown>;+ rel = condition("." in table ? table["."] : table);+ }+ rel ??= typeof pkg.main === "string" ? pkg.main : "./index.js";+ const file = path.resolve(dir, rel);+ if (!existsSync(file) && path.extname(file) === "" && existsSync(`${file}.js`)) {+ return `${file}.js`;+ }+ return file;+}++/** Where a specifier resolves from — the entry file and the base that found it — or null. */+function resolvePlugin(+ specifier: string,+ bases: readonly PluginBase[],+): { file: string; base: PluginBase } | null {+ // A path IS the entry: what the operator named is the file to import, whatever the+ // package above it declares (the dev-checkout path).+ if (path.isAbsolute(specifier)) {+ return existsSync(specifier)+ ? { file: specifier, base: { file: specifier, builtin: false } }+ : null;+ }+ // A subpath would resolve to the PACKAGE (findPackageJSON finds its manifest) and load its+ // root entry — the wrong module, silently. Refused up front, by name.+ if (!PACKAGE_NAME.test(specifier)) return null;+ const found = resolvePluginPackage(specifier, bases);+ if (found === null) return null;+ const file = packageEntry(found.dir, found.manifest);+ return file === null ? null : { file, base: found.base };+}++/**+ * The plugins a set of bases SHIPS: every package under a builtin prefix's node_modules+ * (scoped or not) whose package.json declares `penguin`. Being shipped means installing one+ * needs no download — it does not mean it is installed. Nothing here loads; the list is what+ * marks a catalogue row as available offline and lets an install skip npm.+ */+export async function discoverBuiltinPlugins(bases: readonly PluginBase[]): Promise<string[]> {+ const names: string[] = [];+ for (const base of bases) {+ if (!base.builtin) continue;+ // The prefix's own manifest names what the build shipped; what npm installed beside+ // them (their dependencies) is not offered.+ let manifest: { dependencies?: unknown };+ try {+ manifest = JSON.parse(await fs.readFile(base.file, "utf8")) as { dependencies?: unknown };+ } catch {+ continue;+ }+ const deps = manifest.dependencies;+ if (typeof deps !== "object" || deps === null) continue;+ for (const name of Object.keys(deps)) if (!names.includes(name)) names.push(name);+ }+ return names.sort();+}++/**+ * The entry file's modification time, the part of its identity a path alone misses: a+ * package updated in place keeps its path, and Node's module cache would keep serving the+ * code it loaded first. Null when the file cannot be stat'ed (the import then says why).+ */+function entryStamp(file: string): number | null {+ try {+ return statSync(file).mtimeMs;+ } catch {+ return null;+ }+}++/**+ * Resolved against the data root and the installation, never the bundle's location. The+ * import URL carries the entry's stamp, so a file rewritten in place is evaluated again+ * rather than answered from the module cache. (Only the entry: what it imports by relative+ * path stays cached, which a bundled plugin — one file — does not notice.)+ */+async function importPlugin(+ specifier: string,+ bases: readonly PluginBase[],+): Promise<{ module: unknown; file: string | null; stamp: number | null }> {+ const resolved = resolvePlugin(specifier, bases);+ if (resolved !== null) {+ if (!existsSync(resolved.file)) {+ throw new Error(`the package's entry file does not exist: ${resolved.file}`);+ }+ const stamp = entryStamp(resolved.file);+ const url = pathToFileURL(resolved.file).href + (stamp === null ? "" : `?v=${stamp}`);+ return { module: await import(url), file: resolved.file, stamp };+ }+ return { module: await import(specifier), file: null, stamp: null };}/** The generated table a plugin package ships beside its package.json. */export const IFACES_FILE = "ifaces.json";+/** The `plugin` entry of a package's table: the names its default export lists, read statically by the generator. */+export interface PluginDeclaration {+ modules: readonly string[];+ replaces: readonly string[];+}++/**+/**+ * What a listed specifier DECLARES, read from its generated table alone — the package is never+ * imported. Lets a surface say which plugin a loaded module came from, and why a listed one is+ * not there, without the runtime having to publish its load report.+ */+export async function readPluginDeclaration(+ specifier: string,+ bases: readonly PluginBase[],+): Promise<{ modules: string[]; replaces: string[]; builtin: boolean } | { error: string }> {+ const fault = specifierFault(specifier);+ if (fault !== null) return { error: fault };+ const resolved = resolvePlugin(specifier, bases);+ if (resolved === null) {+ return {+ error: `'${specifier}' is not installed on this machine (nothing under <root>/plugins, the shipped plugins or the installation resolves it)`,+ };+ }+ if (!existsSync(resolved.file)) {+ return { error: `the package's entry file does not exist: ${resolved.file}` };+ }+ let read: Awaited<ReturnType<typeof readPackageTable>>;+ try {+ read = await readPackageTable(resolved.file);+ } catch (err) {+ return { error: err instanceof Error ? err.message : String(err) };+ }+ if (read === null) return { error: `no package.json above ${resolved.file}` };+ return {+ modules: [...read.plugin.modules],+ replaces: [...read.plugin.replaces],+ builtin: resolved.base.builtin,+ };+}+/*** The package's generated table (`ifaces.json` beside its `package.json`, the nearest one* above the resolved entry file): the manifest of every decorated class, the signature of@@ -93,9 +386,13 @@ export const IFACES_FILE = "ifaces.json";* MODULE payload, and a package without one ships no modules (`manifests` empty). Null* only when no `package.json` is above the file at all.*/-async function readPackageTable(- file: string | null,-): Promise<{ where: string; ifaces: IfaceTable; manifests: ManifestTable } | null> {+async function readPackageTable(file: string | null): Promise<{+ where: string;+ ifaces: IfaceTable;+ manifests: ManifestTable;+ /** What the default export names, as the generator read it: the modules added and the nodes stood in for. */+ plugin: PluginDeclaration;+} | null> {if (file === null) return null;let dir = path.dirname(file);for (;;) {@@ -108,17 +405,30 @@ async function readPackageTable(text = await fs.readFile(tableFile, "utf8");} catch (err) {if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;- return { where, ifaces: { ifaces: {}, types: {} }, manifests: {} };+ return {+ where,+ ifaces: { ifaces: {}, types: {} },+ manifests: {},+ plugin: { modules: [], replaces: [] },+ };}const table = JSON.parse(text) as {ifaces?: unknown;types?: unknown;modules?: unknown;+ plugin?: unknown;};const isRecord = (v: unknown) => typeof v === "object" && v !== null && !Array.isArray(v);if (!isRecord(table.ifaces) || !isRecord(table.types) || !isRecord(table.modules)) {throw new Error(`${tableFile}: expected { ifaces, types, modules } (gen-ifaces output)`);}+ const names = (v: unknown) => Array.isArray(v) && v.every((n) => typeof n === "string");+ const plugin = (table.plugin ?? {}) as { modules?: unknown; replaces?: unknown };+ if (!isRecord(plugin) || !names(plugin.modules ?? []) || !names(plugin.replaces ?? [])) {+ throw new Error(+ `${tableFile}#plugin: expected { modules: [<name>, …], replaces: [<name>, …] }`,+ );+ }const manifests: Record<string, ModuleDef["manifest"]> = {};for (const [name, doc] of Object.entries(table.modules as Record<string, unknown>)) {manifests[name] = parseManifest(doc, `${tableFile}#modules.${name}`);@@ -127,6 +437,10 @@ async function readPackageTable(where,ifaces: { ifaces: table.ifaces, types: table.types } as IfaceTable,manifests,+ plugin: {+ modules: (plugin.modules ?? []) as string[],+ replaces: (plugin.replaces ?? []) as string[],+ },};} catch (err) {if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;@@ -155,21 +469,66 @@ function asPlugin(module: unknown): Plugin | null {/*** Loads every configured plugin.*- * The two failure classes are deliberately different. A PER-ENTRY failure (unresolvable- * specifier, no table, a throw at import) is collected and skipped: that- * capability is unavailable, which a deployment can recover from. A CONFIG-level failure- * — the list itself unreadable or malformed — THROWS, because there is no honest way to- * continue: the operator configured something this process cannot even read, and booting- * with an empty plugin set would present as a healthy server that silently dropped every- * capability the config asked for.+ * Every failure is per entry, collected and skipped: an unresolvable specifier, a missing+ * table, a throw at import — that capability is unavailable, which a deployment can recover+ * from, and the reason is kept on the host for the list view. A Project whose config cannot+ * be read or parsed contributes nothing (readProjectPluginList): the deployment comes up for+ * every other Project, and that one's list view reports the fault.*/-export async function loadPlugins(root: string): Promise<PluginLoadResult> {+export async function loadPlugins(+ root: string,+ /**+ * The assets of the version being booted, or undefined to read the COMMITTED one.+ *+ * The distinction is the difference between loading this push's plugins and the previous+ * one's. A hot upgrade materializes its assets and publishes them BEFORE the new platform's+ * create() runs, but commits `harness.json` only after that boot succeeds — so a create()+ * that reads the committed pointer is reading the version it is replacing, and every push+ * would ship plugins one version stale. Seen exactly that way: a corrected plugin arrived+ * on a machine and the previous build's copy kept running until the NEXT push.+ */+ assetsDir?: string | null,+ /**+ * Entries an earlier App already imported, by specifier. Reused when the specifier still+ * resolves to the FILE that entry came from, unchanged since — the objects then keep their+ * identity across a swap, which is what the plugin host is parked for. A different file+ * (a push moves the builtin plugins to a new assets directory) or a file rewritten in+ * place (a package updated under `<root>/plugins`) means different code, and that is imported.+ */+ reuse: ReadonlyMap<string, LoadedPlugin> = new Map(),+): Promise<PluginLoadResult> {const failed = new Map<string, string>();- const specifiers = await readPluginList(root);+ const bases = pluginBases(+ root,+ assetsDir === undefined ? await committedAssetsDir(root) : assetsDir,+ );+ // The closure over this root's Projects, and nothing else. A plugin the BUILD ships is+ // available without a download — that is what `builtin` means — but availability is not+ // consent: it loads when a Project asks for it, like every other plugin.+ const specifiers = await readPluginClosure(root);const loaded: LoadedPlugin[] = [];for (const specifier of specifiers) {+ // Reused only when the SAME FILE is behind the name. A push writes the builtin plugins to+ // a new assets directory, so keeping an entry by specifier alone would run the previous+ // build's plugin code forever — the push would land everywhere except the plugins.+ const fault = specifierFault(specifier);+ if (fault !== null) {+ failed.set(specifier, fault);+ continue;+ }+ const held = reuse.get(specifier);+ const heldFile = held?.file;+ if (+ held !== undefined &&+ heldFile != null &&+ heldFile === resolvePlugin(specifier, bases)?.file &&+ held.stamp === entryStamp(heldFile)+ ) {+ loaded.push(held);+ continue;+ }try {- const { module, file } = await importPlugin(specifier);+ const { module, file, stamp } = await importPlugin(specifier, bases);const read = await readPackageTable(file);if (read === null) {failed.set(specifier, `no package.json above ${file}`);@@ -204,10 +563,54 @@ export async function loadPlugins(root: string): Promise<PluginLoadResult> {});const modules = pair(plugin.modules);const replaces = pair(plugin.replaces);- loaded.push({ specifier, modules, replaces, ifaces: read.ifaces });+ loaded.push({ specifier, file, stamp, modules, replaces, ifaces: read.ifaces });} catch (err) {failed.set(specifier, err instanceof Error ? err.message : String(err));}}return { loaded, failed };}++/**+ * The plugin host THIS App runs — built by the PLATFORM, at its own boot (hmr/platform.ts).+ *+ * This is the point of the whole file living below the seam: which plugins a deployment runs+ * is configuration, and how that configuration is read is policy. Both therefore travel by+ * push. A machine whose program predates a new rule — the Project closure replacing the data+ * root's plugins.json, say — learns it from the pushed platform, instead of being unable to+ * act on a list it has already been given until someone restarts it.+ *+ * What the registry keeps is the imported objects, claimed here and handed back at the+ * commit: state, not a capability. An entry the closure no longer asks for is simply not in+ * the new host; its modules leave the tree with the App that had them.+ */+export async function loadPluginHost(+ resources: Resources,+ root: string,+ /** The booting version's assets (hmr.assetsDir()), not the committed ones — see loadPlugins. */+ assetsDir?: string | null,+): Promise<PluginHost> {+ const inherited = pluginHostFrom(resources);+ // An older generation's host may predate `entries()`; then nothing is reused and every+ // specifier is imported again, which the ESM cache makes cheap.+ const reuse =+ typeof inherited.entries === "function" ? inherited.entries() : new Map<string, LoadedPlugin>();+ const result = await loadPlugins(root, assetsDir, reuse);+ const host = new PluginHost();+ for (const entry of result.loaded) {+ // A module name clash is a LOAD failure, isolated per entry like an import failure.+ try {+ host.use(entry);+ } catch (err) {+ result.failed.set(entry.specifier, err instanceof Error ? err.message : String(err));+ }+ }+ // The reason stays on the host, not only in the log: the installed-plugins page reads it+ // there, so a plugin that failed to load is shown with why rather than as a restart that+ // would not help.+ for (const [specifier, reason] of result.failed) {+ host.skip(specifier, reason);+ console.warn(`[plugins] skipped ${specifier}: ${reason}`);+ }+ return host;+}diff --git a/packages/server/src/plugin/registry.ts b/packages/server/src/plugin/registry.tsnew file mode 100644index 00000000..40c3abbe--- /dev/null+++ b/packages/server/src/plugin/registry.ts@@ -0,0 +1,139 @@+/**+ * Plugin registries: WHERE plugin index entries come from. A registry is one source+ * of `PluginIndexEntry` rows — the shared index format every registry speaks (see+ * api/types.ts; the schema follows typst/packages' `index.json`: a flat array of+ * per-version entries). Discovery only: a Project asks for an entry on the Plugins page+ * (http/routes/plugins-installed.ts), and nothing here imports plugin code.+ *+ * Two implementations, one contract:+ * - the builtin registry serves the index embedded in this package+ * (builtin-index.json — the four sandbox backends the workspace ships);+ * - the HTTP registry fetches an `index.json` URL and runs it through the same+ * validator, so a remote index is trusted no further than the embedded one.+ *+ * The deployment's registry list is fixed to the builtin one for now; additional+ * sources plug in as more `PluginRegistry` values.+ */+import type { PluginIndexEntry } from "../api/types.js";+import builtinIndex from "./builtin-index.json" with { type: "json" };+import fs from "node:fs/promises";+import path from "node:path";+import { resolvePluginPackage } from "./loader.js";+import type { PluginBase } from "./loader.js";++/** One source of plugin index entries; `source` identifies it for display and errors. */+export interface PluginRegistry {+ readonly source: string;+ index(): Promise<PluginIndexEntry[]>;+ /**+ * Long-form documentation for one entry, or null when this source has none for it.+ *+ * Separate from `index` because the shapes differ: the index is a listing sent in full+ * on every page load, a readme is large and wanted only for the entry someone opened.+ */+ readme(name: string): Promise<string | null>;+}++function isStringArray(value: unknown): value is string[] {+ return Array.isArray(value) && value.every((v) => typeof v === "string");+}++/** Validates one raw entry; returns null instead of throwing so the caller can name the index position. */+function asIndexEntry(value: unknown): PluginIndexEntry | null {+ if (typeof value !== "object" || value === null) return null;+ const e = value as Record<string, unknown>;+ if (+ typeof e.name !== "string" ||+ typeof e.version !== "string" ||+ typeof e.description !== "string" ||+ !isStringArray(e.authors) ||+ typeof e.license !== "string"+ ) {+ return null;+ }+ for (const key of ["repository", "homepage"] as const) {+ if (e[key] !== undefined && typeof e[key] !== "string") return null;+ }+ for (const key of ["keywords", "categories"] as const) {+ if (e[key] !== undefined && !isStringArray(e[key])) return null;+ }+ if (e.updatedAt !== undefined && typeof e.updatedAt !== "number") return null;+ return value as PluginIndexEntry;+}++/**+ * Validates a whole index document. Strict, not per-entry-tolerant: an index is one+ * publisher's single artifact, so a malformed row means the artifact is broken —+ * unlike a Project's plugin list, whose entries are independent choices skipped one+ * by one.+ */+export function parsePluginIndex(data: unknown, source: string): PluginIndexEntry[] {+ if (!Array.isArray(data)) {+ throw new Error(`plugin index from ${source} is not an array`);+ }+ return data.map((raw, i) => {+ const entry = asIndexEntry(raw);+ if (entry === null) {+ throw new Error(`plugin index from ${source} has a malformed entry at index ${i}`);+ }+ return entry;+ });+}++export const BUILTIN_REGISTRY_SOURCE = "builtin";++/**+ * The registry embedded in this package: the workspace's own plugin packages. The index is+ * the listing; a readme is the package's own README.md, read from wherever the package is on+ * this machine (`bases`: the shipped prefix, the data root's, the installation) — the file+ * npm shipped with it, never a second copy. A listed package that is not on this machine+ * has none to show.+ */+export function builtinPluginRegistry(+ bases: () => readonly PluginBase[] = () => [],+): PluginRegistry {+ return {+ source: BUILTIN_REGISTRY_SOURCE,+ // Validated like any other source: a broken embedded index should fail loudly+ // in tests rather than serve garbage.+ index: () => Promise.resolve(parsePluginIndex(builtinIndex, BUILTIN_REGISTRY_SOURCE)),+ readme: async (name) => {+ const found = resolvePluginPackage(name, bases());+ if (found === null) return null;+ try {+ return await fs.readFile(path.join(found.dir, "README.md"), "utf8");+ } catch {+ return null;+ }+ },+ };+}++/** A registry behind an `index.json` URL; `fetchImpl` is injectable for tests. */+export function httpPluginRegistry(+ indexUrl: string,+ fetchImpl: typeof fetch = fetch,+): PluginRegistry {+ return {+ source: indexUrl,+ index: async () => {+ const res = await fetchImpl(indexUrl);+ if (!res.ok) {+ throw new Error(`plugin index from ${indexUrl} answered HTTP ${res.status}`);+ }+ let data: unknown;+ try {+ data = await res.json();+ } catch (err) {+ throw new Error(+ `plugin index from ${indexUrl} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ return parsePluginIndex(data, indexUrl);+ },+ // The shared index format carries no readme location, so a remote source has none to+ // offer yet. Null rather than a guessed URL: inventing one would have the Web App+ // render whatever answered it.+ readme: () => Promise.resolve(null),+ };+}diff --git a/packages/server/src/sandbox/index.ts b/packages/server/src/sandbox/index.tsindex 6f89761f..5df56c4e 100644--- a/packages/server/src/sandbox/index.ts+++ b/packages/server/src/sandbox/index.ts@@ -14,7 +14,7 @@* (../plugin/loader.ts), which is why nothing here imports one and why the harness does* not depend on the DSH ecosystem at all:*- * sandbox service ← registered backends ← plugins.json+ * sandbox service ← registered backends ← the Projects' plugin lists** The backends shipped in this repo:*diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.tsindex ba66250f..9db1546b 100644--- a/packages/server/src/services/project-config-service.ts+++ b/packages/server/src/services/project-config-service.ts@@ -33,6 +33,8 @@ import {DEFAULT_COMMAND_POLICY_RULES,effectiveCommandPolicyRules,parseCommandPolicy,+ parsePluginTable,+ pluginTableToToml,GenerativeModel,canonicalClientType,listEndpointModels as coreListEndpointModels,@@ -48,6 +50,7 @@ import {} from "@prismshadow/penguin-core";import { providerInfo } from "@prismshadow/penguin-core/model-catalog";import type {+ PluginTable,CommandPolicyRule,GenerativeModelConfig,LLMOutcome,@@ -642,6 +645,23 @@ export class ProjectConfigService implements ProjectConfigStore {return this.getCommandPolicy(projectId);}+ /** The `[plugins]` table this Project asks for, in the file's order; empty when it asks for none. */+ async getPlugins(projectId: string): Promise<PluginTable> {+ return parsePluginTable((await this.readRaw(projectId)).plugins) ?? {};+ }++ /**+ * Replaces this Project's plugin table (a declarative PUT, validated at the route).+ * Read-modify-write like setCommandPolicy, so every other key survives. An empty table is+ * written as an empty table rather than removed: "this Project asks for none" is a+ * decision, and a reader cannot tell it from "never configured" if the key vanishes.+ */+ async setPlugins(projectId: string, plugins: PluginTable): Promise<PluginTable> {+ const raw = await this.readRaw(projectId);+ await this.writeRaw(projectId, { ...raw, plugins: pluginTableToToml(plugins) });+ return this.getPlugins(projectId);+ }+/** Pricing lookup for usage-recorder: the current pricing for this paired reference (undefined if none -> cost is NULL). */async getPricing(projectId: string,diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.tsindex ade55952..ed96e7a1 100644--- a/packages/server/test/helpers.ts+++ b/packages/server/test/helpers.ts@@ -370,6 +370,7 @@ export async function createTestApp(options: TestAppOptions = {}): Promise<TestAmessagingLineDelayMs: 0,...overrides,}),+ undefined,plugins,);// Consistent with the startup entrypoint: seed the built-in admin (owning default_project).diff --git a/packages/server/test/plugin-apply.test.ts b/packages/server/test/plugin-apply.test.tsnew file mode 100644index 00000000..81539bc3--- /dev/null+++ b/packages/server/test/plugin-apply.test.ts@@ -0,0 +1,147 @@+/**+ * Loading the plugin host, after the loading moved below the seam.+ *+ * The host every surface reads from must always describe the tree that is actually running.+ * The platform's own create() reads the closure and imports it, and only a create() that+ * succeeded writes the registry; applying a change is the App re-assembling itself+ * (hmr/platform.ts), which plugins-installed.test.ts drives end to end. What these tests pin+ * is the load: what is reused, what is dropped, which assets are read, and what a failure does.+ */+import { describe, expect, it } from "vitest";+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { HotResources } from "@prismshadow/penguin-hmr";+import { PLUGINS_RESOURCE_ID, PluginHost, pluginHostFrom } from "../src/plugin/host.js";+import { writeClassPackage } from "./plugin-fixtures.js";+import { loadPluginHost } from "../src/plugin/loader.js";+import type { LoadedPlugin } from "../src/plugin/host.js";++/** A data root whose one Project asks for these specifiers. */+async function rootAsking(specifiers: string[]): Promise<string> {+ const root = await mkdtemp(path.join(tmpdir(), "penguin-apply-"));+ await mkdir(path.join(root, "p1"), { recursive: true });+ await writeFile(+ path.join(root, "p1", ".project_config.toml"),+ `models = []\n[plugins]\n${specifiers.map((s) => `${JSON.stringify(s)} = "*"`).join("\n")}\n`,+ "utf8",+ );+ return root;+}++/** An entry as an earlier App would have left it: one module, already imported. */+const entry = (specifier: string, name: string, file?: string): LoadedPlugin => ({+ specifier,+ ...(file === undefined ? {} : { file }),+ modules: [+ {+ manifest: { name, requires: {}, provides: {}, contributes: {}, children: [] },+ create: () => ({ api: {} }),+ },+ ],+ replaces: [],+});++describe("loadPluginHost", () => {+ it("keeps what the closure still asks for, by identity, and drops the rest", async () => {+ const root = await rootAsking(["@acme/kept"]);+ try {+ const resources = new HotResources();+ const inherited = new PluginHost();+ // Held from a file that no longer resolves (nothing installs @acme/kept here): the+ // held file and the resolved one are both absent-or-different, so this is the case+ // where an entry is NOT reused. Kept for the drop half of the assertion.+ const kept = entry("@acme/kept", "Kept");+ inherited.use(kept);+ inherited.use(entry("@acme/dropped", "Dropped"));+ resources.register(PLUGINS_RESOURCE_ID, inherited);++ const host = await loadPluginHost(resources, root);++ // A plugin the closure no longer names is simply not in the new host.+ expect([...host.entries().keys()]).toEqual([]);+ // Registering is the caller's, at its commit: a create() that throws must leave the+ // previous App's host in place.+ expect(pluginHostFrom(resources)).toBe(inherited);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it("reuses an entry only while the same file is behind the name", async () => {+ // The push this rule exists for: a hot update writes the builtin plugins to a NEW assets+ // directory, so an entry held by specifier alone would keep running the previous build's+ // plugin code — the push would land everywhere except the plugins. Seen for real: a fixed+ // claude-code plugin shipped to a machine and the old one kept spawning.+ const root = await rootAsking(["@acme/real"]);+ try {+ const dir = path.join(root, "plugins", "node_modules", "@acme", "real");+ await writeClassPackage(dir, { name: "@acme/real", module: "AcmeReal" });++ const resources = new HotResources();+ const first = await loadPluginHost(resources, root);+ const held = first.entries().get("@acme/real");+ expect(held?.file).toBe(path.join(dir, "index.js"));++ // Same file behind the name: the same object, not a second import.+ resources.register(PLUGINS_RESOURCE_ID, first);+ const again = await loadPluginHost(resources, root);+ expect(again.entries().get("@acme/real")).toBe(held);++ // A different file behind it — what a push produces — is imported again.+ const moved = new PluginHost();+ moved.use({ ...held!, file: path.join(root, "old-assets", "index.js") });+ resources.register(PLUGINS_RESOURCE_ID, moved);+ const afterPush = await loadPluginHost(resources, root);+ expect(afterPush.entries().get("@acme/real")).not.toBe(held);+ expect(afterPush.entries().get("@acme/real")?.file).toBe(path.join(dir, "index.js"));+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it("loads the assets it is BOOTING with, not the ones already committed", async () => {+ // A hot upgrade materializes the new assets and publishes them before create() runs, but+ // commits harness.json only after that boot succeeds. A loader reading the committed+ // pointer therefore reads the version it is replacing — and every push would ship plugins+ // one version stale. Seen exactly that way on a machine: a corrected plugin arrived and+ // the previous build's copy kept running until the next push.+ const root = await rootAsking(["@acme/shipped"]);+ try {+ const build = async (dir: string, marker: string) => {+ const pkg = path.join(dir, "plugins", "node_modules", "@acme", "shipped");+ await writeClassPackage(pkg, { name: "@acme/shipped", module: marker });+ };+ const committed = path.join(root, "hmr", "store", "assets", "old");+ const booting = path.join(root, "hmr", "store", "assets", "new");+ await build(committed, "Old");+ await build(booting, "New");+ await mkdir(path.join(root, "hmr"), { recursive: true });+ await writeFile(+ path.join(root, "hmr", "harness.json"),+ JSON.stringify({ assets: { dir: "store/assets/old" } }),+ );++ // What harness.json names, when nobody says otherwise.+ const committedHost = await loadPluginHost(new HotResources(), root);+ expect(committedHost.modules().map((m) => m.manifest.name)).toEqual(["Old"]);++ // What the booting version carries, when the host says which assets those are.+ const bootingHost = await loadPluginHost(new HotResources(), root, booting);+ expect(bootingHost.modules().map((m) => m.manifest.name)).toEqual(["New"]);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it("skips a specifier it cannot import instead of failing the boot", async () => {+ const root = await rootAsking(["@acme/not-installed"]);+ try {+ const resources = new HotResources();+ const host = await loadPluginHost(resources, root);+ expect([...host.entries().keys()]).toEqual([]);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });+});diff --git a/packages/server/test/plugin-fixtures.ts b/packages/server/test/plugin-fixtures.tsnew file mode 100644index 00000000..e9462e95--- /dev/null+++ b/packages/server/test/plugin-fixtures.ts@@ -0,0 +1,79 @@+/**+ * Plugin packages on disk, in the shape a built plugin has: a `package.json`, the+ * generated `ifaces.json` beside it (the module payload), and an entry whose default export+ * names the module classes. Plugin source is written the way a plugin author writes it+ * and lowered the way its build would lower it, so the fixture exercises the same+ * decorators the host reads.+ */+import { mkdir, writeFile } from "node:fs/promises";+import path from "node:path";+import ts from "typescript";++/**+ * The decorators, as a plugin's bundle would carry them — here imported from this+ * checkout's built SDK by file URL, since a package under a temp dir resolves nothing.+ */+export const decorators = new URL("../../core/dist/plugin/index.js", import.meta.url).href;++/** Plugin source as a plugin author writes it, lowered the way its build would lower it. */+export function lower(source: string): string {+ return ts.transpileModule(source, {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },+ }).outputText;+}++export interface ClassPackage {+ name: string;+ /** The one module class the package exports (a `@Module()` with nothing to require or provide). */+ module: string;+ /** package.json `main`; default `./index.js`. */+ main?: string;+ /** package.json `exports`, when the package declares them. */+ exports?: unknown;+ /** The entry's source, when it is not the default class (a package that throws on import, say). */+ index?: string;+}++/** Writes one plugin package into `dir` and returns its entry file. */+export async function writeClassPackage(dir: string, pkg: ClassPackage): Promise<string> {+ const main = pkg.main ?? "./index.js";+ const entry = path.join(dir, main);+ await mkdir(path.dirname(entry), { recursive: true });+ await writeFile(+ path.join(dir, "package.json"),+ JSON.stringify({+ name: pkg.name,+ type: "module",+ main,+ ...(pkg.exports !== undefined ? { exports: pkg.exports } : {}),+ }),+ "utf8",+ );+ await writeFile(+ path.join(dir, "ifaces.json"),+ JSON.stringify({+ ifaces: {},+ types: {},+ modules: {+ [pkg.module]: {+ name: pkg.module,+ requires: {},+ provides: {},+ contributes: {},+ children: [],+ },+ },+ plugin: { modules: [pkg.module], replaces: [] },+ }),+ "utf8",+ );+ await writeFile(+ entry,+ pkg.index ??+ lower(`import { Module } from ${JSON.stringify(decorators)};+ @Module() export class ${pkg.module} {}+ export default { modules: [${pkg.module}] };`),+ "utf8",+ );+ return entry;+}diff --git a/packages/server/test/plugin-loader.test.ts b/packages/server/test/plugin-loader.test.tsindex e576bd98..4984f90f 100644--- a/packages/server/test/plugin-loader.test.ts+++ b/packages/server/test/plugin-loader.test.ts@@ -4,12 +4,23 @@* non-fatal — the capability a plugin would have provided stays unavailable rather* than the boot failing.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { mkdtemp, rm, writeFile, mkdir } from "node:fs/promises";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdtemp, readFile, rm, writeFile, mkdir } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import ts from "typescript";-import { IFACES_FILE, PLUGINS_FILE, loadPlugins, readPluginList } from "../src/plugin/loader.js";+import {+ IFACES_FILE,+ PLUGINS_FILE,+ committedAssetsDir,+ discoverBuiltinPlugins,+ loadPlugins,+ pluginBases,+ readPluginClosure,+ readProjectPluginList,+ listProjectIds,+} from "../src/plugin/loader.js";+import { writeClassPackage } from "./plugin-fixtures.js";let root: string;@@ -20,8 +31,16 @@ afterEach(async () => {await rm(root, { recursive: true, force: true });});-async function writeConfig(value: unknown): Promise<void> {- await writeFile(path.join(root, PLUGINS_FILE), JSON.stringify(value), "utf8");+/** A Project asking for these plugins: its `[plugins]` table is what the closure is read from. */+async function writeConfig(value: { plugins?: string[] }, projectId = "p1"): Promise<void> {+ const rows = (value.plugins ?? []).map((s) => `${JSON.stringify(s)} = "*"`);+ await writeProject(projectId, `models = []\n[plugins]\n${rows.join("\n")}\n`);+}++/** Raw config text, for the malformed cases. */+async function writeProject(projectId: string, text: string): Promise<void> {+ await mkdir(path.join(root, projectId), { recursive: true });+ await writeFile(path.join(root, projectId, PLUGINS_FILE), text, "utf8");}/** A plugin module on disk, imported by absolute specifier (the dev-checkout path). */@@ -33,53 +52,88 @@ async function writePluginModule(name: string, body: string): Promise<string> {return file;}+/**+ * The decorators, as a plugin's bundle would carry them — here imported from this+ * checkout's built SDK by file URL, since a package under a temp dir resolves nothing.+ */+const decorators = new URL("../../core/dist/plugin/index.js", import.meta.url).href;++/** Plugin source as a plugin author writes it, lowered the way its build would lower it. */+function lower(source: string): string {+ return ts.transpileModule(source, {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },+ }).outputText;+}+describe("plugin list", () => {- it("no config file means no plugins — the default deployment shape, not an error", async () => {- expect(await readPluginList(root)).toEqual([]);+ it("no Project means no plugins — the default deployment shape, not an error", async () => {+ expect(await readPluginClosure(root)).toEqual([]);expect(await loadPlugins(root)).toEqual({ loaded: [], failed: new Map() });});it("reads the configured specifiers in order", async () => {await writeConfig({ plugins: ["a", "b"] });- expect(await readPluginList(root)).toEqual(["a", "b"]);+ expect(await readProjectPluginList(root, "p1")).toEqual(["a", "b"]);+ expect(await readPluginClosure(root)).toEqual(["a", "b"]);});- it("a malformed config fails the load rather than presenting as empty", async () => {- await writeFile(path.join(root, PLUGINS_FILE), "{not json", "utf8");- await expect(readPluginList(root)).rejects.toThrow(/not valid JSON/);- // A CONFIG-level failure propagates: booting with an empty plugin set would present- // as healthy while silently dropping every capability the config asked for.- await expect(loadPlugins(root)).rejects.toThrow(/not valid JSON/);+ it("the closure is the union over Projects, each specifier once", async () => {+ // Loading is per process — one module tree — so what a deployment runs is what any of+ // its Projects asked for, and a plugin two Projects both want is still one entry.+ await writeConfig({ plugins: ["a", "shared"] }, "p1");+ await writeConfig({ plugins: ["shared", "b"] }, "p2");+ expect(await listProjectIds(root)).toEqual(["p1", "p2"]);+ expect(await readPluginClosure(root)).toEqual(["a", "shared", "b"]);});- it("a config that exists but cannot be read is an error, not 'no plugins'", async () => {+ it("a directory that is not a Project is not read as one", async () => {+ await mkdir(path.join(root, "hmr"), { recursive: true });+ await writeConfig({ plugins: ["a"] }, "p1");+ expect(await listProjectIds(root)).toEqual(["p1"]);+ });++ it("a Project whose config will not parse is skipped, not fatal for the rest", async () => {+ // Its models are just as unreadable; the deployment still has to come up for everyone else.+ await writeProject("broken", "[plugins]\nx = [oops\n");+ await writeConfig({ plugins: ["a"] }, "p1");+ expect(await readProjectPluginList(root, "broken")).toEqual([]);+ expect(await readPluginClosure(root)).toEqual(["a"]);+ });++ it("a config that exists but cannot be read is skipped like one that will not parse", async () => {// A directory in its place stands in for every non-ENOENT read failure (EACCES,- // EPERM, EISDIR, an I/O fault): something was configured and cannot be honored.- await mkdir(path.join(root, PLUGINS_FILE));- await expect(readPluginList(root)).rejects.toThrow(/exists but could not be read/);- await expect(loadPlugins(root)).rejects.toThrow(/exists but could not be read/);+ // EPERM, EISDIR, an I/O fault). It is that Project's fault to report (its list view+ // does), not a reason to keep every other Project's deployment from coming up.+ await writeProject("p2", 'models = []\n[plugins]\n"@acme/two" = "*"\n');+ await mkdir(path.join(root, "p1", PLUGINS_FILE), { recursive: true });+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ try {+ await expect(readProjectPluginList(root, "p1")).resolves.toEqual([]);+ expect(await readPluginClosure(root)).toEqual(["@acme/two"]);+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(/p1: .*could not be read/));+ } finally {+ warn.mockRestore();+ }+ });++ it("entries that are not requirements are dropped, not fatal", async () => {+ // Leniency on purpose: a typo in this table must not take the Project's models with it.+ await writeProject(+ "p1",+ 'models = []\n[plugins]\nok = "*"\npinned = "1.2.3"\ntabled = { version = "2" }\nbad = 7\nworse = { version = 3 }\n',+ );+ expect(await readProjectPluginList(root, "p1")).toEqual(["ok", "pinned", "tabled"]);});- it("a config with the wrong shape names the shape it wanted", async () => {- await writeConfig({ plugins: [1, 2] });- await expect(readPluginList(root)).rejects.toThrow(/package specifier/);+ it("the list form this key once had is not read: such a Project asks for none", async () => {+ // Deliberately no compatibility (PRFC-0010): a table replaced the list before release,+ // and a file still carrying the list starts with no plugins until it is written again.+ await writeProject("p1", 'plugins = ["@acme/old"]\nmodels = []\n');+ expect(await readProjectPluginList(root, "p1")).toEqual([]);});});describe("plugin loading", () => {- /**- * The decorators, as a plugin's bundle would carry them — here imported from this- * checkout's built SDK by file URL, since a package under a temp dir resolves nothing.- */- const decorators = new URL("../../core/dist/plugin/index.js", import.meta.url).href;-- /** Plugin source as a plugin author writes it, lowered the way its build would lower it. */- function lower(source: string): string {- return ts.transpileModule(source, {- compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },- }).outputText;- }-/** The table the plugin's build would generate: one component, contributing one provider. */const oneModule = {ifaces: {@@ -252,3 +306,120 @@ describe("plugin loading", () => {expect(result.failed.get(file)).toMatch(/ifaces\.json#modules\.Thing/);});});++describe("builtin plugins", () => {+ /** A plugin package under a prefix's node_modules, the shape scripts/build-plugins.mjs ships. */+ async function writeBuiltin(prefix: string, name: string, moduleName: string): Promise<void> {+ const dir = path.join(prefix, "node_modules", ...name.split("/"));+ await mkdir(dir, { recursive: true });+ // The prefix manifest names what was shipped, the way build-plugins writes it.+ const manifestFile = path.join(prefix, "package.json");+ const manifest = JSON.parse(+ await readFile(manifestFile, "utf8").catch(() => '{"name":"prefix","private":true}'),+ ) as { dependencies?: Record<string, string> };+ manifest.dependencies = { ...manifest.dependencies, [name]: "0.0.0" };+ await writeFile(manifestFile, JSON.stringify(manifest), "utf8");+ await writeFile(+ path.join(dir, "package.json"),+ JSON.stringify({ name, main: "./index.js", type: "module" }),+ "utf8",+ );+ await writeFile(+ path.join(dir, IFACES_FILE),+ JSON.stringify({+ ifaces: {},+ types: {},+ modules: {+ [moduleName]: {+ name: moduleName,+ requires: {},+ provides: {},+ contributes: {},+ children: [],+ },+ },+ plugin: { modules: [moduleName], replaces: [] },+ }),+ "utf8",+ );+ await writeFile(+ path.join(dir, "index.js"),+ lower(`import { Module } from ${JSON.stringify(decorators)};+ @Module() export class ${moduleName} {}+ export default { modules: [${moduleName}] };`),+ "utf8",+ );+ }++ it("lists what the build ships, scoped and unscoped, and not what the root's own prefix holds", async () => {+ const assets = path.join(root, "hmr", "store", "assets", "abc");+ await writeBuiltin(path.join(assets, "plugins"), "@acme/penguin-plugin-one", "One");+ await writeBuiltin(path.join(assets, "plugins"), "plain-plugin", "Plain");+ // The operator's own prefix is not builtin: what it holds loads only when listed.+ await writeBuiltin(path.join(root, "plugins"), "@acme/installed", "Installed");+ const bases = pluginBases(root, assets);+ expect(bases[0]).toMatchObject({ builtin: false });+ expect(bases[1]).toMatchObject({ builtin: true });+ expect(await discoverBuiltinPlugins(bases)).toEqual([+ "@acme/penguin-plugin-one",+ "plain-plugin",+ ]);+ });++ it("does not load a shipped plugin until it is listed, and then loads it from the shipped prefix", async () => {+ const assetsRel = path.join("store", "assets", "abc");+ const assets = path.join(root, "hmr", assetsRel);+ await writeBuiltin(path.join(assets, "plugins"), "@acme/penguin-plugin-one", "One");+ await mkdir(path.join(root, "hmr"), { recursive: true });+ // harness.json is what names the committed assets; the loader reads it without a host.+ await writeFile(+ path.join(root, "hmr", "harness.json"),+ JSON.stringify({ assets: { dir: assetsRel.split(path.sep).join("/") } }),+ "utf8",+ );+ // Shipped, and nothing lists it: available is not installed.+ await writeConfig({ plugins: [] });+ expect((await loadPlugins(root)).loaded).toEqual([]);++ // Listed: it loads, resolved from the assets the push carried — no npm, nothing under+ // <root>/plugins.+ await writeConfig({ plugins: ["@acme/penguin-plugin-one"] });+ const result = await loadPlugins(root);+ expect([...result.failed.entries()]).toEqual([]);+ expect(result.loaded.map((p) => p.specifier)).toEqual(["@acme/penguin-plugin-one"]);+ expect(result.loaded[0]!.modules.map((m) => m.manifest.name)).toEqual(["One"]);+ });++ it("resolves a package through its exports' import condition, as npm shipped it", async () => {+ // The sandbox backends declare `exports: { ".": { types, import: "./dist/index.js" } }`+ // and no `require` condition; the loader reads the entry an importer would, not what+ // require.resolve would (it has none).+ const assets = path.join(root, "hmr", "store", "assets", "abc");+ const dir = path.join(assets, "plugins", "node_modules", "@acme", "exported");+ await mkdir(path.join(assets, "plugins"), { recursive: true });+ await writeFile(+ path.join(assets, "plugins", "package.json"),+ '{"name":"prefix","private":true}',+ );+ await writeClassPackage(dir, {+ name: "@acme/exported",+ module: "Exported",+ main: "./dist/index.js",+ exports: { ".": { types: "./dist/index.d.ts", import: "./dist/index.js" } },+ });+ await writeConfig({ plugins: ["@acme/exported"] });+ const result = await loadPlugins(root, assets);+ expect([...result.failed.entries()]).toEqual([]);+ expect(result.loaded[0]!.file).toBe(path.join(dir, "dist", "index.js"));+ });++ it("reads a committed assets dir from harness.json, or null without one", async () => {+ expect(await committedAssetsDir(root)).toBeNull();+ await mkdir(path.join(root, "hmr"), { recursive: true });+ await writeFile(+ path.join(root, "hmr", "harness.json"),+ JSON.stringify({ assets: { dir: "store/assets/x" } }),+ );+ expect(await committedAssetsDir(root)).toBe(path.join(root, "hmr", "store/assets/x"));+ });+});diff --git a/packages/server/test/plugin-registry.test.ts b/packages/server/test/plugin-registry.test.tsnew file mode 100644index 00000000..bef5c931--- /dev/null+++ b/packages/server/test/plugin-registry.test.ts@@ -0,0 +1,302 @@+/**+ * Plugin registry tests: the shared index format (strict whole-document validation —+ * one malformed row fails the artifact, unlike a plugin list's per-entry tolerance),+ * the builtin registry serving the embedded four sandbox backends (readmes read from the+ * packages as npm shipped them), the HTTP registry+ * running a fetched document through the same validator (fetch stubbed, no network),+ * and GET /api/plugins behind the auth gate.+ */+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { PluginIndexEntry, PluginIndexResponse } from "../src/api/types.js";+import type { PluginBase } from "../src/plugin/loader.js";+import {+ BUILTIN_REGISTRY_SOURCE,+ builtinPluginRegistry,+ httpPluginRegistry,+ parsePluginIndex,+} from "../src/plugin/registry.js";+import { apiClient, createTestApp, loginAdmin } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const VALID_ENTRY: PluginIndexEntry = {+ name: "@example/penguin-plugin-demo",+ version: "1.0.0",+ description: "A demo plugin.",+ authors: ["Example"],+ license: "MIT",+};++describe("parsePluginIndex", () => {+ it("accepts a flat array of per-version entries and preserves order", () => {+ const doc = [+ VALID_ENTRY,+ { ...VALID_ENTRY, version: "1.1.0", keywords: ["linux"], updatedAt: 1755600000 },+ ];+ const parsed = parsePluginIndex(doc, "test");+ expect(parsed.map((e) => e.version)).toEqual(["1.0.0", "1.1.0"]);+ });++ it("rejects a non-array document and names the source", () => {+ expect(() => parsePluginIndex({ plugins: [] }, "https://x.example/index.json")).toThrow(+ /https:\/\/x\.example\/index\.json is not an array/,+ );+ });++ it("rejects the whole document on one malformed entry, naming its position", () => {+ for (const bad of [+ null,+ { ...VALID_ENTRY, version: 2 },+ { ...VALID_ENTRY, authors: "Example" },+ { ...VALID_ENTRY, keywords: [1] },+ { ...VALID_ENTRY, updatedAt: "yesterday" },+ ]) {+ expect(() => parsePluginIndex([VALID_ENTRY, bad], "test")).toThrow(+ /malformed entry at index 1/,+ );+ }+ });+});++describe("builtinPluginRegistry", () => {+ it("serves the four sandbox backends, valid under the shared format", async () => {+ const registry = builtinPluginRegistry();+ expect(registry.source).toBe(BUILTIN_REGISTRY_SOURCE);+ const entries = await registry.index();+ expect(entries.map((e) => e.name)).toEqual([+ "@prismshadow/penguin-plugin-sandbox-bwrap",+ "@prismshadow/penguin-plugin-sandbox-seatbelt",+ "@prismshadow/penguin-plugin-sandbox-mxc",+ "@prismshadow/penguin-plugin-sandbox-dsh",+ ]);+ for (const entry of entries) {+ expect(entry.categories).toEqual(["sandbox"]);+ expect(entry.license).toBe("Apache-2.0");+ }+ });+});++describe("httpPluginRegistry", () => {+ const url = "https://registry.example/index.json";++ it("fetches the index URL and validates the document with the shared parser", async () => {+ const seen: string[] = [];+ const fetchImpl: typeof fetch = async (input) => {+ seen.push(String(input));+ return new Response(JSON.stringify([VALID_ENTRY]), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ };+ const entries = await httpPluginRegistry(url, fetchImpl).index();+ expect(seen).toEqual([url]);+ expect(entries).toEqual([VALID_ENTRY]);+ });++ it("fails on an HTTP error status, on non-JSON, and on a malformed document", async () => {+ const respond =+ (body: string, status = 200) =>+ async () =>+ new Response(body, { status });+ await expect(httpPluginRegistry(url, respond("[]", 503)).index()).rejects.toThrow(/HTTP 503/);+ await expect(httpPluginRegistry(url, respond("not json")).index()).rejects.toThrow(+ /not valid JSON/,+ );+ await expect(httpPluginRegistry(url, respond('{"plugins":[]}')).index()).rejects.toThrow(+ /not an array/,+ );+ });+});++describe("GET /api/plugins/registry", () => {+ let t: TestApp;+ beforeEach(async () => {+ t = await createTestApp();+ });+ afterEach(async () => {+ await t.cleanup();+ });++ it("requires auth, then serves the builtin index", async () => {+ expect((await t.app.request("/api/plugins/registry")).status).toBe(401);++ const admin = await loginAdmin(t.app);+ const res = await apiClient(t.app, admin.cookie).get("/api/plugins/registry");+ expect(res.status).toBe(200);+ const body = (await res.json()) as PluginIndexResponse;+ expect(body.plugins).toHaveLength(4);+ expect(body.plugins.every((p) => p.name.startsWith("@prismshadow/penguin-plugin-"))).toBe(true);+ });+});++/**+ * The index asserts a name, version, description and license for four packages that live+ * beside it in this workspace, and their readmes are those packages' own README.md files.+ * None of that is enforced by anything the packages do, so it is asserted here: the listing+ * is the specifier a Project's list names, and a catalogue that describes+ * its entries wrongly is worse than one that omits them.+ */+const PLUGINS_DIR = fileURLToPath(new URL("../../../plugins/", import.meta.url));++interface PackageManifest {+ name: string;+ version: string;+ description?: string;+ license?: string;+ files?: string[];+}++const packages = new Map<string, { dir: string; manifest: PackageManifest }>();+for (const dir of readdirSync(PLUGINS_DIR)) {+ // A worktree can hold a directory a build left behind; only a real package counts.+ if (!existsSync(`${PLUGINS_DIR}${dir}/package.json`)) continue;+ const manifest = JSON.parse(+ readFileSync(`${PLUGINS_DIR}${dir}/package.json`, "utf8"),+ ) as PackageManifest;+ packages.set(manifest.name, { dir, manifest });+}++/**+ * The packages as npm ships them, staged as a prefix a registry can read from: each listed+ * package's own package.json and README.md under `node_modules/<name>/` — what+ * scripts/build-plugins.mjs installs, minus the code, which a readme lookup never touches.+ */+async function shippedPrefix(+ names: Iterable<string>,+): Promise<{ dir: string; bases: PluginBase[] }> {+ const dir = await mkdtemp(path.join(tmpdir(), "penguin-shipped-"));+ await writeFile(+ path.join(dir, "package.json"),+ '{"name":"penguin-builtin-plugins","private":true}',+ );+ for (const name of names) {+ const pkg = packages.get(name);+ if (pkg === undefined) continue;+ const dest = path.join(dir, "node_modules", ...name.split("/"));+ await mkdir(dest, { recursive: true });+ for (const file of ["package.json", "README.md"]) {+ await cp(path.join(PLUGINS_DIR, pkg.dir, file), path.join(dest, file));+ }+ }+ return { dir, bases: [{ file: path.join(dir, "package.json"), builtin: true }] };+}++describe("plugin readmes", () => {+ /**+ * The detail page's whole content. A listed entry with no readme renders an empty page,+ * which is a gap nobody sees until they click it — so the pairing is pinned here rather+ * than left to whoever adds the next backend.+ */+ it("every builtin entry has one, read from the package on this machine", async () => {+ const index = await builtinPluginRegistry().index();+ const shipped = await shippedPrefix(index.map((e) => e.name));+ try {+ const registry = builtinPluginRegistry(() => shipped.bases);+ for (const entry of index) {+ const readme = await registry.readme(entry.name);+ expect(readme, `${entry.name} has no readme`).not.toBeNull();+ expect(readme).toContain("#");+ }+ } finally {+ await rm(shipped.dir, { recursive: true, force: true });+ }+ });++ it("a listed package that is not on this machine has none, rather than an invented one", async () => {+ const [first] = await builtinPluginRegistry().index();+ expect(await builtinPluginRegistry().readme(first!.name)).toBeNull();+ expect(await builtinPluginRegistry().readme("@someone/not-listed")).toBeNull();+ });++ /**+ * A remote index cannot describe where its readmes live yet, so the HTTP registry+ * answers null instead of guessing a URL and rendering whatever replied.+ */+ it("a remote registry offers none", async () => {+ expect(await httpPluginRegistry("https://example.invalid/index.json").readme("x")).toBeNull();+ });+});++describe("the builtin catalogue and the packages it lists", () => {+ it("names each package as that package names itself", async () => {+ for (const entry of await builtinPluginRegistry().index()) {+ const pkg = packages.get(entry.name);+ expect(pkg, `${entry.name} is listed but is no package in plugins/`).toBeDefined();+ expect(pkg!.manifest.version, entry.name).toBe(entry.version);+ expect(pkg!.manifest.description, entry.name).toBe(entry.description);+ expect(pkg!.manifest.license, entry.name).toBe(entry.license);+ }+ });++ it("serves each package's own README.md, which the package ships", async () => {+ const index = await builtinPluginRegistry().index();+ const shipped = await shippedPrefix(index.map((e) => e.name));+ try {+ const registry = builtinPluginRegistry(() => shipped.bases);+ for (const entry of index) {+ const pkg = packages.get(entry.name)!;+ const own = readFileSync(`${PLUGINS_DIR}${pkg.dir}/README.md`, "utf8");+ expect(await registry.readme(entry.name), entry.name).toBe(own);+ expect(pkg.manifest.files, `${entry.name} would publish without its readme`).toContain(+ "README.md",+ );+ }+ } finally {+ await rm(shipped.dir, { recursive: true, force: true });+ }+ });+});++describe("GET /api/plugins/registry/readme", () => {+ let t: TestApp;+ beforeEach(async () => {+ t = await createTestApp();+ });+ afterEach(async () => {+ await t.cleanup();+ });++ it("requires auth, then serves a listed entry's readme from the package on this machine", async () => {+ const name = "@prismshadow/penguin-plugin-sandbox-bwrap";+ const url = `/api/plugins/registry/readme?name=${encodeURIComponent(name)}`;+ expect((await t.app.request(url)).status).toBe(401);++ // The package as npm installs it into the data root's own prefix — the first base the+ // lookup tries, ahead of the installation's (which, in a checkout, is the workspace).+ const admin = await loginAdmin(t.app);+ const pkg = packages.get(name)!;+ const dest = path.join(t.root, "plugins", "node_modules", ...name.split("/"));+ await mkdir(dest, { recursive: true });+ await writeFile(+ path.join(t.root, "plugins", "package.json"),+ '{"name":"prefix","private":true}',+ );+ for (const file of ["package.json", "README.md"]) {+ await cp(path.join(PLUGINS_DIR, pkg.dir, file), path.join(dest, file));+ }+ const res = await apiClient(t.app, admin.cookie).get(url);+ expect(res.status).toBe(200);+ const body = (await res.json()) as { name: string; readme: string | null };+ expect(body.name).toBe(name);+ expect(body.readme).toContain("Bubblewrap");+ });++ it("refuses a name the deployment does not list, so it cannot probe for what exists", async () => {+ const admin = await loginAdmin(t.app);+ const res = await apiClient(t.app, admin.cookie).get(+ "/api/plugins/registry/readme?name=" + encodeURIComponent("@someone/not-listed"),+ );+ expect(res.status).toBe(404);+ });++ it("requires the name", async () => {+ const admin = await loginAdmin(t.app);+ expect((await apiClient(t.app, admin.cookie).get("/api/plugins/registry/readme")).status).toBe(+ 400,+ );+ });+});diff --git a/packages/server/test/plugins-installed.test.ts b/packages/server/test/plugins-installed.test.tsnew file mode 100644index 00000000..74ead7d6--- /dev/null+++ b/packages/server/test/plugins-installed.test.ts@@ -0,0 +1,238 @@+/**+ * The installed-plugins surface: what a PROJECT asks for, which of those the process is+ * actually running, and that writing the list is an admin operation which does not pretend to+ * load anything (plugins load once per process, in the runtime).+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import fs from "node:fs/promises";+import path from "node:path";+import type { InstalledPluginsResponse } from "../src/api/types.js";+import { decorators, lower, writeClassPackage } from "./plugin-fixtures.js";+import type { ClassPackage } from "./plugin-fixtures.js";+import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++describe("installed plugins", () => {+ let t: TestApp;+ let admin: ReturnType<typeof apiClient>;+ const programEntry = process.argv[1];++ const listFile = () => path.join(t.root, "default_project", ".project_config.toml");++ /**+ * Ships a package the way the build does: under the installation's `plugins/` prefix,+ * named in that prefix's manifest. The installation is what `process.argv[1]` points+ * into (plugin/loader.ts pluginBases), so the test app's program entry is pointed at a+ * directory of the temp root for the file's duration.+ */+ const ship = async (pkg: ClassPackage) => {+ const prefix = path.join(t.root, "install", "plugins");+ process.argv[1] = path.join(t.root, "install", "bin", "server.js");+ const manifestFile = path.join(prefix, "package.json");+ const manifest = JSON.parse(+ await fs.readFile(manifestFile, "utf8").catch(() => '{"name":"prefix","private":true}'),+ ) as { dependencies?: Record<string, string> };+ manifest.dependencies = { ...manifest.dependencies, [pkg.name]: "0.0.0" };+ await fs.mkdir(prefix, { recursive: true });+ await fs.writeFile(manifestFile, JSON.stringify(manifest));+ await writeClassPackage(path.join(prefix, "node_modules", ...pkg.name.split("/")), pkg);+ };++ beforeEach(async () => {+ t = await createTestApp();+ admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);+ });++ afterEach(async () => {+ if (programEntry !== undefined) process.argv[1] = programEntry;+ await t.cleanup();+ });++ const view = async () =>+ (await (+ await admin.get("/api/projects/default_project/plugins/installed")+ ).json()) as InstalledPluginsResponse;++ it("reports an empty list when nothing is installed", async () => {+ const res = await view();+ expect(res.plugins).toEqual([]);+ expect(res.file).toBe(".project_config.toml");+ expect(res.restartPending).toBe(false);+ });++ it("a plugin the build ships is offered, not installed", async () => {+ // The shipped set is a tag for the catalogue: nothing appears as installed, and nothing+ // loads, until a Project names it. (A test app ships none, so the set is empty; the+ // load-time half of this is plugin-loader.test.ts.)+ const res = await view();+ expect(res.shipped).toEqual([]);+ expect(res.plugins).toEqual([]);+ });++ it("says a listed plugin is not active, and why when it cannot even be read", async () => {+ await fs.writeFile(listFile(), 'models = []\n[plugins]\n"@acme/not-installed" = "*"\n');+ const res = await view();+ expect(res.plugins).toHaveLength(1);+ expect(res.plugins[0]).toMatchObject({ specifier: "@acme/not-installed", active: false });+ // A specifier with no package on the machine is a configuration error, not a pending restart.+ expect(res.plugins[0]!.error).toMatch(/not installed on this machine/);+ expect(res.restartPending).toBe(false);+ });++ it("rewrites the list for an admin, and refuses everyone else", async () => {+ await ship({ name: "@acme/one", module: "One" });+ const saved = await admin.put("/api/projects/default_project/plugins/installed", {+ plugins: ["@acme/one", "@acme/one"],+ });+ expect(saved.status).toBe(200);+ // Written once: the table is keyed by name, in the order given — and it lands in the+ // Project's own config, beside its models, rather than in a file of its own.+ expect(+ ((await saved.json()) as InstalledPluginsResponse).plugins.map((p) => p.specifier),+ ).toEqual(["@acme/one"]);+ const written = await fs.readFile(listFile(), "utf8");+ expect(written).toContain("[plugins]");+ expect(written).toContain('"@acme/one" = "*"');++ const member = apiClient(t.app, (await provisionUser(t.app, "member")).cookie);+ // The list is the PROJECT's now, so it is reachable only by that Project's people. An+ // outsider is refused before the admin check ever runs.+ expect((await member.get("/api/projects/default_project/plugins/installed")).status).toBe(404);+ expect(+ (await admin.post("/api/projects/default_project/members", { userId: "member" })).status,+ ).toBe(201);+ // Reading is not an admin operation: a member of the Project sees what it asked for.+ expect((await member.get("/api/projects/default_project/plugins/installed")).status).toBe(200);+ // Writing still is.+ expect(+ (await member.put("/api/projects/default_project/plugins/installed", { plugins: [] })).status,+ ).toBe(403);+ expect(+ (await admin.put("/api/projects/default_project/plugins/installed", { plugins: [""] }))+ .status,+ ).toBe(400);+ });++ it("a rewrite is gated like an add: a new name must be a shipped package's", async () => {+ // What a single add refuses, a list rewrite refuses too — otherwise PUT would be the+ // way to name a path or an unshipped package. A name already on the list was consented+ // to when it was written and stays writable, so removing another name beside it works.+ await fs.writeFile(listFile(), 'models = []\n[plugins]\n"@acme/by-hand" = "*"\n');+ for (const bad of ["/tmp/anything.js", "../x", "@acme/tools/sandbox", "[email protected]"]) {+ const res = await admin.put("/api/projects/default_project/plugins/installed", {+ plugins: ["@acme/by-hand", bad],+ });+ expect(res.status, bad).toBe(400);+ expect(await res.json(), bad).toMatchObject({ error: { code: "bad_request" } });+ }+ const unshipped = await admin.put("/api/projects/default_project/plugins/installed", {+ plugins: ["@acme/by-hand", "@acme/not-shipped"],+ });+ expect(unshipped.status).toBe(400);+ expect(await unshipped.json()).toMatchObject({ error: { code: "plugin_not_shipped" } });+ expect(await fs.readFile(listFile(), "utf8")).toContain('"@acme/by-hand" = "*"');+ expect(await fs.readFile(listFile(), "utf8")).not.toContain("not-shipped");+ const kept = await admin.put("/api/projects/default_project/plugins/installed", {+ plugins: ["@acme/by-hand"],+ });+ expect(kept.status).toBe(200);+ });++ it("refuses a specifier that is not a package name, or one the build does not ship", async () => {+ for (const bad of ["../evil", "https://example.com/x.tgz", "", "Has Spaces", "[email protected]"]) {+ expect(+ (await admin.post("/api/projects/default_project/plugins/installed", { specifier: bad }))+ .status,+ bad,+ ).toBe(400);+ }+ // A well-formed name the build does not ship is fetched from nowhere: refused, and the+ // list is left as it was rather than naming a package that is not on the machine.+ const res = await admin.post("/api/projects/default_project/plugins/installed", {+ specifier: "@acme/not-shipped",+ });+ expect(res.status).toBe(400);+ expect(await res.json()).toMatchObject({ error: { code: "plugin_not_shipped" } });+ expect(await view()).toMatchObject({ plugins: [] });+ });++ it("drops a specifier from the list on delete", async () => {+ await ship({ name: "@acme/one", module: "One" });+ await ship({ name: "@acme/two", module: "Two" });+ await admin.put("/api/projects/default_project/plugins/installed", {+ plugins: ["@acme/one", "@acme/two"],+ });+ const res = await admin.delete(+ "/api/projects/default_project/plugins/installed?specifier=@acme/one",+ );+ expect(res.status).toBe(200);+ expect((await view()).plugins.map((p) => p.specifier)).toEqual(["@acme/two"]);+ const member = apiClient(t.app, (await provisionUser(t.app, "other")).cookie);+ expect(+ (await member.delete("/api/projects/default_project/plugins/installed?specifier=@acme/two"))+ .status,+ ).toBe(403);+ });++ it("reports why a listed plugin failed to load, not a restart that would not help", async () => {+ // A shipped package that throws on import.+ await ship({+ name: "@acme/broken",+ module: "Broken",+ index: 'throw new Error("deliberately broken");\n',+ });+ const saved = await admin.put("/api/projects/default_project/plugins/installed", {+ plugins: ["@acme/broken"],+ });+ expect(saved.status).toBe(200);+ const body = (await saved.json()) as InstalledPluginsResponse;+ expect(body.plugins[0]).toMatchObject({ specifier: "@acme/broken", active: false });+ expect(body.plugins[0]!.error).toMatch(/deliberately broken/);+ expect(body.restartPending).toBe(false);+ });++ it("a plugin that breaks the boot is undone, and the previous App keeps serving", async () => {+ // A load failure is isolated per entry; a BOOT failure (the module's setup throws) is+ // not — the kernel fails the whole tree. The change that introduced it is undone before+ // the previous tree is restored, so the process is not left forwarding to a disposed+ // App, and the next start does not fail on the same list.+ await ship({ name: "@acme/fine", module: "Fine" });+ await ship({+ name: "@acme/bad-boot",+ module: "BadBoot",+ index: lower(`import { Module } from ${JSON.stringify(decorators)};+ @Module() export class BadBoot { setup() { throw new Error("deliberately fails to boot"); } }+ export default { modules: [BadBoot] };`),+ });+ expect(+ (+ await admin.post("/api/projects/default_project/plugins/installed", {+ specifier: "@acme/fine",+ })+ ).status,+ ).toBe(200);+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ try {+ const res = await admin.post("/api/projects/default_project/plugins/installed", {+ specifier: "@acme/bad-boot",+ });+ expect(res.status).toBe(200);+ const body = (await res.json()) as InstalledPluginsResponse;+ // Undone: the list is as it was, and what runs is what ran.+ expect(body.plugins.map((p) => [p.specifier, p.active])).toEqual([["@acme/fine", true]]);+ expect(await fs.readFile(listFile(), "utf8")).not.toContain("bad-boot");+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(/deliberately fails to boot/));+ } finally {+ warn.mockRestore();+ }+ // Still serving, on the restored App.+ expect((await admin.get("/api/projects/default_project/plugins/installed")).status).toBe(200);+ });++ it("reports a list file that cannot be read, rather than an empty deployment", async () => {+ await fs.writeFile(listFile(), "{ not json");+ const res = await admin.get("/api/projects/default_project/plugins/installed");+ expect(res.status).toBe(400);+ expect(await res.text()).toContain(".project_config.toml");+ });+});diff --git a/packages/web/e2e/layout.spec.mjs b/packages/web/e2e/layout.spec.mjsindex 9af3d179..4ca10e0a 100644--- a/packages/web/e2e/layout.spec.mjs+++ b/packages/web/e2e/layout.spec.mjs@@ -27,7 +27,7 @@* chrome used to stop fitting below ~412px;* - the sidebar's "New chat" button has no background fill (same gray-scale style as nav items);* - the collapsed rail shows, in product-specified order, last conversation / new chat /- * Agents / Plugin library / Models / Cost Center / Evaluation Center, each labeled by a+ * Agents / Plugins / Models / Cost Center / Evaluation Center, each labeled by a* localized (en + zh) styled tooltip on hover and by no native `title` (two tooltips would* stack); "last conversation" targets the most recently active non-archived session and is* disabled while none exists; expanding from the rail restores the pinned sidebar;@@ -419,7 +419,7 @@ test("layout: collapsed rail — order, bilingual tooltips, last conversation","Last conversation","New chat","Agents",- "Plugin library",+ "Plugins","Models","Cost Center","Evaluation Center",@@ -482,15 +482,15 @@ test("layout: collapsed rail — order, bilingual tooltips, last conversation",);// --- Page entries navigate and highlight like the pinned nav ---- await rail.getByRole("link", { name: "Plugin library" }).click();+ await rail.getByRole("link", { name: "Plugins" }).click();await expect(page).toHaveURL(`${BASE}/plugins`);- await expect(rail.getByRole("link", { name: "Plugin library" })).toHaveClass(ACTIVE_FILL);+ await expect(rail.getByRole("link", { name: "Plugins" })).toHaveClass(ACTIVE_FILL);// --- zh: tooltips follow the product-specified wording ---await page.addInitScript(() => localStorage.setItem("penguin.lang", "zh"));await page.reload();await expect(entries).toHaveCount(7);- const ZH = ["最近一次对话", "新建对话", "智能体", "插件库", "模型库", "成本中心", "评估中心"];+ const ZH = ["最近一次对话", "新建对话", "智能体", "插件市场", "模型库", "成本中心", "评估中心"];expect(await attrs("aria-label"), "rail order (zh)").toEqual(ZH);expect(await attrs("title"), "rail carries no native tooltips (zh)").toEqual(ZH.map(() => null));await rail.getByRole("link", { name: "模型库" }).hover();diff --git a/packages/web/e2e/project-switch.spec.mjs b/packages/web/e2e/project-switch.spec.mjsindex 65f3741d..45a18773 100644--- a/packages/web/e2e/project-switch.spec.mjs+++ b/packages/web/e2e/project-switch.spec.mjs@@ -98,16 +98,19 @@ test("clicking the current Project in the dropdown: Agent and Session lists mustawait byName.first().click();await page.getByRole("button", { name: U }).first().click();await expect(generalAgent).toBeVisible();- await page.getByRole("link", { name: "插件库" }).click();+ await page.getByRole("link", { name: "插件市场" }).click();await expect(page).toHaveURL(/\/plugins$/);- await page.getByRole("button", { name: "管理安装 agent-initialization" }).click();+ // The installed section is folded on entry; its cards are inert until it is opened. The+ // library's plugin is agent-tuning; agent-initialization is one of its skills.+ await page.getByRole("button", { name: /已安装的插件|Installed plugins/ }).click();+ await page.getByRole("button", { name: "管理安装 agent-tuning" }).click();await expect(page.getByRole("button", { name: "卸载 default_agent" })).toBeVisible();await page.keyboard.press("Escape");// Staying on the plugin library page while switching to target: the same-named default_agent's state must flip to "Install" (not installed).await page.getByRole("button", { name: U }).first().click();await byName.first().click();- await page.getByRole("button", { name: "管理安装 agent-initialization" }).click();+ await page.getByRole("button", { name: "管理安装 agent-tuning" }).click();await expect(page.getByRole("button", { name: "安装 default_agent" })).toBeVisible();await page.keyboard.press("Escape");});diff --git a/packages/web/e2e/skills.spec.mjs b/packages/web/e2e/skills.spec.mjsindex e14a9edf..69c31d26 100644--- a/packages/web/e2e/skills.spec.mjs+++ b/packages/web/e2e/skills.spec.mjs@@ -1,6 +1,6 @@/*** End-to-end test for the plugin library (locale zh-CN):- * - the sidebar nav shows "插件库" ("Plugin library"), and the page renders the library's plugin+ * - the sidebar nav shows "插件市场" ("Plugins"), and the page renders the library's plugin* cards across group sections (a collapsible group header: category name + plugin count,* **no icon**; the group name follows the UI language — when the server ships a Chinese* group name it's "办公效率 / 软件开发 / AI 应用开发 / Agent 调优", falling back to@@ -34,14 +34,16 @@ const MOCK = process.env.MOCK_URL;const U = "skillsuser";const P = "password123";-// Group names follow the UI language: Chinese when the server dist ships titleZh, otherwise-// falling back to English (both states are asserted).-// The group header is a collapsible button (category name + plugin count); matched by a substring of its accessible name.-const GROUPS = [+// Category names follow the UI language: Chinese when the server dist ships titleZh, otherwise+// falling back to English (both states are asserted). A category is a tag on each library+// plugin's row now; the page is one flat list, with the installed section folded by default.+const CATEGORIES = [/Office Productivity|办公效率/,/Software Development|软件开发/,/AI App Development|AI 应用开发/,];+// The "Installed plugins (N)" section header: a collapsible button, folded on entry.+const INSTALLED_HEADER = /已安装的插件|Installed plugins/;// Library plugin cards the page renders (merged plugins carry several skills each).const PLUGINS = ["agent-tuning",@@ -68,7 +70,7 @@ const SKILLS = [// and the card renders a custom icon.svg — neither spot should show this fallback path.const BOOK_PATH_PREFIX = "M2 3h6a4";-test("skills: library groups and cards -> manage-install Modal -> quick-invoke prefill -> dropdown filter and slash selection", async ({+test("skills: library list and cards -> manage-install Modal -> quick-invoke prefill -> dropdown filter and slash selection", async ({page,}) => {await provisionAndLogin(page.request, U, P);@@ -100,18 +102,21 @@ test("skills: library groups and cards -> manage-install Modal -> quick-invoke p});expect(created.ok(), "create helper agent").toBeTruthy();- // —— Plugin library page: sidebar nav entry + grouped cards (group headers are collapsible buttons, all expanded by default) ——+ // —— Plugin library page: sidebar nav entry + one list of cards under a folded "Installed plugins" header ——await page.goto(`${BASE}/chat`);- const navLink = page.getByRole("link", { name: "插件库" });+ const navLink = page.getByRole("link", { name: "插件市场" });await expect(navLink).toBeVisible();await navLink.click();await expect(page).toHaveURL(/\/plugins$/);- for (const g of GROUPS) {- const header = page.getByRole("button", { name: g });- await expect(header).toBeVisible();- await expect(header).toHaveAttribute("aria-expanded", "true");- // The group header no longer has an icon: the book path must not appear in the group header button.- await expect(header.locator(`svg path[d^="${BOOK_PATH_PREFIX}"]`)).toHaveCount(0);+ const installedHeader = page.getByRole("button", { name: INSTALLED_HEADER });+ await expect(installedHeader).toBeVisible();+ await expect(installedHeader).toHaveAttribute("aria-expanded", "false");+ await installedHeader.click();+ await expect(installedHeader).toHaveAttribute("aria-expanded", "true");+ // The section header carries no icon: the book path must not appear in it.+ await expect(installedHeader.locator(`svg path[d^="${BOOK_PATH_PREFIX}"]`)).toHaveCount(0);+ for (const c of CATEGORIES) {+ await expect(page.getByText(c).first()).toBeVisible();}for (const s of PLUGINS) {await expect(page.getByText(s, { exact: true })).toBeVisible();@@ -140,18 +145,17 @@ test("skills: library groups and cards -> manage-install Modal -> quick-invoke pawait expect(creationCard.locator("span[aria-hidden] > svg")).toHaveCount(1);await expect(creationCard.locator(`svg path[d^="${BOOK_PATH_PREFIX}"]`)).toHaveCount(0);- // Clicking the group header collapses it: aria-expanded flips, and the group's content- // becomes inert (a zero-height card can't be interacted with); clicking again expands it back.- // The collapsed content is still in the DOM (a grid-rows 0fr height transition), so assert+ // Clicking the section header folds it: aria-expanded flips, and the section's content+ // becomes inert (a zero-height card can't be interacted with); clicking again unfolds it.+ // The folded content is still in the DOM (a grid-rows 0fr height transition), so assert// inert rather than visibility.- const firstHeader = page.getByRole("button", { name: GROUPS[0] });- const firstGroup = page.locator("section").filter({ has: firstHeader });- await firstHeader.click();- await expect(firstHeader).toHaveAttribute("aria-expanded", "false");- await expect(firstGroup.locator("[inert]")).toHaveCount(1);- await firstHeader.click();- await expect(firstHeader).toHaveAttribute("aria-expanded", "true");- await expect(firstGroup.locator("[inert]")).toHaveCount(0);+ const installedSection = page.locator("section").filter({ has: installedHeader });+ await installedHeader.click();+ await expect(installedHeader).toHaveAttribute("aria-expanded", "false");+ await expect(installedSection.locator("[inert]")).toHaveCount(1);+ await installedHeader.click();+ await expect(installedHeader).toHaveAttribute("aria-expanded", "true");+ await expect(installedSection.locator("[inert]")).toHaveCount(0);// —— Manage installation Modal: an Agent row + Install/Installed (clicking Installed uninstalls) ——await page.getByRole("button", { name: "管理安装 data-analysis" }).click();diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex aaee88c1..10dfbf00 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -156,6 +156,8 @@ import type {SessionPatchRequest,SessionProcessesResponse,SessionResponse,+ PluginIndexResponse,+ PluginReadmeResponse,SessionsResponse,SessionTracesResponse,SkillArchiveInstallRequest,@@ -188,6 +190,7 @@ import type {UsageResponse,VaultResponse,VaultUpdateRequest,+ InstalledPluginsResponse,VersionResponse,WeChatBindingPutRequest,WeChatBindingResponse,@@ -1211,6 +1214,12 @@ export const installAgentPlugins = (projectId: string, agentId: string, names: s{ method: "POST", body: { names } satisfies PluginInstallRequest },);+/** Plugin index (available to any logged-in user): the merged index of every configured registry. */+export const getPluginIndex = () => apiFetch<PluginIndexResponse>("/api/plugins/registry");++export const getPluginReadme = (name: string) =>+ apiFetch<PluginReadmeResponse>(`/api/plugins/registry/readme?name=${encodeURIComponent(name)}`);+export const getAgentSkills = (projectId: string, agentId: string) =>apiFetch<AgentSkillsResponse>(`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/skills`,@@ -1703,3 +1712,35 @@ export const getDesktopTray = () => apiFetch<DesktopTrayStatusResponse>("/api/de*/export const setDesktopTray = (patch: DesktopTrayPatch) =>apiFetch<void>("/api/desktop/tray", { method: "PUT", body: patch });++// ---- The plugins a Project asks for ----+/**+ * A Project's plugin list. Project-scoped because machines are lent to Projects, so this is+ * what says which machines a plugin has to reach; what the process RUNS is the union over+ * the Projects, since loading is per process (see the server's plugin/loader.ts).+ */+const pluginsPath = (projectId: string) =>+ `/api/projects/${encodeURIComponent(projectId)}/plugins/installed`;+export const getInstalledPlugins = (projectId: string) =>+ apiFetch<InstalledPluginsResponse>(pluginsPath(projectId));+/** Admin only; applied without a restart where the runtime can re-assemble the App. */+export const putInstalledPlugins = (projectId: string, plugins: readonly string[]) =>+ apiFetch<InstalledPluginsResponse>(pluginsPath(projectId), {+ method: "PUT",+ body: { plugins },+ });+/**+ * Admin only: asks this Project for a plugin the build ships — refused for one it does not,+ * so the list never names a package that is not on the machine — then re-assembles the App.+ */+export const installPlugin = (projectId: string, specifier: string) =>+ apiFetch<InstalledPluginsResponse>(pluginsPath(projectId), {+ method: "POST",+ body: { specifier },+ });+/** Admin only: drops it from this Project's list and re-assembles the App; nothing on disk changes. */+export const uninstallPlugin = (projectId: string, specifier: string) =>+ apiFetch<InstalledPluginsResponse>(+ `${pluginsPath(projectId)}?specifier=${encodeURIComponent(specifier)}`,+ { method: "DELETE" },+ );diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsxindex 53105683..33433ee5 100644--- a/packages/web/src/components/layout/app-layout.tsx+++ b/packages/web/src/components/layout/app-layout.tsx@@ -116,7 +116,7 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {navigate(`/chat/${DRAFT_SESSION_ID}`, agentId ? { state: { agentId } } : undefined);};- /** Page entries (rail positions 3-7): same routes, same labels as the pinned nav.+ /** Page entries (rail positions 3-8): same routes, same labels as the pinned nav.Traces is not among them: reading a Trace happens in the chat toolbar's panelswitcher, which is the only place it happens. */const pages: ReadonlyArray<{diff --git a/packages/web/src/features/plugins/plugin-detail-page.tsx b/packages/web/src/features/plugins/plugin-detail-page.tsxnew file mode 100644index 00000000..d850f820--- /dev/null+++ b/packages/web/src/features/plugins/plugin-detail-page.tsx@@ -0,0 +1,203 @@+/**+ * One plugin's detail page: the index entry's metadata plus its long-form readme,+ * rendered from Markdown.+ *+ * The readme is fetched separately from the index (GET /api/plugins/registry/readme) because the+ * shapes differ — the listing is sent in full on every visit to the Plugins page, while a+ * readme is large and wanted only for the entry someone opened.+ *+ * The specifier is the page's identity and arrives as the route's splat, since it is+ * scoped (`@scope/name`) and therefore contains a slash of its own.+ */+import { useEffect, useState } from "react";+import { Link, useParams } from "react-router";+import type { PluginIndexEntry } from "@prismshadow/penguin-server/api";+import ReactMarkdown from "react-markdown";+import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";+import * as api from "../../api/endpoints";+import { S } from "../../lib/strings";+import { apiErrorText } from "../../lib/api-error";+import { useDocumentTitle } from "../../lib/use-document-title";+import { Button } from "../../components/ui/button";+import { CopiedStatus, CopyCheckGlyph, useCopied } from "../../components/ui/copy-button";+import { GlyphIcon } from "../../components/ui/glyph-icon";+import { NAV_ICONS } from "../../components/ui/icons";+import { Skeleton } from "../../components/ui/skeleton";+import { toneInk } from "../../lib/tone";++export function PluginDetailPage() {+ const params = useParams();+ const name = params["*"] ?? "";+ useDocumentTitle(name || S.pluginRegistry.pageTitle);++ const [entry, setEntry] = useState<PluginIndexEntry | null | undefined>(undefined);+ const [readme, setReadme] = useState<string | null | undefined>(undefined);+ const [error, setError] = useState<string | null>(null);+ const { copied, flash } = useCopied();++ // The index carries every field this page shows except the readme, and it is one cached+ // call — cheaper and simpler than a per-entry metadata endpoint that would duplicate it.+ useEffect(() => {+ let cancelled = false;+ setError(null);+ setEntry(undefined);+ setReadme(undefined);+ api+ .getPluginIndex()+ .then((res) => {+ if (cancelled) return;+ setEntry(res.plugins.find((p) => p.name === name) ?? null);+ })+ .catch((e: unknown) => {+ if (!cancelled) setError(apiErrorText(e));+ });+ api+ .getPluginReadme(name)+ .then((res) => {+ if (!cancelled) setReadme(res.readme);+ })+ // A missing readme is not a page error: the metadata above it is still worth showing.+ .catch(() => {+ if (!cancelled) setReadme(null);+ });+ return () => {+ cancelled = true;+ };+ }, [name]);++ return (+ // The list's frame exactly — same column, same reserved gutter — so the content's edges stay+ // put when a row is opened and closed again.+ <div className="h-full overflow-y-auto p-4 [scrollbar-gutter:stable] md:p-6">+ <div className="mx-auto max-w-5xl">+ <Link+ to="/plugins"+ className="inline-flex items-center gap-1.5 text-xs text-gray-500 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"+ >+ <GlyphIcon d="M15 6l-6 6 6 6" size={14} />+ {S.pluginRegistry.back}+ </Link>++ {error ? (+ <div className="mt-6 flex items-center gap-3">+ <p className={`text-sm ${toneInk.danger}`}>{error}</p>+ <Button size="sm" onClick={() => window.location.reload()}>+ {S.common.retry}+ </Button>+ </div>+ ) : entry === undefined ? (+ <div className="mt-6">+ <Skeleton className="h-6 w-72" />+ <Skeleton className="mt-3 h-4 w-full" />+ <Skeleton className="mt-6 h-40 w-full" />+ </div>+ ) : entry === null ? (+ <p className="mt-6 text-sm text-gray-400 dark:text-gray-500">+ {S.pluginRegistry.notFound}+ </p>+ ) : (+ <>+ <header className="mt-4 flex items-start gap-3">+ <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-lg bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400">+ <GlyphIcon d={NAV_ICONS.plugins} size={22} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-baseline gap-2">+ <h1 className="min-w-0 break-all font-mono text-base font-semibold">+ {entry.name}+ </h1>+ <span className="font-mono text-xs text-gray-400">v{entry.version}</span>+ <button+ type="button"+ onClick={() => flash(entry.name)}+ title={copied ? S.common.copied : S.pluginRegistry.copySpecifier}+ className="inline-flex items-center gap-1 rounded border border-gray-200 px-1.5 py-0.5 text-[11px] text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800"+ >+ <CopyCheckGlyph copied={copied} size={12} />+ {S.pluginRegistry.copySpecifier}+ </button>+ <CopiedStatus copied={copied} />+ </div>+ <p className="mt-1 text-sm text-gray-600 dark:text-gray-300">{entry.description}</p>+ </div>+ </header>++ <dl className="mt-4 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5 text-xs">+ <Field label={S.pluginRegistry.license}>{entry.license}</Field>+ {entry.authors.length > 0 && (+ <Field label={S.pluginRegistry.authors}>{entry.authors.join(", ")}</Field>+ )}+ {entry.repository && (+ <Field label={S.pluginRegistry.repository}>+ <ExternalLink href={entry.repository} />+ </Field>+ )}+ {entry.homepage && (+ <Field label={S.pluginRegistry.homepage}>+ <ExternalLink href={entry.homepage} />+ </Field>+ )}+ </dl>++ {(entry.keywords ?? []).length > 0 && (+ <div className="mt-3 flex flex-wrap items-center gap-1.5 text-[11px]">+ {(entry.keywords ?? []).map((keyword) => (+ <span+ key={keyword}+ className="rounded-full bg-gray-100 px-2 py-0.5 font-mono text-gray-500 dark:bg-gray-800 dark:text-gray-400"+ >+ {keyword}+ </span>+ ))}+ </div>+ )}++ <p className="mt-4 rounded-md bg-gray-50 px-3 py-2 text-xs text-gray-500 dark:bg-gray-800/60 dark:text-gray-400">+ {S.pluginRegistry.installHint}+ </p>++ <section className="mt-6 border-t border-gray-200 pt-5 dark:border-gray-800">+ <h2 className="text-sm font-semibold">{S.pluginRegistry.readme}</h2>+ {readme === undefined ? (+ <Skeleton className="mt-3 h-40 w-full" />+ ) : readme === null ? (+ <p className="mt-3 text-sm text-gray-400 dark:text-gray-500">+ {S.pluginRegistry.noReadme}+ </p>+ ) : (+ <div className="md-body mt-3 text-sm text-gray-800 dark:text-gray-100">+ <ReactMarkdown remarkPlugins={REMARK_PLUGINS} rehypePlugins={REHYPE_PLUGINS}>+ {readme}+ </ReactMarkdown>+ </div>+ )}+ </section>+ </>+ )}+ </div>+ </div>+ );+}++function Field({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <>+ <dt className="text-gray-400 dark:text-gray-500">{label}</dt>+ <dd className="min-w-0 break-all text-gray-600 dark:text-gray-300">{children}</dd>+ </>+ );+}++/** Index entries carry publisher-supplied URLs, so open them isolated from this origin. */+function ExternalLink({ href }: { href: string }) {+ return (+ <a+ href={href}+ target="_blank"+ rel="noreferrer noopener"+ className="text-blue-600 hover:underline dark:text-blue-400"+ >+ {href}+ </a>+ );+}diff --git a/packages/web/src/features/plugins/plugins-page.tsx b/packages/web/src/features/plugins/plugins-page.tsxindex d1ed1996..97e1c3fc 100644--- a/packages/web/src/features/plugins/plugins-page.tsx+++ b/packages/web/src/features/plugins/plugins-page.tsx@@ -37,12 +37,14 @@* which is why the page fetches both lists per Agent. Uninstall takes the plugin apart the* same way: one DELETE per skill and one for the hook package.*/-import { useEffect, useState } from "react";-import { useNavigate } from "react-router";+import { useCallback, useEffect, useState } from "react";+import { Link, useNavigate } from "react-router";import type {AgentSummary,HookItem,+ InstalledPluginsResponse,PluginGroupItem,+ PluginIndexEntry,PluginItem,SkillMetadataItem,} from "@prismshadow/penguin-server/api";@@ -61,8 +63,10 @@ import { AgentAvatar } from "../../components/ui/agent-avatar";import { Button } from "../../components/ui/button";import { Chevron } from "../../components/ui/chevron";import { GlyphIcon } from "../../components/ui/glyph-icon";-import { PLUGIN_ICON } from "../../components/ui/icons";+import { NAV_ICONS, PLUGIN_ICON } from "../../components/ui/icons";import { Modal } from "../../components/ui/modal";+import { TRASH_ICON } from "../../components/ui/session-row-menu";+import { StatusIcon } from "../../components/ui/status-icon";import { TodoNotice } from "../../components/ui/todo-notice";import { UpdateDot } from "../../components/ui/update-dot";import { ConfirmModal } from "../../components/ui/confirm-modal";@@ -77,6 +81,8 @@ import { formatRelativeDate } from "../../lib/format";import { SkillTile } from "../skills/skill-icon-view";import { InfoPopover } from "../../components/ui/info-popover";import { ICON_SIZE } from "../../lib/icon-scale";+import { toneInk, toneStrip, toneSurface } from "../../lib/tone";+import { Input } from "../../components/ui/input";/*** What one Agent has installed, by name → the installed copy's version (`YYYY.MM.DD.N`, or ""@@ -194,12 +200,12 @@ export function pluginUpdatePlan(}return { perAgent, plugins: [...plugins].sort() };}-export function PluginsPage() {useDocumentTitle(S.nav.plugins);const navigate = useNavigate();const { locale } = useLocale();- const userId = useAuth().user?.userId ?? null;+ const { user } = useAuth();+ const userId = user?.userId ?? null;const { currentProject, agents, currentAgent, setCurrentAgentId, reloadAgents } = useProject();const projectId = currentProject?.projectId ?? null;@@ -212,8 +218,82 @@ export function PluginsPage() {const [groups, setGroups] = useState<PluginGroupItem[] | null>(null);const [error, setError] = useState<string | null>(null);const [installed, setInstalled] = useState<InstalledMap>(new Map());- /** Collapsed groups (all expanded by default; same convention as the model page's provider groups). */- const [collapsed, setCollapsed] = useState<Set<string>>(new Set());+ /** What this Project asks for of the module plugins, and which of those the process runs. */+ const [deployment, setDeployment] = useState<InstalledPluginsResponse | null>(null);+ /** The registry: every module plugin this deployment could ask for. */+ const [index, setIndex] = useState<PluginIndexEntry[] | null>(null);+ /** The specifier whose install or removal is running: the list is written one verb at a time. */+ const [pendingSpecifier, setPendingSpecifier] = useState<string | null>(null);+ const isAdmin = user?.isAdmin === true;+ /** Free text over name, specifier and description. */+ const [query, setQuery] = useState("");+ /** The filter column's choices: a row shows when it carries one selected category and every selected tag. */+ const [pickedCategories, setPickedCategories] = useState<ReadonlySet<string>>(new Set());+ const [pickedKinds, setPickedKinds] = useState<ReadonlySet<PluginKind>>(new Set());+ const [pickedStates, setPickedStates] = useState<ReadonlySet<PluginState>>(new Set());+ /** The installed list starts folded — it is the long one; a search or a filter opens both. */+ const [installedOpen, setInstalledOpen] = useState(false);+ const [availableOpen, setAvailableOpen] = useState(true);++ // The Project's list, re-read whenever the Project changes; a read that fails leaves the+ // module rows without their state rather than failing the page.+ const reloadDeployment = useCallback(() => {+ if (projectId === null) return;+ api.getInstalledPlugins(projectId).then(setDeployment, () => setDeployment(null));+ }, [projectId]);+ useEffect(reloadDeployment, [reloadDeployment]);++ // The registry, fetched once on page entry.+ useEffect(() => {+ let cancelled = false;+ api.getPluginIndex().then(+ (res) => {+ if (!cancelled) setIndex(res.plugins);+ },+ () => {+ if (!cancelled) setIndex([]);+ },+ );+ return () => {+ cancelled = true;+ };+ }, []);++ /**+ * A module plugin change waiting for its confirmation (null = none). Applying one+ * re-assembles the App, which stops the agent runs in flight in EVERY Project — the same+ * cost a hot push has — so it is said before it is done.+ */+ const [pendingApply, setPendingApply] = useState<{ specifier: string; install: boolean } | null>(+ null,+ );++ /**+ * Asks this Project for a module plugin (or drops it); the server lists it and re-assembles+ * the App, so the row's state afterwards is what the running process has — including a+ * load that failed, which is reported as such rather than toasted as installed.+ */+ const runDeploymentInstall = async (specifier: string, install: boolean) => {+ if (pendingSpecifier !== null || projectId === null) return;+ setPendingSpecifier(specifier);+ try {+ const next = install+ ? await api.installPlugin(projectId, specifier)+ : await api.uninstallPlugin(projectId, specifier);+ setDeployment(next);+ const row = next.plugins.find((p) => p.specifier === specifier);+ if (install && row?.error !== undefined) {+ toastError(S.plugins.deploymentFailedToast(specifier, row.error));+ } else {+ toastSuccess(install ? S.plugins.deploymentInstalledToast(specifier) : S.common.saved);+ }+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setPendingSpecifier(null);+ setPendingApply(null);+ }+ };// Library list: readable once logged in, fetched once on page entry.useEffect(() => {@@ -445,13 +525,36 @@ export function PluginsPage() {navigate(`/chat/${DRAFT_SESSION_ID}`, { state: { agentId } });};+ const allInstalled = installedPluginRows(groups ?? [], locale, deployment, index ?? []);+ const allAvailable = availablePluginRows(deployment, index ?? []);+ const facets = pluginFacets([...allInstalled, ...allAvailable]);+ const picked = { categories: pickedCategories, kinds: pickedKinds, states: pickedStates };+ const filtering =+ query.trim() !== "" ||+ pickedCategories.size > 0 ||+ pickedKinds.size > 0 ||+ pickedStates.size > 0;+ const keep = (row: PluginRow) => rowMatches(row, query, picked);+ const installedRows = allInstalled.filter(keep);+ const availableRows = allAvailable.filter(keep);+ const toggle = <T,>(set: ReadonlySet<T>, value: T): Set<T> => {+ const next = new Set(set);+ if (next.has(value)) next.delete(value);+ else next.add(value);+ return next;+ };++ // The scrollbar gutter stays reserved: a filter that shortens the page below the viewport+ // would otherwise take the scrollbar with it and shift everything sideways at the click.return (- <div className="h-full overflow-y-auto p-4 md:p-6">+ <div className="h-full overflow-y-auto p-4 [scrollbar-gutter:stable] md:p-6"><div className="mx-auto max-w-5xl">- <h1 className="flex items-center gap-1.5 text-xl font-semibold">- {S.plugins.pageTitle}- <InfoPopover label={S.plugins.pageTitle}>{S.plugins.pageDesc}</InfoPopover>- </h1>+ <div className="flex items-center justify-between gap-2">+ <h1 className="flex items-center gap-1.5 text-xl font-semibold">+ {S.plugins.pageTitle}+ <InfoPopover label={S.plugins.pageTitle}>{S.plugins.pageDesc}</InfoPopover>+ </h1>+ </div>{/* Last stop on the plugins trail: what the sidebar's dot was pointing at, the controlthat takes all of it in one press, and the way to clear it for someone who has lookedand decided to stay on the installed copies. A plugin is never NEW here — one nobody@@ -469,15 +572,21 @@ export function PluginsPage() {/>)}+ {deployment !== null && deployment.restartPending && (+ <div className={`mt-4 rounded-md px-3 py-2 text-xs ${toneStrip.attention}`}>+ {S.plugins.restartPending}+ </div>+ )}+{error ? (<div className="mt-6 flex items-center gap-3">- <p className="text-sm text-red-600 dark:text-red-400">{error}</p>+ <p className={`text-sm ${toneInk.danger}`}>{error}</p><Button size="sm" onClick={() => window.location.reload()}>{S.common.retry}</Button></div>) : groups === null ? (- <div className="mt-6 grid grid-cols-1 gap-2.5 sm:grid-cols-2">+ <div className="mt-6 grid grid-cols-1 gap-2.5">{Array.from({ length: 4 }, (_, i) => (<SkeletonCard key={i} className="p-4"><Skeleton className="h-4 w-32" />@@ -487,80 +596,124 @@ export function PluginsPage() {))}</div>) : (- <div className="mt-6 space-y-3">- {groups.map((group) => {- const open = !collapsed.has(group.id);- return (- <section- key={group.id}- className="overflow-hidden rounded-md bg-white dark:bg-gray-900"+ <div className="mt-6 md:grid md:grid-cols-[minmax(0,1fr)_12rem] md:gap-4">+ <div className="min-w-0 space-y-3">+ <Input+ size="sm"+ type="search"+ value={query}+ placeholder={S.plugins.searchPlaceholder}+ aria-label={S.plugins.searchPlaceholder}+ onChange={(e) => setQuery(e.target.value)}+ />+ {/* ONE list, one plugin per row, every kind in the same card: what is installed+ first — the library's plugins (they ship with the build and every Agent may use+ them) and the module plugins this Project asks for — then what could be. A+ plugin's category is a tag on its row, not a group around it. */}+ <PluginList+ title={S.plugins.installedSection(installedRows.length)}+ open={installedOpen || filtering}+ onToggle={() => setInstalledOpen((v) => !v)}+ >+ {installedRows.map((row) =>+ row.kind === "library" ? (+ <PluginCard+ key={`library:${row.plugin.name}`}+ plugin={row.plugin}+ category={row.category}+ installed={installed}+ onQuickInvoke={quickInvoke}+ onToggleInstall={toggleInstall}+ onUpdateOutdated={updateOutdated}+ />+ ) : (+ <ModuleRow+ key={`module:${row.specifier}`}+ specifier={row.specifier}+ entry={row.entry}+ state={row.state}+ error={row.error}+ shipped={row.shipped}+ busy={pendingSpecifier === row.specifier}+ blocked={pendingSpecifier !== null && pendingSpecifier !== row.specifier}+ onInstall={null}+ onRemove={+ isAdmin+ ? () => setPendingApply({ specifier: row.specifier, install: false })+ : null+ }+ />+ ),+ )}+ </PluginList>+ {availableRows.length > 0 && (+ <PluginList+ title={S.plugins.availableSection(availableRows.length)}+ open={availableOpen || filtering}+ onToggle={() => setAvailableOpen((v) => !v)}>- {/* Group header (styled like the model page's provider groups): category name +- plugin count (no icon, no description); the whole row toggles- collapse on click and highlights on hover. */}- <button- type="button"- aria-expanded={open}- onClick={() =>- setCollapsed((prev) => {- const next = new Set(prev);- if (next.has(group.id)) next.delete(group.id);- else next.add(group.id);- return next;- })- }- className="flex w-full items-center gap-2.5 bg-gray-50 px-3 py-2.5 text-left transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900/60 dark:hover:bg-gray-800/60"- >- {/* Group name can truncate (min-w-0): the count and collapse arrow must not shrink. */}- <span className="min-w-0 truncate text-sm font-semibold">- {localizedText(locale, group.title, group.titleZh)}- </span>- <span className="shrink-0 whitespace-nowrap font-mono text-xs text-gray-400">- {S.plugins.pluginCount(group.plugins.length)}- </span>- <span className="min-w-0 flex-1" />- <Chevron open={open} className="text-gray-400" />- </button>-- {/* Expand/collapse height transition: grid-template-rows tweens between- 0fr and 1fr, with the inner overflow-hidden clipping the content- (same convention as the model page). */}- <div- className={`grid transition-[grid-template-rows] duration-200 ease-out ${open ? "grid-rows-[1fr]" : "grid-rows-[0fr]"}`}- >- {/* inert while collapsed: cards at zero height shouldn't still be Tab-focusable or clickable. */}- <div className="overflow-hidden" inert={!open}>- {/* Generously sized cards: 2 columns ≥sm, 1 column on narrow screens.- `grid-cols-1` is load-bearing, not redundant: with no declared track the- single implicit column is `auto`-sized, and an auto track never goes below- the widest card's min-content width — which `truncate` does not lower,- since `nowrap` leaves no wrap opportunity and `overflow: hidden` only- clips at paint time. A card then overflows the section's `overflow-hidden`- and its action buttons land off-viewport, unreachable. Tailwind's- `grid-cols-*` is `minmax(0, 1fr)`, which clamps that floor to 0. */}- <div- className={`grid grid-cols-1 gap-2.5 p-2.5 transition-opacity duration-200 sm:grid-cols-2 ${open ? "opacity-100" : "opacity-0"}`}- >- {group.plugins.map((plugin) => (- <PluginCard- key={plugin.name}- plugin={plugin}- installed={installed}- onQuickInvoke={quickInvoke}- onToggleInstall={toggleInstall}- onUpdateOutdated={updateOutdated}- />- ))}- </div>- </div>- </div>- </section>- );- })}+ {availableRows.map((row) => (+ <ModuleRow+ key={`module:${row.specifier}`}+ specifier={row.specifier}+ entry={row.entry}+ state={row.state}+ shipped={row.shipped}+ busy={pendingSpecifier === row.specifier}+ blocked={pendingSpecifier !== null && pendingSpecifier !== row.specifier}+ onInstall={+ isAdmin+ ? () => setPendingApply({ specifier: row.specifier, install: true })+ : null+ }+ onRemove={null}+ />+ ))}+ </PluginList>+ )}+ {filtering && installedRows.length === 0 && availableRows.length === 0 && (+ <p className="px-1 text-sm text-gray-400 dark:text-gray-500">{S.plugins.noMatch}</p>+ )}+ </div>+ {/* The filter column: the categories on the page, then two attributes with a+ handful of values each (what a plugin carries, what it is here). Free-form+ keywords are not a facet — they feed the search box. A pick narrows both lists,+ and the lists unfold while anything is picked or typed. */}+ <PluginFilters+ facets={facets}+ picked={picked}+ onCategory={(c) => setPickedCategories((prev) => toggle(prev, c))}+ onKind={(k) => setPickedKinds((prev) => toggle(prev, k))}+ onState={(st) => setPickedStates((prev) => toggle(prev, st))}+ onClear={() => {+ setPickedCategories(new Set());+ setPickedKinds(new Set());+ setPickedStates(new Set());+ setQuery("");+ }}+ /></div>)}</div>+ {/* A module plugin change: what it costs is said before it runs. */}+ {pendingApply !== null && (+ <ConfirmModal+ open+ title={+ pendingApply.install+ ? S.plugins.applyConfirmInstall(pendingApply.specifier)+ : S.plugins.applyConfirmRemove(pendingApply.specifier)+ }+ tone="primary"+ confirmLabel={pendingApply.install ? S.plugins.install : S.plugins.uninstall}+ busy={pendingSpecifier !== null}+ onClose={() => setPendingApply(null)}+ onConfirm={() => void runDeploymentInstall(pendingApply.specifier, pendingApply.install)}+ >+ <p>{S.plugins.applyConfirmBody}</p>+ </ConfirmModal>+ )}{/* Bulk update confirmation. Same warning as the per-plugin confirm — an update is anoverwriting reinstall — and the same primary (overwrite) tone, with the list namingevery plugin the batch would rewrite. Confirm-first is the point of the button: it@@ -592,15 +745,336 @@ export function PluginsPage() {);}+/** One row of the page: a library plugin (skills / hooks, installed per Agent) or a module plugin (listed per Project). */+type PluginRow = { kind: "library"; plugin: PluginItem; category: string } | ModulePluginRow;+interface ModulePluginRow {+ kind: "module";+ specifier: string;+ entry: PluginIndexEntry | undefined;+ state: ModuleState;+ /** Why the process could not load it, when `state` is `failed`. */+ error?: string;+ shipped: boolean;+}+/**+ * What a listed module plugin is here: running; waiting for a runtime that can re-assemble+ * (`pending`); or FAILED — the process tried and could not load it, for the reason the+ * server sends, which no restart would change.+ */+type ModuleState = "none" | "pending" | "active" | "failed";++/**+ * What is installed, in one list: the library's plugins — they ship with the build, so+ * every Agent may use them, and the category their group gave them rides along as a tag —+ * followed by the module plugins this Project asks for, each with its registry entry+ * (description, version, categories) when the registry has one.+ */+export function installedPluginRows(+ groups: readonly PluginGroupItem[],+ locale: Parameters<typeof localizedText>[0],+ deployment: InstalledPluginsResponse | null,+ index: readonly PluginIndexEntry[],+): PluginRow[] {+ const rows: PluginRow[] = [];+ for (const group of groups) {+ const category = localizedText(locale, group.title, group.titleZh);+ for (const plugin of group.plugins) rows.push({ kind: "library", plugin, category });+ }+ for (const listed of deployment?.plugins ?? []) {+ rows.push({+ kind: "module",+ specifier: listed.specifier,+ entry: index.find((e) => e.name === listed.specifier),+ state: listed.active ? "active" : listed.error !== undefined ? "failed" : "pending",+ ...(listed.error !== undefined ? { error: listed.error } : {}),+ shipped: listed.builtin || deployment?.shipped.includes(listed.specifier) === true,+ });+ }+ return rows;+}++/**+ * What could be asked for: the registry's entries this Project does not list yet, and what+ * the build ships that the registry does not know (offered with no description — the build+ * has it, so it is installable without a download).+ */+export function availablePluginRows(+ deployment: InstalledPluginsResponse | null,+ index: readonly PluginIndexEntry[],+): ModulePluginRow[] {+ const listed = new Set((deployment?.plugins ?? []).map((p) => p.specifier));+ const seen = new Set<string>();+ const rows: ModulePluginRow[] = [];+ for (const entry of index) {+ if (listed.has(entry.name) || seen.has(entry.name)) continue;+ seen.add(entry.name);+ rows.push({+ kind: "module",+ specifier: entry.name,+ entry,+ state: "none",+ shipped: deployment?.shipped.includes(entry.name) === true,+ });+ }+ for (const name of deployment?.shipped ?? []) {+ if (listed.has(name) || seen.has(name)) continue;+ seen.add(name);+ rows.push({ kind: "module", specifier: name, entry: undefined, state: "none", shipped: true });+ }+ return rows;+}++/**+ * A titled list of rows: the header bar the library's groups had — the whole row toggles+ * the fold, as on the model page — with one column of cards under it.+ */+function PluginList({+ title,+ open,+ onToggle,+ children,+}: {+ title: string;+ open: boolean;+ onToggle: () => void;+ children: React.ReactNode;+}) {+ return (+ <section className="overflow-hidden rounded-md bg-white dark:bg-gray-900">+ <button+ type="button"+ aria-expanded={open}+ onClick={onToggle}+ className="flex w-full items-center gap-2.5 bg-gray-50 px-3 py-2.5 text-left transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900/60 dark:hover:bg-gray-800/60"+ >+ <span className="min-w-0 truncate text-sm font-semibold">{title}</span>+ <span className="min-w-0 flex-1" />+ <Chevron open={open} className="text-gray-400" />+ </button>+ <div+ className={`grid transition-[grid-template-rows] duration-200 ease-out ${open ? "grid-rows-[1fr]" : "grid-rows-[0fr]"}`}+ >+ <div className="overflow-hidden" inert={!open}>+ <div+ className={`grid grid-cols-1 gap-2.5 p-2.5 transition-opacity duration-200 ${open ? "opacity-100" : "opacity-0"}`}+ >+ {children}+ </div>+ </div>+ </div>+ </section>+ );+}++/** What a plugin carries: the payload kinds a row is filtered by. */+export type PluginKind = "skills" | "hooks" | "modules";+/** What a plugin is for this deployment. */+export type PluginState = "installed" | "available" | "running" | "restart" | "failed";+export const PLUGIN_KINDS: readonly PluginKind[] = ["skills", "hooks", "modules"];+export const PLUGIN_STATES: readonly PluginState[] = [+ "installed",+ "available",+ "running",+ "restart",+ "failed",+];++/** The category a row belongs to, what it carries and what it is here — the three facets the filter column offers. */+export function rowFacets(row: PluginRow): {+ categories: string[];+ kinds: PluginKind[];+ states: PluginState[];+} {+ if (row.kind === "library") {+ const kinds: PluginKind[] = [];+ if (row.plugin.skills.length > 0) kinds.push("skills");+ if (row.plugin.hooks.length > 0) kinds.push("hooks");+ return { categories: [row.category], kinds, states: ["installed"] };+ }+ const states: PluginState[] =+ row.state === "active"+ ? ["installed", "running"]+ : row.state === "pending"+ ? ["installed", "restart"]+ : row.state === "failed"+ ? ["installed", "failed"]+ : ["available"];+ return { categories: row.entry?.categories ?? [], kinds: ["modules"], states };+}++export interface PluginFacets {+ /** Every category on the page, each once, in first-seen order, with how many rows carry it. */+ categories: { value: string; count: number }[];+ kinds: { value: PluginKind; count: number }[];+ states: { value: PluginState; count: number }[];+}+export interface PickedFacets {+ categories: ReadonlySet<string>;+ kinds: ReadonlySet<PluginKind>;+ states: ReadonlySet<PluginState>;+}++export function pluginFacets(rows: readonly PluginRow[]): PluginFacets {+ const categories = new Map<string, number>();+ const kinds = new Map<PluginKind, number>(PLUGIN_KINDS.map((k) => [k, 0]));+ const states = new Map<PluginState, number>(PLUGIN_STATES.map((st) => [st, 0]));+ for (const row of rows) {+ const f = rowFacets(row);+ for (const c of f.categories) categories.set(c, (categories.get(c) ?? 0) + 1);+ for (const k of f.kinds) kinds.set(k, (kinds.get(k) ?? 0) + 1);+ for (const st of f.states) states.set(st, (states.get(st) ?? 0) + 1);+ }+ const list = <T,>(m: Map<T, number>) =>+ [...m].filter(([, count]) => count > 0).map(([value, count]) => ({ value, count }));+ return { categories: list(categories), kinds: list(kinds), states: list(states) };+}++/**+ * Whether a row survives the search box and the filter column: text anywhere in its name,+ * description or keywords; within a facet any picked value matches, across facets all must.+ */+export function rowMatches(row: PluginRow, query: string, picked: PickedFacets): boolean {+ const f = rowFacets(row);+ if (picked.categories.size > 0 && !f.categories.some((c) => picked.categories.has(c)))+ return false;+ if (picked.kinds.size > 0 && !f.kinds.some((k) => picked.kinds.has(k))) return false;+ if (picked.states.size > 0 && !f.states.some((st) => picked.states.has(st))) return false;+ const q = query.trim().toLowerCase();+ if (q === "") return true;+ const text =+ row.kind === "library"+ ? `${row.plugin.name} ${row.plugin.description} ${row.plugin.descriptionZh ?? ""} ${row.plugin.shortDescription ?? ""} ${row.plugin.shortDescriptionZh ?? ""}`+ : `${row.specifier} ${row.entry?.description ?? ""} ${(row.entry?.keywords ?? []).join(" ")}`;+ return text.toLowerCase().includes(q);+}++/**+ * The filter column: three groups, each a vertical list of options with its count — the+ * marketplace sidebar shape. A picked option is filled and carries a check; the heading+ * offers Clear while anything is picked.+ */+function PluginFilters({+ facets,+ picked,+ onCategory,+ onKind,+ onState,+ onClear,+}: {+ facets: PluginFacets;+ picked: PickedFacets;+ onCategory: (category: string) => void;+ onKind: (kind: PluginKind) => void;+ onState: (state: PluginState) => void;+ onClear: () => void;+}) {+ const option = (key: string, label: string, count: number, on: boolean, onClick: () => void) => (+ <button+ key={key}+ type="button"+ aria-pressed={on}+ onClick={onClick}+ className={`flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-[13px] transition-colors duration-150 ${+ on+ ? "bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-700/70 dark:text-gray-100"+ : "text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800/70"+ }`}+ >+ <span+ className={`flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-sm border ${+ on+ ? "border-gray-800 bg-gray-800 text-white dark:border-gray-100 dark:bg-gray-100 dark:text-gray-900"+ : "border-gray-300 dark:border-gray-600"+ }`}+ >+ {on && <GlyphIcon d="M20 6 9 17l-5-5" size={10} />}+ </span>+ <span className="min-w-0 flex-1 truncate">{label}</span>+ <span className="shrink-0 font-mono text-[11px] text-gray-400 dark:text-gray-500">+ {count}+ </span>+ </button>+ );+ const group = (title: string, children: React.ReactNode) => (+ <div>+ <div className="mb-1 px-2 text-[11px] font-semibold tracking-wide text-gray-400 uppercase dark:text-gray-500">+ {title}+ </div>+ <div className="space-y-0.5">{children}</div>+ </div>+ );+ const active = picked.categories.size > 0 || picked.kinds.size > 0 || picked.states.size > 0;+ return (+ <aside className="mt-3 space-y-4 md:mt-0 md:sticky md:top-0 md:self-start">+ {/* Always in the flow, hidden until a pick is made: appearing and vanishing would shift+ every option below by a line at the moment of the click. */}+ <button+ type="button"+ onClick={onClear}+ tabIndex={active ? 0 : -1}+ aria-hidden={!active}+ className={`px-2 text-[11px] text-gray-400 underline-offset-2 hover:underline dark:text-gray-500 ${active ? "" : "invisible"}`}+ >+ {S.plugins.filterClear}+ </button>+ {group(+ S.plugins.filterCategories,+ facets.categories.map(({ value, count }) =>+ option(value, value, count, picked.categories.has(value), () => onCategory(value)),+ ),+ )}+ {group(+ S.plugins.filterKind,+ facets.kinds.map(({ value, count }) =>+ option(value, S.plugins.kindLabel[value], count, picked.kinds.has(value), () =>+ onKind(value),+ ),+ ),+ )}+ {group(+ S.plugins.filterState,+ facets.states.map(({ value, count }) =>+ option(value, S.plugins.stateLabel[value], count, picked.states.has(value), () =>+ onState(value),+ ),+ ),+ )}+ </aside>+ );+}++/** One tag on a row's tag line: a category, "built in", a license, a keyword. */+function Tag({+ children,+ mono,+ title,+}: {+ children: React.ReactNode;+ mono?: boolean;+ title?: string;+}) {+ return (+ <span+ title={title}+ className={`rounded-full bg-gray-100 px-2 py-0.5 dark:bg-gray-800 ${mono ? "font-mono text-gray-500 dark:text-gray-400" : "font-medium text-gray-600 dark:text-gray-300"}`}+ >+ {children}+ </span>+ );+}+/** A single plugin card: metadata display (contents badges + a semantic metadata line) + update reminder + quick start + "manage installs" Modal. */function PluginCard({plugin,+ category,installed,onQuickInvoke,onToggleInstall,onUpdateOutdated,}: {plugin: PluginItem;+ /** The library's category, shown as the row's first tag (the page has no groups). */+ category: string;installed: InstalledMap;onQuickInvoke: (skillName: string) => void;onToggleInstall: (agentId: string, plugin: PluginItem, on: boolean) => Promise<void>;@@ -664,7 +1138,7 @@ function PluginCard({.filter((v): v is string => v !== null).join(" · ");return (- <div className="flex h-full items-center gap-3 rounded-md p-4 transition-colors hover:bg-gray-100/70 dark:hover:bg-gray-800/60">+ <div className="flex items-center gap-3 rounded-md p-4 transition-colors hover:bg-gray-100/70 dark:hover:bg-gray-800/60"><buttontype="button"onClick={() => setDetailOpen(true)}@@ -702,6 +1176,13 @@ function PluginCard({<p className="mt-2.5 truncate text-[11px] text-gray-400 dark:text-gray-500" title={meta}>{meta}</p>+ {/* Tag line: the category, "built in" (the library ships with the build), what it carries. */}+ <div className="mt-2 flex flex-wrap items-center gap-1.5 text-[11px]">+ <Tag>{category}</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></button>{detailOpen && (<PluginDetailModal plugin={plugin} meta={meta} onClose={() => setDetailOpen(false)} />@@ -907,3 +1388,165 @@ function InstallRow({</div>);}++/**+ * A module plugin as a row in the library card's shape: the icon tile, the specifier and+ * version, the description, a metadata line saying what the deployment's own state is (not+ * installed → nothing yet; installed but not loaded → the restart it waits for; running → the+ * modules it holds), then the tag line — its categories, "built in" when this build ships+ * it, the license, the keywords. The trailing cluster is the verb: Install on an available+ * row, Remove on an installed one. The row is a link to the registry page when the registry+ * knows the package; the cluster sits BESIDE that link — a button inside an anchor is invalid+ * markup, and the click would have two meanings.+ */+function ModuleRow({+ specifier,+ entry,+ state,+ error,+ shipped,+ busy,+ blocked,+ onInstall,+ onRemove,+}: {+ specifier: string;+ entry: PluginIndexEntry | undefined;+ state: ModuleState;+ /** Why it failed to load, when it did. */+ error?: string;+ /** The build carries this one: installing it copies nothing over the network. */+ shipped: boolean;+ /** This row's own install or removal is running. */+ busy: boolean;+ /** Another row's is: one at a time, so the rest are held rather than queued. */+ blocked: boolean;+ onInstall: (() => void) | null;+ onRemove: (() => void) | null;+}) {+ const { locale } = useLocale();+ const stateText =+ state === "active"+ ? S.plugins.stateActive+ : state === "pending"+ ? S.plugins.installedRestart+ : state === "failed"+ ? S.plugins.stateFailed+ : S.plugins.notInstalled;+ // Metadata line, the library card's shape: version · updated · what it is here.+ const updated =+ entry?.updatedAt === undefined+ ? null+ : formatRelativeDate(new Date(entry.updatedAt * 1000).toISOString().slice(0, 10), locale);+ const meta = [entry === undefined ? null : `v${entry.version}`, updated]+ .filter((v): v is string => v !== null)+ .join(" · ");+ const body = (+ <>+ <div className="flex items-center gap-3">+ <SkillTile name={specifier} fallback={PLUGIN_ICON} size={36} glyph={20} />+ <div className="min-w-0 flex-1">+ <div className="flex items-baseline gap-2">+ <span+ className="min-w-0 truncate font-mono text-[13px] font-semibold"+ title={`${S.pluginRegistry.specifierHint}: ${specifier}`}+ >+ {specifier}+ </span>+ </div>+ <p+ className="mt-0.5 truncate text-xs leading-5 text-gray-500 dark:text-gray-400"+ title={entry?.description}+ >+ {entry?.description ?? S.plugins.shippedNoEntry}+ </p>+ </div>+ </div>+ <p+ className="mt-2.5 truncate text-[11px] text-gray-400 dark:text-gray-500"+ title={`${meta}${meta === "" ? "" : " · "}${stateText}`}+ >+ {meta !== "" && <span>{meta} · </span>}+ <span+ className={+ state === "active"+ ? toneInk.success+ : state === "pending"+ ? toneInk.attention+ : state === "failed"+ ? toneInk.danger+ : undefined+ }+ >+ {stateText}+ </span>+ </p>+ {state === "failed" && error !== undefined && (+ <p className={`mt-1 truncate text-[11px] ${toneInk.danger}`} title={error}>+ {error}+ </p>+ )}+ <div className="mt-2 flex flex-wrap items-center gap-1.5 text-[11px]">+ {(entry?.categories ?? []).map((category) => (+ <Tag key={category}>{category}</Tag>+ ))}+ {shipped && <Tag title={S.plugins.builtinHint}>{S.plugins.builtin}</Tag>}+ {(entry?.keywords ?? []).map((keyword) => (+ <Tag key={keyword} mono>+ {keyword}+ </Tag>+ ))}+ </div>+ </>+ );+ return (+ <div className="flex items-center gap-3 rounded-md p-4 transition-colors hover:bg-gray-100/70 dark:hover:bg-gray-800/60">+ {entry !== undefined ? (+ <Link to={`/plugins/registry/${specifier}`} className="min-w-0 flex-1">+ {body}+ </Link>+ ) : (+ <div className="min-w-0 flex-1">{body}</div>+ )}+ {/* The verb, in the library card's shape: one square light icon button, its copy in+ aria-label and title. While it runs, a spinner stands in for the glyph. */}+ <div className="flex shrink-0 items-center justify-center gap-1.5">+ {state === "none"+ ? onInstall !== null && (+ <Button+ size="sm"+ className="h-8 w-8 shrink-0 justify-center p-0"+ aria-label={`${busy ? S.plugins.installing : S.plugins.install} ${specifier}`}+ aria-busy={busy}+ title={busy ? S.plugins.installing : S.plugins.install}+ disabled={busy || blocked}+ onClick={onInstall}+ >+ {busy ? (+ <StatusIcon state="running" size={ICON_SIZE.iconButton} />+ ) : (+ <GlyphIcon d={INSTALL_ICON} size={ICON_SIZE.iconButton} />+ )}+ </Button>+ )+ : onRemove !== null && (+ <Button+ size="sm"+ className="h-8 w-8 shrink-0 justify-center p-0"+ aria-label={`${S.plugins.uninstall} ${specifier}`}+ aria-busy={busy}+ title={S.plugins.uninstall}+ disabled={busy || blocked}+ onClick={onRemove}+ >+ {busy ? (+ <StatusIcon state="running" size={ICON_SIZE.iconButton} />+ ) : (+ <GlyphIcon d={TRASH_ICON} size={ICON_SIZE.iconButton} />+ )}+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 4f947caf..d6feac45 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -14,9 +14,9 @@ export const en: Strings = {chat: "Chat",newChat: "New chat",agents: "Agents",- plugins: "Plugin library",models: "Models",machines: "Machines",+ plugins: "Plugins",usage: "Cost Center",traces: "Trajectories",benchmark: "Evaluation Center",@@ -185,7 +185,6 @@ export const en: Strings = {tls: "TLS handshake failed",network: "Unreachable",},- /** Admin-only sub-page (server-global). */uploadLimitsTitle: "Upload limits",/** Its two number fields, both in whole MB. */attachmentMaxMb: "Max attachment size (MB)",@@ -1527,9 +1526,55 @@ export const en: Strings = {/** Plugin library page (features/plugins/plugins-page.tsx): one card per library plugin, installed on agents as a whole. */plugins: {- pageTitle: "Plugin library",+ installedTitle: "Installed plugins",+ installedDesc:+ "What this Project asks for, and which of those this process is running. A change applies without a restart where the server can re-assemble itself; re-assembling stops the agent runs in progress in every Project.",+ installedEmpty: "No plugins installed yet.",+ stateActive: "running",+ builtin: "built in",+ builtinHint:+ "Ships with this build: installing it downloads nothing, and it loads only once you install it.",+ installedRestart: "restart to load",+ stateFailed: "failed to load",+ replacesLabel: "replaces",+ restartPending:+ "A listed plugin is not running and this server could not apply it without a restart: restart the server to load it.",+ uninstall: "Remove",+ install: "Install",+ installing: "Installing…",+ /** The Project-level install: the plugin is listed, and running unless the row says otherwise. */+ deploymentInstalledToast: (name: string) => `Installed ${name}`,+ /** Listed, but the process could not load it: the reason, not a success. */+ deploymentFailedToast: (name: string, reason: string) => `${name} failed to load: ${reason}`,+ applyConfirmInstall: (name: string) => `Install ${name}?`,+ applyConfirmRemove: (name: string) => `Remove ${name}?`,+ applyConfirmBody: "Agent runs in progress in every Project will be stopped.",+ pageTitle: "Plugins",pageDesc:- "Built-in plugin library: each plugin ships skills and/or a hook package — browse, quick-start a chat, or install to agents.",+ "Every plugin in one list. The library's plugins ship with this build (skills and/or a hook package — quick-start a chat, or install to agents); the module plugins this Project asks for run in the server, and the rest of the registry can be installed for it.",+ /** The list's header: how many plugins are installed — the library's (shipped, every Agent may use them) plus the module plugins this Project lists. */+ installedSection: (n: number): string => `Installed plugins (${n})`,+ /** The second list: registry entries this Project does not ask for yet. */+ availableSection: (n: number): string => `Available (${n})`,+ notInstalled: "not installed",+ /** The filter column beside the lists, and the empty result. */+ filterCategories: "Categories",+ filterKind: "Contains",+ filterState: "Status",+ filterClear: "Clear filters",+ kindLabel: { skills: "Skills", hooks: "Hooks", modules: "Modules" },+ stateLabel: {+ installed: "Installed",+ available: "Available",+ running: "Running",+ restart: "Restart to load",+ failed: "Failed to load",+ },+ noMatch: "No plugin matches that.",+ /** The description of a shipped package the registry has no entry for. */+ shippedNoEntry: "Ships with this build; the registry has no entry for it yet.",+ /** The "built in" tag on a library plugin: it ships with the build and needs no download. */+ libraryBuiltinHint: "Ships with this build; install it to an agent to use it there.",pluginCount: (n: number): string => (n === 1 ? "1 plugin" : `${n} plugins`),searchPlaceholder: "Search plugins",/** Section labels of the plugin detail Modal. */@@ -1612,6 +1657,23 @@ export const en: Strings = {},},+ pluginRegistry: {+ pageTitle: "Plugins",+ empty: "No plugins yet",+ specifierHint: "Package name, as a Project's plugin list names it",+ back: "Back to Plugins",+ readme: "Documentation",+ noReadme: "This plugin has no documentation yet.",+ notFound: "No such plugin.",+ repository: "Repository",+ homepage: "Homepage",+ authors: "Authors",+ license: "License",+ copySpecifier: "Copy specifier",+ installHint:+ "Install from the Plugins page: the row's Install button asks the current Project for it.",+ },+skills: {quickInvoke: "Quick start",quickInvokeText: (name: string): string => `use the ${name} skill`,diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 58f1e4c7..9c5f4818 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -18,9 +18,9 @@ export const zh = {chat: "对话",newChat: "新对话",agents: "智能体",- plugins: "插件库",models: "模型库",machines: "机器",+ plugins: "插件市场",usage: "成本中心",traces: "轨迹观测",benchmark: "评估中心",@@ -202,7 +202,6 @@ export const zh = {tls: "TLS 握手失败",network: "无法连接",},- /** Admin-only sub-page (server-global). */uploadLimitsTitle: "上传限制",/** Its two number fields, both in whole MB. */attachmentMaxMb: "单个附件上限(MB)",@@ -1525,8 +1524,53 @@ export const zh = {/** Plugin library page (features/plugins/plugins-page.tsx): one card per library plugin, installed on Agents as a whole. */plugins: {- pageTitle: "插件库",- pageDesc: "内置插件库:每个插件带有技能和/或钩子包,可浏览、快捷调用,或安装到 Agent。",+ installedTitle: "已安装的插件",+ installedDesc:+ "当前 Project 要求的插件,以及其中哪些正在被本进程运行。服务器能自行重组时,改动无需重启即可生效;重组会中止所有 Project 正在进行的 Agent 运行。",+ installedEmpty: "还没有安装任何插件。",+ stateActive: "运行中",+ builtin: "内置",+ builtinHint: "随本次构建自带:安装它不需要下载,但仍需你点安装才会加载。",+ installedRestart: "待重启",+ stateFailed: "加载失败",+ replacesLabel: "替换",+ restartPending: "有已列出但未运行的插件,且本服务器无法免重启应用:重启服务器后加载。",+ uninstall: "移除",+ install: "安装",+ installing: "安装中…",+ /** The Project-level install: the plugin is listed, and running unless the row says otherwise. */+ deploymentInstalledToast: (name: string) => `已安装 ${name}`,+ /** Listed, but the process could not load it: the reason, not a success. */+ deploymentFailedToast: (name: string, reason: string) => `${name} 加载失败:${reason}`,+ applyConfirmInstall: (name: string) => `安装 ${name}?`,+ applyConfirmRemove: (name: string) => `移除 ${name}?`,+ applyConfirmBody: "所有 Project 中正在进行的 Agent 运行都会被中止。",+ pageTitle: "插件",+ pageDesc:+ "所有插件在一个列表里。插件库里的随本次构建自带(技能和/或钩子包——快捷调用,或安装到 Agent);当前 Project 要求的模块插件在服务端运行,市场里其余的可以为它安装。",+ /** The list's header: how many plugins are installed — the library's (shipped, every Agent may use them) plus the module plugins this Project lists. */+ installedSection: (n: number): string => `已安装的插件 (${n})`,+ /** The second list: registry entries this Project does not ask for yet. */+ availableSection: (n: number): string => `可安装 (${n})`,+ notInstalled: "未安装",+ /** The filter column beside the lists, and the empty result. */+ filterCategories: "分类",+ filterKind: "包含",+ filterState: "状态",+ filterClear: "清除筛选",+ kindLabel: { skills: "技能", hooks: "钩子", modules: "模块" },+ stateLabel: {+ installed: "已安装",+ available: "可安装",+ running: "运行中",+ restart: "待重启",+ failed: "加载失败",+ },+ noMatch: "没有匹配的插件。",+ /** The description of a shipped package the registry has no entry for. */+ shippedNoEntry: "随本次构建自带;市场里还没有它的条目。",+ /** The "built in" tag on a library plugin: it ships with the build and needs no download. */+ libraryBuiltinHint: "随本次构建自带;安装到 Agent 即可在那里使用。",/** Plugin count in the group header (small text to the right of the category name). */pluginCount: (n: number): string => `${n} 个插件`,/** Search box of the create dialog's plugin picker. */@@ -1609,6 +1653,23 @@ export const zh = {},},+ pluginRegistry: {+ pageTitle: "插件市场",+ empty: "暂无插件",+ /** Card metadata: the entry's package specifier doubles as the install string. */+ specifierHint: "包名,即 Project 插件列表里写的那串",+ back: "返回插件市场",+ readme: "说明文档",+ noReadme: "该插件暂无说明文档。",+ notFound: "找不到这个插件。",+ repository: "源码仓库",+ homepage: "主页",+ authors: "作者",+ license: "许可证",+ copySpecifier: "复制包名",+ installHint: "在插件市场页安装:该行的「安装」按钮会为当前 Project 要求它。",+ },+skills: {quickInvoke: "快捷调用",/** Pre-filled body for quick invoke (per UI language; English is `use the <name> skill`). */diff --git a/packages/web/src/module.json b/packages/web/src/module.jsonindex 69ead2fe..2d54b9aa 100644--- a/packages/web/src/module.json+++ b/packages/web/src/module.json@@ -49,6 +49,17 @@"builtin": "PluginsPage"}},+ {+ "id": "web.pages.plugin-detail",+ "key": "plugin-detail",+ "path": "/plugins/registry/*",+ "nav": "none",+ "admin": false,+ "released": true,+ "renderer": {+ "builtin": "PluginDetailPage"+ }+ },{"id": "web.models","key": "models",diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsxindex e66eeb9e..468379ee 100644--- a/packages/web/src/router.tsx+++ b/packages/web/src/router.tsx@@ -15,6 +15,7 @@ import { AgentsPage } from "./features/agents/agents-page";import { AgentSettingsPage } from "./features/agents/agent-settings-page";import { PluginsPage } from "./features/plugins/plugins-page";import { ModelsPage } from "./features/models/models-page";+import { PluginDetailPage } from "./features/plugins/plugin-detail-page";import { UsagePage } from "./features/usage/usage-page";import { BenchmarkPage } from "./features/benchmark/benchmark-page";import { BenchmarkDetailPage } from "./features/benchmark/benchmark-detail-page";@@ -41,6 +42,7 @@ const BUILTIN_PAGES: Record<string, React.ComponentType> = {AgentSettingsPage,PluginsPage,ModelsPage,+ PluginDetailPage,MachinesPage,UsagePage,BenchmarkPage,diff --git a/packages/web/test/nav-group-collapse.test.ts b/packages/web/test/nav-group-collapse.test.tsindex d6b9dd1b..a5b1ecbe 100644--- a/packages/web/test/nav-group-collapse.test.ts+++ b/packages/web/test/nav-group-collapse.test.ts@@ -74,7 +74,8 @@ describe("navKeysFor", () => {// keys), so offering a member the row would only ever produce a 403.expect([...navKeysFor(false)]).toEqual(["agents", "plugins", "models", "usage", "benchmark"]);// An admin sees the manifest minus what is built but not yet offered — `machines` today,- // which is why neither answer contains it and the two are equal for now.+ // which is why neither answer contains it and the two are equal for now. The Plugins page+ // carries the built-in library and the deployment's registry both, under one key.expect([...navKeysFor(true)]).toEqual(["agents", "plugins", "models", "usage", "benchmark"]);expect(NAV_GROUP_KEYS as readonly string[]).toContain("machines");});diff --git a/plugins/sandbox-bwrap/README.md b/plugins/sandbox-bwrap/README.mdindex 8951ac8b..86e3c4dc 100644--- a/plugins/sandbox-bwrap/README.md+++ b/plugins/sandbox-bwrap/README.md@@ -29,11 +29,13 @@ than restrict it.## Install-Add the specifier to your deployment's `plugins.json` and restart, or push a platform that-carries it:+It ships with the harness build. On the Plugins page, install it to the Project that should+run it: the App re-assembles itself, no restart. Written by hand, it is a row of the Project's+`.project_config.toml`:-```json-{ "plugins": ["@prismshadow/penguin-plugin-sandbox-bwrap"] }+```toml+[plugins]+"@prismshadow/penguin-plugin-sandbox-bwrap" = "*"```Installing is an operator-side action: the harness resolves the package from the installation,diff --git a/plugins/sandbox-bwrap/src/index.ts b/plugins/sandbox-bwrap/src/index.tsindex e7bd0b3e..29192e88 100644--- a/plugins/sandbox-bwrap/src/index.ts+++ b/plugins/sandbox-bwrap/src/index.ts@@ -1,8 +1,8 @@/*** @prismshadow/penguin-plugin-sandbox-bwrap — a bubblewrap sandbox backend.*- * A PLUGIN PACKAGE, not part of the platform: a deployment lists it in plugins.json and- * the harness resolves it from the installation (see the server's plugin/loader.ts).+ * A PLUGIN PACKAGE, not part of the platform: a Project asks for it on the Plugins page+ * and the harness resolves it from the installation (see the server's plugin/loader.ts).* It compiles against the `@prismshadow/penguin-core/plugin` surface (types, plus the* decorators its bundle carries) and has no runtime dependency on the harness — and* none on the DSH ecosystem either:diff --git a/plugins/sandbox-dsh/README.md b/plugins/sandbox-dsh/README.mdindex 680bb5ac..d5542d64 100644--- a/plugins/sandbox-dsh/README.md+++ b/plugins/sandbox-dsh/README.md@@ -34,11 +34,13 @@ instead of failing the whole platform bundle's import.## Install-Add the specifier to your deployment's `plugins.json` and restart, or push a platform that-carries it:+It ships with the harness build. On the Plugins page, install it to the Project that should+run it: the App re-assembles itself, no restart. Written by hand, it is a row of the Project's+`.project_config.toml`:-```json-{ "plugins": ["@prismshadow/penguin-plugin-sandbox-dsh"] }+```toml+[plugins]+"@prismshadow/penguin-plugin-sandbox-dsh" = "*"```Installing is an operator-side action: the harness resolves the package from the installation,diff --git a/plugins/sandbox-dsh/src/index.ts b/plugins/sandbox-dsh/src/index.tsindex 27dfab21..59008dee 100644--- a/plugins/sandbox-dsh/src/index.ts+++ b/plugins/sandbox-dsh/src/index.ts@@ -2,8 +2,8 @@* @prismshadow/penguin-plugin-sandbox-dsh — the DeepSeek Harness sandbox ecosystem* behind this harness's own sandbox interface.*- * A PLUGIN PACKAGE, not part of the platform: a deployment lists it in plugins.json and- * the harness resolves it from the installation (see the server's plugin/loader.ts).+ * A PLUGIN PACKAGE, not part of the platform: a Project asks for it on the Plugins page+ * and the harness resolves it from the installation (see the server's plugin/loader.ts).* The DSH dependencies live HERE, in this package — the harness itself does not depend* on them, which is what "plugins are configuration, not built-in capability" means in* dependency terms.diff --git a/plugins/sandbox-mxc/README.md b/plugins/sandbox-mxc/README.mdindex a22860a4..0b7b3300 100644--- a/plugins/sandbox-mxc/README.md+++ b/plugins/sandbox-mxc/README.md@@ -34,11 +34,13 @@ and routing moves on.## Install-Add the specifier to your deployment's `plugins.json` and restart, or push a platform that-carries it:+It ships with the harness build. On the Plugins page, install it to the Project that should+run it: the App re-assembles itself, no restart. Written by hand, it is a row of the Project's+`.project_config.toml`:-```json-{ "plugins": ["@prismshadow/penguin-plugin-sandbox-mxc"] }+```toml+[plugins]+"@prismshadow/penguin-plugin-sandbox-mxc" = "*"```Installing is an operator-side action: the harness resolves the package from the installation,diff --git a/plugins/sandbox-mxc/src/index.ts b/plugins/sandbox-mxc/src/index.tsindex 2f9e0b44..33488c05 100644--- a/plugins/sandbox-mxc/src/index.ts+++ b/plugins/sandbox-mxc/src/index.ts@@ -2,8 +2,8 @@* @prismshadow/penguin-plugin-sandbox-mxc — a Windows sandbox backend over Microsoft* MXC (Microsoft eXecution Containers).*- * A PLUGIN PACKAGE, not part of the platform: a deployment lists it in plugins.json and- * the harness resolves it from the installation. It compiles against the+ * A PLUGIN PACKAGE, not part of the platform: a Project asks for it on the Plugins page+ * and the harness resolves it from the installation. It compiles against the* `@prismshadow/penguin-core/plugin` surface (types, plus the decorators its bundle* carries) and has no runtime dependency on the* harness or on any other backend.diff --git a/plugins/sandbox-seatbelt/README.md b/plugins/sandbox-seatbelt/README.mdindex 57ce5377..cc372489 100644--- a/plugins/sandbox-seatbelt/README.md+++ b/plugins/sandbox-seatbelt/README.md@@ -32,11 +32,13 @@ subpath rule silently matches nothing.## Install-Add the specifier to your deployment's `plugins.json` and restart, or push a platform that-carries it:+It ships with the harness build. On the Plugins page, install it to the Project that should+run it: the App re-assembles itself, no restart. Written by hand, it is a row of the Project's+`.project_config.toml`:-```json-{ "plugins": ["@prismshadow/penguin-plugin-sandbox-seatbelt"] }+```toml+[plugins]+"@prismshadow/penguin-plugin-sandbox-seatbelt" = "*"```Installing is an operator-side action: the harness resolves the package from the installation,diff --git a/plugins/sandbox-seatbelt/src/index.ts b/plugins/sandbox-seatbelt/src/index.tsindex 0a6aec0a..4139407e 100644--- a/plugins/sandbox-seatbelt/src/index.ts+++ b/plugins/sandbox-seatbelt/src/index.ts@@ -1,8 +1,8 @@/*** @prismshadow/penguin-plugin-sandbox-seatbelt — a macOS Seatbelt sandbox backend.*- * A PLUGIN PACKAGE, not part of the platform: a deployment lists it in plugins.json and- * the harness resolves it from the installation. It compiles against the+ * A PLUGIN PACKAGE, not part of the platform: a Project asks for it on the Plugins page+ * and the harness resolves it from the installation. It compiles against the* `@prismshadow/penguin-core/plugin` surface (types, plus the decorators its bundle* carries) and has no runtime dependency on the* harness or on any other backend.diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 0a12e057..012e2776 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -1,6 +1,6 @@packages:- "packages/*"- # Plugin packages a deployment installs and lists in plugins.json. They sit at the top+ # Plugin packages a Project asks for (the [plugins] table of its config). They sit at the top# level, outside packages/, because they are not part of the harness: nothing under# packages/ depends on one, and the platform bundle carries none of them — what ships# them is scripts/build-plugins.mjs, which packs each self-contained.diff --git a/scripts/build-plugins.mjs b/scripts/build-plugins.mjsnew file mode 100644index 00000000..785d6bd0--- /dev/null+++ b/scripts/build-plugins.mjs@@ -0,0 +1,214 @@+/**+ * The builtin plugins, shipped as the npm packages they are: every `plugins/*` package with+ * a code entry is built by its own `build` script, packed by `pnpm pack` — exactly what+ * `npm publish` would send — and installed by npm into a staging directory laid out as an npm+ * prefix (`<out>/package.json` + `<out>/node_modules/<name>/…`, dependencies included). That+ * prefix is the one shape both consumers resolve from: the hot push ships it under `plugins/`+ * in its assets, the desktop build stages it beside `skills/`.+ *+ * Nothing about a package is rewritten. Its `package.json`, its `exports`, its `dist/` and its+ * `README.md` reach the target as the package's own build produced them; a dependency it+ * declares is installed beside it the way npm installs it anywhere. The SDK's runtime is not+ * among those dependencies — a plugin compiles against `@prismshadow/penguin-core`'s types+ * (a devDependency) and shares the host's copy at run time.+ *+ * Cached by content: the hash over every plugin's `src/`, `package.json`, `README.md` and+ * `tsup.config.ts` names a directory under `node_modules/.cache/penguin-plugins/`, and an+ * unchanged set is not built, packed or installed again — a push of an unrelated change costs+ * nothing here. Installing needs the registry (for the dependencies) the first time only.+ *+ * Usage (a library for deploy.mjs / desktop build-assets.mjs, and a CLI):+ * node scripts/build-plugins.mjs --out <dir> stage the prefix into <dir>+ */+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import fs from "node:fs";+import fsp from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+const PLUGINS_SRC = path.join(ROOT, "plugins");+const CACHE = path.join(ROOT, "node_modules", ".cache", "penguin-plugins");+const COMPLETE = ".complete";+/** Folded into the cache key: bump when what this script WRITES changes, not only what it reads. */+const PACK_FORMAT = 4;+/** The prefix's own manifest: npm needs one above `node_modules`, and it is ours, never a package's. */+const PREFIX_MANIFEST = { name: "penguin-builtin-plugins", private: true, version: "0.0.0" };+/** What npm leaves in the prefix that is not a package: its hidden lockfile. Never shipped. */+const NOT_SHIPPED = new Set(["node_modules/.package-lock.json"]);++/** Files under `dir`, as sorted relative posix paths (symlinks — `.bin` shims — excluded). */+async function walk(dir, prefix = "") {+ const out = [];+ for (const e of await fsp.readdir(dir, { withFileTypes: true })) {+ const rel = prefix === "" ? e.name : `${prefix}/${e.name}`;+ if (e.isDirectory()) out.push(...(await walk(path.join(dir, e.name), rel)));+ else if (e.isFile()) out.push(rel);+ }+ return out.sort();+}++/** A package manager's command, as the platform names it. */+function command(name) {+ return process.platform === "win32" ? `${name}.cmd` : name;+}+// cmd.exe does not unquote spawn args by itself: under `shell: true` the args are joined+// into one command line, so a path with a space (the pack directory lives under the user's+// temp directory, i.e. their profile) splits into two. Quoted the way run-with-env.mjs quotes.+const quote = (a) => (/[\s"^&|<>;,()%!]/.test(a) ? `"${a.replace(/"/g, '\\"')}"` : a);+function run(name, args, cwd) {+ const windows = process.platform === "win32";+ try {+ execFileSync(command(name), windows ? args.map(quote) : args, {+ cwd,+ stdio: ["ignore", "pipe", "pipe"],+ shell: windows,+ env: process.env,+ });+ } catch (err) {+ const stderr = err instanceof Object && "stderr" in err ? String(err.stderr).trim() : "";+ throw new Error(`${name} ${args.slice(0, 3).join(" ")} failed in ${cwd}\n${stderr}`);+ }+}++/** What a plugin's pack depends on: its sources, its manifest, its README and its build config. */+async function sourceHash(dir, into) {+ for (const rel of ["package.json", "README.md", "tsup.config.ts"]) {+ const file = path.join(dir, rel);+ if (fs.existsSync(file))+ into+ .update(rel)+ .update("\0")+ .update(await fsp.readFile(file))+ .update("\0");+ }+ const src = path.join(dir, "src");+ if (fs.existsSync(src)) {+ for (const rel of await walk(src)) {+ into+ .update(`src/${rel}`)+ .update("\0")+ .update(await fsp.readFile(path.join(src, rel)))+ .update("\0");+ }+ }+}++/** Every plugin package under `plugins/`: a package.json that declares `penguin`. */+async function pluginPackages() {+ const out = [];+ const entries = fs.existsSync(PLUGINS_SRC) ? await fsp.readdir(PLUGINS_SRC) : [];+ for (const dirName of entries.sort()) {+ const dir = path.join(PLUGINS_SRC, dirName);+ const manifestFile = path.join(dir, "package.json");+ if (!fs.existsSync(manifestFile)) continue;+ const pkg = JSON.parse(await fsp.readFile(manifestFile, "utf8"));+ // A package with a code entry is built and packed; one without (skills, hooks) carries no code.+ if (pkg.main === undefined && pkg.exports === undefined) continue;+ out.push({ name: pkg.name, version: pkg.version, dir });+ }+ return out;+}++/**+ * Builds, packs and installs every builtin plugin into one staged prefix (from cache when+ * nothing changed) and returns `{ dir, files, plugins }`: the prefix directory, the relative+ * paths to ship, and `[{ name, version }]` of what it holds.+ */+export async function buildBuiltinPlugins({ log = () => {} } = {}) {+ const plugins = await pluginPackages();+ const h = createHash("sha256").update(`pack ${PACK_FORMAT}\0`);+ for (const plugin of plugins) {+ h.update(plugin.name).update("\0");+ await sourceHash(plugin.dir, h);+ }+ const hash = h.digest("hex").slice(0, 16);+ const out = path.join(CACHE, hash);+ if (fs.existsSync(path.join(out, COMPLETE))) {+ log(`${plugins.length} builtin plugins: cached (${hash})`);+ } else {+ await fsp.rm(out, { recursive: true, force: true });+ await fsp.mkdir(out, { recursive: true });+ const packed = await fsp.mkdtemp(path.join(os.tmpdir(), "penguin-plugins-pack-"));+ try {+ const tarballs = [];+ for (const plugin of plugins) {+ // The package's own build, then the package as npm would publish it (`files` honored,+ // `workspace:` ranges rewritten) — nothing this script decides.+ run("pnpm", ["--filter", plugin.name, "run", "build"], ROOT);+ run("pnpm", ["pack", "--pack-destination", packed], plugin.dir);+ const tarball = (await fsp.readdir(packed)).find(+ (f) => f.endsWith(".tgz") && !tarballs.some((t) => path.basename(t) === f),+ );+ if (tarball === undefined) throw new Error(`pnpm pack left no tarball for ${plugin.name}`);+ tarballs.push(path.join(packed, tarball));+ log(`plugin ${plugin.name}@${plugin.version}: packed`);+ }+ // The manifest names what is shipped — how the loader tells the plugins from what npm+ // installs beside them — and --no-save below keeps npm from rewriting it.+ const dependencies = Object.fromEntries(plugins.map((p) => [p.name, p.version]));+ await fsp.writeFile(+ path.join(out, "package.json"),+ `${JSON.stringify({ ...PREFIX_MANIFEST, dependencies }, null, 2)}\n`,+ );+ if (tarballs.length > 0) {+ // npm installs the packages and their dependencies into the prefix; --no-save keeps+ // the prefix's manifest ours (no `file:` paths into a temp directory), --omit=dev+ // leaves the SDK's types and the build tools behind.+ run(+ "npm",+ [+ "install",+ "--no-save",+ "--no-package-lock",+ "--omit=dev",+ "--no-audit",+ "--no-fund",+ "--ignore-scripts",+ "--",+ ...tarballs,+ ],+ out,+ );+ }+ await fsp.writeFile(path.join(out, COMPLETE), hash);+ log(`${plugins.length} builtin plugins: installed (${hash})`);+ } catch (err) {+ await fsp.rm(out, { recursive: true, force: true });+ throw err;+ } finally {+ await fsp.rm(packed, { recursive: true, force: true });+ }+ }+ const files = (await walk(out)).filter((f) => f !== COMPLETE && !NOT_SHIPPED.has(f));+ return { dir: out, files, plugins: plugins.map(({ name, version }) => ({ name, version })) };+}++/** The prefix as a file map, relative to the prefix, each value an absolute source path. */+export function prefixLayout(built) {+ return new Map(built.files.map((rel) => [rel, { path: path.join(built.dir, rel) }]));+}++/** Writes the prefix into `dest`, replacing what was there. */+export async function stagePrefix(built, dest) {+ await fsp.rm(dest, { recursive: true, force: true });+ for (const [rel, source] of prefixLayout(built)) {+ const target = path.join(dest, ...rel.split("/"));+ await fsp.mkdir(path.dirname(target), { recursive: true });+ await fsp.copyFile(source.path, target);+ }+}++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const outIdx = process.argv.indexOf("--out");+ const out = outIdx === -1 ? null : process.argv[outIdx + 1];+ const built = await buildBuiltinPlugins({ log: (m) => console.log(`[build-plugins] ${m}`) });+ if (out) {+ await stagePrefix(built, path.resolve(out));+ console.log(+ `[build-plugins] staged ${built.plugins.length} plugins (${built.files.length} files) into ${path.resolve(out)}`,+ );+ }+}diff --git a/scripts/deploy.mjs b/scripts/deploy.mjsindex 72c39960..00747e82 100644--- a/scripts/deploy.mjs+++ b/scripts/deploy.mjs@@ -30,6 +30,7 @@ import { unsafePlaintextTarget } from "./deploy-target-safety.mjs";import { buildGitDefine, checkoutFacts, originUrl } from "./build-git-stamp.mjs";import { ESM_CJS_BANNER } from "./esm-cjs-banner.mjs";import { FAR_SIDE_SCRIPTS } from "./far-side-scripts.mjs";+import { buildBuiltinPlugins, prefixLayout } from "./build-plugins.mjs";import { createHash } from "node:crypto";const require = createRequire(import.meta.url);@@ -245,6 +246,14 @@ async function readNativeAssets() {for (const { name, from } of FAR_SIDE_SCRIPTS) {files[name] = await fsp.readFile(path.join(ROOT, from));}+ // The builtin plugins, as the npm prefix the loader resolves from (`plugins/package.json`+ // + `plugins/node_modules/<name>/…`, see scripts/build-plugins.mjs): the packages as npm+ // publishes them, installed by npm, from cache when unchanged — so a push carries the+ // plugins of the revision it was built from.+ const built = await buildBuiltinPlugins({ log });+ for (const [rel, source] of prefixLayout(built)) {+ files[`plugins/${rel}`] = await fsp.readFile(source.path);+ }return { files, exec };}diff --git a/scripts/gen-ifaces.mjs b/scripts/gen-ifaces.mjsindex 43d6099a..04b52690 100644--- a/scripts/gen-ifaces.mjs+++ b/scripts/gen-ifaces.mjs@@ -105,6 +105,12 @@ const implementationDeps = [];const types = {};/** Module manifests, extracted STATICALLY from each module.ts's defineModule({...}) literal. */const manifests = {};+/**+ * What a PLUGIN package's default export names — `{ modules: [A, B], replaces: [C] }` —+ * read off the source, so a surface can say what a listed package adds without importing+ * it. Absent for a package that has no such default export (the harness itself).+ */+let pluginDecl = null;for (const project of projects) {const configPath = path.resolve(project);@@ -310,6 +316,65 @@ for (const project of projects) {if (kind === "component")componentKeyBySymbol.set(sym, `${moduleNameOf(node.getSourceFile().fileName)}#${className}`);}+ // The plugin declaration: `export default { modules: [...], replaces: [...] }`, or a+ // default-exported binding initialized to that literal (`const plugin: Plugin = {...}`).+ // Each element must be a module class of this package; anything else is refused.+ const unwrap = (e) =>+ ts.isSatisfiesExpression(e) || ts.isAsExpression(e) || ts.isParenthesizedExpression(e)+ ? unwrap(e.expression)+ : e;+ for (const sf of program.getSourceFiles()) {+ if (sf.isDeclarationFile || sf.fileName.includes("/node_modules/")) continue;+ for (const st of sf.statements) {+ if (!ts.isExportAssignment(st) || st.isExportEquals) continue;+ let literal = unwrap(st.expression);+ if (ts.isIdentifier(literal)) {+ const sym0 = checker.getSymbolAtLocation(literal);+ const sym =+ sym0 && sym0.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(sym0) : sym0;+ const decl = sym?.valueDeclaration;+ if (decl && ts.isVariableDeclaration(decl) && decl.initializer)+ literal = unwrap(decl.initializer);+ }+ if (!ts.isObjectLiteralExpression(literal)) continue;+ const lists = { modules: [], replaces: [] };+ let isPlugin = false;+ for (const prop of literal.properties) {+ const key =+ ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) ? prop.name.text : null;+ if (key !== "modules" && key !== "replaces") continue;+ isPlugin = true;+ const file = path.relative(process.cwd(), sf.fileName);+ const arr = unwrap(prop.initializer);+ if (!ts.isArrayLiteralExpression(arr)) {+ errors.push(+ `${file}: the default export's ${key} must be an array literal of module classes`,+ );+ continue;+ }+ for (const el of arr.elements) {+ const sym0 = ts.isIdentifier(el) ? checker.getSymbolAtLocation(el) : undefined;+ const sym =+ sym0 && sym0.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(sym0) : sym0;+ const name = sym === undefined ? undefined : moduleNameBySymbol.get(sym);+ if (name === undefined) {+ errors.push(+ `${file}: the default export's ${key} names '${el.getText()}', which is not a @Module or @Component class of this package`,+ );+ continue;+ }+ lists[key].push(name);+ }+ }+ if (!isPlugin) continue;+ if (pluginDecl !== null) {+ errors.push(+ `${path.relative(process.cwd(), sf.fileName)}: a second default export names modules — a package has one plugin declaration`,+ );+ }+ pluginDecl = lists;+ }+ }/** interfaces with methods, by symbol → key; filled as they are met so references resolve. */const keys = new Map();const pending = [];@@ -1099,7 +1164,12 @@ const sortKeys = (o) =>// The table's identity: a sha256 over its canonical content, so two builds can tell at// a glance whether they agree on every interface and manifest (the page CI publishes// carries it, and a pre-push check compares it). The hash is not part of what it hashes.-const body = { ifaces: sortKeys(table), types: sortKeys(types), modules: sortKeys(manifests) };+const body = {+ ifaces: sortKeys(table),+ types: sortKeys(types),+ modules: sortKeys(manifests),+ ...(pluginDecl === null ? {} : { plugin: pluginDecl }),+};const hash = createHash("sha256").update(JSON.stringify(body)).digest("hex");const text = `${JSON.stringify({ hash, ...body }, null, 1)}\n`;const existing = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : null;