A local-first multi-agent app development platform, built on PenguinHarness
feat: add confinement interface, with backends as plugins (#354)
Myriad-Dreaminb95c230ede98
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex ebd87c7a..e3bc004e 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -110,6 +110,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 |Responsibilities split by source of truth: the **SDK** owns protocol and execution(message parsing, the agent loop, tools), the **Server** owns the multi-user runtime@@ -170,7 +171,8 @@ pnpm test:e2e # core live-model e2e, needDocker Hub access token with read/write scope on that repository — and the Docker Hubrepository is created public on the first push.- **Release prep bumps the repo version**: the same `release: X.Y.Z` PR that renames- `changelog/unreleased/` also bumps the root and every `packages/*/package.json`+ `changelog/unreleased/` also bumps the root and every workspace `package.json`+ (`packages/*` and `plugins/*`)`version`, plus core's `VERSION` constant (`packages/core/src/index.ts`), to the releaseversion. The release workflow refuses a tag push whose version does not match therepo's, so a forgotten bump fails before anything is published (v0.2.1 was tagged with adiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex e8e853c6..a0b17f17 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -139,7 +139,8 @@ jobs:TAG="${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}"V="${TAG#v}"printf '%s\n' "$TAG" | grep -Eq '^v[0-9A-Za-z][0-9A-Za-z._-]*$'- # Guard: release prep must bump the repo to the tag's version (root + packages/*/package.json+ # Guard: release prep must bump the repo to the tag's version (root + every workspace+ # package.json — packages/* and plugins/* —# and core's VERSION constant move together in the release: X.Y.Z PR). v0.2.1 was tagged with# a 0.2.0 repo, so every dev/source build nagged about updates until the repo caught up —# fail the tag push instead. Manual dispatch (EVENT_NAME unset in replays) only warns,@@ -148,7 +149,7 @@ jobs:if [ -f package.json ]; thenPKG_V="$(node -p 'require("./package.json").version')"if [ "$PKG_V" != "$V" ]; then- MSG="tag $TAG does not match the repo version $PKG_V; bump root + packages/*/package.json + plugins/*/package.json and core VERSION during release prep, then re-tag (see .github/CONTRIBUTING.md)."+ MSG="tag $TAG does not match the repo version $PKG_V; bump root + every workspace package.json (packages/*, plugins/*) and core VERSION during release prep, then re-tag (see .github/CONTRIBUTING.md)."if [ "${EVENT_NAME:-}" = "push" ]; thenecho "error: $MSG" >&2exit 1@@ -566,7 +567,7 @@ jobs:if [ -f package.json ]; thenPKG_V="$(node -p 'require("./package.json").version')"if [ "$PKG_V" != "$V" ]; then- MSG="tag $TAG does not match the repo version $PKG_V; bump root + packages/*/package.json + plugins/*/package.json and core VERSION during release prep, then re-tag (see .github/CONTRIBUTING.md)."+ MSG="tag $TAG does not match the repo version $PKG_V; bump root + every workspace package.json (packages/*, plugins/*) and core VERSION during release prep, then re-tag (see .github/CONTRIBUTING.md)."if [ "${EVENT_NAME:-}" = "push" ]; thenecho "error: $MSG" >&2exit 1diff --git a/changelog/unreleased/2026-08-22-sandbox.md b/changelog/unreleased/2026-08-22-sandbox.mdnew file mode 100644index 00000000..ca7b4fc6--- /dev/null+++ b/changelog/unreleased/2026-08-22-sandbox.md@@ -0,0 +1,27 @@+# Command confinement, with backends as plugins++- **Date:** 2026-08-22+- **Type:** feature+- **Scope:** `core`, `server`, `plugins`, `docs`+- **PR:** [#354](https://github.com/Prism-Shadow/penguin-harness/pull/354)+- **Breaking:** yes — `extensions.json` is read no longer and both SDK subpaths moved to `/plugin`; the plugin contract is closed, so `context.terminals` needs a cast++[中文版](2026-08-22-sandbox.zh.md)++Shell commands an agent runs can now be confined. The harness gained its own sandbox interface — argv rewriting, honest enforcement reporting, fail-closed — naming three dimensions: `fs-write`, `network` and `mask-paths`. No backend is part of the harness: each is a plugin package a deployment installs and names in `plugins.json`, which is why this builds on the plugin mechanism — shipped in 0.2.8 as the [extension mechanism](../0.2.8/2026-08-22-extension-mechanism.md) and renamed here. A default deployment names none and confines nothing.++## Details++- **The seam is in core.** `confineSpawn` is threaded along the existing `proxyEnv` line and applied in `ManagedSession` immediately before spawn: it receives the exact argv, `cwd` and `workspaceDir`, and returns the argv to spawn instead. Mechanism only — it never interprets the argv.+- **Routing cannot silently drop a dimension.** A backend declares which dimensions it implements (declaring none means filesystem-only) and the service routes each policy to one that covers what it requires. A requirement nothing covers fails closed, naming what each mounted backend does cover. `confine` must return enforcing argv or throw; a throw aborts the spawn and surfaces as the command's spawn error, so a command never runs unconfined because a backend failed.+- **Four backends ship as packages:** `plugin-sandbox-dsh` (the portable DSH adaptor, file effects on all three platforms), plus `plugin-sandbox-bwrap` (Linux), `-seatbelt` (macOS) and `-mxc` (Windows, through Microsoft MXC's `processcontainer`) — the three native ones implementing all three dimensions. Each declares `Apache-2.0` and ships a `README.md` documenting what it actually enforces, down to bwrap's mount ordering and Seatbelt's rule precedence: a deployment chooses a backend by exactly that. With no backend inside the platform bundle, the bundle no longer inlines any native-adjacent module, and `deploy.mjs`'s runtime-resolved-natives shim is gone. Confinement settings ride the parked platform context, so a hot push cannot silently un-confine a deployment.+- **The plugin contract is closed, and owns the sandbox vocabulary.** `PenguinContext` and `PenguinInterface` name every member instead of being reopened by `declare module`: a plugin checking against the contract used to compile against members only one embedder supplies. `SandboxPolicy`, `SandboxProvider`, `ConfinedArgv` and the mode/dimension unions live in `@prismshadow/penguin-core/plugin` now, since a backend is written against those names and nothing else — while the helpers that read them stay in the server package, which keeps both plugin subpaths emitting types and nothing else. A backend therefore names core alone: all four dropped `@prismshadow/penguin-server` from their dependencies and can no longer resolve it, and the server's plugin subpath narrowed to the one member it owns, `HarnessContext`.+- **One word for the mechanism: plugin.** What 0.2.8 shipped as the extension mechanism is the plugin mechanism from here on, so a reader meets the same term wherever the concept appears. The config file is `<root>/plugins.json` with a `plugins` key; the SDK subpaths are `@prismshadow/penguin-core/plugin` and `@prismshadow/penguin-server/plugin`; the contract names `Plugin` / `PluginContext` / `PluginEvents`, and the harness `PluginHost`; the four backends are `@prismshadow/penguin-plugin-sandbox-*` under `plugins/`. `PenguinContext`, `PenguinInterface`, `HarnessContext` and the whole sandbox vocabulary keep their names. The word stays taken elsewhere and none of it moved: file extensions, remark/micromark syntax extensions, the composer's "+" extension menu, and the SDK's own "Extension seams". Nor is it cordis's `plugin` — the DSH adaptor mounts DSH's chain through cordis's `Context.plugin`, and the two vocabularies share nothing but the word.++## Compatibility++An `extensions.json` already on disk is **not read** and not migrated. A deployment that configured plugins under the old name keeps running with none of them loaded and their capability silently unavailable — for these sandbox backends, that means commands spawn unconfined. Rename the file to `plugins.json` and its `"extensions"` key to `"plugins"`; the specifiers inside change only where they name this repository's sandbox backends, whose packages are now `@prismshadow/penguin-plugin-sandbox-*`. A package compiled against `@prismshadow/penguin-core/extension` or `@prismshadow/penguin-server/extension` no longer resolves: point the import at `/plugin` and rename the three types it uses.++`terminals` is a harness class and cannot be in the contract. It is named on `HarnessContext`, which extends it, so the emitted value still satisfies the contract and the seam is unchanged — but a plugin reading `context.terminals` now writes `ctx as HarnessContext`, stating where it is used that it depends on this embedder.++Nothing about the wire format, the database or any other on-disk document changes.diff --git a/changelog/unreleased/2026-08-22-sandbox.zh.md b/changelog/unreleased/2026-08-22-sandbox.zh.mdnew file mode 100644index 00000000..6d7dd5cd--- /dev/null+++ b/changelog/unreleased/2026-08-22-sandbox.zh.md@@ -0,0 +1,27 @@+# 命令沙箱,后端以插件形式提供++- **Date:** 2026-08-22+- **Type:** feature+- **Scope:** `core`, `server`, `plugins`, `docs`+- **PR:** [#354](https://github.com/Prism-Shadow/penguin-harness/pull/354)+- **Breaking:** yes — `extensions.json` 不再被读取,两个 SDK 子路径改为 `/plugin`;插件契约改为封闭,`context.terminals` 现在需要类型转换++[English](2026-08-22-sandbox.md)++Agent 运行的 Shell 命令现在可以被约束。harness 拥有了自己的沙箱接口——改写 argv、如实报告强制程度、失败即关闭——并命名三个维度:`fs-write`、`network` 与 `mask-paths`。没有任何后端属于 harness:每个后端都是部署自行安装、并写入 `plugins.json` 的插件包,这也是它建立在插件机制之上的原因——该机制以[扩展机制](../0.2.8/2026-08-22-extension-mechanism.zh.md)之名随 0.2.8 发布,并在本次更名。默认部署不列出任何插件,因此不约束任何命令。++## 细节++- **接缝在 core。** `confineSpawn` 沿既有的 `proxyEnv` 线穿过,在 `ManagedSession` 中于 spawn 前一刻应用:它收到确切的 argv、`cwd` 与 `workspaceDir`,返回应当改为 spawn 的 argv。只是机制——它从不解释 argv。+- **路由不会悄悄丢掉某个维度。** 后端声明自己实现哪些维度(不声明即表示仅文件系统),服务把每条策略路由到覆盖其所需的那个后端。若某项要求无人覆盖,则失败即关闭,并列出每个已挂载后端各自覆盖什么。`confine` 必须返回具强制力的 argv 或抛出;抛出会中止 spawn 并呈现为该命令的 spawn 错误,因此绝不会因为后端失败而让命令在无约束状态下运行。+- **四个后端以独立包形式发布:** `plugin-sandbox-dsh`(可移植的 DSH 适配器,在三个平台上覆盖文件效果),以及 `plugin-sandbox-bwrap`(Linux)、`-seatbelt`(macOS)与 `-mxc`(Windows,经由 Microsoft MXC 的 `processcontainer`)——三个原生后端实现全部三个维度。每个包都声明 `Apache-2.0`,并随包发布自己的 `README.md`,写明它实际强制了什么,细到 bwrap 的挂载顺序与 Seatbelt 的规则优先级:部署正是据此挑选后端。由于 platform bundle 内不含任何后端,它不再内联任何贴近原生的模块,`deploy.mjs` 中运行时解析原生模块的兜底代码也已删除。沙箱设置随 park 的 platform context 一同保存,因此一次热推送不会悄悄解除某个部署的约束。+- **插件契约改为封闭,并纳入沙箱词汇。** `PenguinContext` 与 `PenguinInterface` 写明每一个成员,不再被 `declare module` 重新打开:此前,一个对着契约做检查的插件,实际编译时面对的是只有某一个宿主才提供的成员。`SandboxPolicy`、`SandboxProvider`、`ConfinedArgv` 以及模式与维度联合类型现在位于 `@prismshadow/penguin-core/plugin`,因为后端正是针对这些名字编写、除此之外别无所需——而读取它们的辅助函数仍留在 server 包,这让两个插件子路径继续只输出类型。因此后端只需引用 core:四个后端都已从依赖中移除 `@prismshadow/penguin-server`,现在也无法再解析到它;server 的插件子路径则收窄为它真正拥有的那一个成员 `HarnessContext`。+- **这套机制统一称为「插件」。** 0.2.8 中以「扩展机制」发布的那一套,从此叫插件机制,读者在概念出现的任何地方遇到的都是同一个称呼。配置文件是 `<root>/plugins.json`,键为 `plugins`;SDK 子路径是 `@prismshadow/penguin-core/plugin` 与 `@prismshadow/penguin-server/plugin`;契约中的名字是 `Plugin` / `PluginContext` / `PluginEvents`,宿主侧是 `PluginHost`;四个后端为 `plugins/` 下的 `@prismshadow/penguin-plugin-sandbox-*`。`PenguinContext`、`PenguinInterface`、`HarnessContext` 以及整套沙箱词汇均未改名。这个词在别处仍另有其义,那些地方一概未动:文件扩展名、remark/micromark 语法扩展、输入框的「+」扩展菜单,以及 SDK 自己的「扩展点」。它也不是 cordis 的 `plugin`——DSH 适配器正是通过 cordis 的 `Context.plugin` 挂载 DSH 的链路,两套词汇除了这个词之外毫无关系。++## 兼容性++磁盘上已有的 `extensions.json` **不会被读取**,也不会被迁移。用旧名字配置了插件的部署仍能运行,但其中的插件一个也不会加载,对应能力静默失效——对这几个沙箱后端而言,这意味着命令将在无约束状态下 spawn。请把该文件改名为 `plugins.json`,并把其中的 `"extensions"` 键改为 `"plugins"`;里面的 specifier 只在点名本仓库的沙箱后端时需要改动,那几个包现在叫 `@prismshadow/penguin-plugin-sandbox-*`。针对 `@prismshadow/penguin-core/extension` 或 `@prismshadow/penguin-server/extension` 编译的包将无法解析:把 import 指向 `/plugin`,并改用新的三个类型名即可。++`terminals` 是 harness 的类,不可能进入契约。它被命名在继承契约的 `HarnessContext` 上,因此发出的值仍满足契约、接缝没有变化——但读取 `context.terminals` 的插件现在需写 `ctx as HarnessContext`,在使用处表明它依赖这个宿主。++线上格式、数据库以及其他任何磁盘文档均无变化。diff --git a/packages/cli/test/tsup-target.test.ts b/packages/cli/test/tsup-target.test.tsindex 42563296..89ace2b4 100644--- a/packages/cli/test/tsup-target.test.ts+++ b/packages/cli/test/tsup-target.test.ts@@ -63,8 +63,13 @@ function requiredMajor(pkgPath: string): number | null {}describe("tsup build target", () => {- it("covers every package that builds with tsup", () => {- expect(tsupPackages.map((p) => p.name).sort()).toEqual(["cli", "core", "desktop", "server"]);+ it("discovers the packages that build with tsup", () => {+ // Deliberately not an exact list: new packages arrive (the sandbox backends were the+ // first), and a closed enumeration would fail for the one reason that is not a defect.+ // What has to hold is that discovery works at all — if it silently found nothing, the+ // target assertion below would pass vacuously.+ const names = tsupPackages.map((p) => p.name);+ expect(names).toEqual(expect.arrayContaining(["cli", "core", "desktop", "server"]));});it("is the same Node version everywhere", () => {@@ -74,6 +79,10 @@ describe("tsup build target", () => {);});+ it("has something to check — discovery finding nothing would pass the rule vacuously", () => {+ expect(tsupPackages.length).toBeGreaterThan(0);+ });+it("never emits syntax newer than a published package admits to needing", () => {for (const { name, configPath, pkgPath } of tsupPackages) {const target = declaredTarget(configPath);diff --git a/packages/core/package.json b/packages/core/package.jsonindex 048ea6b4..be0ab010 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -29,9 +29,9 @@"types": "./dist/interfaces/index.d.ts","import": "./dist/interfaces/index.js"},- "./extension": {- "types": "./dist/extension/index.d.ts",- "import": "./dist/extension/index.js"+ "./plugin": {+ "types": "./dist/plugin/index.d.ts",+ "import": "./dist/plugin/index.js"},"./context-limits": {"types": "./dist/llm/context-limits.d.ts",diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.tsindex 6dce8363..3fa4dd10 100644--- a/packages/core/src/agent.ts+++ b/packages/core/src/agent.ts@@ -93,6 +93,7 @@ import type {CommandPolicyConfig,GenerativeModelConfig,ProxyEnvPolicy,+ SpawnConfiner,SubagentHandle,SubagentRunner,ThinkingLevelName,@@ -142,6 +143,14 @@ export interface CreateAgentOptions {* at every spawn. Absent = PATH is untouched (SDK/CLI standalone use).*/pathPrepend?: () => string[];+ /**+ * Sandbox-confinement seam for the command subprocesses of every Session this Agent+ * creates or resumes — and of its subagents' Sessions, which inherit the getter (see+ * {@link SpawnConfiner}). Host policy exactly like `proxyEnv`: re-read at every+ * spawn, so the hosting server can swap the active confiner without restarting+ * Sessions. Absent = commands spawn unconfined.+ */+ confineSpawn?: () => SpawnConfiner | null;}/** The Session coordinates a {@link CreateAgentOptions.controlEnv} policy is evaluated with. */@@ -321,7 +330,14 @@ export async function createAgent(opts: CreateAgentOptions = {}): Promise<Agent>init: {},});const projectConfig = await loadProjectConfig(state.root, state.projectId);- return new Agent(state, projectConfig, opts.proxyEnv, opts.controlEnv, opts.pathPrepend);+ return new Agent(+ state,+ projectConfig,+ opts.proxyEnv,+ opts.controlEnv,+ opts.pathPrepend,+ opts.confineSpawn,+ );}export class Agent {@@ -334,6 +350,8 @@ export class Agent {private readonly controlEnv?: (ctx: ControlEnvContext) => Record<string, string>,/** See {@link CreateAgentOptions.pathPrepend}; forwarded into every Session's Environment and hooks. */private readonly pathPrepend?: () => string[],+ /** See {@link CreateAgentOptions.confineSpawn}; forwarded into every Session's Environment. */+ private readonly confineSpawn?: () => SpawnConfiner | null,) {}/**@@ -900,14 +918,15 @@ export class Agent {root,projectId,agentId,- // A child Agent loads its own vault/config, but the proxy-env and- // control-env policy getters are host policy, not Agent state: the+ // A child Agent loads its own vault/config, but the proxy-env, control-env+ // and spawn-confinement getters are host policy, not Agent state: the// subagent's commands run in the same serving process, so they follow the// same settings as the parent's — controlEnv is then evaluated with the// child Session's own coordinates....(parentAgent.proxyEnv ? { proxyEnv: parentAgent.proxyEnv } : {}),...(parentAgent.controlEnv ? { controlEnv: parentAgent.controlEnv } : {}),...(parentAgent.pathPrepend ? { pathPrepend: parentAgent.pathPrepend } : {}),+ ...(parentAgent.confineSpawn ? { confineSpawn: parentAgent.confineSpawn } : {}),}): parentAgent;// The child Session follows the PARENT Session, never the Project default: with the@@ -956,6 +975,7 @@ export class Agent {...(parentAgent.proxyEnv ? { proxyEnv: parentAgent.proxyEnv } : {}),...(parentAgent.controlEnv ? { controlEnv: parentAgent.controlEnv } : {}),...(parentAgent.pathPrepend ? { pathPrepend: parentAgent.pathPrepend } : {}),+ ...(parentAgent.confineSpawn ? { confineSpawn: parentAgent.confineSpawn } : {}),});const childSession = await childAgent.resumeSession({ sessionId });return subagentHandleFor(childSession);@@ -1114,6 +1134,7 @@ export class Agent {}: {}),...(this.pathPrepend ? { pathPrepend: this.pathPrepend } : {}),+ ...(this.confineSpawn ? { confineSpawn: this.confineSpawn } : {}),});// The tool_call_id uniqueness registry is shared by every context's LLM object: itsdiff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.tsindex 13660e9a..43abc3d6 100644--- a/packages/core/src/environment/environment.ts+++ b/packages/core/src/environment/environment.ts@@ -175,6 +175,8 @@ export class Environment implements EnvironmentInterface {...(config.proxyEnv !== undefined ? { proxyEnv: config.proxyEnv } : {}),...(config.controlEnv !== undefined ? { controlEnv: config.controlEnv } : {}),...(config.pathPrepend !== undefined ? { pathPrepend: config.pathPrepend } : {}),+ ...(config.confineSpawn !== undefined ? { confineSpawn: config.confineSpawn } : {}),+ workspaceDir: config.workspaceDir,});this.subagentSessions = new SubagentSessionManager();// Background-task liveness fans in from both registries and from the subagent run-statediff --git a/packages/core/src/environment/tools/command/session-manager.ts b/packages/core/src/environment/tools/command/session-manager.tsindex 25a0b827..e2bd9db3 100644--- a/packages/core/src/environment/tools/command/session-manager.ts+++ b/packages/core/src/environment/tools/command/session-manager.ts@@ -13,7 +13,7 @@ import { statSync } from "node:fs";import { ManagedSession } from "./session.js";import { prependPathEnv } from "./path-prepend.js";import { BackgroundRegistry } from "../background/index.js";-import type { ProxyEnvPolicy } from "../../../interfaces/index.js";+import type { ProxyEnvPolicy, SpawnConfiner } from "../../../interfaces/index.js";/** Concurrent managed-session cap: evicts once exceeded (exited sessions first, otherwise LRU — killing a background process has bounded cost). */const MAX_SESSIONS = 64;@@ -221,17 +221,36 @@ export class CommandSessionManager {private readonly pathPrepend: (() => string[]) | undefined;/** Single change listener (see onChange); null until the Environment subscribes. */private changeListener: (() => void) | null = null;+ /**+ * Sandbox-confinement seam (see {@link SpawnConfiner}): rewrites the exact argv of+ * every spawn. A getter for the same reason as `proxyEnv`: the active confiner can+ * change at runtime (the hosting server's platform layer is hot-swappable), and+ * re-reading at every spawn makes the change reach Sessions that are already+ * running. Absent, or returning null = commands spawn unconfined.+ */+ private readonly confineSpawn: (() => SpawnConfiner | null) | undefined;+ /**+ * The Session's Workspace root, bound into every confiner call as+ * `opts.workspaceDir` (a workspace-scoped policy must key off the Workspace, not the+ * per-command cwd). Optional for standalone embedders without a Workspace concept;+ * those fall back to the spawn cwd.+ */+ private readonly workspaceDir: string | undefined;constructor(opts?: {vault?: Record<string, string>;proxyEnv?: () => ProxyEnvPolicy | null;controlEnv?: () => Record<string, string>;pathPrepend?: () => string[];+ confineSpawn?: () => SpawnConfiner | null;+ workspaceDir?: string;}) {this.vault = opts?.vault ?? {};this.proxyEnv = opts?.proxyEnv;this.controlEnv = opts?.controlEnv;this.pathPrepend = opts?.pathPrepend;+ this.confineSpawn = opts?.confineSpawn;+ this.workspaceDir = opts?.workspaceDir;this.registry.onChange(() => this.changeListener?.());}@@ -268,10 +287,17 @@ export class CommandSessionManager {// half that actually decides which `penguin` a command resolves (see ManagedSession).const prepend = this.pathPrepend?.() ?? [];const hostEnv = prependPathEnv(hostEnvForChild(this.proxyEnv?.() ?? null), prepend);+ const confiner = this.confineSpawn?.() ?? null;return new ManagedSession({cmd: opts.cmd,cwd: opts.cwd,...(prepend.length > 0 ? { pathPrepend: prepend } : {}),+ ...(confiner !== null+ ? {+ confine: (argv: readonly string[], o: { cwd: string }) =>+ confiner(argv, { cwd: o.cwd, workspaceDir: this.workspaceDir ?? o.cwd }),+ }+ : {}),// Spread order is priority: vault overrides host variables of the same name; the// host's control variables (controlEnv) override the vault — they are the hosting// server's own wiring (API URL/token, Session coordinates) and a vault entry mustdiff --git a/packages/core/src/environment/tools/command/session.ts b/packages/core/src/environment/tools/command/session.tsindex d5550a90..a94289d9 100644--- a/packages/core/src/environment/tools/command/session.ts+++ b/packages/core/src/environment/tools/command/session.ts@@ -80,6 +80,14 @@ export interface SpawnOptions {* is spawned exactly as given.*/pathPrepend?: readonly string[];+ /**+ * Sandbox-confinement seam: receives the exact argv about to be spawned and returns+ * the argv to spawn instead. A throw aborts the spawn — fail-closed — and surfaces as+ * the command's spawn error. The manager binds the Session-level context (the+ * Workspace root) before handing the confiner down, so this narrower shape only+ * carries what the spawn itself knows (see `SpawnConfiner` in interfaces.ts).+ */+ confine?: (argv: readonly string[], opts: { cwd: string }) => readonly string[];}export class ManagedSession {@@ -111,7 +119,17 @@ export class ManagedSession {// what the model is shown; only the string actually handed to the shell carries the// PATH statement in front of it.const prefix = pathPrependPrefix(shell.name, opts.pathPrepend ?? []);- this.child = spawn(shell.command, [...shell.args, prefix + opts.cmd], {+ // The confinement seam runs BEFORE spawn on the exact argv (shell included), so a+ // confiner that cannot enforce its policy aborts the spawn by throwing (fail-closed)+ // rather than letting the command run unconfined. The rewritten argv is spawned in+ // place of the original; env assembly is unaffected (the runner inherits it).+ const argv = [shell.command, ...shell.args, prefix + opts.cmd];+ const confined = opts.confine ? [...opts.confine(argv, { cwd: opts.cwd })] : argv;+ const program = confined[0];+ if (program === undefined) {+ throw new Error("spawn confiner returned an empty argv");+ }+ this.child = spawn(program, confined.slice(1), {cwd: opts.cwd,env: opts.env,detached: SUPPORTS_PROCESS_GROUP, // Become the process-group leader, so the whole group can be signaleddiff --git a/packages/core/src/interfaces/environment.ts b/packages/core/src/interfaces/environment.tsindex 8c983516..d1c5ded8 100644--- a/packages/core/src/interfaces/environment.ts+++ b/packages/core/src/interfaces/environment.ts@@ -324,6 +324,15 @@ export interface EnvironmentConfig {* `proxyEnv`. Absent, or a getter returning nothing = PATH is untouched.*/pathPrepend?: () => string[];+ /**+ * Sandbox-confinement seam for exec_command / input_command subprocesses (see+ * {@link SpawnConfiner}). Like {@link EnvironmentConfig.proxyEnv} it is a getter+ * re-read at every spawn, so the hosting server can change the active confiner at+ * runtime (e.g. via a platform hot push) and reach Sessions that are already+ * running. Absent, or a getter returning null = commands spawn unconfined (the+ * default for SDK/CLI standalone use).+ */+ confineSpawn?: () => SpawnConfiner | null;}/**@@ -343,6 +352,28 @@ export interface EnvironmentConfig {*/export type ProxyEnvPolicy = { mode: "strip" } | { mode: "inject"; url: string; noProxy: string };+/**+ * Rewrites the exact argv a command session is about to spawn so it executes+ * confined — typically the original invocation wrapped in a sandbox runner+ * (`[runner, ...profileArgs, "--", ...argv]`). Mechanism only: which confinement+ * policy applies, and which backend enforces it, is decided by whoever supplies+ * the confiner (the hosting server's platform layer); this seam never interprets+ * the argv. Fail-closed by contract: a confiner that cannot enforce its policy+ * must THROW — the error surfaces as the command's spawn failure instead of the+ * command running unconfined. Returning the argv unchanged is reserved for+ * policies that genuinely mean "unconfined".+ * @param argv - the exact argv about to be spawned (`[shellCommand, ...shellArgs, cmd]`), not a shell string.+ * @param opts - spawn context: `cwd` is the working directory of THIS command (per-call,+ * may differ from the workspace); `workspaceDir` is the Session's Workspace root — the+ * directory a workspace-scoped confinement policy should treat as writable, never+ * inferred from `cwd` (a command may run in a workdir outside the Workspace).+ * @returns the argv to spawn instead.+ */+export type SpawnConfiner = (+ argv: readonly string[],+ opts: { cwd: string; workspaceDir: string },+) => readonly string[];+/*** An approved tool-call execution request.* Docs: /docs/interfaces § "ToolExecutionRequest and EnvironmentConfig".diff --git a/packages/core/src/extension/index.ts b/packages/core/src/plugin/index.tssimilarity index 59%rename from packages/core/src/extension/index.tsrename to packages/core/src/plugin/index.tsindex aa93b91d..f5b6f4c8 100644--- a/packages/core/src/extension/index.ts+++ b/packages/core/src/plugin/index.ts@@ -1,17 +1,17 @@/**- * The extension contract: what an extension package compiles against.+ * The plugin contract: what a plugin package compiles against.** Types only — the host that drives them lives in whatever embeds this SDK (for the- * harness, `@prismshadow/penguin-server/extension`). An extension reaches this module with+ * harness, `@prismshadow/penguin-server/plugin`). A plugin reaches this module with* `import type`, so it carries no runtime dependency on either and stays a* self-contained library that happens to satisfy an interface.*- * An extension is a module exporting one function:+ * A plugin is a module exporting one function:*- * export function activate(ctx: ExtensionContext): void+ * export function activate(ctx: PluginContext): void** It runs once per process at load time, before any App exists. Everything after that- * is events ({@link ExtensionEvents}), both fired at EVERY App creation — the packaged+ * is events ({@link PluginEvents}), both fired at EVERY App creation — the packaged* boot and each hot-swap boot alike:** - `"initialize"` — {@link PenguinInterface}, the harness's DEFINITION view, where@@ -23,23 +23,32 @@* App, so subscribing from inside one would accumulate a copy per hot swap. Sealing* turns that slow leak into a loud error at the packaged boot.*- * {@link PenguinContext} and {@link PenguinInterface} are OPEN: an embedder contributes- * the members it owns by augmenting this module, which is why the harness's terminals- * are not named here. Each layer declares what it actually provides, and no layer has- * to be reachable from this one.+ * {@link PenguinContext} and {@link PenguinInterface} are CLOSED. They name every member+ * a plugin may rely on, and are not reopened by declaration merging: an embedder that+ * augmented this module would put members into the contract that only its own build has,+ * so a plugin type-checking against the contract would compile against a surface that+ * the next embedder does not provide — and nothing at this layer could tell.+ *+ * An embedder with more to offer declares its own interface EXTENDING these and hands that+ * in; reaching those extra members is then an explicit cast at the point of use, which is+ * the honest cost of depending on one embedder (see the harness's `HarnessContext`).*/+import type { SandboxControl, SandboxProviderRegistry } from "./sandbox.js";import type { WorkflowFactory, WorkflowInstances } from "./workflow.js";export type { WorkflowFactory, WorkflowInstance, WorkflowInstances } from "./workflow.js";+export type * from "./sandbox.js";-/** A tool factory — RESERVED. The shape lands with the first extension-provided tool. */+/** A tool factory — RESERVED. The shape lands with the first plugin-provided tool. */export type ToolFactory = unknown;-/** An INSTANCE of the harness. Members an embedder owns flatten on by augmentation. */+/** An INSTANCE of the harness. Closed — see the module doc. */export interface PenguinContext {/** Instances built from `iface.workflow`. */workflows: WorkflowInstances;+ /** Flips confinement for this instance (see {@link SandboxControl}). */+ sandbox: SandboxControl;}/** The DEFINITION view of the harness: factories by name. */@@ -48,13 +57,15 @@ export interface PenguinInterface {workflow: Map<string, WorkflowFactory>;/** RESERVED (see {@link ToolFactory}). */tool: Map<string, ToolFactory>;+ /** Sandbox backend registration (see {@link SandboxProviderRegistry}). */+ sandbox: SandboxProviderRegistry;}/*** Event name → payload, the one place the vocabulary lives: adding an entry types the- * platform's emit and every extension's handler at once.+ * platform's emit and every plugin's handler at once.*/-export interface ExtensionEvents {+export interface PluginEvents {initialize: PenguinInterface;create: PenguinContext;}@@ -67,7 +78,7 @@ export interface Disposable {* What `activate` receives — process-level, NOT the harness instance (that is* {@link PenguinContext}, delivered by `"create"`).*/-export interface ExtensionContext {+export interface PluginContext {/*** Callable only while `activate` runs. Handlers are delivered synchronously and* unwrapped — a throwing handler fails that App's boot. A handler must NOT be async:@@ -75,19 +86,16 @@ export interface ExtensionContext {* and its rejection would escape as an unhandled one. Returning a thenable is refused* at delivery.*/- on<E extends keyof ExtensionEvents>(- event: E,- handler: (payload: ExtensionEvents[E]) => void,- ): void;+ on<E extends keyof PluginEvents>(event: E, handler: (payload: PluginEvents[E]) => void): void;/** Cleanup, disposed concurrently — entries must be mutually independent. */disposables: Disposable[];}-export interface Extension {+export interface Plugin {/*** May be async: loading awaits it, so a rejection is an ordinary load failure and the* subscription window does not seal until it settles. Event handlers, by contrast, are- * synchronous — see {@link ExtensionContext.on}.+ * synchronous — see {@link PluginContext.on}.*/- activate(ctx: ExtensionContext): void | Promise<void>;+ activate(ctx: PluginContext): void | Promise<void>;}diff --git a/packages/core/src/plugin/sandbox.ts b/packages/core/src/plugin/sandbox.tsnew file mode 100644index 00000000..348b42ed--- /dev/null+++ b/packages/core/src/plugin/sandbox.ts@@ -0,0 +1,134 @@+/**+ * The sandbox vocabulary a plugin compiles against — types only.+ *+ * It lives in core, alongside the rest of the plugin contract, because a backend is+ * written against these names and nothing else: a package implementing {@link+ * SandboxProvider} needs the policy it is handed and the argv it must return, not the+ * harness that routes them. The routing itself (which policy goes to which backend, and+ * the settings behind it) is the embedder's, and stays there.+ *+ * Confinement is argv rewriting and nothing else: a provider returns the argv the caller+ * should spawn instead of its own, and never executes anything itself.+ *+ * Nothing here emits runtime code. The helpers that read these shapes+ * (`SANDBOX_DIMENSIONS`, `providerDimensions`, `requestedDimensions`) are the embedder's+ * and live in the server package, so a plugin carries no runtime dependency on core.+ */++/**+ * File-effect mode. `read-only` permits only required sinks (e.g. /dev/null);+ * `workspace-write` also permits the workspace and a backend-defined temp area;+ * `danger-full-access` means confinement is off and no provider is consulted.+ */+export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";++/** A mode that actually confines — the modes a {@link SandboxPolicy} can carry. */+export type ConfinedSandboxMode = Exclude<SandboxMode, "danger-full-access">;++/**+ * The isolation dimensions of this interface. A provider declares the subset it+ * implements; `fs-write` is the floor every confining backend covers, while `network`+ * and `mask-paths` are optional implementations (see {@link SandboxProvider.dimensions}).+ */+export type SandboxDimension = "fs-write" | "network" | "mask-paths";++/**+ * What one confined execution is allowed to touch — carried PER CALL, not fixed on the+ * provider. The optional members are the optional dimensions: present means the policy+ * REQUIRES that dimension, and the service only routes such a policy to a provider that+ * implements it (never silently dropped).+ */+export interface SandboxPolicy {+ /** The file-effect mode this execution runs under (`fs-write`). */+ mode: ConfinedSandboxMode;+ /** Absolute root directory `workspace-write` may write under. */+ workspaceRoot: string;+ /** `network`: "none" = the confined process gets no network at all. */+ network?: "none";+ /** `mask-paths`: absolute paths hidden from the confined process, reads included. */+ maskPaths?: readonly string[];+}++/**+ * Enforcement completeness for this host. `partial` means the backend or an older+ * kernel ABI cannot govern every promised effect; a caller requiring an absolute+ * boundary must not treat it as `full`. Reported as fact, never requested.+ */+export type SandboxEnforcement = "full" | "partial";++/**+ * Evidence identifying a runner that failed BEFORE executing the wrapped command.+ * A consumer applies `allowedExitCodes` when present, drops `informationalLines` by+ * exact line equality, then matches `fatalSignatures` case-insensitively per remaining+ * stderr line. Exit status alone never proves runner failure.+ */+export interface RunnerFailureRule {+ allowedExitCodes?: readonly number[];+ fatalSignatures: readonly string[];+ informationalLines?: readonly string[];+}++/** The result of confining one argv. */+export interface ConfinedArgv {+ /** The wrapped argv (runner, profile, separator, then the caller's argv). */+ argv: string[];+ /** How completely the backend enforces this policy here. */+ enforcement: SandboxEnforcement;+ /**+ * The backend's denial DIALECT: the case-insensitive stderr substrings a denied+ * effect produces under THIS backend. A consumer inferring denials matches these+ * rather than a cross-backend union, which would claim denials a backend never emits.+ */+ denialSignatures: readonly string[];+ /** Structured runner-failure evidence (see {@link RunnerFailureRule}). */+ runnerFailureRules: readonly RunnerFailureRule[];+}++/**+ * A sandbox backend. `confine` must return enforcing argv or THROW — returning the+ * original argv unconfined is forbidden, which is what makes the whole capability+ * fail-closed.+ */+export interface SandboxProvider {+ /**+ * The dimensions this backend implements. Absent = `["fs-write"]`: a backend that+ * says nothing governs file writes only, which is the honest default and exactly+ * what a stock DSH backend is. The service routes by this declaration, so an+ * unimplemented dimension can never be silently ignored.+ */+ readonly dimensions?: readonly SandboxDimension[];+ confine(argv: readonly string[], policy: SandboxPolicy): ConfinedArgv;+}++/** A provider, or a promise of one: backends load asynchronously (dynamic imports, probes). */+export type SandboxProviderSource = SandboxProvider | PromiseLike<SandboxProvider | null> | null;++/**+ * The active confinement settings, resolved per spawn. A type literal with plain+ * arrays because it parks as Json in the platform context (see PlatformCtx.sandbox).+ */+export type SandboxSettings = {+ /** `danger-full-access` = confinement off; commands spawn exactly as before. */+ mode: SandboxMode;+ network?: "none";+ maskPaths?: string[];+};++/**+ * Sandbox backend registration — the floor where plugins are PROVIDERS. Nothing is+ * built in: every backend is a package a deployment installs and names in plugins.json,+ * so a third-party one enters by the same door. A backend declares which dimensions it+ * implements (declaring none means filesystem only) and the service routes each policy+ * to one that covers it, so an unimplemented dimension can never be silently ignored.+ * A provider may be a promise — loading is async, and the service fails closed while it+ * is pending or failed.+ */+export interface SandboxProviderRegistry {+ registerProvider(name: string, provider: SandboxProviderSource): void;+}++/** Flips confinement. Settings park with the platform context, so they survive swaps. */+export interface SandboxControl {+ configure(settings: SandboxSettings): void;+ settings(): SandboxSettings;+}diff --git a/packages/core/src/extension/workflow.ts b/packages/core/src/plugin/workflow.tssimilarity index 91%rename from packages/core/src/extension/workflow.tsrename to packages/core/src/plugin/workflow.tsindex c5402d81..ac1f05b8 100644--- a/packages/core/src/extension/workflow.ts+++ b/packages/core/src/plugin/workflow.ts@@ -1,5 +1,5 @@/**- * Workflows: the named units an extension registers and anyone can call.+ * Workflows: the named units a plugin registers and anyone can call.** Registration plus a plain JS call — nothing more. Anything needing a Session,* approval or streaming is a different capability and does not belong on this floor.diff --git a/packages/core/test/exec-session.test.ts b/packages/core/test/exec-session.test.tsindex 3646ec6e..840c7d91 100644--- a/packages/core/test/exec-session.test.ts+++ b/packages/core/test/exec-session.test.ts@@ -2,13 +2,18 @@* Behavior tests for long-running command sessions (exec_command yield + input_command).*/import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { access, chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import { Environment, ManagedSession } from "../src/environment/index.js";import { toolCall } from "../src/omnimessage/index.js";import type { OmniMessage } from "../src/omnimessage/index.js";-import type { ProxyEnvPolicy, ToolConfig, ToolDefinitionConfig } from "../src/interfaces/index.js";+import type {+ ProxyEnvPolicy,+ SpawnConfiner,+ ToolConfig,+ ToolDefinitionConfig,+} from "../src/interfaces/index.js";function execTool(overrides: Partial<ToolDefinitionConfig> = {}): ToolDefinitionConfig {return {@@ -490,6 +495,68 @@ describe("harness environment variables never reach a spawned command", () => {});});+describe("confineSpawn seam rewrites the exact argv a command spawns", () => {+ // The hosting server's platform layer supplies a SpawnConfiner getter through+ // Agent -> Environment -> CommandSessionManager: the confiner sees the exact argv+ // (shell included) and returns the argv to spawn instead; a throw fails the spawn+ // closed. Standalone Environments (no getter) keep the historical direct spawn.+ let confiner: SpawnConfiner | null = null;+ let confinedEnv: Environment;++ beforeEach(() => {+ confiner = null;+ confinedEnv = new Environment({+ workspaceDir: tmp,+ toolConfig: sessionConfig(),+ confineSpawn: () => confiner,+ });+ });+ afterEach(() => {+ confinedEnv.dispose();+ });++ it("the confiner receives the exact argv plus cwd, and its rewrite is what runs", async () => {+ let seen: { argv: readonly string[]; cwd: string; workspaceDir: string } | null = null;+ confiner = (argv, opts) => {+ seen = { argv, cwd: opts.cwd, workspaceDir: opts.workspaceDir };+ // Stand-in runner: replaces the invocation wholesale and prints a marker, proving+ // the child that actually ran is the rewritten argv, not the original shell.+ return [process.execPath, "-e", "console.log('CONFINED wrapped=' + process.argv.length)"];+ };+ const res = await runTool(confinedEnv, "exec_command", { cmd: "echo original" });+ expect(res.output).toContain("CONFINED wrapped=");+ expect(res.output).not.toContain("original\n");+ expect(seen).not.toBeNull();+ // The exact argv contract: last element is the command string, preceded by the shell.+ expect(seen!.argv.at(-1)).toBe("echo original");+ expect(seen!.argv.length).toBeGreaterThanOrEqual(2);+ expect(seen!.cwd).toBe(tmp);+ expect(seen!.workspaceDir).toBe(tmp);+ });++ it("a throwing confiner fails the spawn closed: reported as spawn error, nothing runs", async () => {+ confiner = () => {+ throw new Error('sandbox mode "workspace-write" requested but no backend is usable');+ };+ const res = await runTool(confinedEnv, "exec_command", {+ cmd: "echo leaked > confine-leak.txt",+ });+ expect(res.stopReason).toBe("fatal");+ expect(res.output).toContain('[spawn error: sandbox mode "workspace-write"');+ // Fail-closed means the command never executed — not even unconfined.+ await expect(access(path.join(tmp, "confine-leak.txt"))).rejects.toThrow();+ });++ it("the getter is re-read at every spawn, so a hot-swapped confiner needs no new Environment", async () => {+ const first = await runTool(confinedEnv, "exec_command", { cmd: "echo unconfined-run" });+ expect(first.output).toContain("unconfined-run");+ confiner = () => [process.execPath, "-e", "console.log('CONFINED')"];+ const second = await runTool(confinedEnv, "exec_command", { cmd: "echo unconfined-run" });+ expect(second.output).toContain("CONFINED");+ expect(second.output).not.toContain("unconfined-run");+ });+});+describe("proxyEnv policy governs the proxy variables commands inherit", () => {// The Web server's proxy settings thread a ProxyEnvPolicy getter through// Agent -> Environment -> CommandSessionManager: strip (switch off), inject (explicitdiff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.tsindex 5769bb42..2096f471 100644--- a/packages/core/tsup.config.ts+++ b/packages/core/tsup.config.ts@@ -12,9 +12,9 @@ export default defineConfig({// producers and parsers without pulling the rest of the SDK surface."src/omnimessage/markers/index.ts","src/interfaces/index.ts",- // The extension contract: types only, so an extension package compiles against the SDK+ // The plugin contract: types only, so a plugin package compiles against the SDK// without depending on whatever embeds it.- "src/extension/index.ts",+ "src/plugin/index.ts","src/state/model-catalog.ts",// Window/threshold arithmetic plus its two defaults: pure numbers, no Node dependency, so// the web app can bundle the compaction-threshold derivation its context ring fills against.diff --git a/packages/docs/content/server-boot.en.md b/packages/docs/content/server-boot.en.mdindex 8506ad77..30a10c4c 100644--- a/packages/docs/content/server-boot.en.md+++ b/packages/docs/content/server-boot.en.md@@ -1,11 +1,11 @@---title: Server Boot and Subsystems-description: The assembly order from process entry to HTTP listen, each subsystem's external surface, and where extensions sit in the two-level process/App lifecycle.+description: The assembly order from process entry to HTTP listen, each subsystem's external surface, and where plugins sit in the two-level process/App lifecycle.---`server/src/index.ts` is a side-effecting module: importing it starts the server — the contract the CLI relies on to run a server inside its own process. The startup order is written out in `main()`, one `PenguinServer` method per step, the method name being the step name. Assembly itself is split in two — `bootAppDeps(config)` builds the runtime core, publishes its capabilities and boots the platform (the business surface is assembled inside it), while `createApp(deps)` assembles the runtime shell's Hono route table without listening — so tests can take the full app and drive it via `app.request(...)` with no port involved and without going through `index.ts` at all.-This page answers two questions: in what order does the process bring each subsystem up, from entry to listen; and what is each subsystem's **external surface** — the way others depend on it: exported types, HTTP routes, events, or the context members extensions receive.+This page answers two questions: in what order does the process bring each subsystem up, from entry to listen; and what is each subsystem's **external surface** — the way others depend on it: exported types, HTTP routes, events, or the context members plugins receive.## Process entry@@ -25,9 +25,9 @@ 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)-├─ ④ loadExtensions read <root>/extensions.json → import → fill this process's one ExtensionHost+├─ ④ loadPlugins read <root>/plugins.json → import → fill this process's one PluginHost├─ ⑤ buildDeps = bootAppDeps open the DB → runtime core (auth, ChannelHub, HmrHost) → publish the-│ capabilities (db/auth/channels/config/proxy/desktop/extension host) →+│ capabilities (db/auth/channels/config/proxy/desktop/plugin host) →│ hmr.ensure() boots the platform: its create() assembles the WHOLE│ business surface (services, routes, scheduler) and delivers the hooks├─ ⑥ applyPersistedProxy the DB is open: align the dispatcher with the persisted settings@@ -37,13 +37,13 @@ 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; extensions 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 extensions 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; 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.-Extension 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.+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.## Two lifecycles: process and App-The runtime core (the DB, auth, the ChannelHub, the HmrHost) is built once and lives until the process exits. **Everything else is platform-level**: the whole business surface — services, routes, the SessionManager, the Scheduler — together with the terminal manager, extension delivery and workflow instances is rebuilt at every App creation (every boot and every hot swap, a new bundle pushed via `POST /api/hmr/upgrade`).+The runtime core (the DB, auth, the ChannelHub, the HmrHost) is built once and lives until the process exits. **Everything else is platform-level**: the whole business surface — services, routes, the SessionManager, the Scheduler — together with the terminal manager, plugin delivery and workflow instances is rebuilt at every App creation (every boot and every hot swap, a new bundle pushed via `POST /api/hmr/upgrade`).```textProcess-level (runtime mechanism, once) App-level (the business surface, re-run per boot + per hot swap)@@ -51,18 +51,18 @@ 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)-extensions.json load + activate (⑤ pub.) "initialize" / "create" event delivery · workflow instances+plugins.json load + activate (⑤ pub.) "initialize" / "create" event delivery · workflow instances```**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.Resources carry an interface contract of their own — but it does not live on the kernel iface: the declaration is itself a registry entry (`resource-interfaces`, group→version by ID prefix, e.g. `{ terminal: 1, platform: 1 }`), written by each App's `create()` and left for its successor. Before adopting anything, the new App reads its predecessor's declaration and compares it with its own compiled-in one: a group both declare at the same version integrates and rides across; a group whose versions differ, or that this build stops declaring, is disposed entry by entry in **reverse registration order** and rebuilt fresh (live objects cannot be strict-parsed the way the context document is, so declaration agreement is the integration criterion). The kernel's park/validate/swap mechanism neither participates in nor knows about this convention — which means the reconciliation policy itself evolves by platform push. Runtime capabilities (`runtime:*`) get the symmetric defense on their side: a bundle carries the capability-contract version it was compiled against, and `claimRuntimeCapabilities` handshakes it against the runtime's published one before trusting any claim — a mismatch declines the whole set and degrades to terminals-only instead of a TypeError at use time.-The dividing line is the **resource registry**: it sits outside the reloadable platform tree, so it survives across Apps. The pty processes are parked in it and the new App merely reclaims their handles, which is why a hot swap is invisible to whoever is typing in a terminal; the ExtensionHost, the DB handle, the auth service and the SSE hub travel the same road — published by the runtime, claimed by each App.+The dividing line is the **resource registry**: it sits outside the reloadable platform tree, so it survives across Apps. The pty processes are parked in it and the new App merely reclaims their handles, which is why a hot swap is invisible to whoever is typing in a terminal; the PluginHost, the DB handle, the auth service and the SSE hub travel the same road — published by the runtime, claimed by each App.-This is not merely tidiness. A pushed bundle is compiled **standalone** — a self-contained ESM file (`bundle: true`, no externals) with its own module graph — so a module-level host singleton on the platform side would, after a push, be that bundle's own empty host, and every configured extension would silently vanish on the first hot push. Claiming rather than importing is what makes the packaged App and the pushed App drive the same host. When the runtime published none, the fallback is an empty host — the honest reading of "this runtime knows nothing about extensions". The same reasoning is spelled out in `terminal/identity.ts`.+This is not merely tidiness. A pushed bundle is compiled **standalone** — a self-contained ESM file (`bundle: true`, no externals) with its own module graph — so a module-level host singleton on the platform side would, after a push, be that bundle's own empty host, and every configured plugin would silently vanish on the first hot push. Claiming rather than importing is what makes the packaged App and the pushed App drive the same host. When the runtime published none, the fallback is an empty host — the honest reading of "this runtime knows nothing about plugins". The same reasoning is spelled out in `terminal/identity.ts`.-## App creation: where extensions run+## App creation: where plugins runThe full App-creation order is `platformImpl.create` in `server/src/hmr/platform.ts`:@@ -70,28 +70,31 @@ The full App-creation order is `platformImpl.create` in `server/src/hmr/platformplatformImpl.create│├─ new TerminalManager(resources) # adopt the ptys the previous instance parked-├─ extensions = extensionHostFrom(resources) # claim the host the runtime loaded in ④ (empty host if none was published)-├─ iface = { workflow: new Map(), tool: new Map() } # a fresh definition view per App-├─ extensions.emit("initialize", iface) # the definition view, to every handler, in activation order-├─ extensions.emit("create", { # the instance view, assembled after registration closes+├─ plugins = pluginHostFrom(resources) # claim the host the runtime loaded in ④ (empty host if none was published)+├─ iface = { workflow, tool, sandbox } # a fresh definition view per App+├─ plugins.emit("initialize", iface) # the definition view, to every handler, in activation order+├─ sandbox = new SandboxService(registered backends) # rehydrated from the parked settings+├─ plugins.emit("create", { # the instance view, assembled after registration closes│ workflows: instantiateWorkflows(iface.workflow), # every factory is called eagerly here│ terminals,+│ sandbox: { configure, settings },│ })├─ caps = claimRuntimeCapabilities(resources) # db/auth/channels/config/proxy/desktop-└─ business assembly (when caps are all present): buildAppDeps → scheduler.start()+└─ business assembly (when caps are all present): buildAppDeps — the sandbox confiner+ rides in as an argument, into the session loader's spawn path → scheduler.start()→ createApp (terminal + business groups in ONE Hono app)→ one registry write publishes the {deps, app, shutdown} pointer→ ctx.effect registers the hard stop for the next swap```-Split by frequency, the extension lifecycle has three tiers:+Split by frequency, the plugin lifecycle has three tiers:| Moment | Frequency | What happens || ----------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------- |-| Load + `activate(ctx)` | Once per process | Boot step ④ `loadExtensions`: resolve and import each specifier in `extensions.json`, then run its exported `activate` (awaited when async) — the only window where `ctx.on(...)` subscribes and `ctx.disposables` accepts cleanup. A failing entry is rolled back (its disposables run) and skipped; an unreadable or malformed `extensions.json` fails the boot |-| `"initialize"` event | Once per App | Handlers register workflow factories into the fresh `iface` (the `tool` slot is reserved, unused) |+| Load + `activate(ctx)` | Once per process | Boot step ④ `loadPlugins`: resolve and import each specifier in `plugins.json`, then run its exported `activate` (awaited when async) — the only window where `ctx.on(...)` subscribes and `ctx.disposables` accepts cleanup. A failing entry is rolled back (its disposables run) and skipped; an unreadable or malformed `plugins.json` fails the boot |+| `"initialize"` event | Once per App | Handlers register workflow factories and sandbox backends into the fresh `iface` (the `tool` slot is reserved, unused) || Workflow instantiation | Once per App | `instantiateWorkflows` calls **every** factory synchronously before the emit — instances are born in one batch at App creation, not on first call |-| `"create"` event | Once per App | Handlers receive the instance view `ctx` (`workflows` + `terminals`) |+| `"create"` event | Once per App | Handlers receive the instance view `ctx` (`workflows` + `terminals` + `sandbox`) || `workflows.run` | Per call | A plain function call: no Session, no approval, no streaming || Disposables | Once per process | Awaited (≤5s) in the graceful shutdown; disposers may be async, run concurrently with failures isolated — so they must be mutually independent |@@ -100,11 +103,12 @@ Several behavioral facts follow:- **Per-App redelivery**: `"initialize"` and `"create"` are redelivered at every App creation, so registrations always land in the current instance — a post-swap App can never run with empty registrations.- **Instances do not cross a swap**: factories re-run per App, so a stateful workflow never carries the previous instance's state across a hot swap.- **The subscription window is `activate`, sealed on return**: a handler-time `ctx.on(...)` would accumulate one copy per hot swap, so it throws instead — at the packaged boot, loudly, not as a slow leak. Disposables seal with the same window for the same reason.-- **Handlers are synchronous and unwrapped**: extension *loading* failures (import, or a throwing/rejecting `activate`) are isolated per entry, but event handlers run without a try/catch — a throwing handler fails that platform boot, and a handler that returns a promise is refused for the same reason (an App is assembled synchronously around the emit, so its rejection could only escape unhandled).-- **A duplicate workflow name is refused**: `iface.workflow` is a registry whose `set` throws, so a name cannot change owner depending on `extensions.json` ordering.-- **The event vocabulary is typed and lives in one place**: `ExtensionEvents` maps each name to its payload — adding an event types the platform's emit and every handler at once.+- **Handlers are synchronous and unwrapped**: plugin *loading* failures (import, or a throwing/rejecting `activate`) are isolated per entry, but event handlers run without a try/catch — a throwing handler fails that platform boot, and a handler that returns a promise is refused for the same reason (an App is assembled synchronously around the emit, so its rejection could only escape unhandled).+- **A duplicate workflow name is refused**: `iface.workflow` is a registry whose `set` throws, so a name cannot change owner depending on `plugins.json` ordering.+- **The event vocabulary is typed and lives in one place**: `PluginEvents` maps each name to its payload — adding an event types the platform's emit and every handler at once.+- **Confinement is same-generation wiring**: the confiner reaches core as a plain argument to `buildAppDeps`, and the sessions spawning through it are hard-stopped with their App — what crosses the swap is the active settings on the parked context, so a push cannot silently un-confine a deployment.-The extension contract (`Extension` / `ExtensionContext` / `ExtensionEvents` / `PenguinInterface` / `PenguinContext`) is declared in the SDK, at `@prismshadow/penguin-core/extension`. `PenguinContext` and `PenguinInterface` are open: the harness contributes the members it owns — `terminals` — by augmenting that module, and re-exports both halves from `@prismshadow/penguin-server/extension`. Both subpaths emit types only. Which extensions exist is the deployment's `<root>/extensions.json`; the harness itself imports no extension.+The plugin contract (`Plugin` / `PluginContext` / `PluginEvents` / `PenguinInterface` / `PenguinContext`, and the sandbox vocabulary a backend is written against) is declared in the SDK, at `@prismshadow/penguin-core/plugin`. `PenguinContext` and `PenguinInterface` are closed: they name every member a plugin may rely on, and are not reopened by declaration merging. `terminals` cannot be among them — it is a harness class — so it is named on `HarnessContext`, which extends the contract and is the whole of `@prismshadow/penguin-server/plugin`; a plugin reading it writes `ctx as HarnessContext` and thereby states where it is used that it depends on this embedder. A plugin that needs no harness-only member names core alone: each sandbox backend in this repo does, and none depends on the server package. Both subpaths emit types only. Which plugins exist is the deployment's `<root>/plugins.json`; the harness itself imports no plugin.## Subsystem inventory@@ -122,7 +126,8 @@ 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 |-| Extension host | built by ④ `loadExtensions`, published to the registry in ⑤ | `activate(ctx: ExtensionContext)` + the `ExtensionEvents` registry; the configuration surface is `<root>/extensions.json` |+| Plugin host | built by ④ `loadPlugins`, published to the registry in ⑤ | `activate(ctx: PluginContext)` + the `PluginEvents` registry; the configuration surface is `<root>/plugins.json` |+| Sandbox | `sandbox/service.ts` — **App-level** (built in create, over the backends plugins registered) | `iface.sandbox.registerProvider` / `ctx.sandbox.{configure,settings}`; enforcement reaches commands through core's spawn seam, and backends are plugin packages named in `plugins.json` || Model catalog | No boot-time construction — static core data | `/api/projects/:projectId/models`; the catalog itself lives in `core/src/state/model-catalog.ts` |One request-time path is worth knowing: the platform's HTTP seam offers every request to the current App's `http(request)` first, and only a `null` return falls through to the runtime's own routes; while a hot swap is in flight, requests queue at the seam for the new App instead of hitting a half-disposed one.diff --git a/packages/docs/content/server-boot.zh.md b/packages/docs/content/server-boot.zh.mdindex 58f09e71..d6d3723c 100644--- a/packages/docs/content/server-boot.zh.md+++ b/packages/docs/content/server-boot.zh.md@@ -1,11 +1,11 @@---title: Server 启动与子系统-description: 从进程入口到 HTTP 监听的组装顺序、各子系统的对外表面,以及扩展在进程级与 App 级两层生命周期中的位置。+description: 从进程入口到 HTTP 监听的组装顺序、各子系统的对外表面,以及插件在进程级与 App 级两层生命周期中的位置。---`server/src/index.ts` 是一个副作用模块:import 它即启动服务——CLI 就是靠这一条契约在自己进程里跑起 server 的。启动次序写在 `main()` 里,每一步是 `PenguinServer` 的一个方法,方法名即步骤名。组装本身又拆成两个函数——`bootAppDeps(config)` 构建运行时核心、发布能力并启动平台(业务面在平台内组装),`createApp(deps)` 组装运行时壳层的 Hono 路由表但不监听——因此测试可以拿到完整的 app 直接 `app.request(...)`,不占端口,也不经过 `index.ts`。-本页回答两个问题:进程从入口到监听按什么顺序把子系统立起来;每个子系统的**对外表面**(surface)是什么——即别人依赖它的方式:导出类型、HTTP 路由、事件,或扩展拿到的 context 成员。+本页回答两个问题:进程从入口到监听按什么顺序把子系统立起来;每个子系统的**对外表面**(surface)是什么——即别人依赖它的方式:导出类型、HTTP 路由、事件,或插件拿到的 context 成员。## 进程入口@@ -25,10 +25,10 @@ main() —— 每行一个 PenguinServer 方法├─ ① loadEnv · installProxy dotenv 先行(.env 自己可能定义 HTTP_PROXY),随后全局代理接管 fetch├─ ② readConfig 仅环境变量:PENGUIN_HOME、PORT、HOST、PENGUIN_WEB_DB …├─ ③ ensureSoleInstance 数据根被另一存活实例持有 → 退出码 3(先于开库)-├─ ④ loadExtensions 读 <root>/extensions.json → import → 装进本进程唯一的 ExtensionHost+├─ ④ loadPlugins 读 <root>/plugins.json → import → 装进本进程唯一的 PluginHost├─ ⑤ buildDeps = bootAppDeps 开库 → 运行时核心(auth、ChannelHub、HmrHost)→ 发布能力(db/auth/-│ channels/config/proxy/desktop/扩展 host)→ hmr.ensure() 启动平台:-│ 其 create() 组装整个业务面(服务、路由、scheduler)并投递扩展钩子+│ channels/config/proxy/desktop/插件 host)→ hmr.ensure() 启动平台:+│ 其 create() 组装整个业务面(服务、路由、scheduler)并投递插件钩子├─ ⑥ applyPersistedProxy 库已打开,用持久化的代理设置校准 dispatcher├─ ⑦ buildApp 运行时壳层:守卫、/api/auth、/api/desktop、/api/hmr、seam、静态托管├─ ⑧ seedAdmin 内置 admin 种子(初始 Project 供给经注册表晚绑定到当前业务面)@@ -36,13 +36,13 @@ main() —— 每行一个 PenguinServer 方法└─ ⑩ installProcessHandlers 信号、Desktop 退出路径、进程级错误兜底```-这个顺序不是随意排的,其中四条是硬约束:代理在任何出站请求可能发生之前接管全局 `fetch`;单实例锁在开库**之前**预检,因为 `web.db` 是单写者;扩展在 ⑤ **之前**加载完毕,host 随其他能力一起在平台 boot 前进入注册表,因此首个 App 创建时它们已经在场;平台(连同整个业务面)在 `listen` 之前完成启动,因此**没有任何请求会在业务与扩展就位之前被服务**。收尾的 `installProcessHandlers` 排在 `listen` 之后,这样关停流程不会在监听器存在之前被触发。+这个顺序不是随意排的,其中四条是硬约束:代理在任何出站请求可能发生之前接管全局 `fetch`;单实例锁在开库**之前**预检,因为 `web.db` 是单写者;插件在 ⑤ **之前**加载完毕,host 随其他能力一起在平台 boot 前进入注册表,因此首个 App 创建时它们已经在场;平台(连同整个业务面)在 `listen` 之前完成启动,因此**没有任何请求会在业务与插件就位之前被服务**。收尾的 `installProcessHandlers` 排在 `listen` 之后,这样关停流程不会在监听器存在之前被触发。-扩展加载排在 `ensureSoleInstance` 之后也是有意的:一个即将以退出码 3 退出的进程不应该先去 import 一堆第三方模块、执行它们的顶层副作用。+插件加载排在 `ensureSoleInstance` 之后也是有意的:一个即将以退出码 3 退出的进程不应该先去 import 一堆第三方模块、执行它们的顶层副作用。## 两级生命周期:进程与 App-运行时核心(DB、认证、ChannelHub、HmrHost)随进程构建一次、活到进程退出。**其余全部是平台层**:整个业务面——服务、路由、SessionManager、Scheduler——连同终端管理器、扩展投递、workflow 实例,都在每次 App 创建时重建(每次启动 + 每次热更新,`POST /api/hmr/upgrade` 推送新 bundle)。+运行时核心(DB、认证、ChannelHub、HmrHost)随进程构建一次、活到进程退出。**其余全部是平台层**:整个业务面——服务、路由、SessionManager、Scheduler——连同终端管理器、插件投递、workflow 实例,都在每次 App 创建时重建(每次启动 + 每次热更新,`POST /api/hmr/upgrade` 推送新 bundle)。```text进程级(运行时机制,构建一次) App 级(业务面,每次启动 + 每次热更新重跑)@@ -50,18 +50,18 @@ main() —— 每行一个 PenguinServer 方法SQLite · 认证(AuthService) 全部业务服务与路由(services + http/routes)ChannelHub(SSE 跨 swap 存活) SessionManager · SchedulerHmrHost · 资源注册表 TerminalManager(接管寄存的 pty)-extensions.json 加载 + activate(⑤ 发布) "initialize" / "create" 事件投递 · workflow 实例+plugins.json 加载 + activate(⑤ 发布) "initialize" / "create" 事件投递 · workflow 实例```**swap 语义:未实现 park 的状态一律硬中止**——待审批全部拒绝、运行中任务中止、scheduler 随旧 App 死掉,新 App 从认领的能力重建一切。只有实现了 park/adopt 的资源(终端 pty)跨 swap 存活。资源本身也有接口契约,但它不进 kernel 的 iface——声明本身就是注册表里的一个条目(`resource-interfaces`,按 ID 前缀组记版本,如 `{ terminal: 1, platform: 1 }`),由每代 App 的 `create()` 写入并留给继任者。新 App 在 adopt 任何东西之前读前任的声明、与自己编译期的声明比对:同版本的组整体集成存续;版本不同或本代不再声明的组,按**逆注册序**逐一 dispose 后重建(活对象无法像 context 文档那样 strict-parse,声明一致就是集成的判据)。kernel 的 park/validate/swap 机制不参与也不感知这套约定,因此调和策略本身也随平台热推送演进。运行时能力(`runtime:*`)走另一条对称防线:bundle 编译期携带能力契约版本,`claimRuntimeCapabilities` 先与运行时发布的版本握手,不符则整组拒领、退化为 terminals-only,而不是在使用时抛 TypeError。-分界线是**资源注册表**:它位于可重载的平台树之外,因此跨 App 存活。pty 进程本身寄存在里面,新 App 只是接管句柄——所以热更新对正在敲终端的人不可见;ExtensionHost、DB 句柄、认证服务、SSE hub 走的是同一条路:运行时发布进注册表,每个 App 认领同一份。+分界线是**资源注册表**:它位于可重载的平台树之外,因此跨 App 存活。pty 进程本身寄存在里面,新 App 只是接管句柄——所以热更新对正在敲终端的人不可见;PluginHost、DB 句柄、认证服务、SSE hub 走的是同一条路:运行时发布进注册表,每个 App 认领同一份。-这一点不只是整洁问题。推送的 bundle 是**独立编译**的自包含 ESM(`bundle: true`,无 external),拥有自己的模块图;若平台侧持有一个模块级 host 单例,推送后拿到的会是 bundle 自己那个空 host,所有已配置扩展都会在第一次热推送时静默消失。认领而非导入,正是为了让打包的 App 与推送的 App 驱动同一个 host。运行时未发布 host 时回退为空 host——「这个运行时不认识扩展」的诚实读法。同样的理由见 `terminal/identity.ts`。+这一点不只是整洁问题。推送的 bundle 是**独立编译**的自包含 ESM(`bundle: true`,无 external),拥有自己的模块图;若平台侧持有一个模块级 host 单例,推送后拿到的会是 bundle 自己那个空 host,所有已配置插件都会在第一次热推送时静默消失。认领而非导入,正是为了让打包的 App 与推送的 App 驱动同一个 host。运行时未发布 host 时回退为空 host——「这个运行时不认识插件」的诚实读法。同样的理由见 `terminal/identity.ts`。-## App 创建:扩展的舞台+## App 创建:插件的舞台App 创建的完整顺序在 `server/src/hmr/platform.ts` 的 `platformImpl.create`:@@ -69,27 +69,30 @@ App 创建的完整顺序在 `server/src/hmr/platform.ts` 的 `platformImpl.creaplatformImpl.create│├─ new TerminalManager(resources) # 接管上一实例寄存的 pty-├─ extensions = extensionHostFrom(resources) # 认领运行时在 ④ 加载好的那个 host(未发布则为空 host)-├─ iface = { workflow: new Map(), tool: new Map() } # 每个 App 全新的定义视图-├─ extensions.emit("initialize", iface) # 定义视图,按激活顺序投递给每个 handler-├─ extensions.emit("create", { # 实例视图,注册关闭后组装+├─ plugins = pluginHostFrom(resources) # 认领运行时在 ④ 加载好的那个 host(未发布则为空 host)+├─ iface = { workflow, tool, sandbox } # 每个 App 全新的定义视图+├─ plugins.emit("initialize", iface) # 定义视图,按激活顺序投递给每个 handler+├─ sandbox = new SandboxService(已注册的后端) # 由寄存的设置重新水合+├─ plugins.emit("create", { # 实例视图,注册关闭后组装│ workflows: instantiateWorkflows(iface.workflow), # 全部 factory 在此被急切调用│ terminals,+│ sandbox: { configure, settings },│ })├─ caps = claimRuntimeCapabilities(resources) # db/auth/channels/config/proxy/desktop-└─ 业务面组装(caps 齐全时):buildAppDeps → scheduler.start()+└─ 业务面组装(caps 齐全时):buildAppDeps——sandbox confiner 作为普通参数传入,+ 进入 session loader 的 spawn 路径 → scheduler.start()→ createApp(终端组 + 业务组注册进同一个 Hono app)→ 一次注册表写入发布 {deps, app, shutdown} 指针 → ctx.effect 注册 swap 硬中止```-按频率拆开,扩展生命周期是三层:+按频率拆开,插件生命周期是三层:| 时机 | 频率 | 发生什么 || -------------- | ----------- | ---------------------------------------------------------------------------------------------------- |-| 加载 + `activate(ctx)` | 每进程一次 | 启动步骤 ④ `loadExtensions`:解析 `extensions.json` 里的 specifier、import、执行其导出的 `activate`(async 会被等待)——`ctx.on(...)` 订阅与 `ctx.disposables` 登记只在这个窗口内有效。单条失败会回滚(跑掉它已登记的 disposable)并跳过;`extensions.json` 不可读或格式错误则启动失败 |-| `"initialize"` 事件 | 每 App 一次 | handler 向全新的 `iface` 注册 workflow factory(`tool` 槽位保留未用) |+| 加载 + `activate(ctx)` | 每进程一次 | 启动步骤 ④ `loadPlugins`:解析 `plugins.json` 里的 specifier、import、执行其导出的 `activate`(async 会被等待)——`ctx.on(...)` 订阅与 `ctx.disposables` 登记只在这个窗口内有效。单条失败会回滚(跑掉它已登记的 disposable)并跳过;`plugins.json` 不可读或格式错误则启动失败 |+| `"initialize"` 事件 | 每 App 一次 | handler 向全新的 `iface` 注册 workflow factory 与 sandbox 后端(`tool` 槽位保留未用) || workflow 实例化 | 每 App 一次 | `instantiateWorkflows` 在 emit 之前同步调用**全部** factory——实例随 App 创建整批诞生,不是首次调用时 |-| `"create"` | 每 App 一次 | 扩展拿到实例视图 `ctx`(`workflows` + `terminals`) |+| `"create"` | 每 App 一次 | 插件拿到实例视图 `ctx`(`workflows` + `terminals` + `sandbox`) || `workflows.run` | 每次调用 | 纯函数调用:无 Session、无审批、无流式 || Disposables | 每进程一次 | 优雅关停时被 await(≤5s);disposer 可以是 async,全部并发执行、单条失败被隔离——因此彼此必须独立 |@@ -98,11 +101,12 @@ platformImpl.create- **每 App 重投递**:`"initialize"` 与 `"create"` 在每次 App 创建时重新投递,注册永远落在当前实例上——热更新后的新 App 不可能带着空注册运行。- **实例不跨热更新**:factory 每 App 重新执行,带状态的 workflow 不会把上一个实例的状态带过热更新。- **订阅窗口就是 `activate`,返回即封闭**:handler 里再调 `ctx.on(...)` 会每次热 swap 累积一份,所以它直接抛错——在打包启动时就大声失败,而不是变成慢泄漏。disposables 与订阅同窗封闭,理由相同。-- **handler 同步且不被包裹**:扩展*加载*失败(import,或 `activate` 抛错/reject)按条目隔离,但事件 handler 没有 try/catch——抛错会使该次平台启动失败;返回 promise 的 handler 出于同样理由被拒绝(App 是围绕这次 emit 同步组装的,它的 rejection 只能以未处理形式逃逸)。-- **workflow 重名被拒绝**:`iface.workflow` 是一个 `set` 会抛错的注册表,名字的归属不会随 `extensions.json` 顺序改变。-- **事件词汇表有类型且只有一处**:`ExtensionEvents` 把每个事件名映射到它的载荷——加一个事件,平台的 emit 端和所有 handler 同时获得类型。+- **handler 同步且不被包裹**:插件*加载*失败(import,或 `activate` 抛错/reject)按条目隔离,但事件 handler 没有 try/catch——抛错会使该次平台启动失败;返回 promise 的 handler 出于同样理由被拒绝(App 是围绕这次 emit 同步组装的,它的 rejection 只能以未处理形式逃逸)。+- **workflow 重名被拒绝**:`iface.workflow` 是一个 `set` 会抛错的注册表,名字的归属不会随 `plugins.json` 顺序改变。+- **事件词汇表有类型且只有一处**:`PluginEvents` 把每个事件名映射到它的载荷——加一个事件,平台的 emit 端和所有 handler 同时获得类型。+- **约束是同代接线**:confiner 作为 `buildAppDeps` 的普通参数进入 core,经它 spawn 的 session 随所属 App 硬停——跨过 swap 的是寄存上下文上的生效设置,因此一次推送无法悄悄解除一个部署的约束。-扩展契约(`Extension` / `ExtensionContext` / `ExtensionEvents` / `PenguinInterface` / `PenguinContext`)声明在 SDK 里,即 `@prismshadow/penguin-core/extension`。`PenguinContext` 与 `PenguinInterface` 是开放的:harness 通过对该模块做声明合并,贡献自己拥有的成员——`terminals`——并从 `@prismshadow/penguin-server/extension` 一并再导出。两个子路径都只产出类型。哪些扩展存在由部署的 `<root>/extensions.json` 决定,harness 自身不 import 任何扩展。+插件契约(`Plugin` / `PluginContext` / `PluginEvents` / `PenguinInterface` / `PenguinContext`,以及后端所针对编写的沙箱词汇)声明在 SDK 里,即 `@prismshadow/penguin-core/plugin`。`PenguinContext` 与 `PenguinInterface` 是封闭的:它们写明插件可以依赖的每一个成员,不再被声明合并重新打开。`terminals` 不可能位列其中——它是 harness 的类——因此它被命名在继承契约的 `HarnessContext` 上,而 `HarnessContext` 就是 `@prismshadow/penguin-server/plugin` 的全部;读取它的插件需写 `ctx as HarnessContext`,从而在使用处表明自己依赖这个宿主。不需要宿主专属成员的插件只引用 core:本仓库的每个沙箱后端都是如此,都不依赖 server 包。两个子路径都只产出类型。哪些插件存在由部署的 `<root>/plugins.json` 决定,harness 自身不 import 任何插件。## 子系统一览@@ -120,7 +124,8 @@ 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 寄存跨热更新存活 |-| 扩展宿主 | ④ `loadExtensions` 构建,⑤ 发布进资源注册表 | `activate(ctx: ExtensionContext)` + `ExtensionEvents` 事件表;配置面是 `<root>/extensions.json` |+| 插件宿主 | ④ `loadPlugins` 构建,⑤ 发布进资源注册表 | `activate(ctx: PluginContext)` + `PluginEvents` 事件表;配置面是 `<root>/plugins.json` |+| 沙盒 | `sandbox/service.ts`——**App 级**(create 内基于插件注册的后端构建) | `iface.sandbox.registerProvider` / `ctx.sandbox.{configure,settings}`;约束经 core 的 spawn seam 落到命令上,后端是 `plugins.json` 里点名的插件包 || 模型目录 | 无启动期构建——core 静态数据 | `/api/projects/:projectId/models`;目录本体在 `core/src/state/model-catalog.ts` |请求期还有一条固定路径值得知道:平台的 HTTP seam 把每个请求先交给当前 App 的 `http(request)`,返回 `null` 才落到运行时自己的路由;热更新进行中时请求在 seam 上排队等新 App 就绪,而不是打到半旧的实例上。diff --git a/packages/server/package.json b/packages/server/package.jsonindex 535ef4d2..30a9d945 100644--- a/packages/server/package.json+++ b/packages/server/package.json@@ -50,9 +50,9 @@"types": "./dist/secret-file.d.ts","import": "./dist/secret-file.js"},- "./extension": {- "types": "./dist/extension/index.d.ts",- "import": "./dist/extension/index.js"+ "./plugin": {+ "types": "./dist/plugin/index.d.ts",+ "import": "./dist/plugin/index.js"}},"main": "./dist/index.js",diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 420be8f8..841e3a2c 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -60,7 +60,7 @@ import { mintApiToken, storeApiToken } from "./auth/api-token.js";import type { Identity } from "./terminal/identity.js";import { terminalRoutes } from "./terminal/routes.js";import type { TerminalManager } from "./terminal/manager.js";-import { EXTENSIONS_RESOURCE_ID, type ExtensionHost } from "./extension/host.js";+import { PLUGINS_RESOURCE_ID, type PluginHost } from "./plugin/host.js";import type { AppEnv } from "./auth/middleware.js";import { AuthService } from "./auth/service.js";import { newAuthRuntimeState } from "./auth/runtime-state.js";@@ -127,7 +127,7 @@ import {} from "./services/preview-token.js";import type { PreviewTokenSigner } from "./services/preview-token.js";-import type { ControlEnvContext, ProxyEnvPolicy } from "@prismshadow/penguin-core";+import type { ControlEnvContext, ProxyEnvPolicy, SpawnConfiner } from "@prismshadow/penguin-core";import { declined } from "./hmr/hono-seam.js";import { AgentsRepo } from "./db/repos/agents.js";import { MembersRepo } from "./db/repos/members.js";@@ -285,15 +285,15 @@ export interface BuildDepsOverrides {* the business surface — see app.ts), and return the merged view. Shared* by production and tests; tests pass dbPath=":memory:" and a temp root.*- * `extensions` is the host index.ts's loadExtensions step filled from extensions.json — handed in+ * `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 extension/index.ts's extensionHostFrom).+ * falls back to an empty host (see plugin/index.ts's pluginHostFrom).*/export async function bootAppDeps(config: ServerConfig,overrides: BuildDepsOverrides = {},- extensions?: ExtensionHost,+ plugins?: PluginHost,): Promise<AppDeps> {const db = openDatabase(config.dbPath);@@ -361,11 +361,11 @@ export async function bootAppDeps(const desktop = config.desktopToken !== null ? new DesktopService(config.desktopToken) : null;hmr.resources.register(RUNTIME_DESKTOP_RESOURCE_ID, desktop);hmr.resources.register(RUNTIME_LIFECYCLE_RESOURCE_ID, new LifecycleService(config.supervised));- // The registry sweep only STARTS extension disposal (its disposers are sync) — the+ // The registry sweep only STARTS plugin disposal (its disposers are sync) — the// fallback for exit paths that skip the graceful shutdown. The graceful path awaits// host.dispose() itself, bounded (index.ts); dispose is idempotent, so both may fire.- if (extensions !== undefined) {- hmr.resources.register(EXTENSIONS_RESOURCE_ID, extensions, () => void extensions.dispose());+ if (plugins !== undefined) {+ hmr.resources.register(PLUGINS_RESOURCE_ID, plugins, () => void plugins.dispose());}// Boot the platform now rather than on the first request: the business surface —@@ -788,6 +788,13 @@ function registerStaticRoutes(app: Hono<AppEnv>, resolveSource: () => Promise<Weexport function buildAppDeps(caps: RuntimeCapabilities,overrides: BuildDepsOverrides = {},+ // Spawn confinement (mechanism only here): platform.ts's create() hands in a getter+ // over its own SandboxService, and it is threaded untouched through BOTH core entry+ // paths — the loader (resume/self-heal) and SessionService (creation) — then re-read+ // at every command spawn, like proxyEnv. Same-generation wiring on purpose: the+ // sessions spawning through it are hard-stopped with their App, so no channel with a+ // longer lifetime is needed. Policy itself lives in ../sandbox/.+ confineSpawn: () => SpawnConfiner | null = () => null,): AppDeps {const { config, db, authState, channels, hmr } = caps;const log = overrides.log ?? ((line: string) => console.log(line));@@ -966,7 +973,12 @@ export function buildAppDeps(channels,loader:overrides.loader ??- createCoreSessionLoader(config.root, sessionSources, { proxyEnv, controlEnv, pathPrepend }),+ createCoreSessionLoader(config.root, sessionSources, {+ proxyEnv,+ controlEnv,+ pathPrepend,+ confineSpawn,+ }),sources: sessionSources,recorder,errors,@@ -1077,6 +1089,7 @@ export function buildAppDeps(? enabled.channel: null;},+ confineSpawn,});// Schedule scheduler: assembled here, started by platform.ts's create() (tests drive it// via tickOnce, no real timer), stopped by the same create()'s dispose effect.diff --git a/packages/server/src/extension/index.ts b/packages/server/src/extension/index.tsdeleted file mode 100644index d60812f1..00000000--- a/packages/server/src/extension/index.ts+++ /dev/null@@ -1,30 +0,0 @@-/**- * The harness's extension surface — the `@prismshadow/penguin-server/extension` subpath.- *- * The contract itself lives in `@prismshadow/penguin-core/extension`; what this module adds- * is the harness's own members, contributed by AUGMENTING that contract rather than by- * redeclaring it. Core names nothing it cannot reach, this layer names what it owns, and- * an extension sees one `PenguinContext` either way.- *- * Re-exported here so an extension package has one import site for both halves.- */-import type { TerminalManager } from "../terminal/manager.js";--declare module "@prismshadow/penguin-core/extension" {- interface PenguinContext {- terminals: TerminalManager;- }-}--export type {- Disposable,- PenguinContext,- PenguinInterface,- Extension,- ExtensionContext,- ExtensionEvents,- ToolFactory,- WorkflowFactory,- WorkflowInstance,- WorkflowInstances,-} from "@prismshadow/penguin-core/extension";diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.tsindex f28d75f9..ec019cd6 100644--- a/packages/server/src/hmr/platform.ts+++ b/packages/server/src/hmr/platform.ts@@ -30,6 +30,12 @@ import { TerminalManager } from "../terminal/manager.js";import type { TerminalSession } from "../terminal/session.js";import { identityFrom } from "../terminal/identity.js";import { bindTerminalStream } from "../terminal/stream.js";+import type {+ PenguinInterface,+ SandboxProviderSource,+ SandboxSettings,+} from "@prismshadow/penguin-core/plugin";+import { SandboxService } from "../sandbox/index.js";import { buildAppDeps, createApp, type AppDeps, type BuildDepsOverrides } from "../app.js";import { seamHttp } from "./hono-seam.js";import {@@ -38,9 +44,9 @@ import {claimRuntimeCapabilities,} from "./capabilities.js";import type { Interfaces, MembersOf } from "./capabilities.js";-import type { PenguinInterface } from "../extension/index.js";-import { extensionHostFrom } from "../extension/host.js";-import { instantiateWorkflows, WorkflowFactories } from "../extension/workflow.js";+import type { HarnessContext } from "../plugin/index.js";+import { pluginHostFrom } from "../plugin/host.js";+import { instantiateWorkflows, WorkflowFactories } from "../plugin/workflow.js";export interface PlatformApi extends Park {info(): Json;@@ -78,12 +84,32 @@ export interface PlatformApi extends Park {* in the runtime's resource registry (they must — a swap disposes this tree), and the* document carries only their handle ids so the next instance can claim them back.*/-export type PlatformCtx = { motd: string; terminals?: string[] };+export type PlatformCtx = {+ motd: string;+ terminals?: string[];+ /**+ * Active sandbox settings — parked state, not service memory: a hot swap constructs a+ * fresh SandboxService, and without this the swap would silently reset a confining+ * deployment to unconfined. Optional so a document parked before the field existed+ * (and a default deployment, which never writes it) restores as confinement off.+ */+ sandbox?: SandboxSettings;+};export const PlatformIface = defineIface<PlatformApi, PlatformCtx>({name: "platform",version: 1,- context: schema<PlatformCtx>(type({ motd: "string", "terminals?": "string[]" })),+ context: schema<PlatformCtx>(+ type({+ motd: "string",+ "terminals?": "string[]",+ "sandbox?": {+ mode: "'read-only' | 'workspace-write' | 'danger-full-access'",+ "network?": "'none'",+ "maskPaths?": "string[]",+ },+ }),+ ),methods: ["park", "info", "http", "terminals", "attachStream"],});@@ -188,20 +214,50 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {// and must not adopt them. It does not dispose them either: that happens at the// commit below, so a failed boot leaves them for the recovered predecessor.terminals.adopt(doomedGroups.includes("terminal") ? [] : (context.terminals ?? []));- // The extension seam (see ../extension/index.ts): the definition view first, then the- // instance context, with the workflows built in between — so an extension that registers+ // The plugin seam (see ../plugin/index.ts): the definition view first, then the+ // instance context, with the workflows built in between — so a plugin that registers// one always sees it instantiated in the App it registered into. The host is CLAIMED- // from the registry, never imported (see extensionHostFrom).- const extensions = extensionHostFrom(ctx.resources);- const extIface: PenguinInterface = {+ // from the registry, never imported (see pluginHostFrom).+ const plugins = pluginHostFrom(ctx.resources);+ // Sandbox backends arrive as plugins through iface.sandbox (see ../plugin/);+ // duplicates are refused, and the service routes policies by capability.+ const sandboxProviders = new Map<string, SandboxProviderSource>();+ const pluginIface: PenguinInterface = {workflow: new WorkflowFactories(),tool: new Map(),+ sandbox: {+ registerProvider(name, provider) {+ if (sandboxProviders.has(name)) {+ throw new Error(`sandbox provider '${name}' is already registered`);+ }+ sandboxProviders.set(name, provider);+ },+ },};- extensions.emit("initialize", extIface);- extensions.emit("create", {- workflows: instantiateWorkflows(extIface.workflow),+ plugins.emit("initialize", pluginIface);+ // "Which commands run confined, under which policy, by which backend" is policy —+ // the whole capability lives in ../sandbox/ and reaches deployed machines by push;+ // only core's spawn seam is mechanism. The confiner reaches core as a plain argument+ // to buildAppDeps below — same-generation wiring, because the sessions that spawn+ // through it are hard-stopped with this App (see the dispose effect), so nothing+ // outlives the service that confines it.+ const sandbox = new SandboxService(sandboxProviders);+ // Rehydrate the parked settings (state rides the swap): without this, every hot push+ // would construct a fresh service on defaults and silently un-confine a deployment+ // that had confinement on.+ if (context.sandbox !== undefined) sandbox.configure(context.sandbox);+ // Typed as HarnessContext, not the bare contract: `terminals` is this harness's own+ // (see ../plugin/index.ts). Handlers receive it as PenguinContext and reach that+ // member only by casting, which is where the dependency on this embedder gets stated.+ const pluginContext: HarnessContext = {+ workflows: instantiateWorkflows(pluginIface.workflow),terminals,- });+ sandbox: {+ configure: (settings) => sandbox.configure(settings),+ settings: () => sandbox.currentSettings(),+ },+ };+ plugins.emit("create", pluginContext);// The business deps, built per App over the runtime's published capabilities — see// app.ts's buildAppDeps and ./capabilities.ts. Null only for a declared bare kernel;@@ -210,7 +266,7 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {if (caps === null) {console.warn("[platform] bare kernel: terminals only, no business surface");} else {- deps = buildAppDeps(caps, caps.overrides);+ deps = buildAppDeps(caps, caps.overrides, () => sandbox.confiner());// Schedule scheduler: startup reconciliation (missed, don't backfill) + periodic// scan; only active while this App is.await deps.scheduler.start();@@ -323,7 +379,18 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {// Deliberately NOT disposing the terminals here (no ctx.effect): the shells are// resources, and outliving a swap is the whole point. Process exit sweeps them// through the registry's own disposers.- park: () => ({ motd: context.motd, terminals: terminals.handleIds() }),+ park: () => {+ // The sandbox field is omitted while settings are the pristine default: a+ // default deployment keeps parking what it always did, compatible with any+ // bundle's schema; once confinement is configured, pushing a sandbox-ignorant+ // bundle blocks rather than silently un-confining.+ const parkedSandbox = sandbox.parkedSettings();+ return {+ motd: context.motd,+ terminals: terminals.handleIds(),+ ...(parkedSandbox !== undefined ? { sandbox: parkedSandbox } : {}),+ };+ },info: () => ({impl: "packaged",ifaceVersion: PlatformIface.version,diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex 3e6778f6..11cb564a 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -8,7 +8,7 @@* main() comes first in the file and is the sequence itself: each step is one PenguinServer* method, named after what it does and appearing in the order main() calls it. The order* carries real constraints — the proxy dispatcher before any outbound request, the instance- * lock before the database opens, extensions loaded before the platform boots against them,+ * lock before the database opens, plugins loaded before the platform boots against them,* the platform (and with it the whole business surface) before the first request is* served — so each step documents the constraint it stands on.*@@ -25,8 +25,8 @@ import { ADMIN_USER_ID } from "./auth/service.js";import { resolveServerConfig, type ServerConfig } from "./config.js";import { clearInitialAdminPassword, renderFirstLoginNotice } from "./initial-password.js";import { applyProxySettings, installGlobalProxyDispatcher } from "./net/proxy.js";-import { ExtensionHost } from "./extension/host.js";-import { loadExtensions } from "./extension/loader.js";+import { PluginHost } from "./plugin/host.js";+import { loadPlugins } from "./plugin/loader.js";import { attachTerminalWebSocket } from "./terminal/ws.js";import { loopbackHostRoles } from "./services/preview-token.js";import { acquireServerLock, liveServerLock, releaseServerLock } from "./lock.js";@@ -44,7 +44,7 @@ async function main(): Promise<void> {server.installProxy();server.readConfig();await server.ensureSoleInstance();- await server.loadExtensions();+ await server.loadPlugins();await server.buildDeps();server.applyPersistedProxy();server.buildApp();@@ -66,8 +66,8 @@ class PenguinServer {/** Assigned by readConfig(); every later step reads it. */private config!: ServerConfig;- /** Assigned by loadExtensions(); published to the platform tree by buildDeps(). */- private extensions!: ExtensionHost;+ /** Assigned by loadPlugins(); published to the platform tree by buildDeps(). */+ private plugins!: PluginHost;/** Assigned by buildDeps(); the merged runtime + business view (see app.ts). */private deps!: AppDeps;/** Assigned by buildApp(). */@@ -118,44 +118,44 @@ class PenguinServer {}/**- * Extensions are configuration, and reading configuration is the runtime's job: take the- * specifiers extensions.json names, import them, and register each into this process's one- * ExtensionHost. Once per process — a hot swap re-delivers the hooks to these same extension+ * 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.*- * An extension that fails to load is skipped with a warning instead of taking the server+ * 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* recover from, whereas a server that refuses to boot serves nobody.*/- async loadExtensions(): Promise<void> {- this.extensions = new ExtensionHost();- const result = await loadExtensions(this.config.root);- for (const { specifier, extension } of result.loaded) {- // use() runs the extension's activate (awaiting an async one) and rolls back whatever+ async loadPlugins(): Promise<void> {+ this.plugins = new PluginHost();+ const result = await loadPlugins(this.config.root);+ for (const { specifier, plugin } of result.loaded) {+ // use() runs the plugin's activate (awaiting an async one) and rolls back whatever// it registered before failing; a throw here is a LOAD failure, isolated per entry// like an import failure, not a per-App handler failure.try {- await this.extensions.use(extension);+ await this.plugins.use(plugin);} catch (err) {result.failed.set(specifier, err instanceof Error ? err.message : String(err));}}for (const [specifier, reason] of result.failed) {- console.warn(`[extensions] skipped ${specifier}: ${reason}`);+ console.warn(`[plugins] skipped ${specifier}: ${reason}`);}}/*** Builds the service graph: opens the database, publishes the runtime capabilities —- * the loaded extension host among them — and boots the platform, whose create() assembles- * the whole business surface (services, routes, the scheduler) and delivers the extension+ * the loaded plugin host among them — and boots the platform, whose create() assembles+ * the whole business surface (services, routes, the scheduler) and delivers the plugin* hooks. The host is handed in rather than registered here because the platform boots* INSIDE bootAppDeps: everything it claims has to be in the registry first, and the* registry is the only way a pushed bundle — compiled standalone — can reach these- * extension objects at all (see extension/index.ts's extensionHostFrom).+ * plugin objects at all (see plugin/index.ts's pluginHostFrom).*/async buildDeps(): Promise<void> {- this.deps = await bootAppDeps(this.config, {}, this.extensions);+ this.deps = await bootAppDeps(this.config, {}, this.plugins);}/**@@ -382,12 +382,12 @@ class PenguinServer {// for wrap-up) — through the instance the host holds, which a hot swap keeps current;// no registry pointer needed.await (await this.deps.hmr.ensure()).api.shutdown();- // Extension disposables: async-capable and awaited HERE — the one exit path that can+ // Plugin disposables: async-capable and awaited HERE — the one exit path that can// await — under the same ≤5s convention as the manager's wrap-up above. The registry// sweep below would only fire them without awaiting. Idempotent, so the sweep's// fallback firing right after is a no-op.await Promise.race([- this.extensions.dispose(),+ this.plugins.dispose(),new Promise<void>((resolve) => setTimeout(resolve, 5000).unref()),]);// Disposing the host drains the App's effects (scheduler stop, manager hard-stop) anddiff --git a/packages/server/src/extension/host.ts b/packages/server/src/plugin/host.tssimilarity index 59%rename from packages/server/src/extension/host.tsrename to packages/server/src/plugin/host.tsindex b2629a0e..91f74feb 100644--- a/packages/server/src/extension/host.ts+++ b/packages/server/src/plugin/host.ts@@ -1,47 +1,42 @@/**- * The extension host: it owns activation, event delivery and disposal. Kept out of- * ./index.ts so the published `@prismshadow/penguin-server/extension` subpath stays types- * only — an extension package cannot take a runtime dependency on the harness even by+ * The plugin host: it owns activation, event delivery and disposal. Kept out of+ * ./index.ts so the published `@prismshadow/penguin-server/plugin` subpath stays types+ * only — a plugin package cannot take a runtime dependency on the harness even by* accident, which is what keeps it a self-contained library.*/import type { Resources } from "@prismshadow/penguin-core/kernel";-import type { Disposable, Extension, ExtensionEvents } from "./index.js";+import type { Disposable, Plugin, PluginEvents } from "@prismshadow/penguin-core/plugin";interface ActivatedPlugin {- handlers: { [E in keyof ExtensionEvents]?: Array<(payload: ExtensionEvents[E]) => void> };+ handlers: { [E in keyof PluginEvents]?: Array<(payload: PluginEvents[E]) => void> };disposables: Disposable[];}/** One host per server process; activation order is delivery order. */-export class ExtensionHost {- private readonly extensions: ActivatedPlugin[] = [];+export class PluginHost {+ private readonly plugins: ActivatedPlugin[] = [];/*** Runs `activate` (awaiting it when async), then seals its subscription window.*- * TRANSACTIONAL: an extension may have registered disposables before it threw, and the+ * TRANSACTIONAL: a plugin may have registered disposables before it threw, and the* caller is about to drop it — so those run here, before the failure is reported.* Without this the entry is never published and `dispose()` could never reach them.*/- async use(extension: Extension): Promise<void> {+ async use(plugin: Plugin): Promise<void> {const entry: ActivatedPlugin = { handlers: {}, disposables: [] };let sealed = false;try {- await extension.activate({- on<E extends keyof ExtensionEvents>(- event: E,- handler: (payload: ExtensionEvents[E]) => void,- ) {+ await plugin.activate({+ on<E extends keyof PluginEvents>(event: E, handler: (payload: PluginEvents[E]) => void) {if (sealed) {throw new Error(- `extension subscribed to '${event}' after activate settled — a handler-time ` ++ `plugin subscribed to '${event}' after activate settled — a handler-time ` +`subscription would accumulate one copy per hot swap`,);}// Sound, but under a generic key TS folds the mapped type to a union.- const list = (entry.handlers[event] ??= []) as Array<- (payload: ExtensionEvents[E]) => void- >;+ const list = (entry.handlers[event] ??= []) as Array<(payload: PluginEvents[E]) => void>;list.push(handler);},disposables: entry.disposables,@@ -53,12 +48,12 @@ export class ExtensionHost {}sealed = true;Object.freeze(entry.disposables);- this.extensions.push(entry);+ this.plugins.push(entry);}- emit<E extends keyof ExtensionEvents>(event: E, payload: ExtensionEvents[E]): void {- for (const extension of this.extensions) {- for (const handler of extension.handlers[event] ?? []) {+ emit<E extends keyof PluginEvents>(event: E, payload: PluginEvents[E]): void {+ for (const plugin of this.plugins) {+ for (const handler of plugin.handlers[event] ?? []) {// An App is assembled synchronously around this call, so a returned promise// could not be awaited and its rejection would escape unhandled — possibly// killing the process, since boot runs before the process handlers are on.@@ -73,7 +68,7 @@ export class ExtensionHost {(returned as Promise<unknown>).catch(() => {});}throw new Error(- `extension handler for '${event}' returned a promise — event handlers must be ` ++ `plugin handler for '${event}' returned a promise — event handlers must be ` +`synchronous (do async work in activate, or start it without awaiting)`,);}@@ -87,12 +82,12 @@ export class ExtensionHost {* — the graceful shutdown awaits it (bounded), the registry sweep only starts it.*/async dispose(): Promise<void> {- const extensions = this.extensions.splice(0);- await runDisposables(extensions.flatMap((extension) => [...extension.disposables]));+ const plugins = this.plugins.splice(0);+ await runDisposables(plugins.flatMap((plugin) => [...plugin.disposables]));}}-/** Concurrent, failure-isolated teardown — see {@link ExtensionHost.dispose}. */+/** Concurrent, failure-isolated teardown — see {@link PluginHost.dispose}. */async function runDisposables(disposables: readonly Disposable[]): Promise<void> {await Promise.all(disposables.map(async (disposable) => {@@ -100,7 +95,7 @@ async function runDisposables(disposables: readonly Disposable[]): Promise<void>await disposable.dispose();} catch (err) {console.warn(- `[extensions] disposer failed: ${err instanceof Error ? err.message : String(err)}`,+ `[plugins] disposer failed: ${err instanceof Error ? err.message : String(err)}`,);}}),@@ -108,16 +103,16 @@ async function runDisposables(disposables: readonly Disposable[]): Promise<void>}/** Registry key the runtime publishes its loaded host under. */-export const EXTENSIONS_RESOURCE_ID = "runtime:extensions";+export const PLUGINS_RESOURCE_ID = "runtime:plugins";/*** The host the runtime loaded (see ./loader.ts), or an empty one — the honest reading- * of "this runtime knows nothing about extensions".+ * of "this runtime knows nothing about plugins".** CLAIMED, not imported: a pushed bundle is compiled standalone, so a module-level host- * inside it would be a second, empty one and every configured extension would go missing+ * inside it would be a second, empty one and every configured plugin would go missing* on the first hot push.*/-export function extensionHostFrom(resources: Resources): ExtensionHost {- return resources.claim<ExtensionHost>(EXTENSIONS_RESOURCE_ID) ?? new ExtensionHost();+export function pluginHostFrom(resources: Resources): PluginHost {+ return resources.claim<PluginHost>(PLUGINS_RESOURCE_ID) ?? new PluginHost();}diff --git a/packages/server/src/plugin/index.ts b/packages/server/src/plugin/index.tsnew file mode 100644index 00000000..eec27358--- /dev/null+++ b/packages/server/src/plugin/index.ts@@ -0,0 +1,30 @@+/**+ * What this harness offers a plugin BEYOND the contract — the+ * `@prismshadow/penguin-server/plugin` subpath.+ *+ * The contract is `@prismshadow/penguin-core/plugin` and is CLOSED: this module does not+ * reopen it by declaration merging. Augmenting it would put `terminals` into the contract+ * itself, so a plugin type-checking against core would compile against a member only+ * THIS embedder supplies, with nothing at the core layer able to say so.+ *+ * What the harness offers beyond the contract is named here instead, on an interface that+ * EXTENDS it. Values of that type still satisfy the contract, so the seam is unchanged;+ * what changes is that a plugin wanting `terminals` writes the cast itself+ * (`ctx as HarnessContext`) and thereby states, at the point of use, that it depends on+ * running inside this harness rather than on any embedder.+ *+ * Nor does this module re-export the contract. A plugin imports the contract from core+ * and this subpath only for what its name promises, so a package's import sites say which+ * of the two it actually needs: a sandbox backend, written against the sandbox vocabulary+ * and nothing else, names core alone and does not depend on this package at all.+ */+import type { PenguinContext } from "@prismshadow/penguin-core/plugin";+import type { TerminalManager } from "../terminal/manager.js";++/**+ * The instance view this harness actually hands to `"create"` handlers: the contract plus+ * the members only it owns. A plugin reaching `terminals` casts to this deliberately.+ */+export interface HarnessContext extends PenguinContext {+ terminals: TerminalManager;+}diff --git a/packages/server/src/extension/loader.ts b/packages/server/src/plugin/loader.tssimilarity index 62%rename from packages/server/src/extension/loader.tsrename to packages/server/src/plugin/loader.tsindex 25e4dc14..0593ab9e 100644--- a/packages/server/src/extension/loader.ts+++ b/packages/server/src/plugin/loader.ts@@ -1,51 +1,51 @@/**- * Extension loading: WHICH extensions a deployment runs is CONFIGURATION, not capability+ * 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>/extensions.json` lists them and each entry resolves against the+ * delivers one — `<root>/plugins.json` lists them and each entry resolves against the* INSTALLATION, so installing or upgrading one is an install-side action.** 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* its own, so anchoring at the bundle would find nothing.*- * Failure is per-entry and non-fatal: an unresolvable or malformed extension is reported+ * Failure is per-entry and non-fatal: an unresolvable or malformed plugin is reported* and skipped, leaving its capability unavailable rather than failing the boot.*/import fs from "node:fs/promises";import { createRequire } from "node:module";import path from "node:path";import { pathToFileURL } from "node:url";-import type { Extension } from "./index.js";+import type { Plugin } from "@prismshadow/penguin-core/plugin";/** The config file's name inside the data root. */-export const EXTENSIONS_FILE = "extensions.json";+export const PLUGINS_FILE = "plugins.json";-export interface LoadedExtension {+export interface LoadedPlugin {specifier: string;- extension: Extension;+ plugin: Plugin;}-export interface ExtensionLoadResult {- loaded: LoadedExtension[];+export interface PluginLoadResult {+ loaded: LoadedPlugin[];/** specifier → why it was skipped. */failed: Map<string, string>;}/**- * An ABSENT file means "no extensions" — the default deployment shape, not an error. Any+ * 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 readExtensionList(root: string): Promise<string[]> {+export async function readPluginList(root: string): Promise<string[]> {let text: string;try {- text = await fs.readFile(path.join(root, EXTENSIONS_FILE), "utf8");+ text = await fs.readFile(path.join(root, PLUGINS_FILE), "utf8");} catch (err) {if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];throw new Error(- `${EXTENSIONS_FILE} exists but could not be read: ${err instanceof Error ? err.message : String(err)}`,+ `${PLUGINS_FILE} exists but could not be read: ${err instanceof Error ? err.message : String(err)}`,);}let parsed: unknown;@@ -53,18 +53,18 @@ export async function readExtensionList(root: string): Promise<string[]> {parsed = JSON.parse(text);} catch (err) {throw new Error(- `${EXTENSIONS_FILE} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,+ `${PLUGINS_FILE} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,);}- const list = (parsed as { extensions?: unknown }).extensions;+ const list = (parsed as { plugins?: unknown }).plugins;if (!Array.isArray(list) || list.some((entry) => typeof entry !== "string")) {- throw new Error(`${EXTENSIONS_FILE} must be { "extensions": ["<package specifier>", …] }`);+ throw new Error(`${PLUGINS_FILE} must be { "plugins": ["<package specifier>", …] }`);}return list as string[];}/** Resolved against the installation rather than the bundle's location. */-async function importExtension(specifier: string): Promise<unknown> {+async function importPlugin(specifier: string): Promise<unknown> {const entry = process.argv[1];if (typeof entry === "string" && entry.length > 0) {try {@@ -77,35 +77,35 @@ async function importExtension(specifier: string): Promise<unknown> {return await import(specifier);}-/** An extension module's contract is one named export: `activate(ctx)`. */-function asExtension(module: unknown): Extension | null {+/** A plugin module's contract is one named export: `activate(ctx)`. */+function asPlugin(module: unknown): Plugin | null {const activate = (module as { activate?: unknown }).activate;- return typeof activate === "function" ? { activate: activate as Extension["activate"] } : null;+ return typeof activate === "function" ? { activate: activate as Plugin["activate"] } : null;}/**- * Loads every configured extension.+ * Loads every configured plugin.** The two failure classes are deliberately different. A PER-ENTRY failure (unresolvable* specifier, no `activate` export, 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 extension set would present as a healthy server that silently dropped every+ * with an empty plugin set would present as a healthy server that silently dropped every* capability the config asked for.*/-export async function loadExtensions(root: string): Promise<ExtensionLoadResult> {+export async function loadPlugins(root: string): Promise<PluginLoadResult> {const failed = new Map<string, string>();- const specifiers = await readExtensionList(root);- const loaded: LoadedExtension[] = [];+ const specifiers = await readPluginList(root);+ const loaded: LoadedPlugin[] = [];for (const specifier of specifiers) {try {- const extension = asExtension(await importExtension(specifier));- if (extension === null) {+ const plugin = asPlugin(await importPlugin(specifier));+ if (plugin === null) {failed.set(specifier, "module does not export an activate(ctx) function");continue;}- loaded.push({ specifier, extension });+ loaded.push({ specifier, plugin });} catch (err) {failed.set(specifier, err instanceof Error ? err.message : String(err));}diff --git a/packages/server/src/extension/workflow.ts b/packages/server/src/plugin/workflow.tssimilarity index 76%rename from packages/server/src/extension/workflow.tsrename to packages/server/src/plugin/workflow.tsindex 0dd4eaa2..de7506f5 100644--- a/packages/server/src/extension/workflow.ts+++ b/packages/server/src/plugin/workflow.ts@@ -1,13 +1,17 @@/*** Building the workflow instance view. The types are the SDK's contract- * (`@prismshadow/penguin-core/extension`); this is the harness's implementation of it.+ * (`@prismshadow/penguin-core/plugin`); this is the harness's implementation of it.*/-import type { WorkflowFactory, WorkflowInstance, WorkflowInstances } from "./index.js";+import type {+ WorkflowFactory,+ WorkflowInstance,+ WorkflowInstances,+} from "@prismshadow/penguin-core/plugin";/**- * The Map handed to extensions at `"initialize"` — `iface.workflow` itself — with the one+ * The Map handed to plugins at `"initialize"` — `iface.workflow` itself — with the one* guarantee the contract states: a duplicate name is an ERROR, not a silent replacement.- * A bare Map would make the winner depend on extensions.json ordering, and an extension could+ * A bare Map would make the winner depend on plugins.json ordering, and a plugin could* take over a name another one already owns without either noticing.** Named for what it holds rather than for the concept: a workflow REGISTRY is the App'sdiff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex 5585ea9b..6baa8649 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -48,6 +48,7 @@ import type {ControlEnvContext,OmniMessage,ProxyEnvPolicy,+ SpawnConfiner,SessionMetaPayload,SessionTitleResult,SubagentMessageOptions,@@ -233,6 +234,7 @@ export function createCoreSessionLoader(proxyEnv?: () => ProxyEnvPolicy | null;controlEnv?: (ctx: ControlEnvContext) => Record<string, string>;pathPrepend?: () => string[];+ confineSpawn?: () => SpawnConfiner | null;} = {},): SessionLoader {return {@@ -244,6 +246,7 @@ export function createCoreSessionLoader(...(opts.proxyEnv ? { proxyEnv: opts.proxyEnv } : {}),...(opts.controlEnv ? { controlEnv: opts.controlEnv } : {}),...(opts.pathPrepend ? { pathPrepend: opts.pathPrepend } : {}),+ ...(opts.confineSpawn ? { confineSpawn: opts.confineSpawn } : {}),});const located = await findLatestTraceFile(tracesDir(root, row.projectId, row.agentId),diff --git a/packages/server/src/sandbox/dimensions.ts b/packages/server/src/sandbox/dimensions.tsnew file mode 100644index 00000000..0f04901e--- /dev/null+++ b/packages/server/src/sandbox/dimensions.ts@@ -0,0 +1,35 @@+/**+ * Runtime helpers over the sandbox vocabulary.+ *+ * The vocabulary itself is `@prismshadow/penguin-core/plugin` — a backend compiles+ * against those names, so they belong with the rest of the plugin contract rather than+ * inside the harness that routes them. What stays here is the code that READS those+ * shapes: which dimensions a provider covers and which a settings object requires, the two+ * questions service.ts routes on. That is the embedder's business, and keeping it out of+ * the contract is what stops it becoming a runtime dependency of every plugin package.+ */+import type {+ SandboxDimension,+ SandboxProvider,+ SandboxSettings,+} from "@prismshadow/penguin-core/plugin";++/** Every dimension, in the order error messages list them. */+export const SANDBOX_DIMENSIONS: readonly SandboxDimension[] = [+ "fs-write",+ "network",+ "mask-paths",+];++/** The dimensions a provider implements (absent declaration = filesystem only). */+export function providerDimensions(provider: SandboxProvider): readonly SandboxDimension[] {+ return provider.dimensions ?? ["fs-write"];+}++/** The dimensions a settings object actually requires. */+export function requestedDimensions(settings: SandboxSettings): SandboxDimension[] {+ const dims: SandboxDimension[] = ["fs-write"];+ if (settings.network !== undefined) dims.push("network");+ if (settings.maskPaths !== undefined && settings.maskPaths.length > 0) dims.push("mask-paths");+ return dims;+}diff --git a/packages/server/src/sandbox/index.ts b/packages/server/src/sandbox/index.tsnew file mode 100644index 00000000..6f89761f--- /dev/null+++ b/packages/server/src/sandbox/index.ts@@ -0,0 +1,34 @@+/**+ * The sandbox capability: the service that routes each spawn's policy to whatever backend+ * implements it. Reached from hmr/platform.ts, so it rides the platform bundle — a+ * deployment changes it by one hot push.+ *+ * The vocabulary it routes ON is not here. `SandboxPolicy`, `SandboxProvider`,+ * `ConfinedArgv` and the mode/dimension unions belong to the plugin contract in+ * `@prismshadow/penguin-core/plugin`, because a backend is written against those names+ * and nothing else. What this directory holds is the embedder's half: which policy reaches+ * which backend, the settings behind it, and the fail-closed behaviour when nothing covers+ * the request.+ *+ * No backend is part of it. Backends are PLUGIN PACKAGES a deployment configures+ * (../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+ *+ * The backends shipped in this repo:+ *+ * plugin platform fs-write network mask-paths+ * penguin-plugin-sandbox-bwrap Linux yes yes yes+ * penguin-plugin-sandbox-seatbelt macOS yes yes yes+ * penguin-plugin-sandbox-mxc Windows yes yes yes+ * penguin-plugin-sandbox-dsh all three yes — —+ *+ * The DSH adaptor is the portable floor covering file effects only (its own chain picks+ * bwrap/Landlock, Seatbelt or the Windows ACL runner per host); the three native+ * backends add the other two dimensions, one per platform. Where none implements a+ * requested dimension, service.ts fails closed naming what each covers rather than+ * quietly confining less than was asked.+ */+export { SandboxService } from "./service.js";+export { SANDBOX_DIMENSIONS, providerDimensions, requestedDimensions } from "./dimensions.js";diff --git a/packages/server/src/sandbox/service.ts b/packages/server/src/sandbox/service.tsnew file mode 100644index 00000000..45d095b6--- /dev/null+++ b/packages/server/src/sandbox/service.ts@@ -0,0 +1,161 @@+/**+ * The sandbox service: owns the registered backends, routes each spawn's policy to a+ * backend that implements the dimensions it requires, and produces the SpawnConfiner+ * closure the runtime transports into core's command-session seam.+ *+ * Routing is by CAPABILITY, not by registration order alone: a policy requiring only+ * `fs-write` goes to the first backend that covers it (the DSH adaptor, which works on+ * Linux/macOS/Windows alike), while a policy also requiring `network` or `mask-paths`+ * goes to the first backend implementing those (penguin-bwrap). Registration order+ * only breaks ties between backends that both cover the request. A request nothing+ * covers fails closed — never a silent unconfined run, and never a silently dropped+ * dimension.+ */+import type { SpawnConfiner } from "@prismshadow/penguin-core";+import type {+ SandboxDimension,+ SandboxPolicy,+ SandboxProvider,+ SandboxProviderSource,+ SandboxSettings,+} from "@prismshadow/penguin-core/plugin";+import { providerDimensions, requestedDimensions } from "./dimensions.js";++interface MountedProvider {+ name: string;+ provider: SandboxProvider;+}++export class SandboxService {+ private readonly mounted: MountedProvider[] = [];+ /** name → why it failed to load; surfaced in the fail-closed message. */+ private readonly loadErrors = new Map<string, string>();+ /**+ * Ships with confinement OFF (`danger-full-access`): the default flips to+ * workspace-write together with the deployment-facing config surface, so a+ * deployment gains the switch before the enforcement — otherwise every host without+ * a usable backend would fail every command the moment this code arrives.+ */+ private settings: SandboxSettings = { mode: "danger-full-access" };+ private readonly ready: Promise<void>;++ /**+ * @param registrations - the backends plugins registered (see the sandbox registry on+ * PenguinInterface). Loading is async, but create() and the confiner are sync: a+ * confining policy resolved before loading settles fails closed rather than+ * waiting. The default settings never consult a backend, so that window only+ * exists for deployments flipping the mode in the first milliseconds after boot.+ */+ constructor(registrations: Iterable<[string, SandboxProviderSource]> = []) {+ this.ready = (async () => {+ for (const [name, source] of registrations) {+ try {+ const provider = await source;+ if (provider !== null && provider !== undefined) this.mounted.push({ name, provider });+ } catch (err) {+ this.loadErrors.set(name, err instanceof Error ? err.message : String(err));+ }+ }+ })();+ }++ /** Resolves when every registered backend has loaded (or failed to). */+ whenReady(): Promise<void> {+ return this.ready;+ }++ /** Replaces the active settings (the config surface's write path). */+ configure(settings: SandboxSettings): void {+ this.settings = settings;+ }++ /** The active settings as a plain copy (the config surface's read side). */+ currentSettings(): SandboxSettings {+ return copySettings(this.settings);+ }++ /**+ * The active settings as parked state, or undefined for the pristine default. The+ * omission is load-bearing compatibility: a default deployment keeps parking+ * `{ motd }`, which any platform bundle's context schema accepts. Once confinement+ * is configured the field enters the document, and from then on pushing a+ * sandbox-ignorant bundle is BLOCKED by schema validation — the right failure:+ * refusing the swap beats a swap that silently un-confines the deployment.+ */+ parkedSettings(): SandboxSettings | undefined {+ const s = this.settings;+ if (s.mode === "danger-full-access" && s.network === undefined && s.maskPaths === undefined) {+ return undefined;+ }+ return copySettings(s);+ }++ /** The mounted backends and what each implements (diagnostics / the config surface). */+ backends(): Array<{ name: string; dimensions: readonly SandboxDimension[] }> {+ return this.mounted.map(({ name, provider }) => ({+ name,+ dimensions: providerDimensions(provider),+ }));+ }++ /**+ * The closure handed to the runtime: rewrites each spawn's argv under the active+ * settings. Pure and self-contained, so the previous platform's confiner keeps+ * serving during a hot-swap freeze window.+ */+ confiner(): SpawnConfiner {+ return (argv, opts) => {+ const settings = this.settings;+ if (settings.mode === "danger-full-access") return argv;+ const required = requestedDimensions(settings);+ const provider = this.pick(required, settings.mode);+ // workspaceRoot is the Session's Workspace, never the per-command cwd: a command+ // running in a workdir outside the Workspace must not widen the writable roots.+ const policy: SandboxPolicy = {+ mode: settings.mode,+ workspaceRoot: opts.workspaceDir,+ ...(settings.network !== undefined ? { network: settings.network } : {}),+ ...(settings.maskPaths !== undefined && settings.maskPaths.length > 0+ ? { maskPaths: settings.maskPaths }+ : {}),+ };+ // ConfinedArgv also carries enforcement / denialSignatures / runnerFailureRules;+ // the classification consumer (denial vs runner failure) lands with escalation.+ return provider.confine(argv, policy).argv;+ };+ }++ /** The first mounted backend implementing every required dimension, or a fail-closed throw. */+ private pick(required: readonly SandboxDimension[], mode: string): SandboxProvider {+ const match = this.mounted.find(({ provider }) => {+ const implemented = providerDimensions(provider);+ return required.every((dimension) => implemented.includes(dimension));+ });+ if (match !== undefined) return match.provider;+ throw new Error(+ this.mounted.length === 0+ ? `sandbox mode "${mode}" is configured but no sandbox backend is mounted${this.failedSuffix()}; ` ++ "refusing to run the command unconfined."+ : `sandbox policy requires ${required.join(" + ")}, but no mounted sandbox backend ` ++ `implements all of it (${this.mounted+ .map(({ name, provider }) => `${name}: ${providerDimensions(provider).join(", ")}`)+ .join("; ")})${this.failedSuffix()}; refusing to run the command unconfined.`,+ );+ }++ private failedSuffix(): string {+ if (this.loadErrors.size === 0) return "";+ const failures = [...this.loadErrors]+ .map(([name, message]) => `${name} (${message})`)+ .join("; ");+ return `; backends that failed to load: ${failures}`;+ }+}++function copySettings(settings: SandboxSettings): SandboxSettings {+ return {+ mode: settings.mode,+ ...(settings.network !== undefined ? { network: settings.network } : {}),+ ...(settings.maskPaths !== undefined ? { maskPaths: [...settings.maskPaths] } : {}),+ };+}diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.tsindex d472ec73..49d25dc1 100644--- a/packages/server/src/services/session-service.ts+++ b/packages/server/src/services/session-service.ts@@ -15,7 +15,7 @@*/import fs from "node:fs/promises";import { agentsDir, createAgent, isSessionMeta } from "@prismshadow/penguin-core";-import type { ControlEnvContext, ProxyEnvPolicy } from "@prismshadow/penguin-core";+import type { ControlEnvContext, ProxyEnvPolicy, SpawnConfiner } from "@prismshadow/penguin-core";import type {ApprovalMode,MessagingChannel,@@ -79,6 +79,8 @@ export interface SessionServiceDeps {* means the field is never set.*/messagingChannel?: (sessionId: string) => MessagingChannel | null;+ /** Spawn-confinement getter (see app.ts): claimed from the platform's registered resource, forwarded into core beside proxyEnv. */+ confineSpawn?: () => SpawnConfiner | null;}export class SessionService {@@ -365,6 +367,7 @@ export class SessionService {...(this.deps.proxyEnv ? { proxyEnv: this.deps.proxyEnv } : {}),...(this.deps.controlEnv ? { controlEnv: this.deps.controlEnv } : {}),...(this.deps.pathPrepend ? { pathPrepend: this.deps.pathPrepend } : {}),+ ...(this.deps.confineSpawn ? { confineSpawn: this.deps.confineSpawn } : {}),});let session;try {diff --git a/packages/server/test/extension-loader.test.ts b/packages/server/test/extension-loader.test.tsdeleted file mode 100644index 9d8aa009..00000000--- a/packages/server/test/extension-loader.test.ts+++ /dev/null@@ -1,105 +0,0 @@-/**- * Behavior tests for extension loading: extensions are CONFIGURATION read from the data- * root, resolved against the installation, and every failure is per-entry and- * non-fatal — the capability an extension 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 { tmpdir } from "node:os";-import path from "node:path";-import { EXTENSIONS_FILE, loadExtensions, readExtensionList } from "../src/extension/loader.js";--let root: string;--beforeEach(async () => {- root = await mkdtemp(path.join(tmpdir(), "penguin-extensions-"));-});-afterEach(async () => {- await rm(root, { recursive: true, force: true });-});--async function writeConfig(value: unknown): Promise<void> {- await writeFile(path.join(root, EXTENSIONS_FILE), JSON.stringify(value), "utf8");-}--/** An extension module on disk, imported by absolute specifier (the dev-checkout path). */-async function writeExtensionModule(name: string, body: string): Promise<string> {- const dir = path.join(root, "mods");- await mkdir(dir, { recursive: true });- const file = path.join(dir, `${name}.mjs`);- await writeFile(file, body, "utf8");- return file;-}--describe("extension list", () => {- it("no config file means no extensions — the default deployment shape, not an error", async () => {- expect(await readExtensionList(root)).toEqual([]);- expect(await loadExtensions(root)).toEqual({ loaded: [], failed: new Map() });- });-- it("reads the configured specifiers in order", async () => {- await writeConfig({ extensions: ["a", "b"] });- expect(await readExtensionList(root)).toEqual(["a", "b"]);- });-- it("a malformed config fails the load rather than presenting as empty", async () => {- await writeFile(path.join(root, EXTENSIONS_FILE), "{not json", "utf8");- await expect(readExtensionList(root)).rejects.toThrow(/not valid JSON/);- // A CONFIG-level failure propagates: booting with an empty extension set would present- // as healthy while silently dropping every capability the config asked for.- await expect(loadExtensions(root)).rejects.toThrow(/not valid JSON/);- });-- it("a config that exists but cannot be read is an error, not 'no extensions'", 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, EXTENSIONS_FILE));- await expect(readExtensionList(root)).rejects.toThrow(/exists but could not be read/);- await expect(loadExtensions(root)).rejects.toThrow(/exists but could not be read/);- });-- it("a config with the wrong shape names the shape it wanted", async () => {- await writeConfig({ extensions: [1, 2] });- await expect(readExtensionList(root)).rejects.toThrow(/package specifier/);- });-});--describe("extension loading", () => {- it("loads an extension module's exported activate", async () => {- const file = await writeExtensionModule("ok", "export function activate() {}");- await writeConfig({ extensions: [file] });- const result = await loadExtensions(root);- expect(result.failed.size).toBe(0);- expect(result.loaded).toHaveLength(1);- expect(result.loaded[0]!.specifier).toBe(file);- expect(typeof result.loaded[0]!.extension.activate).toBe("function");- });-- it("an unresolvable specifier is skipped with its reason, not fatal", async () => {- const good = await writeExtensionModule("good", "export function activate() {}");- await writeConfig({ extensions: ["@nope/definitely-not-installed", good] });- const result = await loadExtensions(root);- // The good one still loads: failure is per entry.- expect(result.loaded.map((entry) => entry.specifier)).toEqual([good]);- expect(result.failed.get("@nope/definitely-not-installed")).toBeTruthy();- });-- it("a module without an activate export is skipped, saying what was expected", async () => {- const file = await writeExtensionModule("bad", "export default { activate() {} };");- await writeConfig({ extensions: [file] });- const result = await loadExtensions(root);- // The contract is the NAMED export — an activate tucked inside a default object is- // not it, and tolerating it would fork the ecosystem into two shapes.- expect(result.loaded).toEqual([]);- expect(result.failed.get(file)).toMatch(/activate\(ctx\) function/);- });-- it("an extension that throws while loading is skipped with its error", async () => {- const file = await writeExtensionModule("throws", "throw new Error('boom at import');");- await writeConfig({ extensions: [file] });- const result = await loadExtensions(root);- expect(result.loaded).toEqual([]);- expect(result.failed.get(file)).toMatch(/boom at import/);- });-});diff --git a/packages/server/test/plugin-loader.test.ts b/packages/server/test/plugin-loader.test.tsnew file mode 100644index 00000000..5f8db562--- /dev/null+++ b/packages/server/test/plugin-loader.test.ts@@ -0,0 +1,105 @@+/**+ * Behavior tests for plugin loading: plugins are CONFIGURATION read from the data+ * root, resolved against the installation, and every failure is per-entry and+ * 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 { tmpdir } from "node:os";+import path from "node:path";+import { PLUGINS_FILE, loadPlugins, readPluginList } from "../src/plugin/loader.js";++let root: string;++beforeEach(async () => {+ root = await mkdtemp(path.join(tmpdir(), "penguin-plugins-"));+});+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 plugin module on disk, imported by absolute specifier (the dev-checkout path). */+async function writePluginModule(name: string, body: string): Promise<string> {+ const dir = path.join(root, "mods");+ await mkdir(dir, { recursive: true });+ const file = path.join(dir, `${name}.mjs`);+ await writeFile(file, body, "utf8");+ return file;+}++describe("plugin list", () => {+ it("no config file means no plugins — the default deployment shape, not an error", async () => {+ expect(await readPluginList(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"]);+ });++ 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("a config that exists but cannot be read is an error, not 'no plugins'", 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/);+ });++ 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/);+ });+});++describe("plugin loading", () => {+ it("loads a plugin module's exported activate", async () => {+ const file = await writePluginModule("ok", "export function activate() {}");+ await writeConfig({ plugins: [file] });+ const result = await loadPlugins(root);+ expect(result.failed.size).toBe(0);+ expect(result.loaded).toHaveLength(1);+ expect(result.loaded[0]!.specifier).toBe(file);+ expect(typeof result.loaded[0]!.plugin.activate).toBe("function");+ });++ it("an unresolvable specifier is skipped with its reason, not fatal", async () => {+ const good = await writePluginModule("good", "export function activate() {}");+ await writeConfig({ plugins: ["@nope/definitely-not-installed", good] });+ const result = await loadPlugins(root);+ // The good one still loads: failure is per entry.+ expect(result.loaded.map((entry) => entry.specifier)).toEqual([good]);+ expect(result.failed.get("@nope/definitely-not-installed")).toBeTruthy();+ });++ it("a module without an activate export is skipped, saying what was expected", async () => {+ const file = await writePluginModule("bad", "export default { activate() {} };");+ await writeConfig({ plugins: [file] });+ const result = await loadPlugins(root);+ // The contract is the NAMED export — an activate tucked inside a default object is+ // not it, and tolerating it would fork the ecosystem into two shapes.+ expect(result.loaded).toEqual([]);+ expect(result.failed.get(file)).toMatch(/activate\(ctx\) function/);+ });++ it("a plugin that throws while loading is skipped with its error", async () => {+ const file = await writePluginModule("throws", "throw new Error('boom at import');");+ await writeConfig({ plugins: [file] });+ const result = await loadPlugins(root);+ expect(result.loaded).toEqual([]);+ expect(result.failed.get(file)).toMatch(/boom at import/);+ });+});diff --git a/packages/server/test/extension.test.ts b/packages/server/test/plugin.test.tssimilarity index 82%rename from packages/server/test/extension.test.tsrename to packages/server/test/plugin.test.tsindex 27449c77..6ceb1488 100644--- a/packages/server/test/extension.test.ts+++ b/packages/server/test/plugin.test.ts@@ -1,5 +1,5 @@/**- * Behavior tests for the extension seam: activate-once and its sealed subscription window,+ * Behavior tests for the plugin seam: activate-once and its sealed subscription window,* typed event delivery in activation order, the two views (definition iface / flattened* instance context), disposables, workflow registration and calling, and re-delivery on* the boot a hot swap performs.@@ -9,19 +9,28 @@ import { boot, initialDoc } from "@prismshadow/penguin-core/kernel";import { HotResources } from "../src/hmr/resources.js";import { packagedPlatform } from "../src/hmr/platform.js";import { PENGUIN_FAMILY, RUNTIME_INTERFACES_RESOURCE_ID } from "../src/hmr/capabilities.js";-import { EXTENSIONS_RESOURCE_ID, ExtensionHost, extensionHostFrom } from "../src/extension/host.js";-import type { PenguinContext, PenguinInterface, WorkflowFactory } from "../src/extension/index.js";-import { instantiateWorkflows, WorkflowFactories } from "../src/extension/workflow.js";+import { PLUGINS_RESOURCE_ID, PluginHost, pluginHostFrom } from "../src/plugin/host.js";+import type {+ PenguinContext,+ PenguinInterface,+ WorkflowFactory,+} from "@prismshadow/penguin-core/plugin";+import type { HarnessContext } from "../src/plugin/index.js";+import { instantiateWorkflows, WorkflowFactories } from "../src/plugin/workflow.js";function emptyIface(): PenguinInterface {- // The registry, not a bare Map: that IS the surface an extension gets (see platform.ts).- return { workflow: new WorkflowFactories(), tool: new Map() };+ // The registry, not a bare Map: that IS the surface a plugin gets (see platform.ts).+ return {+ workflow: new WorkflowFactories(),+ tool: new Map(),+ sandbox: { registerProvider: () => {} },+ };}/*** A registry whose host declares itself a bare kernel — right family, no capabilities* offered. That declaration is what makes a terminals-only boot legal (see- * capabilities.ts's RuntimeClaim); extension delivery is business-independent, so this is+ * capabilities.ts's RuntimeClaim); plugin delivery is business-independent, so this is* all these tests need behind the platform.*/function bareKernel(): HotResources {@@ -45,9 +54,9 @@ async function quietBoot(r: HotResources) {}}-describe("extension host", () => {+describe("plugin host", () => {it("activate runs once; typed events deliver both views in activation order", async () => {- const host = new ExtensionHost();+ const host = new PluginHost();const log: string[] = [];let activations = 0;let seenIface: PenguinInterface | null = null;@@ -74,15 +83,15 @@ describe("extension host", () => {const iface2 = emptyIface();host.emit("initialize", iface2);- // activate ran once per extension, while every event delivery re-walked the handlers.+ // activate ran once per plugin, while every event delivery re-walked the handlers.expect(activations).toBe(1);expect(log).toEqual(["a:initialize", "a:create", "b:create", "a:initialize"]);expect(seenIface).toBe(iface2);expect(seenCtx).toBe(ctx);});- it("a subscription-less extension is fine, and events with no handlers deliver to no one", async () => {- const host = new ExtensionHost();+ it("a subscription-less plugin is fine, and events with no handlers deliver to no one", async () => {+ const host = new PluginHost();await host.use({ activate: () => {} });expect(() => {host.emit("initialize", emptyIface());@@ -91,7 +100,7 @@ describe("extension host", () => {});it("the subscription window seals when activate settles", async () => {- const host = new ExtensionHost();+ const host = new PluginHost();let leaked: ((event: "create", handler: (ctx: PenguinContext) => void) => void) | null = null;await host.use({activate(extCtx) {@@ -104,7 +113,7 @@ describe("extension host", () => {});it("dispose runs disposables concurrently, awaits async ones, and isolates failures", async () => {- const host = new ExtensionHost();+ const host = new PluginHost();const done: string[] = [];let release!: () => void;const gate = new Promise<void>((resolve) => (release = resolve));@@ -142,7 +151,7 @@ describe("extension host", () => {// Both failure shapes (sync throw, rejected promise) were isolated and reported.expect(warn).toHaveBeenCalledTimes(2);- // Idempotent: a second call finds no extensions and re-runs nothing.+ // Idempotent: a second call finds no plugins and re-runs nothing.await host.dispose();expect(done).toEqual(["fast", "slow"]);expect(warn).toHaveBeenCalledTimes(2);@@ -152,9 +161,9 @@ describe("extension host", () => {});});-describe("extension host — activation is transactional", () => {+describe("plugin host — activation is transactional", () => {it("an async activate is awaited, so its rejection is an ordinary load failure", async () => {- const host = new ExtensionHost();+ const host = new PluginHost();const order: string[] = [];await expect(host.use({@@ -167,13 +176,13 @@ describe("extension host — activation is transactional", () => {},}),).rejects.toThrow(/async boom/);- // The failed extension is not published, so nothing it registered is ever delivered.+ // The failed plugin is not published, so nothing it registered is ever delivered.host.emit("create", {} as PenguinContext);expect(order).toEqual([]);});it("a failed activate still runs whatever it had already registered for cleanup", async () => {- const host = new ExtensionHost();+ const host = new PluginHost();let disposed = 0;await expect(host.use({@@ -191,7 +200,7 @@ describe("extension host — activation is transactional", () => {});it("an async event handler is refused, and its rejection cannot escape", async () => {- const host = new ExtensionHost();+ const host = new PluginHost();const rejections: unknown[] = [];const onRejection = (reason: unknown): void => void rejections.push(reason);process.on("unhandledRejection", onRejection);@@ -247,7 +256,7 @@ describe("workflows: registration and plain invocation", () => {it("a duplicate workflow name is refused, not silently replaced", () => {const iface = emptyIface();iface.workflow.set("same", () => ({ run: () => "A" }));- // A bare Map would let the winner depend on extensions.json ordering, and an extension+ // A bare Map would let the winner depend on plugins.json ordering, and a plugin// could take over a name another one owns without either noticing.expect(() => iface.workflow.set("same", () => ({ run: () => "B" }))).toThrow(/workflow 'same' is already registered/,@@ -262,23 +271,23 @@ describe("workflows: registration and plain invocation", () => {});});-describe("extensionHostFrom", () => {+describe("pluginHostFrom", () => {it("claims the host the runtime published", () => {- const host = new ExtensionHost();+ const host = new PluginHost();const resources = new HotResources();- resources.register(EXTENSIONS_RESOURCE_ID, host);- expect(extensionHostFrom(resources)).toBe(host);+ resources.register(PLUGINS_RESOURCE_ID, host);+ expect(pluginHostFrom(resources)).toBe(host);});it("falls back to an empty host when nothing was published", () => {const iface: PenguinInterface = emptyIface();- // No throw, and nothing registers into the iface: no published host means no extensions.- extensionHostFrom(new HotResources()).emit("initialize", iface);+ // No throw, and nothing registers into the iface: no published host means no plugins.+ pluginHostFrom(new HotResources()).emit("initialize", iface);expect(iface.workflow.size).toBe(0);});});-describe("extension seam on the real platform", () => {+describe("plugin seam on the real platform", () => {it("boots an App when the runtime published no host at all", async () => {const inst = await quietBoot(bareKernel());try {@@ -291,7 +300,7 @@ describe("extension seam on the real platform", () => {it("every App creation re-delivers both events, and the context carries what it registered", async () => {const contexts: PenguinContext[] = [];let initializes = 0;- const host = new ExtensionHost();+ const host = new PluginHost();await host.use({activate(extCtx) {extCtx.on("initialize", (iface) => {@@ -304,18 +313,21 @@ describe("extension seam on the real platform", () => {},});// The registry sits outside the reloadable tree and outlives a swap: publishing the- // host once is what lets both Apps below drive the same loaded extensions.+ // host once is what lets both Apps below drive the same loaded plugins.const resources = bareKernel();- resources.register(EXTENSIONS_RESOURCE_ID, host);+ resources.register(PLUGINS_RESOURCE_ID, host);const instA = await quietBoot(resources);try {expect(initializes).toBe(1);expect(contexts).toHaveLength(1);const ctx = contexts[0]!;- // context.* flatten: the platform's own member is directly on the context.- expect(typeof ctx.terminals.handleIds).toBe("function");- // …and the workflow this extension registered is instantiated and callable.+ // The sandbox config surface rides the same context (see ../src/sandbox/).+ expect(ctx.sandbox.settings()).toEqual({ mode: "danger-full-access" });+ // `terminals` is NOT on the closed contract: it is this harness's own, so reaching it+ // is an explicit cast — the same one a plugin depending on this embedder writes.+ expect(typeof (ctx as HarnessContext).terminals.handleIds).toBe("function");+ // …and the workflow this plugin registered is instantiated and callable.expect(ctx.workflows.names()).toContain("probe-1");expect(ctx.workflows.run("probe-1", 42)).toEqual({ echoed: 42 });diff --git a/packages/server/test/sandbox.test.ts b/packages/server/test/sandbox.test.tsnew file mode 100644index 00000000..671e9076--- /dev/null+++ b/packages/server/test/sandbox.test.ts@@ -0,0 +1,220 @@+/**+ * Behavior tests for the sandbox service: the built-in interface's optional+ * dimensions, capability routing across backends, fail-closed refusal, and the+ * settings' ride on the parked platform context.+ */+import { describe, expect, it, vi } from "vitest";+import { boot, initialDoc } from "@prismshadow/penguin-core/kernel";+import type { Json } from "@prismshadow/penguin-core/kernel";+import { HotResources } from "../src/hmr/resources.js";+import { PENGUIN_FAMILY, RUNTIME_INTERFACES_RESOURCE_ID } from "../src/hmr/capabilities.js";+import { packagedPlatform } from "../src/hmr/platform.js";+import { PluginHost, PLUGINS_RESOURCE_ID } from "../src/plugin/host.js";+import { SandboxService } from "../src/sandbox/index.js";+import type {+ PenguinContext,+ SandboxDimension,+ SandboxPolicy,+ SandboxProvider,+} from "@prismshadow/penguin-core/plugin";++const ARGV = ["bash", "-lc", "echo hi"] as const;+const OPTS = { cwd: "/work/project/sub", workspaceDir: "/work/project" };++/** A recording backend; `dimensions` absent = an undeclared (filesystem-only) backend. */+function fake(label: string, dimensions?: readonly SandboxDimension[]) {+ const calls: SandboxPolicy[] = [];+ const provider: SandboxProvider = {+ ...(dimensions !== undefined ? { dimensions } : {}),+ confine(argv, policy) {+ calls.push(policy);+ return {+ argv: [label, "--", ...argv],+ enforcement: "full",+ denialSignatures: ["permission denied"],+ runnerFailureRules: [{ fatalSignatures: [`${label}: `] }],+ };+ },+ };+ return { provider, calls };+}++async function service(+ entries: Array<[string, SandboxProvider | PromiseLike<SandboxProvider | null> | null]>,+): Promise<SandboxService> {+ const svc = new SandboxService(entries);+ await svc.whenReady();+ return svc;+}++describe("sandbox service — the built-in interface and its optional dimensions", () => {+ it("default settings are danger-full-access: argv passes through, no backend is consulted", async () => {+ const dsh = fake("dsh");+ const svc = await service([["dsh-local", dsh.provider]]);+ expect(svc.confiner()([...ARGV], OPTS)).toEqual([...ARGV]);+ expect(dsh.calls).toHaveLength(0);+ });++ it("a confining mode with no backend mounted fails closed", async () => {+ const svc = await service([]);+ svc.configure({ mode: "workspace-write" });+ expect(() => svc.confiner()([...ARGV], OPTS)).toThrow(/no sandbox backend is mounted/);+ });++ it("a backend that fails to load is named in the fail-closed message", async () => {+ const svc = await service([+ ["dsh-local", Promise.reject(new Error("Cannot find module 'landlock-run'"))],+ ]);+ svc.configure({ mode: "read-only" });+ expect(() => svc.confiner()([...ARGV], OPTS)).toThrow(+ /failed to load: dsh-local \(Cannot find module 'landlock-run'\)/,+ );+ });++ it("an installation missing a backend package keeps the platform usable, sandbox aside", async () => {+ // The deployed-machine shape (see scripts/deploy.mjs): the load fails, the default+ // settings keep working, and only a confining mode fails.+ const svc = await service([["dsh-local", Promise.reject(new Error("MODULE_NOT_FOUND"))]]);+ expect(svc.confiner()([...ARGV], OPTS)).toEqual([...ARGV]);+ svc.configure({ mode: "workspace-write" });+ expect(() => svc.confiner()([...ARGV], OPTS)).toThrow(/MODULE_NOT_FOUND/);+ });++ it("an undeclared backend is filesystem-only, and a filesystem policy routes to it", async () => {+ const dsh = fake("dsh");+ const svc = await service([["dsh-local", dsh.provider]]);+ svc.configure({ mode: "workspace-write" });+ expect(svc.confiner()([...ARGV], OPTS)).toEqual(["dsh", "--", ...ARGV]);+ // workspaceRoot is the Workspace, never the per-command cwd.+ expect(dsh.calls[0]).toMatchObject({ mode: "workspace-write", workspaceRoot: "/work/project" });+ expect(svc.backends()).toEqual([{ name: "dsh-local", dimensions: ["fs-write"] }]);+ });++ it("requiring a dimension nothing implements is refused, naming what each backend does", async () => {+ const dsh = fake("dsh");+ const svc = await service([["dsh-local", dsh.provider]]);+ svc.configure({ mode: "workspace-write", network: "none" });+ expect(() => svc.confiner()([...ARGV], OPTS)).toThrow(+ /requires fs-write \+ network, but no mounted sandbox backend implements all of it \(dsh-local: fs-write\)/,+ );+ // Never silently dropped: the backend was not consulted at all.+ expect(dsh.calls).toHaveLength(0);+ });+});++describe("sandbox service — capability routing across backends", () => {+ const entries = () => {+ const dsh = fake("dsh");+ const bwrap = fake("bwrap", ["fs-write", "network", "mask-paths"]);+ return { dsh, bwrap };+ };++ it("a filesystem-only policy takes the first backend covering it (the portable one)", async () => {+ const { dsh, bwrap } = entries();+ const svc = await service([+ ["dsh-local", dsh.provider],+ ["penguin-bwrap", bwrap.provider],+ ]);+ svc.configure({ mode: "workspace-write" });+ expect(svc.confiner()([...ARGV], OPTS)).toEqual(["dsh", "--", ...ARGV]);+ expect(bwrap.calls).toHaveLength(0);+ });++ it("a policy requiring network or mask-paths routes past it to the backend implementing them", async () => {+ const { dsh, bwrap } = entries();+ const svc = await service([+ ["dsh-local", dsh.provider],+ ["penguin-bwrap", bwrap.provider],+ ]);+ svc.configure({ mode: "workspace-write", network: "none", maskPaths: ["/home/u/.ssh"] });+ expect(svc.confiner()([...ARGV], OPTS)).toEqual(["bwrap", "--", ...ARGV]);+ expect(dsh.calls).toHaveLength(0);+ expect(bwrap.calls[0]).toMatchObject({ network: "none", maskPaths: ["/home/u/.ssh"] });+ });++ it("an empty maskPaths list does not require the dimension", async () => {+ const { dsh, bwrap } = entries();+ const svc = await service([+ ["dsh-local", dsh.provider],+ ["penguin-bwrap", bwrap.provider],+ ]);+ svc.configure({ mode: "read-only", maskPaths: [] });+ expect(svc.confiner()([...ARGV], OPTS)).toEqual(["dsh", "--", ...ARGV]);+ });++ it("a backend throw (unusable runner, etc.) propagates — fail-closed end to end", async () => {+ const svc = await service([+ [+ "boom",+ {+ confine() {+ throw new Error("penguin-bwrap cannot confine on this host");+ },+ },+ ],+ ]);+ svc.configure({ mode: "workspace-write" });+ expect(() => svc.confiner()([...ARGV], OPTS)).toThrow(/cannot confine on this host/);+ });+});++describe("sandbox settings ride the parked context across a swap", () => {+ /**+ * Boots the packaged platform over a fresh registry carrying one observer plugin, and+ * returns what a plugin sees at "create" — the surface an actual consumer has. The+ * confiner itself is same-generation wiring into buildAppDeps (no caps published here,+ * so no business surface boots); enforcement is covered by the service tests above.+ */+ async function bootObserved(doc: Json) {+ const resources = new HotResources();+ // A bare-kernel declaration — right family, no capabilities offered — is what makes a+ // terminals-only boot legal (see capabilities.ts's RuntimeClaim). The sandbox floor is+ // business-independent, so this is all these tests need behind the platform.+ resources.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });+ const host = new PluginHost();+ let seen: PenguinContext | null = null;+ await host.use({ activate: (extCtx) => extCtx.on("create", (ctx) => (seen = ctx)) });+ resources.register(PLUGINS_RESOURCE_ID, host);+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const inst = await boot(+ packagedPlatform.impl,+ packagedPlatform.iface,+ initialDoc(packagedPlatform.iface, doc),+ resources,+ ).finally(() => warn.mockRestore());+ return { inst, ctx: () => seen! };+ }++ it("a confining mode survives park -> fresh boot instead of resetting to unconfined", async () => {+ const a = await bootObserved({ motd: "m", sandbox: { mode: "read-only" } });+ try {+ expect(a.ctx().sandbox.settings()).toEqual({ mode: "read-only" });++ const parked = (await a.inst.api.park()) as { motd: string; sandbox?: { mode: string } };+ expect(parked.sandbox).toEqual({ mode: "read-only" });++ const b = await bootObserved(parked);+ try {+ expect(b.ctx().sandbox.settings()).toEqual({ mode: "read-only" });+ } finally {+ b.inst.dispose();+ }+ } finally {+ a.inst.dispose();+ }+ });++ it("a document parked before the sandbox field existed restores as the default (off)", async () => {+ const a = await bootObserved({ motd: "old-doc" });+ try {+ expect(a.ctx().sandbox.settings()).toEqual({ mode: "danger-full-access" });+ // The sandbox field is absent, not present-and-default: that is what keeps a+ // default deployment's document acceptable to a sandbox-ignorant bundle's schema.+ const parked = (await a.inst.api.park()) as { motd: string; sandbox?: unknown };+ expect(parked.sandbox).toBeUndefined();+ expect(parked.motd).toBe("old-doc");+ } finally {+ a.inst.dispose();+ }+ });+});diff --git a/packages/server/tsup.config.ts b/packages/server/tsup.config.tsindex 9ec36f59..845ebbeb 100644--- a/packages/server/tsup.config.ts+++ b/packages/server/tsup.config.ts@@ -31,10 +31,10 @@ export default defineConfig({"secret-file": "src/secret-file.ts","hmr/manifest": "src/hmr/manifest.ts","version-report": "src/version-report.ts",- // "./extension": the surface extension PACKAGES compile against. Extensions live outside+ // "./plugin": the surface plugin PACKAGES compile against. Plugins live outside// this bundle entirely — they are configuration resolved from the installation,// not platform capability.- "extension/index": "src/extension/index.ts",+ "plugin/index": "src/plugin/index.ts",},format: ["esm"],target: "node24",diff --git a/plugins/sandbox-bwrap/README.md b/plugins/sandbox-bwrap/README.mdnew file mode 100644index 00000000..8951ac8b--- /dev/null+++ b/plugins/sandbox-bwrap/README.md@@ -0,0 +1,44 @@+# Bubblewrap sandbox backend++Confines command subprocesses with [bubblewrap](https://github.com/containers/bubblewrap),+talking to `bwrap` directly. Implements **all three** dimensions of the harness sandbox+interface — filesystem writes, network isolation and path masking.++## Requirements++- Linux, with `bwrap` on PATH.+- Unprivileged user namespaces enabled. The backend probes functionally at load and+ declines when the kernel will not grant them, rather than confining less than asked.++## How the profile is built++bwrap applies mounts **in order**, and a later mount shadows an earlier one, so the+profile is assembled in this sequence:++| Stage | Flags |+| --- | --- |+| The read-only world | `--ro-bind / /`, `--dev /dev`, `--proc /proc`, `--die-with-parent` |+| `workspace-write` | `--tmpfs /tmp`, `--bind <workspaceRoot> <same>` |+| `network: none` | `--unshare-net` |+| `mask-paths` | `--tmpfs <dir>` or `--ro-bind /dev/null <file>` |++Masking comes last on purpose: the entries have to shadow the read-only bind of `/` that+would otherwise expose them. A path that does not exist is skipped — there is nothing to+hide, and materializing an empty directory there would change the filesystem view rather+than restrict it.++## Install++Add the specifier to your deployment's `plugins.json` and restart, or push a platform that+carries it:++```json+{ "plugins": ["@prismshadow/penguin-plugin-sandbox-bwrap"] }+```++Installing is an operator-side action: the harness resolves the package from the installation,+never from this listing.++## License++Apache-2.0.diff --git a/plugins/sandbox-bwrap/package.json b/plugins/sandbox-bwrap/package.jsonnew file mode 100644index 00000000..180dd8c3--- /dev/null+++ b/plugins/sandbox-bwrap/package.json@@ -0,0 +1,30 @@+{+ "name": "@prismshadow/penguin-plugin-sandbox-bwrap",+ "version": "0.2.2",+ "private": true,+ "type": "module",+ "description": "Bubblewrap sandbox backend for PenguinHarness: filesystem confinement plus network isolation and path masking.",+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js"+ }+ },+ "license": "Apache-2.0",+ "files": [+ "dist",+ "README.md"+ ],+ "scripts": {+ "typecheck": "tsc --noEmit -p tsconfig.json",+ "test": "vitest run --passWithNoTests",+ "build": "tsup"+ },+ "devDependencies": {+ "@prismshadow/penguin-core": "workspace:*",+ "tsup": "^8.3.0",+ "vitest": "^3.2.6"+ }+}diff --git a/plugins/sandbox-bwrap/src/index.ts b/plugins/sandbox-bwrap/src/index.tsnew file mode 100644index 00000000..53ace425--- /dev/null+++ b/plugins/sandbox-bwrap/src/index.ts@@ -0,0 +1,136 @@+/**+ * @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).+ * It compiles against the type-only `@prismshadow/penguin-core/plugin` surface and+ * carries no runtime dependency on the harness — and none on the DSH ecosystem either:+ * it talks to `bwrap` directly and implements every dimension of the sandbox interface,+ * including the two DSH's vocabulary does not cover.+ *+ * The bwrap profile is built in order, because bwrap applies mounts in order and a+ * later mount shadows an earlier one:+ *+ * --ro-bind / / --dev /dev --proc /proc --die-with-parent the read-only world+ * [workspace-write] --tmpfs /tmp --bind <workspaceRoot> <same>+ * [network: none] --unshare-net no network namespace+ * [mask-paths] --tmpfs <dir> | --ro-bind /dev/null <file> shadowing the above+ * -- <the caller's argv>+ *+ * Masking is why order matters: the entries must come after the read-only bind of `/`+ * that would otherwise expose them. A path that does not exist is skipped — there is+ * nothing to hide, and materializing an empty directory there would change the+ * filesystem view rather than restrict it.+ *+ * Known limitation, verified live: `--unshare-net` gives the process an empty network+ * namespace (its /proc/net/dev holds only `lo`, and nothing resolves or connects), but+ * `/sys` still arrives through the read-only bind of `/`, so `/sys/class/net` keeps+ * listing the HOST's interfaces. Network ACCESS is enforced; host network topology+ * remains readable as stale metadata. Mask it explicitly with `maskPaths` if that+ * matters for a deployment.+ */+import { spawnSync } from "node:child_process";+import { statSync } from "node:fs";+import path from "node:path";+import { tmpdir } from "node:os";+import type {+ ConfinedArgv,+ PluginContext,+ SandboxPolicy,+ SandboxProvider,+} from "@prismshadow/penguin-core/plugin";++/** Default probe budget; a probe that hangs must not hang the first spawn forever. */+const PROBE_TIMEOUT_MS = 5_000;++/** Test seams: inject the probe verdict and capture the runner name. */+export interface PenguinBwrapInternals {+ probe?: (timeoutMs: number) => boolean;+ runner?: string;+}++/** The writable roots `workspace-write` grants: the workspace plus the temp areas, canonical and deduplicated. */+export function writableRoots(policy: SandboxPolicy): string[] {+ if (policy.mode !== "workspace-write") return [];+ const roots = [policy.workspaceRoot, "/tmp", tmpdir()].map((root) => path.resolve(root));+ return [...new Set(roots)];+}++/** The bwrap profile arguments for one policy (everything before `--` and the caller's argv). */+export function bwrapProfileArgs(policy: SandboxPolicy): string[] {+ const args = ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--die-with-parent"];+ if (policy.mode === "workspace-write") {+ args.push("--tmpfs", "/tmp");+ for (const root of writableRoots(policy)) {+ if (root === "/tmp") continue; // already a writable tmpfs above+ args.push("--bind", root, root);+ }+ }+ if (policy.network === "none") args.push("--unshare-net");+ for (const target of policy.maskPaths ?? []) {+ const resolved = path.resolve(target);+ let isDirectory: boolean;+ try {+ isDirectory = statSync(resolved).isDirectory();+ } catch {+ continue; // nothing there to hide+ }+ if (isDirectory) args.push("--tmpfs", resolved);+ else args.push("--ro-bind", "/dev/null", resolved);+ }+ return args;+}++/** Functional probe: can bwrap actually create the base profile on this host? */+function defaultProbe(timeoutMs: number, runner: string): boolean {+ const probe = spawnSync(+ runner,+ ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--die-with-parent", "--", "true"],+ { timeout: timeoutMs, stdio: "ignore" },+ );+ return probe.status === 0;+}++/**+ * The backend. The probe runs once, lazily (first confine), and is cached: an+ * unavailable bwrap throws — fail-closed — rather than degrading to a weaker profile,+ * because the dimensions routed here (network, mask-paths) have no weaker form.+ */+export function createPenguinBwrapProvider(internals: PenguinBwrapInternals = {}): SandboxProvider {+ const runner = internals.runner ?? "bwrap";+ const probe = internals.probe ?? ((timeoutMs: number) => defaultProbe(timeoutMs, runner));+ let usable: boolean | undefined;+ return {+ dimensions: ["fs-write", "network", "mask-paths"],+ confine(argv, policy): ConfinedArgv {+ usable ??= probe(PROBE_TIMEOUT_MS);+ if (!usable) {+ throw new Error(+ `penguin-bwrap cannot confine on this host: '${runner}' is missing or refuses the ` ++ "base profile; refusing to run the command unconfined. Install bubblewrap, or " ++ "drop the network / mask-paths requirements so another backend can serve the policy.",+ );+ }+ return {+ argv: [runner, ...bwrapProfileArgs(policy), "--", ...argv],+ // bwrap enforces the whole profile it accepts: mounts, and the network+ // namespace when asked. Nothing here is best-effort.+ enforcement: "full",+ // The kernel's dialect under these mounts: a write to the read-only world is+ // EROFS, a write into a masked tmpfs (or through the /dev/null file mask) is+ // EACCES/EPERM.+ denialSignatures: ["read-only file system", "permission denied", "operation not permitted"],+ runnerFailureRules: [{ fatalSignatures: [`${runner}: `] }],+ };+ },+ };+}++/** The plugin: registered per App creation, like every other backend. Default export = the plugin. */+export function activate(ctx: PluginContext): void {+ // Backends register per App creation — a hot swap re-registers them into the fresh+ // registry — so the subscription is to the event, not a one-time registration here.+ ctx.on("initialize", (iface) => {+ iface.sandbox.registerProvider("penguin-bwrap", createPenguinBwrapProvider());+ });+}diff --git a/plugins/sandbox-bwrap/test/live.test.ts b/plugins/sandbox-bwrap/test/live.test.tsnew file mode 100644index 00000000..e81b99ca--- /dev/null+++ b/plugins/sandbox-bwrap/test/live.test.ts@@ -0,0 +1,141 @@+/**+ * Live enforcement for this backend against the real host: real bwrap, real spawns+ * through core's command sessions, real kernel denials.+ *+ * Host-gated — a package whose whole job is kernel confinement can only be proven on a+ * host that has bubblewrap; elsewhere the suite skips and profile.test.ts still pins+ * the profile and the fail-closed path. The backend is driven DIRECTLY here (no+ * SandboxService): what a plugin package owes is that its own confinement works, and+ * routing/settings are the harness's behavior, tested there with fakes.+ */+import { afterAll, describe, expect, it } from "vitest";+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import path from "node:path";+import { CommandSessionManager } from "@prismshadow/penguin-core";+import type { SandboxPolicy } from "@prismshadow/penguin-core/plugin";+import { createPenguinBwrapProvider } from "../src/index.js";++const ws = mkdtempSync(path.join(tmpdir(), "penguin-bwrap-live-"));+const outsideProbe = path.join(homedir(), `penguin-bwrap-live-${process.pid}.txt`);+const provider = createPenguinBwrapProvider();++/** null = spawn unconfined; otherwise confine under this policy (workspaceRoot filled per spawn). */+let policy: Omit<SandboxPolicy, "workspaceRoot"> | null = null;++const usable = (() => {+ try {+ provider.confine(["true"], { mode: "read-only", workspaceRoot: ws });+ return true;+ } catch {+ return false;+ }+})();++const mgr = new CommandSessionManager({+ confineSpawn: () => (argv, opts) =>+ policy === null+ ? argv+ : provider.confine(argv, { ...policy, workspaceRoot: opts.workspaceDir }).argv,+ workspaceDir: ws,+});++async function run(cmd: string): Promise<{ code: number | null; out: string }> {+ const session = mgr.spawn({ cmd, cwd: ws });+ let out = "";+ for await (const chunk of session.collect(15000)) out += chunk;+ if (session.running) session.kill();+ return { code: session.exit?.code ?? null, out };+}++/**+ * Interfaces as the CONFINED process sees them: /proc/net/dev, a fresh procfs inside+ * the namespace — NOT /sys/class/net, which arrives through the read-only bind of `/`+ * and lists the HOST's interfaces whatever the network namespace holds. Probing /sys+ * here would report a failure that is not one, and once masked, a pass that is not one.+ */+const interfaces = (procNetDev: string): string[] =>+ procNetDev+ .split("\n")+ .slice(2)+ .map((line) => line.split(":")[0]!.trim())+ .filter(Boolean);++afterAll(() => {+ mgr.dispose();+ rmSync(ws, { recursive: true, force: true });+ rmSync(outsideProbe, { force: true });+});++describe.skipIf(!usable)("penguin-bwrap live enforcement (host-gated)", () => {+ it("fs-write: the workspace is writable, the world outside it is not", async () => {+ policy = { mode: "workspace-write" };+ const inside = await run("echo confined-ok > inside.txt && cat inside.txt");+ expect(inside.code).toBe(0);+ expect(inside.out).toContain("confined-ok");++ const outside = await run(`echo leak > ${JSON.stringify(outsideProbe)} 2>&1; echo exit=$?`);+ expect(existsSync(outsideProbe)).toBe(false);+ expect(outside.out).toMatch(/read-only file system|permission denied/i);+ });++ it("fs-write: reads outside the workspace still work, and read-only denies the workspace too", async () => {+ policy = { mode: "workspace-write" };+ expect((await run("head -c 1 /etc/hostname > /dev/null && echo READ_OK")).out).toContain(+ "READ_OK",+ );++ policy = { mode: "read-only" };+ const ro = await run("echo x > ro-probe.txt 2>&1; echo exit=$?");+ expect(existsSync(path.join(ws, "ro-probe.txt"))).toBe(false);+ expect(ro.out).toMatch(/read-only file system|permission denied/i);+ });++ it("fs-write: background children are confined with the wrapped shell", async () => {+ policy = { mode: "workspace-write" };+ const r = await run(+ `(sleep 0.2 && echo bg > ${JSON.stringify(outsideProbe)}) & wait; echo done`,+ );+ expect(r.out).toContain("done");+ expect(existsSync(outsideProbe)).toBe(false);+ });++ it("network: none leaves the process with loopback only and no resolution", async () => {+ policy = { mode: "workspace-write" };+ expect(interfaces((await run("cat /proc/net/dev")).out).length).toBeGreaterThan(1);++ policy = { mode: "workspace-write", network: "none" };+ expect(interfaces((await run("cat /proc/net/dev")).out)).toEqual(["lo"]);+ expect((await run("getent hosts github.com 2>&1; echo exit=$?")).out).toMatch(/exit=[^0]/);+ });++ it("mask-paths: a masked directory reads as empty and its secret is unreachable", async () => {+ // Deliberately NOT under /tmp: workspace-write mounts a tmpfs over /tmp, which+ // already hides whatever the host had there — a secret placed in /tmp would make+ // the unmasked baseline fail and the masked assertion pass vacuously.+ const secretDir = mkdtempSync(path.join(homedir(), "penguin-bwrap-secret-"));+ const secretFile = path.join(secretDir, "token.txt");+ writeFileSync(secretFile, "super-secret");+ try {+ policy = { mode: "workspace-write" };+ expect((await run(`cat ${JSON.stringify(secretFile)}`)).out).toContain("super-secret");++ policy = { mode: "workspace-write", maskPaths: [secretDir] };+ const masked = await run(+ `ls -A ${JSON.stringify(secretDir)}; cat ${JSON.stringify(secretFile)} 2>&1`,+ );+ expect(masked.out).not.toContain("super-secret");+ expect(masked.out).toMatch(/no such file|not found/i);+ } finally {+ rmSync(secretDir, { recursive: true, force: true });+ }+ });++ it("the policy is read per spawn: dropping it lifts confinement on the next command", async () => {+ policy = null;+ const r = await run(`echo unconfined > ${JSON.stringify(outsideProbe)}; echo exit=$?`);+ expect(r.code).toBe(0);+ expect(existsSync(outsideProbe)).toBe(true);+ rmSync(outsideProbe, { force: true });+ });+});diff --git a/plugins/sandbox-bwrap/test/profile.test.ts b/plugins/sandbox-bwrap/test/profile.test.tsnew file mode 100644index 00000000..b99fb9d3--- /dev/null+++ b/plugins/sandbox-bwrap/test/profile.test.ts@@ -0,0 +1,134 @@+/**+ * Unit tests for penguin-bwrap: the exact profile it builds for each dimension, and+ * its fail-closed behavior when bubblewrap is unusable. The probe is injected, so both+ * paths are deterministic on any host (a real-bwrap host also runs sandbox-live).+ */+import { describe, expect, it } from "vitest";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { bwrapProfileArgs, createPenguinBwrapProvider } from "../src/index.js";++const ARGV = ["bash", "-lc", "echo hi"] as const;+const WS = "/work/project";++/** argv slice between two markers, for asserting order without pinning the whole array. */+function after(argv: readonly string[], marker: string): readonly string[] {+ return argv.slice(argv.indexOf(marker));+}++describe("penguin-bwrap profile", () => {+ it("read-only: the world is read-only, nothing is writable, no network flag", () => {+ const args = bwrapProfileArgs({ mode: "read-only", workspaceRoot: WS });+ expect(args).toEqual([+ "--ro-bind",+ "/",+ "/",+ "--dev",+ "/dev",+ "--proc",+ "/proc",+ "--die-with-parent",+ ]);+ });++ // skipIf(win32): the profile echoes host path resolution, which turns the POSIX+ // workspace literal into a drive path — and bwrap never runs there anyway.+ it.skipIf(process.platform === "win32")(+ "workspace-write: the workspace and a tmpfs /tmp become writable",+ () => {+ const args = bwrapProfileArgs({ mode: "workspace-write", workspaceRoot: WS });+ expect(args).toContain("--tmpfs");+ expect(args.join(" ")).toContain(`--bind ${WS} ${WS}`);+ // /tmp is the tmpfs, never also a bind of the host's /tmp.+ expect(args.join(" ")).not.toContain("--bind /tmp /tmp");+ },+ );++ it("network: none adds --unshare-net; absent leaves the network alone", () => {+ expect(bwrapProfileArgs({ mode: "read-only", workspaceRoot: WS, network: "none" })).toContain(+ "--unshare-net",+ );+ expect(bwrapProfileArgs({ mode: "read-only", workspaceRoot: WS })).not.toContain(+ "--unshare-net",+ );+ });++ it("mask-paths: a directory becomes an empty tmpfs, a file is shadowed by /dev/null", () => {+ const dir = mkdtempSync(path.join(tmpdir(), "penguin-mask-"));+ const file = path.join(dir, "secret.txt");+ writeFileSync(file, "shh");+ const sub = path.join(dir, "sub");+ mkdirSync(sub);+ try {+ const args = bwrapProfileArgs({+ mode: "read-only",+ workspaceRoot: WS,+ maskPaths: [sub, file],+ });+ expect(args.join(" ")).toContain(`--tmpfs ${sub}`);+ expect(args.join(" ")).toContain(`--ro-bind /dev/null ${file}`);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("mask-paths: a path that does not exist is skipped (nothing to hide)", () => {+ const args = bwrapProfileArgs({+ mode: "read-only",+ workspaceRoot: WS,+ maskPaths: [path.join(tmpdir(), "penguin-definitely-absent-path")],+ });+ expect(args.join(" ")).not.toContain("penguin-definitely-absent-path");+ });++ it("masks come AFTER the read-only bind of / that would otherwise expose them", () => {+ const dir = mkdtempSync(path.join(tmpdir(), "penguin-mask-order-"));+ try {+ const args = bwrapProfileArgs({ mode: "read-only", workspaceRoot: WS, maskPaths: [dir] });+ // bwrap applies mounts in order: the mask must be in the tail after `--ro-bind / /`.+ expect(after(args, "--ro-bind").join(" ")).toContain(`--tmpfs ${dir}`);+ expect(args.indexOf(dir)).toBeGreaterThan(args.indexOf("--die-with-parent"));+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++describe("penguin-bwrap provider", () => {+ it("implements every dimension of the built-in interface", () => {+ expect(createPenguinBwrapProvider({ probe: () => true }).dimensions).toEqual([+ "fs-write",+ "network",+ "mask-paths",+ ]);+ });++ it("wraps the caller's argv behind the profile and a -- separator", () => {+ const provider = createPenguinBwrapProvider({ probe: () => true, runner: "bwrap" });+ const confined = provider.confine([...ARGV], {+ mode: "workspace-write",+ workspaceRoot: WS,+ network: "none",+ });+ expect(confined.argv[0]).toBe("bwrap");+ expect(confined.argv.slice(-3)).toEqual([...ARGV]);+ expect(confined.argv[confined.argv.length - 4]).toBe("--");+ expect(confined.argv).toContain("--unshare-net");+ expect(confined.enforcement).toBe("full");+ });++ it("an unusable bwrap fails closed, and the probe runs once", () => {+ let probes = 0;+ const provider = createPenguinBwrapProvider({+ probe: () => {+ probes++;+ return false;+ },+ });+ const policy = { mode: "read-only", workspaceRoot: WS } as const;+ expect(() => provider.confine([...ARGV], policy)).toThrow(/cannot confine on this host/);+ expect(() => provider.confine([...ARGV], policy)).toThrow(/cannot confine on this host/);+ expect(probes).toBe(1);+ });+});diff --git a/plugins/sandbox-bwrap/tsconfig.json b/plugins/sandbox-bwrap/tsconfig.jsonnew file mode 100644index 00000000..8cd1715a--- /dev/null+++ b/plugins/sandbox-bwrap/tsconfig.json@@ -0,0 +1,7 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "rootDir": "."+ },+ "include": ["src", "test"]+}diff --git a/plugins/sandbox-bwrap/tsup.config.ts b/plugins/sandbox-bwrap/tsup.config.tsnew file mode 100644index 00000000..30688a7a--- /dev/null+++ b/plugins/sandbox-bwrap/tsup.config.ts@@ -0,0 +1,10 @@+import { defineConfig } from "tsup";++export default defineConfig({+ entry: ["src/index.ts"],+ format: ["esm"],+ target: "node24",+ dts: true,+ clean: true,+ sourcemap: true,+});diff --git a/plugins/sandbox-dsh/README.md b/plugins/sandbox-dsh/README.mdnew file mode 100644index 00000000..680bb5ac--- /dev/null+++ b/plugins/sandbox-dsh/README.md@@ -0,0 +1,49 @@+# DeepSeek Harness sandbox adaptor++Puts the **DSH** sandbox ecosystem behind this harness's own sandbox interface. This is the+portable floor: it works on Linux, macOS and Windows, and implements the `fs-write`+dimension.++## What it covers++`@deepseek-ai/dsh-sandbox-local` carries the platform chain and probes each rung+functionally:++| Host | Mechanism |+| --- | --- |+| Linux | dsh-bwrap → Landlock |+| macOS | Seatbelt |+| Windows | ACL restricted-token runner |++DSH's policy vocabulary governs **file-write effects only**, so this adaptor declares+exactly `fs-write`. The sandbox service therefore never routes a `network` or+`mask-paths` policy here, and the adaptor never has to silently drop a dimension it+cannot honor — for those, use the bubblewrap, Seatbelt or MXC backend for your platform.++## Requirements++- The DSH dependencies (`@deepseek-ai/cordis`, `@deepseek-ai/dsh-sandbox`,+ `@deepseek-ai/dsh-sandbox-local`) are dependencies of **this package**, not of the+ harness — which is what "plugins are configuration, not built-in capability" means in+ dependency terms.++They load behind dynamic imports, which is load-bearing for hot push: the package reaches+native-adjacent modules that a pushed single-file bundle resolves from the installation, so+an installation missing them fails *this* load — reported fail-closed by the service —+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:++```json+{ "plugins": ["@prismshadow/penguin-plugin-sandbox-dsh"] }+```++Installing is an operator-side action: the harness resolves the package from the installation,+never from this listing.++## License++Apache-2.0.diff --git a/plugins/sandbox-dsh/package.json b/plugins/sandbox-dsh/package.jsonnew file mode 100644index 00000000..b6689615--- /dev/null+++ b/plugins/sandbox-dsh/package.json@@ -0,0 +1,35 @@+{+ "name": "@prismshadow/penguin-plugin-sandbox-dsh",+ "version": "0.2.2",+ "private": true,+ "type": "module",+ "description": "DeepSeek Harness sandbox adaptor for PenguinHarness: the DSH local backend chain behind the harness's own sandbox interface.",+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js"+ }+ },+ "license": "Apache-2.0",+ "files": [+ "dist",+ "README.md"+ ],+ "scripts": {+ "typecheck": "tsc --noEmit -p tsconfig.json",+ "test": "vitest run --passWithNoTests",+ "build": "tsup"+ },+ "dependencies": {+ "@deepseek-ai/cordis": "^4.0.1",+ "@deepseek-ai/dsh-sandbox": "0.1.0-rc.7",+ "@deepseek-ai/dsh-sandbox-local": "0.1.0-rc.7"+ },+ "devDependencies": {+ "@prismshadow/penguin-core": "workspace:*",+ "tsup": "^8.3.0",+ "vitest": "^3.2.6"+ }+}diff --git a/plugins/sandbox-dsh/src/index.ts b/plugins/sandbox-dsh/src/index.tsnew file mode 100644index 00000000..1a248ebe--- /dev/null+++ b/plugins/sandbox-dsh/src/index.ts@@ -0,0 +1,65 @@+/**+ * @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).+ * 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.+ *+ * `@deepseek-ai/dsh-sandbox-local` carries the platform chain (dsh-bwrap → Landlock on+ * Linux, Seatbelt on macOS, the ACL restricted-token runner on Windows) and probes them+ * functionally; this file translates between its vocabulary and ours. Because DSH's+ * policy vocabulary governs file-write effects only, the adaptor declares exactly+ * `fs-write` — the service therefore never routes a network / mask-paths policy here,+ * and the adaptor never has to drop a dimension it cannot honor.+ *+ * Everything DSH loads behind the dynamic imports below, and that is load-bearing for+ * hot push (see scripts/deploy.mjs): the package reaches native-adjacent modules that a+ * pushed single-file bundle resolves from the installation, so an installation missing+ * them fails THIS load — reported fail-closed by the service — instead of failing the+ * whole platform bundle's import.+ */+import type {+ ConfinedArgv,+ PluginContext,+ SandboxProvider,+} from "@prismshadow/penguin-core/plugin";++/** Mount the stock DSH chain on a bare cordis Context — exactly how DSH's own tests mount it. */+export async function loadDshAdaptor(): Promise<SandboxProvider | null> {+ const { Context } = await import("@deepseek-ai/cordis");+ const { LocalSandboxProvider } = await import("@deepseek-ai/dsh-sandbox-local");+ const cordisCtx = new Context();+ // A cordis plugin, not a Penguin one: `Context.plugin` is cordis's own API, and the two+ // vocabularies share nothing but the word. Hence the name — `ctx` in this package is+ // the PluginContext `activate` receives, below.+ await cordisCtx.plugin(LocalSandboxProvider, {});+ const dsh = cordisCtx.sandbox;+ return {+ // DSH's own words: "Network and process visibility are outside this vocabulary."+ dimensions: ["fs-write"],+ confine(argv, policy): ConfinedArgv {+ const confined = dsh.confine(argv, {+ mode: policy.mode,+ workspaceRoot: policy.workspaceRoot,+ });+ return {+ argv: confined.argv,+ enforcement: confined.enforcement,+ denialSignatures: confined.denialSignatures,+ runnerFailureRules: confined.runnerFailureRules,+ };+ },+ };+}++/** The plugin: registered per App creation, so a hot swap re-registers it. Default export = the plugin. */+export function activate(ctx: PluginContext): void {+ // Backends register per App creation — a hot swap re-registers them into the fresh+ // registry — so the subscription is to the event, not a one-time registration here.+ ctx.on("initialize", (iface) => {+ iface.sandbox.registerProvider("dsh-local", loadDshAdaptor());+ });+}diff --git a/plugins/sandbox-dsh/test/live.test.ts b/plugins/sandbox-dsh/test/live.test.tsnew file mode 100644index 00000000..db9c085b--- /dev/null+++ b/plugins/sandbox-dsh/test/live.test.ts@@ -0,0 +1,119 @@+/**+ * Live enforcement for the DSH adaptor against the real host: the real DSH chain+ * (bwrap → Landlock on Linux, Seatbelt on macOS, the ACL runner on Windows), real+ * spawns through core's command sessions, real kernel denials.+ *+ * Host-gated the way DSH gates its own backend e2e: one real confine decides+ * usability, and a host with no usable backend skips. The adaptor is driven DIRECTLY+ * (no SandboxService): what this package owes is that DSH's confinement works behind+ * our interface; routing and settings are the harness's behavior, tested there.+ */+import { afterAll, describe, expect, it } from "vitest";+import { existsSync, mkdtempSync, rmSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import path from "node:path";+import { CommandSessionManager } from "@prismshadow/penguin-core";+import type { SandboxProvider } from "@prismshadow/penguin-core/plugin";+import { loadDshAdaptor } from "../src/index.js";++const ws = mkdtempSync(path.join(tmpdir(), "penguin-dsh-live-"));+const outsideProbe = path.join(homedir(), `penguin-dsh-live-${process.pid}.txt`);++const provider: SandboxProvider | null = await loadDshAdaptor().catch(() => null);++/** null = spawn unconfined; otherwise confine under this mode. */+let mode: "read-only" | "workspace-write" | null = null;++const usable =+ provider !== null &&+ (() => {+ try {+ provider.confine(["true"], { mode: "workspace-write", workspaceRoot: ws });+ return true;+ } catch {+ return false;+ }+ })();++const mgr = new CommandSessionManager({+ confineSpawn: () => (argv, opts) =>+ mode === null || provider === null+ ? argv+ : provider.confine(argv, { mode, workspaceRoot: opts.workspaceDir }).argv,+ workspaceDir: ws,+});++async function run(cmd: string): Promise<{ code: number | null; out: string }> {+ const session = mgr.spawn({ cmd, cwd: ws });+ let out = "";+ for await (const chunk of session.collect(15000)) out += chunk;+ if (session.running) session.kill();+ return { code: session.exit?.code ?? null, out };+}++/**+ * The denial DIALECT depends on which rung the chain selected — EROFS text under+ * bwrap's read-only binds, EACCES under Landlock, EPERM under Seatbelt, and the+ * Windows ACL runner's own wording. That is exactly why ConfinedArgv carries+ * denialSignatures; assert the effect plus a denial in any dialect, never one rung's.+ */+const DENIED = /permission denied|read-only file system|operation not permitted|access is denied/i;++afterAll(() => {+ mgr.dispose();+ rmSync(ws, { recursive: true, force: true });+ rmSync(outsideProbe, { force: true });+});++// skipIf(win32) is NOT a capability gate: the usability gate does open there — the ACL+// chain loads and the kernel denial fires (observed on CI as UTF-16 "Access is denied"+// from the runner). What is missing is a cmd-dialect probe set: these probes are POSIX+// shell (head, /etc/hosts, `(…) & wait`) and the assertions decode UTF-8. TODO(win32):+// a Windows probe set with UTF-16-tolerant denial matching, as its own change.+describe.skipIf(!usable || process.platform === "win32")(+ "DSH adaptor live enforcement (host-gated)",+ () => {+ it("workspace-write: writes inside the workspace work, reads outside still work", async () => {+ mode = "workspace-write";+ // /etc/hosts, not /etc/hostname: the read probe must exist on every POSIX host the+ // usability gate can open, and macOS has no /etc/hostname.+ const r = await run(+ "echo confined-ok > inside.txt && cat inside.txt && head -c 1 /etc/hosts > /dev/null && echo READ_OK",+ );+ expect(r.code).toBe(0);+ expect(r.out).toContain("confined-ok");+ expect(r.out).toContain("READ_OK");+ });++ it("workspace-write: a write outside the workspace is denied by the kernel", async () => {+ mode = "workspace-write";+ const r = await run(`echo leak > ${JSON.stringify(outsideProbe)} 2>&1; echo exit=$?`);+ expect(existsSync(outsideProbe)).toBe(false);+ expect(r.out).toMatch(DENIED);+ });++ it("workspace-write: background children are confined with the wrapped shell", async () => {+ mode = "workspace-write";+ const r = await run(+ `(sleep 0.2 && echo bg > ${JSON.stringify(outsideProbe)}) & wait; echo done`,+ );+ expect(r.out).toContain("done");+ expect(existsSync(outsideProbe)).toBe(false);+ });++ it("read-only: even the workspace is not writable", async () => {+ mode = "read-only";+ const r = await run("echo x > ro-probe.txt 2>&1; echo exit=$?");+ expect(existsSync(path.join(ws, "ro-probe.txt"))).toBe(false);+ expect(r.out).toMatch(DENIED);+ });++ it("the policy is read per spawn: dropping it lifts confinement on the next command", async () => {+ mode = null;+ const r = await run(`echo unconfined > ${JSON.stringify(outsideProbe)}; echo exit=$?`);+ expect(r.code).toBe(0);+ expect(existsSync(outsideProbe)).toBe(true);+ rmSync(outsideProbe, { force: true });+ });+ },+);diff --git a/plugins/sandbox-dsh/tsconfig.json b/plugins/sandbox-dsh/tsconfig.jsonnew file mode 100644index 00000000..8cd1715a--- /dev/null+++ b/plugins/sandbox-dsh/tsconfig.json@@ -0,0 +1,7 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "rootDir": "."+ },+ "include": ["src", "test"]+}diff --git a/plugins/sandbox-dsh/tsup.config.ts b/plugins/sandbox-dsh/tsup.config.tsnew file mode 100644index 00000000..30688a7a--- /dev/null+++ b/plugins/sandbox-dsh/tsup.config.ts@@ -0,0 +1,10 @@+import { defineConfig } from "tsup";++export default defineConfig({+ entry: ["src/index.ts"],+ format: ["esm"],+ target: "node24",+ dts: true,+ clean: true,+ sourcemap: true,+});diff --git a/plugins/sandbox-mxc/README.md b/plugins/sandbox-mxc/README.mdnew file mode 100644index 00000000..a22860a4--- /dev/null+++ b/plugins/sandbox-mxc/README.md@@ -0,0 +1,49 @@+# Windows sandbox backend (Microsoft MXC)++Confines command subprocesses on Windows through+**MXC** (Microsoft eXecution Containers), using its `processcontainer` backend.+Implements **all three** dimensions of the harness sandbox interface.++## Why this exists++Windows has neither bubblewrap nor `sandbox-exec`, and the DSH adaptor's Windows rung+(restricted tokens plus ACLs) governs file writes only. MXC's `processcontainer` backend+is the one Windows mechanism that expresses all three dimensions, and it maps onto them+directly:++| Harness dimension | MXC |+| --- | --- |+| `fs-write` | `filesystem.readwritePaths` / `readonlyPaths` |+| `mask-paths` | `filesystem.deniedPaths` |+| `network` | `network.allowOutbound: false` (MXC already defaults to deny) |++## Requirements++- Windows.+- `@microsoft/mxc-sdk`, an **optional peer dependency**. It carries roughly 40MB of+ per-platform binaries plus a native pty module, so only a deployment that actually wants+ this backend pays for them. It is reached through a dynamic import, and a missing SDK+ fails this backend's load — reported fail-closed — rather than the platform bundle's.++## Windows only, deliberately++MXC also ships Linux (bubblewrap/LXC) and macOS (Seatbelt) backends, but this harness+already has native, live-verified plugins for those. Declaring them here would add an+untested second path to a solved problem, so on any non-Windows host this backend declines+and routing moves on.++## Install++Add the specifier to your deployment's `plugins.json` and restart, or push a platform that+carries it:++```json+{ "plugins": ["@prismshadow/penguin-plugin-sandbox-mxc"] }+```++Installing is an operator-side action: the harness resolves the package from the installation,+never from this listing.++## License++Apache-2.0.diff --git a/plugins/sandbox-mxc/package.json b/plugins/sandbox-mxc/package.jsonnew file mode 100644index 00000000..ec1acf6e--- /dev/null+++ b/plugins/sandbox-mxc/package.json@@ -0,0 +1,39 @@+{+ "name": "@prismshadow/penguin-plugin-sandbox-mxc",+ "version": "0.2.2",+ "private": true,+ "type": "module",+ "description": "Windows sandbox backend for PenguinHarness over Microsoft MXC (Microsoft eXecution Containers): filesystem confinement, network isolation and path masking via the processcontainer backend.",+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js"+ }+ },+ "license": "Apache-2.0",+ "files": [+ "dist",+ "README.md"+ ],+ "scripts": {+ "typecheck": "tsc --noEmit -p tsconfig.json",+ "test": "vitest run --passWithNoTests",+ "build": "tsup"+ },+ "peerDependencies": {+ "@microsoft/mxc-sdk": ">=0.7.0 <1"+ },+ "peerDependenciesMeta": {+ "@microsoft/mxc-sdk": {+ "optional": true+ }+ },+ "devDependencies": {+ "@microsoft/mxc-sdk": "0.7.0",+ "@prismshadow/penguin-core": "workspace:*",+ "tsup": "^8.3.0",+ "vitest": "^3.2.6"+ }+}diff --git a/plugins/sandbox-mxc/src/index.ts b/plugins/sandbox-mxc/src/index.tsnew file mode 100644index 00000000..f301b1a8--- /dev/null+++ b/plugins/sandbox-mxc/src/index.ts@@ -0,0 +1,196 @@+/**+ * @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 type-only+ * `@prismshadow/penguin-core/plugin` surface and has no runtime dependency on the+ * harness or on any other backend.+ *+ * WHY THIS EXISTS: Windows has no bubblewrap and no sandbox-exec, and the DSH adaptor's+ * Windows rung (restricted tokens + ACLs) governs file writes only. MXC's+ * `processcontainer` backend is the one mechanism that expresses all three dimensions+ * of this harness's sandbox interface on Windows, and it maps onto them directly:+ *+ * fs-write → filesystem.readwritePaths / readonlyPaths+ * mask-paths → filesystem.deniedPaths+ * network → network.allowOutbound: false (MXC's default is already deny)+ *+ * WINDOWS ONLY, deliberately. MXC also carries Linux (bubblewrap/LXC) and macOS+ * (Seatbelt) backends, but this harness already ships native, live-verified plugins for+ * those; declaring them here too would only add an untested second path to a solved+ * problem. On any non-Windows host this backend declines and the routing moves on.+ *+ * The SDK is an OPTIONAL PEER DEPENDENCY, loaded through a dynamic import for the same+ * reason the DSH adaptor loads its chain that way: it carries ~40MB of per-platform+ * binaries plus a native pty module, so only a deployment that actually wants it pays+ * for it, and an installation missing it surfaces as an unavailable capability (the+ * sandbox service then fails closed for a confining policy) rather than a broken boot.+ *+ * COUPLING SURFACE, stated because MXC is Public Preview and its schema may move before+ * 1.0. Beyond the published `buildSandboxPayload`/`getPlatformSupport` API this backend+ * relies on exactly two internals, both verified against 0.7.0 and both asserted in the+ * tests: the runner is `bin/<arch>/wxc-exec.exe` inside the SDK package, and it takes+ * the whole config as `--config-base64 <base64 JSON>` with the command inside the+ * config (which is what lets an argv-rewriting seam host it at all — there is no+ * trailing argv to append).+ */+import { createRequire } from "node:module";+import path from "node:path";+import { spawnSync } from "node:child_process";+import type {+ ConfinedArgv,+ PluginContext,+ SandboxPolicy,+ SandboxProvider,+} from "@prismshadow/penguin-core/plugin";++/** Default probe budget; a probe that hangs must not hang the first spawn forever. */+const PROBE_TIMEOUT_MS = 5_000;++/** The MXC policy schema this backend writes. Pinned: a preview schema is a moving target. */+const MXC_POLICY_VERSION = "0.7.0-alpha";++/** The narrow slice of the MXC SDK this backend uses (see the coupling note above). */+export interface MxcSdk {+ buildSandboxPayload(+ script: string,+ policy: Record<string, unknown>,+ workingDirectory?: string,+ containerName?: string,+ containment?: string,+ ): Record<string, unknown>;+}++/** Test seams: inject the SDK, the runner path, and the probe verdict. */+export interface MxcInternals {+ sdk?: MxcSdk;+ runnerPath?: string;+ probe?: (runner: string, timeoutMs: number) => boolean;+ platform?: NodeJS.Platform;+}++/**+ * Quotes one argument the way `CommandLineToArgvW` parses it, so the argv the harness+ * handed us survives the round trip through MXC's single `commandLine` string. The+ * backslash rules are the fiddly part: a run of backslashes is only doubled when it+ * precedes a quote (a closing one included), which is why the two cases below differ.+ */+export function quoteWindowsArg(arg: string): string {+ if (arg.length > 0 && !/[ \t\n\v"]/.test(arg)) return arg;+ let quoted = '"';+ let backslashes = 0;+ for (const char of arg) {+ if (char === "\\") {+ backslashes++;+ continue;+ }+ if (char === '"') {+ quoted += "\\".repeat(backslashes * 2 + 1) + '"';+ } else {+ quoted += "\\".repeat(backslashes) + char;+ }+ backslashes = 0;+ }+ quoted += "\\".repeat(backslashes * 2) + '"';+ return quoted;+}++/** The argv the harness is about to spawn, as one Windows command line. */+export function toCommandLine(argv: readonly string[]): string {+ return argv.map(quoteWindowsArg).join(" ");+}++/** The MXC SandboxPolicy for one harness policy: the three dimensions, mapped. */+export function mxcPolicyFor(policy: SandboxPolicy): Record<string, unknown> {+ const readwritePaths = policy.mode === "workspace-write" ? [policy.workspaceRoot] : [];+ return {+ version: MXC_POLICY_VERSION,+ filesystem: {+ // The whole volume readable, the workspace writable under workspace-write, and+ // the masked paths denied outright — MXC's deniedPaths outranks the grants above.+ readonlyPaths: [path.parse(path.resolve(policy.workspaceRoot)).root],+ readwritePaths,+ deniedPaths: [...(policy.maskPaths ?? [])],+ },+ // MXC defaults to deny; say it explicitly so the intent survives a schema default change.+ network: { allowOutbound: policy.network === "none" ? false : true },+ };+}++/** The runner shipped inside the installed SDK: bin/<arch>/wxc-exec.exe. */+export function resolveRunner(requireFrom: NodeRequire = createRequire(import.meta.url)): string {+ const manifest = requireFrom.resolve("@microsoft/mxc-sdk/package.json");+ return path.join(path.dirname(manifest), "bin", process.arch, "wxc-exec.exe");+}++/** Functional probe: the runner answers `--probe` on a host where it can actually confine. */+function defaultProbe(runner: string, timeoutMs: number): boolean {+ const probe = spawnSync(runner, ["--probe"], { timeout: timeoutMs, stdio: "ignore" });+ return probe.status === 0;+}++/**+ * Loads the backend. Resolves to null where it cannot serve — a non-Windows host, or an+ * installation without the optional SDK — so the harness reports an unavailable+ * capability instead of a failure.+ */+export async function loadMxcProvider(+ internals: MxcInternals = {},+): Promise<SandboxProvider | null> {+ const platform = internals.platform ?? process.platform;+ if (platform !== "win32") return null;+ const sdk = internals.sdk ?? ((await import("@microsoft/mxc-sdk")) as unknown as MxcSdk);+ const runner = internals.runnerPath ?? resolveRunner();+ const probe = internals.probe ?? defaultProbe;+ return createMxcProvider(sdk, runner, probe);+}++/** The backend itself, over an already-resolved SDK and runner (the unit-testable core). */+export function createMxcProvider(+ sdk: MxcSdk,+ runner: string,+ probe: (runner: string, timeoutMs: number) => boolean = defaultProbe,+): SandboxProvider {+ let usable: boolean | undefined;+ return {+ dimensions: ["fs-write", "network", "mask-paths"],+ confine(argv, policy): ConfinedArgv {+ usable ??= probe(runner, PROBE_TIMEOUT_MS);+ if (!usable) {+ throw new Error(+ "penguin-mxc cannot confine on this host: the MXC runner is missing or reports no " ++ "usable containment; refusing to run the command unconfined.",+ );+ }+ const config = sdk.buildSandboxPayload(+ // The command travels INSIDE the config — MXC takes no trailing argv, which is+ // exactly what lets this argv-rewriting seam host it.+ toCommandLine(argv),+ mxcPolicyFor(policy),+ policy.workspaceRoot,+ undefined,+ "process",+ );+ const encoded = Buffer.from(JSON.stringify(config), "utf8").toString("base64");+ return {+ argv: [runner, "--config-base64", encoded],+ // processcontainer enforces the policy it accepts; MXC reports its own inability+ // through the probe and through structured errors, not by confining less.+ enforcement: "full",+ // Win32 denial dialects: cmd, PowerShell/.NET, and Node's own EACCES text.+ denialSignatures: ["access is denied", "access to the path", "permission denied"],+ runnerFailureRules: [{ fatalSignatures: ["wxc-exec", "mxc error"] }],+ };+ },+ };+}++/** The plugin: registered per App creation, like every other backend. Default export = the plugin. */+export function activate(ctx: PluginContext): void {+ // Backends register per App creation — a hot swap re-registers them into the fresh+ // registry — so the subscription is to the event, not a one-time registration here.+ ctx.on("initialize", (iface) => {+ iface.sandbox.registerProvider("penguin-mxc", loadMxcProvider());+ });+}diff --git a/plugins/sandbox-mxc/test/backend.test.ts b/plugins/sandbox-mxc/test/backend.test.tsnew file mode 100644index 00000000..06f250f7--- /dev/null+++ b/plugins/sandbox-mxc/test/backend.test.ts@@ -0,0 +1,195 @@+/**+ * Unit tests for the MXC Windows backend: the dimension mapping, the Windows+ * command-line quoting the argv must survive, the runner invocation shape, and the+ * platform/probe gating. These run on any host — the SDK is injected where the test is+ * about our mapping, and exercised for real where the test is about the SDK contract.+ */+import { describe, expect, it } from "vitest";+import path from "node:path";+import {+ createMxcProvider,+ loadMxcProvider,+ mxcPolicyFor,+ quoteWindowsArg,+ resolveRunner,+ toCommandLine,+ type MxcSdk,+} from "../src/index.js";++const RUNNER = "C:\\app\\node_modules\\@microsoft\\mxc-sdk\\bin\\x64\\wxc-exec.exe";+const WS = "C:\\work\\project";+const ARGV = ["cmd.exe", "/d", "/s", "/c", "echo hi"] as const;++/** Records what the backend asks the SDK to build. */+function recordingSdk(): { sdk: MxcSdk; calls: Array<Record<string, unknown>> } {+ const calls: Array<Record<string, unknown>> = [];+ const sdk: MxcSdk = {+ buildSandboxPayload(script, policy, workingDirectory, _name, containment) {+ calls.push({ script, policy, workingDirectory, containment });+ return { process: { commandLine: script }, containment };+ },+ };+ return { sdk, calls };+}++function decodeConfig(argv: readonly string[]): Record<string, unknown> {+ expect(argv[1]).toBe("--config-base64");+ return JSON.parse(Buffer.from(argv[2]!, "base64").toString("utf8")) as Record<string, unknown>;+}++describe("windows command-line quoting", () => {+ it("leaves simple arguments alone", () => {+ expect(quoteWindowsArg("cmd.exe")).toBe("cmd.exe");+ expect(quoteWindowsArg("/c")).toBe("/c");+ });++ it("quotes anything containing whitespace", () => {+ expect(quoteWindowsArg("echo hi")).toBe('"echo hi"');+ expect(quoteWindowsArg("")).toBe('""');+ });++ it("escapes embedded quotes and the backslashes that precede them", () => {+ // CommandLineToArgvW: a backslash run doubles only before a quote.+ expect(quoteWindowsArg('say "hi"')).toBe('"say \\"hi\\""');+ expect(quoteWindowsArg('a\\"b')).toBe('"a\\\\\\"b"');+ // Inside quotes a trailing backslash run doubles, because the closing quote follows it.+ expect(quoteWindowsArg("C:\\dir\\ x")).toBe('"C:\\dir\\ x"');+ expect(quoteWindowsArg("a b\\")).toBe('"a b\\\\"');+ });++ it("a path without whitespace or quotes passes through, trailing backslash included", () => {+ // CommandLineToArgvW only treats backslashes specially when a quote follows them,+ // and arguments are joined with spaces — so an unquoted trailing backslash round+ // trips exactly. Quoting it would be harmless but is not required, and the simpler+ // rule is the one with fewer ways to be wrong.+ expect(quoteWindowsArg("C:\\Windows\\System32")).toBe("C:\\Windows\\System32");+ expect(quoteWindowsArg("C:\\dir\\")).toBe("C:\\dir\\");+ });++ it("joins an argv into one command line", () => {+ expect(toCommandLine(ARGV)).toBe('cmd.exe /d /s /c "echo hi"');+ });+});++describe("dimension mapping", () => {+ it("workspace-write grants the workspace and nothing else", () => {+ const policy = mxcPolicyFor({ mode: "workspace-write", workspaceRoot: WS });+ expect(policy.filesystem).toMatchObject({+ readwritePaths: [WS],+ readonlyPaths: [path.parse(path.resolve(WS)).root],+ deniedPaths: [],+ });+ });++ it("read-only grants nothing writable", () => {+ expect(mxcPolicyFor({ mode: "read-only", workspaceRoot: WS }).filesystem).toMatchObject({+ readwritePaths: [],+ });+ });++ it("network: none maps to allowOutbound false; absent leaves the network alone", () => {+ expect(mxcPolicyFor({ mode: "read-only", workspaceRoot: WS, network: "none" })).toMatchObject({+ network: { allowOutbound: false },+ });+ expect(mxcPolicyFor({ mode: "read-only", workspaceRoot: WS })).toMatchObject({+ network: { allowOutbound: true },+ });+ });++ it("mask-paths map to deniedPaths", () => {+ expect(+ mxcPolicyFor({+ mode: "workspace-write",+ workspaceRoot: WS,+ maskPaths: ["C:\\Users\\me\\.ssh"],+ }).filesystem,+ ).toMatchObject({ deniedPaths: ["C:\\Users\\me\\.ssh"] });+ });+});++describe("runner invocation", () => {+ it("implements every dimension of the sandbox interface", () => {+ const { sdk } = recordingSdk();+ expect(createMxcProvider(sdk, RUNNER, () => true).dimensions).toEqual([+ "fs-write",+ "network",+ "mask-paths",+ ]);+ });++ it("wraps as [runner, --config-base64, <config>] with the command INSIDE the config", () => {+ const { sdk, calls } = recordingSdk();+ const confined = createMxcProvider(sdk, RUNNER, () => true).confine([...ARGV], {+ mode: "workspace-write",+ workspaceRoot: WS,+ network: "none",+ maskPaths: ["C:\\secrets"],+ });+ expect(confined.argv[0]).toBe(RUNNER);+ expect(confined.argv).toHaveLength(3);+ // No trailing argv: MXC takes the command through the config, which is what lets an+ // argv-rewriting seam host it at all.+ expect(decodeConfig(confined.argv)).toMatchObject({+ process: { commandLine: 'cmd.exe /d /s /c "echo hi"' },+ containment: "process",+ });+ expect(calls[0]).toMatchObject({ workingDirectory: WS, containment: "process" });+ expect(confined.enforcement).toBe("full");+ });++ it("an unusable runner fails closed, and the probe runs once", () => {+ const { sdk } = recordingSdk();+ let probes = 0;+ const provider = createMxcProvider(sdk, RUNNER, () => {+ probes++;+ return false;+ });+ const policy = { mode: "read-only", workspaceRoot: WS } as const;+ expect(() => provider.confine([...ARGV], policy)).toThrow(/cannot confine on this host/);+ expect(() => provider.confine([...ARGV], policy)).toThrow(/refusing to run/);+ expect(probes).toBe(1);+ });+});++describe("platform gating and SDK contract", () => {+ it("declines on every non-Windows host instead of pretending", async () => {+ expect(await loadMxcProvider({ platform: "linux" })).toBeNull();+ expect(await loadMxcProvider({ platform: "darwin" })).toBeNull();+ });++ it("the runner path is bin/<arch>/wxc-exec.exe inside the installed SDK", () => {+ // One of the two MXC internals this backend depends on (see its module doc).+ const runner = resolveRunner();+ expect(runner.endsWith(path.join("bin", process.arch, "wxc-exec.exe"))).toBe(true);+ expect(runner).toContain(path.join("@microsoft", "mxc-sdk"));+ });++ it("the REAL SDK still maps our policy onto the fields this backend relies on", async () => {+ // Drift guard: MXC is Public Preview, so this asserts against the installed SDK+ // rather than a fake — if the schema moves, this fails here instead of on Windows.+ const sdk = (await import("@microsoft/mxc-sdk")) as unknown as MxcSdk;+ const config = sdk.buildSandboxPayload(+ toCommandLine(ARGV),+ mxcPolicyFor({+ mode: "workspace-write",+ workspaceRoot: WS,+ network: "none",+ maskPaths: ["C:\\secrets"],+ }),+ WS,+ undefined,+ "process",+ );+ expect(config).toMatchObject({+ process: { commandLine: 'cmd.exe /d /s /c "echo hi"' },+ filesystem: {+ readwritePaths: [WS],+ deniedPaths: ["C:\\secrets"],+ },+ network: { defaultPolicy: "block" },+ // No containment assertion: the backend passes "process" in but never reads the+ // echo, and the SDK resolves that field per HOST (seatbelt on darwin) — on the+ // only host this backend runs, Windows, it is the process containment requested.+ });+ });+});diff --git a/plugins/sandbox-mxc/tsconfig.json b/plugins/sandbox-mxc/tsconfig.jsonnew file mode 100644index 00000000..8cd1715a--- /dev/null+++ b/plugins/sandbox-mxc/tsconfig.json@@ -0,0 +1,7 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "rootDir": "."+ },+ "include": ["src", "test"]+}diff --git a/plugins/sandbox-mxc/tsup.config.ts b/plugins/sandbox-mxc/tsup.config.tsnew file mode 100644index 00000000..30688a7a--- /dev/null+++ b/plugins/sandbox-mxc/tsup.config.ts@@ -0,0 +1,10 @@+import { defineConfig } from "tsup";++export default defineConfig({+ entry: ["src/index.ts"],+ format: ["esm"],+ target: "node24",+ dts: true,+ clean: true,+ sourcemap: true,+});diff --git a/plugins/sandbox-seatbelt/README.md b/plugins/sandbox-seatbelt/README.mdnew file mode 100644index 00000000..57ce5377--- /dev/null+++ b/plugins/sandbox-seatbelt/README.md@@ -0,0 +1,47 @@+# macOS Seatbelt sandbox backend++The macOS counterpart to the bubblewrap backend, built on `sandbox-exec` (Seatbelt).+Implements **all three** dimensions of the harness sandbox interface — filesystem writes,+network isolation and path masking — as policy rules rather than mounts.++## Requirements++- macOS, with `sandbox-exec` available (part of the base system).++## How the profile is built++```scheme+(allow default) ; start from the host's world+(deny file-write*) ; nothing is writable…+(allow file-write* (literal "/dev/null") …) ; …beyond the required sinks+;; workspace-write+(allow file-write* (subpath "<workspaceRoot>") …)+;; network: none+(deny network*)+;; mask-paths+(deny file-read* file-write* (subpath "<p>"))+```++Rule **order** is the counterpart to bwrap's mount order: in SBPL the *last* matching rule+wins, so mask denials are emitted after the write allowances — otherwise masking a path+inside the workspace would be overridden by the workspace's own allowance.++Paths are canonicalized before entering the profile. Seatbelt matches the real filesystem+path, and on macOS `/tmp` and `/var` are symlinks into `/private`, so an uncanonicalized+subpath rule silently matches nothing.++## Install++Add the specifier to your deployment's `plugins.json` and restart, or push a platform that+carries it:++```json+{ "plugins": ["@prismshadow/penguin-plugin-sandbox-seatbelt"] }+```++Installing is an operator-side action: the harness resolves the package from the installation,+never from this listing.++## License++Apache-2.0.diff --git a/plugins/sandbox-seatbelt/package.json b/plugins/sandbox-seatbelt/package.jsonnew file mode 100644index 00000000..eb6e8b30--- /dev/null+++ b/plugins/sandbox-seatbelt/package.json@@ -0,0 +1,30 @@+{+ "name": "@prismshadow/penguin-plugin-sandbox-seatbelt",+ "version": "0.2.2",+ "private": true,+ "type": "module",+ "description": "macOS Seatbelt sandbox backend for PenguinHarness: filesystem confinement plus network isolation and path masking.",+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js"+ }+ },+ "license": "Apache-2.0",+ "files": [+ "dist",+ "README.md"+ ],+ "scripts": {+ "typecheck": "tsc --noEmit -p tsconfig.json",+ "test": "vitest run --passWithNoTests",+ "build": "tsup"+ },+ "devDependencies": {+ "@prismshadow/penguin-core": "workspace:*",+ "tsup": "^8.3.0",+ "vitest": "^3.2.6"+ }+}diff --git a/plugins/sandbox-seatbelt/src/index.ts b/plugins/sandbox-seatbelt/src/index.tsnew file mode 100644index 00000000..65e156f0--- /dev/null+++ b/plugins/sandbox-seatbelt/src/index.ts@@ -0,0 +1,159 @@+/**+ * @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 type-only+ * `@prismshadow/penguin-core/plugin` surface and has no runtime dependency on the+ * harness or on any other backend.+ *+ * Seatbelt is the macOS counterpart to bubblewrap here, and it expresses all three+ * dimensions of the sandbox interface natively — as POLICY rules rather than mounts:+ *+ * (allow default) start from the host's world+ * (deny file-write*) nothing is writable…+ * (allow file-write* (literal "/dev/null") …) …beyond the required sinks+ * [workspace-write] (allow file-write* (subpath <root>) …)+ * [network: none] (deny network*)+ * [mask-paths] (deny file-read* file-write* (subpath <p>))+ *+ * Rule ORDER is the counterpart to bwrap's mount order: in SBPL the LAST matching rule+ * wins, so the mask denials are emitted after the write allowances — otherwise masking+ * a path inside the workspace would be overridden by the workspace's own allowance.+ *+ * Paths are canonicalized before they enter the profile: Seatbelt matches the real+ * filesystem path, and on macOS `/tmp` and `/var` are symlinks into `/private`, so an+ * uncanonicalized subpath rule silently matches nothing.+ *+ * `sandbox-exec` is deprecated by Apple but ships on every macOS; if it ever stops+ * working, the probe below is what turns that into a fail-closed refusal rather than an+ * unconfined run.+ */+import { spawnSync } from "node:child_process";+import { realpathSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import type {+ ConfinedArgv,+ PluginContext,+ SandboxPolicy,+ SandboxProvider,+} from "@prismshadow/penguin-core/plugin";++/** Default probe budget; a probe that hangs must not hang the first spawn forever. */+const PROBE_TIMEOUT_MS = 5_000;++/** The write sinks a confined process needs even under read-only. */+const REQUIRED_WRITE_SINKS = ["/dev/null", "/dev/stdout", "/dev/stderr", "/dev/dtracehelper"];++/** Test seams: inject the probe verdict and the runner name. */+export interface SeatbeltInternals {+ probe?: (timeoutMs: number) => boolean;+ runner?: string;+}++/** Canonical path (symlinks resolved), falling back to a lexical resolve for paths that do not exist yet. */+export function canonicalPath(target: string): string {+ try {+ return realpathSync(path.resolve(target));+ } catch {+ return path.resolve(target);+ }+}++/** The writable roots `workspace-write` grants: the workspace plus the temp areas, canonical and deduplicated. */+export function writableRoots(policy: SandboxPolicy): string[] {+ if (policy.mode !== "workspace-write") return [];+ return [...new Set([policy.workspaceRoot, "/tmp", tmpdir()].map(canonicalPath))];+}++/** Quote one path as an SBPL string literal. */+function sbplString(value: string): string {+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;+}++/** The SBPL profile for one policy: the exact text handed to `sandbox-exec -p`. */+export function seatbeltProfile(policy: SandboxPolicy): string {+ const forms = [+ "(version 1)",+ "(allow default)",+ "(deny file-write*)",+ `(allow file-write* ${REQUIRED_WRITE_SINKS.map((sink) => `(literal ${sbplString(sink)})`).join(" ")})`,+ ];+ const roots = writableRoots(policy);+ if (roots.length > 0) {+ forms.push(+ `(allow file-write* ${roots.map((root) => `(subpath ${sbplString(root)})`).join(" ")})`,+ );+ }+ if (policy.network === "none") {+ // Seatbelt filters network natively: no sockets at all, outbound or inbound.+ forms.push("(deny network*)");+ }+ // LAST: a mask must outrank the write allowances above, including a masked path that+ // happens to sit inside the workspace.+ for (const target of policy.maskPaths ?? []) {+ const canonical = canonicalPath(target);+ forms.push(`(deny file-read* file-write* (subpath ${sbplString(canonical)}))`);+ }+ return forms.join(" ");+}++/** The `sandbox-exec` arguments before the caller's argv. */+export function seatbeltArgs(policy: SandboxPolicy): string[] {+ return ["-p", seatbeltProfile(policy)];+}++/**+ * Functional probe: apply the real read-only profile through `sandbox-exec` and run+ * `true` under it. Exit 0 means the kernel accepted AND enforced the profile+ * (`sandbox-exec` exits non-zero when `sandbox_init` refuses it). A missing binary —+ * every non-macOS host — fails the spawn and probes unusable the same way, on purpose.+ */+function defaultProbe(timeoutMs: number, runner: string): boolean {+ const probe = spawnSync(+ runner,+ [...seatbeltArgs({ mode: "read-only", workspaceRoot: "/" }), "--", "true"],+ { timeout: timeoutMs, stdio: "ignore" },+ );+ return probe.status === 0;+}++/**+ * The backend. The probe runs once, lazily (first confine), and is cached; an+ * unusable Seatbelt throws — fail-closed — rather than degrading to a weaker profile.+ */+export function createSeatbeltProvider(internals: SeatbeltInternals = {}): SandboxProvider {+ const runner = internals.runner ?? "sandbox-exec";+ const probe = internals.probe ?? ((timeoutMs: number) => defaultProbe(timeoutMs, runner));+ let usable: boolean | undefined;+ return {+ dimensions: ["fs-write", "network", "mask-paths"],+ confine(argv, policy): ConfinedArgv {+ usable ??= probe(PROBE_TIMEOUT_MS);+ if (!usable) {+ throw new Error(+ `penguin-seatbelt cannot confine on this host: '${runner}' is missing or refuses the ` ++ "profile (it exists only on macOS); refusing to run the command unconfined.",+ );+ }+ return {+ argv: [runner, ...seatbeltArgs(policy), "--", ...argv],+ // Seatbelt enforces the whole profile it accepts; nothing here is best-effort.+ enforcement: "full",+ // Seatbelt denials surface as EPERM; a denied network call also shows up as an+ // unreachable/refused socket, which the first two cover in practice.+ denialSignatures: ["operation not permitted", "permission denied"],+ runnerFailureRules: [{ fatalSignatures: [`${runner}: `] }],+ };+ },+ };+}++/** The plugin: registered per App creation, like every other backend. Default export = the plugin. */+export function activate(ctx: PluginContext): void {+ // Backends register per App creation — a hot swap re-registers them into the fresh+ // registry — so the subscription is to the event, not a one-time registration here.+ ctx.on("initialize", (iface) => {+ iface.sandbox.registerProvider("penguin-seatbelt", createSeatbeltProvider());+ });+}diff --git a/plugins/sandbox-seatbelt/test/live.test.ts b/plugins/sandbox-seatbelt/test/live.test.tsnew file mode 100644index 00000000..739138b9--- /dev/null+++ b/plugins/sandbox-seatbelt/test/live.test.ts@@ -0,0 +1,120 @@+/**+ * Live enforcement against a real macOS host: real sandbox-exec, real spawns through+ * core's command sessions, real kernel denials.+ *+ * Host-gated — this suite can only run where Seatbelt exists, so it skips everywhere+ * else and profile.test.ts carries the deterministic coverage. Written to be the exact+ * counterpart of the bwrap package's live suite, so the two backends are held to the+ * same behavioral bar.+ */+import { afterAll, describe, expect, it } from "vitest";+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import path from "node:path";+import { CommandSessionManager } from "@prismshadow/penguin-core";+import type { SandboxPolicy } from "@prismshadow/penguin-core/plugin";+import { canonicalPath, createSeatbeltProvider } from "../src/index.js";++const ws = canonicalPath(mkdtempSync(path.join(tmpdir(), "penguin-seatbelt-live-")));+const outsideProbe = path.join(homedir(), `penguin-seatbelt-live-${process.pid}.txt`);+const provider = createSeatbeltProvider();++/** null = spawn unconfined; otherwise confine under this policy (workspaceRoot filled per spawn). */+let policy: Omit<SandboxPolicy, "workspaceRoot"> | null = null;++const usable = (() => {+ try {+ provider.confine(["true"], { mode: "read-only", workspaceRoot: ws });+ return true;+ } catch {+ return false;+ }+})();++const mgr = new CommandSessionManager({+ confineSpawn: () => (argv, opts) =>+ policy === null+ ? argv+ : provider.confine(argv, { ...policy, workspaceRoot: canonicalPath(opts.workspaceDir) }).argv,+ workspaceDir: ws,+});++async function run(cmd: string): Promise<{ code: number | null; out: string }> {+ const session = mgr.spawn({ cmd, cwd: ws });+ let out = "";+ for await (const chunk of session.collect(15000)) out += chunk;+ if (session.running) session.kill();+ return { code: session.exit?.code ?? null, out };+}++const DENIED = /operation not permitted|permission denied/i;++afterAll(() => {+ mgr.dispose();+ rmSync(ws, { recursive: true, force: true });+ rmSync(outsideProbe, { force: true });+});++describe.skipIf(!usable)("penguin-seatbelt live enforcement (host-gated)", () => {+ it("fs-write: the workspace is writable, the world outside it is not", async () => {+ policy = { mode: "workspace-write" };+ const inside = await run("echo confined-ok > inside.txt && cat inside.txt");+ expect(inside.code).toBe(0);+ expect(inside.out).toContain("confined-ok");++ const outside = await run(`echo leak > ${JSON.stringify(outsideProbe)} 2>&1; echo exit=$?`);+ expect(existsSync(outsideProbe)).toBe(false);+ expect(outside.out).toMatch(DENIED);+ });++ it("fs-write: reads outside the workspace still work, and read-only denies the workspace too", async () => {+ policy = { mode: "workspace-write" };+ expect((await run("head -c 1 /etc/hosts > /dev/null && echo READ_OK")).out).toContain(+ "READ_OK",+ );++ policy = { mode: "read-only" };+ const ro = await run("echo x > ro-probe.txt 2>&1; echo exit=$?");+ expect(existsSync(path.join(ws, "ro-probe.txt"))).toBe(false);+ expect(ro.out).toMatch(DENIED);+ });++ it("network: none blocks sockets and name resolution", async () => {+ // nslookup, not getent: this host-gated suite only ever runs on macOS, which has no+ // getent. The SAME probe first passes without the network dimension, so its later+ // failure is attributable to the sandbox rather than to a missing tool or DNS.+ const LOOKUP = "nslookup -timeout=2 github.com > /dev/null 2>&1; echo exit=$?";+ policy = { mode: "workspace-write" };+ expect((await run(LOOKUP)).out).toContain("exit=0");++ policy = { mode: "workspace-write", network: "none" };+ // Any socket at all is denied, so both a raw connect and a DNS lookup fail.+ expect((await run("nc -z -G 1 127.0.0.1 22 2>&1; echo exit=$?")).out).toMatch(/exit=[^0]/);+ expect((await run(LOOKUP)).out).toMatch(/exit=[^0]/);+ });++ it("mask-paths: a masked directory's secret is unreadable", async () => {+ const secretDir = mkdtempSync(path.join(homedir(), "penguin-seatbelt-secret-"));+ const secretFile = path.join(secretDir, "token.txt");+ writeFileSync(secretFile, "super-secret");+ try {+ policy = { mode: "workspace-write" };+ expect((await run(`cat ${JSON.stringify(secretFile)}`)).out).toContain("super-secret");++ policy = { mode: "workspace-write", maskPaths: [secretDir] };+ const masked = await run(`cat ${JSON.stringify(secretFile)} 2>&1`);+ expect(masked.out).not.toContain("super-secret");+ expect(masked.out).toMatch(DENIED);+ } finally {+ rmSync(secretDir, { recursive: true, force: true });+ }+ });++ it("the policy is read per spawn: dropping it lifts confinement on the next command", async () => {+ policy = null;+ const r = await run(`echo unconfined > ${JSON.stringify(outsideProbe)}; echo exit=$?`);+ expect(r.code).toBe(0);+ expect(existsSync(outsideProbe)).toBe(true);+ rmSync(outsideProbe, { force: true });+ });+});diff --git a/plugins/sandbox-seatbelt/test/profile.test.ts b/plugins/sandbox-seatbelt/test/profile.test.tsnew file mode 100644index 00000000..60102760--- /dev/null+++ b/plugins/sandbox-seatbelt/test/profile.test.ts@@ -0,0 +1,128 @@+/**+ * Unit tests for the Seatbelt backend: the exact SBPL it generates per dimension, the+ * rule ORDER that makes masking outrank the write allowances, and its fail-closed+ * behavior where sandbox-exec is unusable. The probe is injected, so these run on any+ * host — a macOS box also runs live.test.ts.+ */+import { describe, expect, it } from "vitest";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import {+ canonicalPath,+ createSeatbeltProvider,+ seatbeltProfile,+ writableRoots,+} from "../src/index.js";++const ARGV = ["bash", "-lc", "echo hi"] as const;+const WS = "/work/project";++// skipIf(win32): the SBPL path rules echo host path canonicalization (drive letters,+// backslash escaping), and Seatbelt never runs there anyway.+describe.skipIf(process.platform === "win32")("seatbelt profile", () => {+ it("read-only: writes are denied except the required sinks; no network rule", () => {+ const profile = seatbeltProfile({ mode: "read-only", workspaceRoot: WS });+ expect(profile).toContain("(version 1)");+ expect(profile).toContain("(allow default)");+ expect(profile).toContain("(deny file-write*)");+ expect(profile).toContain('(literal "/dev/null")');+ expect(profile).not.toContain("(deny network*)");+ expect(profile).not.toContain(`(subpath "${WS}")`);+ });++ it("workspace-write: the workspace and the temp areas become writable", () => {+ const profile = seatbeltProfile({ mode: "workspace-write", workspaceRoot: WS });+ expect(profile).toContain(`(allow file-write* (subpath "${canonicalPath(WS)}")`);+ expect(profile).toContain(canonicalPath(tmpdir()));+ });++ it("network: none denies every socket", () => {+ expect(seatbeltProfile({ mode: "read-only", workspaceRoot: WS, network: "none" })).toContain(+ "(deny network*)",+ );+ });++ it("mask-paths: a masked path is denied for read AND write", () => {+ const dir = mkdtempSync(path.join(tmpdir(), "penguin-sb-mask-"));+ try {+ const profile = seatbeltProfile({+ mode: "read-only",+ workspaceRoot: WS,+ maskPaths: [dir],+ });+ expect(profile).toContain(`(deny file-read* file-write* (subpath "${canonicalPath(dir)}"))`);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("masks come LAST, so masking a path inside the workspace still wins", () => {+ // SBPL's last matching rule wins — the inverse of bwrap's first-mount-then-shadow,+ // and the reason this ordering is asserted rather than assumed.+ const inside = path.join(WS, "secrets");+ const profile = seatbeltProfile({+ mode: "workspace-write",+ workspaceRoot: WS,+ maskPaths: [inside],+ });+ expect(+ profile.indexOf(`(deny file-read* file-write* (subpath "${canonicalPath(inside)}"))`),+ ).toBeGreaterThan(profile.indexOf("(allow file-write* (subpath"));+ });++ it("paths are canonicalized: an uncanonicalized subpath rule would match nothing on macOS", () => {+ // /tmp is a symlink to /private/tmp on macOS; on Linux realpath is a no-op, so the+ // assertion is the invariant itself — what lands in the profile is the real path.+ const real = canonicalPath("/tmp");+ expect(seatbeltProfile({ mode: "workspace-write", workspaceRoot: "/tmp" })).toContain(+ `(subpath "${real}")`,+ );+ expect(writableRoots({ mode: "workspace-write", workspaceRoot: "/tmp" })).toContain(real);+ });++ it("SBPL strings escape quotes and backslashes", () => {+ const weird = '/tmp/we"ird\\path';+ const profile = seatbeltProfile({ mode: "read-only", workspaceRoot: "/", maskPaths: [weird] });+ expect(profile).toContain('we\\"ird\\\\path');+ });+});++describe("seatbelt provider", () => {+ it("implements every dimension of the sandbox interface", () => {+ expect(createSeatbeltProvider({ probe: () => true }).dimensions).toEqual([+ "fs-write",+ "network",+ "mask-paths",+ ]);+ });++ it("wraps the caller's argv behind -p <profile> and a -- separator", () => {+ const provider = createSeatbeltProvider({ probe: () => true, runner: "sandbox-exec" });+ const confined = provider.confine([...ARGV], {+ mode: "workspace-write",+ workspaceRoot: WS,+ network: "none",+ });+ expect(confined.argv[0]).toBe("sandbox-exec");+ expect(confined.argv[1]).toBe("-p");+ expect(confined.argv[2]).toContain("(deny network*)");+ expect(confined.argv[3]).toBe("--");+ expect(confined.argv.slice(4)).toEqual([...ARGV]);+ expect(confined.enforcement).toBe("full");+ });++ it("an unusable sandbox-exec (every non-macOS host) fails closed, probing once", () => {+ let probes = 0;+ const provider = createSeatbeltProvider({+ probe: () => {+ probes++;+ return false;+ },+ });+ const policy = { mode: "read-only", workspaceRoot: WS } as const;+ expect(() => provider.confine([...ARGV], policy)).toThrow(/cannot confine on this host/);+ expect(() => provider.confine([...ARGV], policy)).toThrow(/only on macOS/);+ expect(probes).toBe(1);+ });+});diff --git a/plugins/sandbox-seatbelt/tsconfig.json b/plugins/sandbox-seatbelt/tsconfig.jsonnew file mode 100644index 00000000..8cd1715a--- /dev/null+++ b/plugins/sandbox-seatbelt/tsconfig.json@@ -0,0 +1,7 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "rootDir": "."+ },+ "include": ["src", "test"]+}diff --git a/plugins/sandbox-seatbelt/tsup.config.ts b/plugins/sandbox-seatbelt/tsup.config.tsnew file mode 100644index 00000000..30688a7a--- /dev/null+++ b/plugins/sandbox-seatbelt/tsup.config.ts@@ -0,0 +1,10 @@+import { defineConfig } from "tsup";++export default defineConfig({+ entry: ["src/index.ts"],+ format: ["esm"],+ target: "node24",+ dts: true,+ clean: true,+ sourcemap: true,+});diff --git a/plugins/skill-porting/skills/skill-porting/SKILL.md b/plugins/skill-porting/skills/skill-porting/SKILL.mdindex 5f8051dd..f73da980 100644--- a/plugins/skill-porting/skills/skill-porting/SKILL.md+++ b/plugins/skill-porting/skills/skill-porting/SKILL.md@@ -5,7 +5,7 @@ description: Install skills from external ecosystems into this agent's agent_sta# Skill Porting-Penguin has no plugin mechanism and needs none: the wider ecosystem's plugins are wrappers around plain skill directories — a `SKILL.md` plus support files — which is exactly the shape Penguin installs. This skill turns any common external source into installed skills: locate the source, fetch it at a pinned revision, review everything, normalize the frontmatter, copy into `agent_state/skills/<name>/`, verify.+A Penguin plugin is a package a deployment installs to add capability the harness does not ship, and nothing here produces one: the wider ecosystem's plugins are wrappers around plain skill directories — a `SKILL.md` plus support files — which is exactly the shape Penguin installs. This skill turns any common external source into installed skills: locate the source, fetch it at a pinned revision, review everything, normalize the frontmatter, copy into `agent_state/skills/<name>/`, verify.## Before you startdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex fc6b0c41..160ac5f0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -553,6 +553,67 @@ importers:plugins/model-development: {}+ plugins/sandbox-bwrap:+ devDependencies:+ '@prismshadow/penguin-core':+ specifier: workspace:*+ version: file:packages/core([email protected])([email protected])+ tsup:+ specifier: ^8.3.0+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: ^3.2.6+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])++ plugins/sandbox-dsh:+ dependencies:+ '@deepseek-ai/cordis':+ specifier: ^4.0.1+ version: 4.0.1+ '@deepseek-ai/dsh-sandbox':+ specifier: 0.1.0-rc.7+ version: 0.1.0-rc.7(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))))(@deepseek-ai/[email protected](fbdb1d988541b64ff002d18c4ded7293))+ '@deepseek-ai/dsh-sandbox-local':+ specifier: 0.1.0-rc.7+ version: 0.1.0-rc.7(aee23af2fa86328531d8fa647b06b497)+ devDependencies:+ '@prismshadow/penguin-core':+ specifier: workspace:*+ version: file:packages/core([email protected])([email protected])+ tsup:+ specifier: ^8.3.0+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: ^3.2.6+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])++ plugins/sandbox-mxc:+ devDependencies:+ '@microsoft/mxc-sdk':+ specifier: 0.7.0+ version: 0.7.0+ '@prismshadow/penguin-core':+ specifier: workspace:*+ version: file:packages/core([email protected])([email protected])+ tsup:+ specifier: ^8.3.0+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: ^3.2.6+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])++ plugins/sandbox-seatbelt:+ devDependencies:+ '@prismshadow/penguin-core':+ specifier: workspace:*+ version: file:packages/core([email protected])([email protected])+ tsup:+ specifier: ^8.3.0+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: ^3.2.6+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+plugins/skill-porting: {}plugins/software-development: {}@@ -798,6 +859,118 @@ packages:resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==}engines: {node: '>=6.9.0'}+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-YBdskTU2Po1kru3GgcUWUbkTsPMA9LkSQDAY8rBkFJeajdgcQad3QPJZE26JyK99Xb6HaASvoXg2DSUTeN/0Nw==}+ hasBin: true+ peerDependencies:+ '@deepseek-ai/cordis-plugin-include': ^1.0.6+ '@deepseek-ai/cordis-plugin-loader': ^1.0.2+ peerDependenciesMeta:+ '@deepseek-ai/cordis-plugin-include':+ optional: true+ '@deepseek-ai/cordis-plugin-loader':+ optional: true++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-muBOKtSrUKU5m/xpq8ZXWL6hQ/jgd4PhU2PqH97bcxIiLEJfNwZOGQEx4t/aS/GgxRAR+ra9pMHPMtTHU4sqqA==}++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-cCrg4WWiav7pGtbdU8dJTpAG28cPnkWVB2YPOrlBCgBbhQziGcG9Dv67Ti6L3PI4OQKC55gYBFinQghFO/7FGg==}+ peerDependencies:+ '@deepseek-ai/cordis': ^4.0.1+ '@deepseek-ai/dsh-brand': ^0.1.0-rc.8+ '@deepseek-ai/dsh-invariants': ^0.1.0-rc.8++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-402aUAfHxIZJrArBV4gDf0I/A/69A/By26FX6HTIOyFmCnB4wUBKh8jnglz1CorKWdZy8AKldAhh8HQhQEbGOQ==}+ peerDependencies:+ '@deepseek-ai/cordis': ^4.0.1+ '@deepseek-ai/dsh-invariants': ^0.1.0-rc.8++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-u0lYqyxOYwfsVnbsfGXZos5vFvA4cqFnBEW3/ezgljNwkYwzeUP/Y5wjPnQjP+ZzBn3CnVeIF6s2N2Vk3iA5mQ==}+ peerDependencies:+ '@deepseek-ai/cordis': ^4.0.1++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-hf6RmX2Stn1UtzpktSHQLkIktQkBm9i/3yFfJlbGSkwyw5Cv9sTYJbyoHzsSnnh6i8nRRcMcBhvMgm23I00oIw==}+ peerDependencies:+ '@deepseek-ai/cordis': ^4.0.1+ '@deepseek-ai/dsh-attachment': ^0.1.0-rc.8+ '@deepseek-ai/dsh-brand': ^0.1.0-rc.8+ '@deepseek-ai/dsh-invariants': ^0.1.0-rc.8+ '@deepseek-ai/dsh-timeout': ^0.1.0-rc.8++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-jahNeS/WnBinCisOB4O+zeS366v7gWt6Uzfso0/C5He/vZFEITW5jPfWrJkZLuuN5S55LshaDEnegsddEIp6kw==}+ peerDependencies:+ '@deepseek-ai/cordis': ^4.0.1+ '@deepseek-ai/dsh-invariants': ^0.1.0-rc.7+ '@deepseek-ai/dsh-llm': ^0.1.0-rc.7+ '@deepseek-ai/dsh-sandbox': ^0.1.0-rc.7+ '@deepseek-ai/dsh-session': ^0.1.0-rc.7++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-3DeFPD+laUbXrzVpEJ0FrF5pMQCqeu7YCJAWgORGj1aju7sIjpineEnKpE6EXhbc8C9Jqu2y5S7B9z6ydOL/Zg==}+ peerDependencies:+ '@deepseek-ai/cordis': ^4.0.1+ '@deepseek-ai/dsh-invariants': ^0.1.0-rc.8++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-he43z39/SC8cMzPDsoP7EEXiXKjav3VClj/U943pxycvRL78JGkNEQQjv21n5mnuto0ti/gFBquybSI4sBAFqA==}+ peerDependencies:+ '@deepseek-ai/cordis': ^4.0.1+ '@deepseek-ai/dsh-invariants': ^0.1.0-rc.7+ '@deepseek-ai/dsh-llm': ^0.1.0-rc.7+ '@deepseek-ai/dsh-session': ^0.1.0-rc.7++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-/o+PxkVV2zUy9lYlMFr4TWSb+ESW4DE+fI891yIbsLzOJdFgfbmmLpGrlWgnz8/unIGJZxjeXdwyppV04Z277Q==}+ peerDependencies:+ '@deepseek-ai/cordis': ^4.0.1+ '@deepseek-ai/dsh-invariants': ^0.1.0-rc.8++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-Qs5Mgn32WPPVB4rKHjsZBgLOkh0TQurUAcc9GaDVudK4dUkpno2HDh++qu/PrwRA3CZ/iwPAoFHCpB3AMMaoLg==}+ peerDependencies:+ '@deepseek-ai/cordis': ^4.0.1+ '@deepseek-ai/dsh-brand': ^0.1.0-rc.8+ '@deepseek-ai/dsh-invariants': ^0.1.0-rc.8+ '@deepseek-ai/dsh-llm': ^0.1.0-rc.8+ '@deepseek-ai/dsh-scope': ^0.1.0-rc.8+ '@deepseek-ai/dsh-typert-protocol': ^0.1.0-rc.8++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-RwOC/qHribE6b+LStAO7aAgweefLE5sqDO7Uz6/mnTDyJxCt7HNQnE/Op8sAvRa33d752aUkPfO9S0mgzVAoFQ==}+ peerDependencies:+ '@deepseek-ai/cordis': ^4.0.1+ '@deepseek-ai/dsh-invariants': ^0.1.0-rc.8++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-scwEAefRBL7gRpaXiEdiHRMvlr8dLmUbiEvy0LOAX/8X3FZBd/5tHQ/8lCppAQNTDZMI/LSiSMpu5XrFId+7cQ==}+ peerDependencies:+ '@deepseek-ai/cordis': ^4.0.1+ '@deepseek-ai/dsh-invariants': ^0.1.0-rc.8++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-lYY2RbcPW4rGRM5hVJbrXlvLqyBxeJBjBqvt+QTHTU+GtfUVVjTODKa4e3CRwMQoCEpOjoARdQBHbN7HvE72WQ==}+ engines: {node: '>=20'}+ cpu: [arm64]+ os: [linux]++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-OHAzPW2Coe/iYobAJAAA8CeVrBoKV4BnNHsgwvXwOfishxkUVSWSvdyxrZPiwYRXutpIGVrSo9zV3WOQy2euBA==}+ engines: {node: '>=20'}+ cpu: [x64]+ os: [linux]++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-aHGhlQJEutfobKM/4K59SERbT7RmQdD2oMKzD8Bne/Ps7TeT8AweCN+dpdfuxQhMNbFcJMymrgPnID0WYQ30Tw==}+ engines: {node: '>=20'}++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-Qn0FCSwCQnpnj6SB31I6i2sIKgKWnkbJM8O0EU91Gv2UsYVvtZTl6IA0sCwk2e2MZf5S8w5hpq9QkeVvK9qwxg==}+'@electron-internal/[email protected]':resolution: {integrity: sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==}engines: {node: '>=22.12.0'}@@ -1033,6 +1206,81 @@ packages:'@jridgewell/[email protected]':resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}+ '@koromix/[email protected]':+ resolution: {integrity: sha512-8FHyXGCZN7/iQf4f7W5BRysmtdlAFvSx6FpmX4u6wmkZiX/2e9hIRdGLiZYlHGudlcA18UmXB/cMiyhJ7fJkzA==}+ cpu: [arm64]+ os: [darwin]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-uzx/jqFQuSHqgg1zaRidTBTCfj8Y9M0SDTO8HeoI9s9fJhiJ1mbB9TTwJO5c2hiMnuWg2m1byczC8BaIH6cG/w==}+ cpu: [x64]+ os: [darwin]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-PjpTVrsCK5YTtixOw7VsseYXJOyoY6k0qBt+bf0T9h3wyV06y73rALsorFDDEoYpLUBZO7R6EIMs6CpUrEkNTQ==}+ cpu: [arm64]+ os: [freebsd]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-ETYwL820HtFwYoOVzgyvmFmzTHRo9DJtGYTxa5Nb7ajaa5ldCum0jbmUJ3PMECxFTLxD5Q6PYZ8Xbp101bGeSg==}+ cpu: [ia32]+ os: [freebsd]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-BkqxkNXhAAT9toU2stvLwx1iKHPDx7h08NCICyBbjYEXkCAEr84igTkpE5V3XJ9xZZ2gKll7VvdhxorHtHUqZw==}+ cpu: [x64]+ os: [freebsd]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-cM4XPm9ljbCrcPgXjzFYjDNxDUvvuR7TCYaEoo1AKjwZT/vmWhu2xN3pomfbsHh6aVn80SFA3enufQnaETW1rQ==}+ cpu: [arm64]+ os: [linux]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-l1SVTpO10iaQt8slbowJpzK4fbwQZ7ufj9tmCyAcIwWUpyAbPS83mJMctU72If6N9/gCS2wuRqwnYB2uPLLhLg==}+ cpu: [ia32]+ os: [linux]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-KpTJpMSbIdCVFU26ynt0xy4x15h+y6AwPJxj2+iVxJhCzJf4oisCPc0YH2VnutuLV2nVzSrFm7sL/WSOqPgkXw==}+ cpu: [loong64]+ os: [linux]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-YdFNpsywnXiYOYQlDAatf7TJLnspbGXdmfwIZhf82kbKSflYUsq4tI6NmoUOzM89oIWDGpYqd4Hz3xL7tsyXsw==}+ cpu: [riscv64]+ os: [linux]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-Xx5mpr9VcaMCXfvbqIiLIWIL9Iuu6F4r3iMXg7+zZCqYUFZPFwJgiDQBLxctHv2OYgIfAoaaHMW0GC1cJkHfbA==}+ cpu: [x64]+ os: [linux]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-39Np4QTxhTlTT6RRveIeP+TnbzrwuDJ0UMyHxEZ+oGtzmb9GqWhl9T1oyehG6v/O+c4BffafG2NwLkCZ7tDKWw==}+ cpu: [ia32]+ os: [openbsd]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-3EynGn3ycQRqaMWGmUJ0tdtuQdStByqSy/tJ0ZGKWizbMGdFAE73YpgLsyd8BDvwnKWytVG/OLNb5nDHpfd9Dg==}+ cpu: [x64]+ os: [openbsd]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-27FdPPRtT4xbO9bsd2OZa95M5YQ7bcJ8QjCRO57UUMI21REfkDegjqKwqo/CFlugxXlJf5IYtG2rq4BEYIrvxg==}+ cpu: [arm64]+ os: [win32]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-5mVelLKVDup4eoxZOpCzCyMPxoctsg+Qe4J9O5BP4KbBEdqoOEqaNEBBRgNzXcdr2g+GGfmIUo+oVR1NvIdiJw==}+ cpu: [ia32]+ os: [win32]++ '@koromix/[email protected]':+ resolution: {integrity: sha512-lPKjAaHz0aoiZXT/wDVqH+joR5y3lCZj1s9Bk5qx/DGRq+0MK8Ib8VoqiBOrJ69NG5AsJSvn0tQDcSqfRgLmBQ==}+ cpu: [x64]+ os: [win32]+'@larksuiteoapi/[email protected]':resolution: {integrity: sha512-gs4EiupJ6RdYAEJGtuYrCVsB7wSMBwtUDK+ilpmOHD6RTvbtciW6AWciQO9coOQVuBZfh7hvAi25dPfCsny/nA==}@@ -1044,6 +1292,10 @@ packages:resolution: {integrity: sha512-9QOtNffcOF/c1seMCDnjckb3R9WHcG34tky+FHpNKKCW0wc/scYLwMtO+ptyGUfMW0/b/n4qRiALlaFHc9Oj7Q==}engines: {node: '>= 10.0.0'}+ '@microsoft/[email protected]':+ resolution: {integrity: sha512-EWhz2pKkcPluZHAOI1yneV+JK0NO/3hdh7nABBb0x4PjyUWMeSWPTBAjtIu+BhtMYOqlaijSPZMZ0Hs/J4ZL4A==}+ engines: {node: '>=18.0.0'}+'@modelcontextprotocol/[email protected]':resolution: {integrity: sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw==}engines: {node: '>=20'}@@ -1630,6 +1882,9 @@ packages:resolution: {integrity: sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==}engines: {node: '>=16.0.0'}+ '@standard-schema/[email protected]':+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}+'@szmarczak/[email protected]':resolution: {integrity: sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==}engines: {node: '>=10'}@@ -2845,6 +3100,9 @@ packages:resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==}+ resolution: {integrity: sha512-ln60chEb3o7Du1ayjwl6BFiNN1wZK+3cTM2wWGiHLEzCY/FdTIN1ER5VWDwHq7J/j4tSnnrHaH5ABS1EO6+6ag==}+resolution: {integrity: sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==}@@ -3239,6 +3497,9 @@ packages:resolution: {integrity: sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg==}+ resolution: {integrity: sha512-vORSzHXi4Ofl7HemVWpuudLqCPdaQb4LfpRCUpE5HPxhp4JYscl8zZwxh11p26v2wvW24WMwnMfLjhRLixrfxA==}+resolution: {integrity: sha512-J6l92tKHX6w8Jy5nO1Vuc01NoIiRGi/d6qBKVxh+IQ8Cr3b6HbVNfKiF8ZpFKufTwpwxMmce2W3iQZ861ZRyTg==}engines: {node: '>=18'}@@ -4624,6 +4885,102 @@ snapshots:'@babel/helper-string-parser': 7.29.7'@babel/helper-validator-identifier': 7.29.7+ '@deepseek-ai/[email protected]':+ dependencies:+ '@deepseek-ai/cosmokit': 1.8.2+ '@standard-schema/spec': 1.1.0++ '@deepseek-ai/[email protected]': {}++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))':+ dependencies:+ '@deepseek-ai/cordis': 4.0.1+ '@deepseek-ai/dsh-brand': 0.1.0-rc.8(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-invariants': 0.1.0-rc.8(@deepseek-ai/[email protected])++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))':+ dependencies:+ '@deepseek-ai/cordis': 4.0.1+ '@deepseek-ai/dsh-invariants': 0.1.0-rc.8(@deepseek-ai/[email protected])++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cordis': 4.0.1+ '@deepseek-ai/schemastery': 3.18.1++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))':+ dependencies:+ '@deepseek-ai/cordis': 4.0.1+ '@deepseek-ai/dsh-attachment': 0.1.0-rc.8(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-brand': 0.1.0-rc.8(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-invariants': 0.1.0-rc.8(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-timeout': 0.1.0-rc.8(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/schemastery': 3.18.1++ '@deepseek-ai/[email protected](aee23af2fa86328531d8fa647b06b497)':+ dependencies:+ '@deepseek-ai/cordis': 4.0.1+ '@deepseek-ai/dsh-invariants': 0.1.0-rc.8(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-llm': 0.1.0-rc.8(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))+ '@deepseek-ai/dsh-sandbox': 0.1.0-rc.7(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))))(@deepseek-ai/[email protected](fbdb1d988541b64ff002d18c4ded7293))+ '@deepseek-ai/dsh-sandbox-windows-acl': 0.1.0-rc.8(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-session': 0.1.0-rc.8(fbdb1d988541b64ff002d18c4ded7293)+ '@deepseek-ai/node-addon-landlock-run': 0.1.1+ '@deepseek-ai/schemastery': 3.18.1++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))':+ dependencies:+ '@deepseek-ai/cordis': 4.0.1+ '@deepseek-ai/dsh-invariants': 0.1.0-rc.8(@deepseek-ai/[email protected])+ koffi: 3.1.6++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))))(@deepseek-ai/[email protected](fbdb1d988541b64ff002d18c4ded7293))':+ dependencies:+ '@deepseek-ai/cordis': 4.0.1+ '@deepseek-ai/dsh-invariants': 0.1.0-rc.8(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-llm': 0.1.0-rc.8(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))+ '@deepseek-ai/dsh-session': 0.1.0-rc.8(fbdb1d988541b64ff002d18c4ded7293)++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))':+ dependencies:+ '@deepseek-ai/cordis': 4.0.1+ '@deepseek-ai/dsh-invariants': 0.1.0-rc.8(@deepseek-ai/[email protected])++ '@deepseek-ai/[email protected](fbdb1d988541b64ff002d18c4ded7293)':+ dependencies:+ '@deepseek-ai/cordis': 4.0.1+ '@deepseek-ai/dsh-brand': 0.1.0-rc.8(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-invariants': 0.1.0-rc.8(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-llm': 0.1.0-rc.8(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))+ '@deepseek-ai/dsh-scope': 0.1.0-rc.8(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-typert-protocol': 0.1.0-rc.8(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))':+ dependencies:+ '@deepseek-ai/cordis': 4.0.1+ '@deepseek-ai/dsh-invariants': 0.1.0-rc.8(@deepseek-ai/[email protected])++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))':+ dependencies:+ '@deepseek-ai/cordis': 4.0.1+ '@deepseek-ai/dsh-invariants': 0.1.0-rc.8(@deepseek-ai/[email protected])++ '@deepseek-ai/[email protected]':+ optional: true++ '@deepseek-ai/[email protected]':+ optional: true++ '@deepseek-ai/[email protected]':+ optionalDependencies:+ '@deepseek-ai/node-addon-landlock-run-linux-arm64': 0.1.1+ '@deepseek-ai/node-addon-landlock-run-linux-x64': 0.1.1++ '@deepseek-ai/[email protected]':+ dependencies:+ '@deepseek-ai/cosmokit': 1.8.2+ '@standard-schema/spec': 1.1.0+'@electron-internal/[email protected]': {}'@electron/[email protected]':@@ -4834,6 +5191,51 @@ snapshots:'@jridgewell/resolve-uri': 3.1.2'@jridgewell/sourcemap-codec': 1.5.5+ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true++ '@koromix/[email protected]':+ optional: true+dependencies:@@ -4862,6 +5264,11 @@ snapshots:transitivePeerDependencies:- supports-color+ '@microsoft/[email protected]':+ dependencies:+ node-pty: 1.2.0-beta.15+ semver: 7.8.5+'@modelcontextprotocol/[email protected]':dependencies:'@modelcontextprotocol/core': 2.0.0@@ -5538,6 +5945,8 @@ snapshots:'@smithy/util-buffer-from': 3.0.0tslib: 2.8.1+ '@standard-schema/[email protected]': {}+'@szmarczak/[email protected]':dependencies:defer-to-connect: 2.0.1@@ -6973,6 +7382,24 @@ snapshots:dependencies:json-buffer: 3.0.1+ optionalDependencies:+ '@koromix/koffi-darwin-arm64': 3.1.6+ '@koromix/koffi-darwin-x64': 3.1.6+ '@koromix/koffi-freebsd-arm64': 3.1.6+ '@koromix/koffi-freebsd-ia32': 3.1.6+ '@koromix/koffi-freebsd-x64': 3.1.6+ '@koromix/koffi-linux-arm64': 3.1.6+ '@koromix/koffi-linux-ia32': 3.1.6+ '@koromix/koffi-linux-loong64': 3.1.6+ '@koromix/koffi-linux-riscv64': 3.1.6+ '@koromix/koffi-linux-x64': 3.1.6+ '@koromix/koffi-openbsd-ia32': 3.1.6+ '@koromix/koffi-openbsd-x64': 3.1.6+ '@koromix/koffi-win32-arm64': 3.1.6+ '@koromix/koffi-win32-ia32': 3.1.6+ '@koromix/koffi-win32-x64': 3.1.6+@@ -7543,6 +7970,10 @@ snapshots:dependencies:node-addon-api: 7.1.1+ dependencies:+ node-addon-api: 7.1.1+diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex ef7a2db8..5b82af06 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -1,5 +1,9 @@packages:- "packages/*"+ # Plugin packages a deployment installs and lists in plugins.json. 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.- "plugins/*"# Dependency pins. pnpm 11 reads overrides ONLY from here — the package.json# "pnpm.overrides" block it used to honour is silently ignored, which resolved a second@@ -21,9 +25,6 @@ syncInjectedDepsAfterScripts:allowBuilds:"@google/genai": trueesbuild: true- # node-pty compiles its native pty binding (node-gyp) on install; without this the- # terminal server has no pty and every session fails to spawn.- node-pty: trueprotobufjs: true# electron's postinstall downloads the platform runtime binary; without this allow# entry pnpm skips it and `electron .` has nothing to launch.@@ -31,10 +32,33 @@ allowBuilds:# electron-winstaller's script fetches Squirrel.Windows binaries; the desktop package# targets NSIS only, so the script is deliberately not run.electron-winstaller: false+ # koffi (a transitive dependency of the DSH sandbox plugin package, never of the+ # harness itself) ships per-platform prebuilds; its build script is only a fallback+ # compile and the prebuilt binding loads fine without it. Deliberately skipped, like+ # electron-winstaller.+ koffi: false+ # node-pty compiles its native pty binding (node-gyp) on install; without this the+ # terminal server has no pty and every session fails to spawn. The allow entry is+ # per-package-name, so it also builds the second, beta copy @microsoft/mxc-sdk pulls+ # in — harmless, and that copy is never loaded (the MXC plugin only asks the SDK to+ # BUILD a config; it spawns the runner through the harness, never through a pty).+ node-pty: true# pnpm 11 withholds freshly published versions by default (supply-chain gate), which# would resolve agenthub back to the previous release and lose the fix the bump is for.# This package is first-party, so the exemption carries no third-party risk.# Every bump lands inside the age gate, so the entry names the pinned version and moves# with each bump rather than being removed.minimumReleaseAgeExclude:+ - "@deepseek-ai/[email protected]"+ - "@deepseek-ai/[email protected]"+ - "@deepseek-ai/[email protected]"+ - "@deepseek-ai/[email protected]"+ - "@deepseek-ai/[email protected]"+ - "@deepseek-ai/[email protected]"+ - "@deepseek-ai/[email protected]"+ - "@deepseek-ai/[email protected]"+ - "@deepseek-ai/[email protected]"+ - "@deepseek-ai/[email protected]"+ - "@deepseek-ai/[email protected]"+ - "@microsoft/[email protected]"- "@prismshadow/[email protected]"