Skip to content

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

feat(server,web,plugins): settings groups on the Settings dialog's Plugins page (#769)

Myriad-Dreaminb7680e569fba
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index f238c4cd..a559eea2 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -33,7 +33,7 @@ body:
id: version
attributes:
label: Version
- description: Output of `penguin version`, or the version the app shows in System settings.
+ description: Output of `penguin version`, or the version the app shows in Settings.
placeholder: v0.2.7, or v0.2.7-14-g9e8f7d6-dirty for a source build
validations:
required: true
diff --git a/changelog/unreleased/2026-09-07-plugin-configuration.md b/changelog/unreleased/2026-09-07-plugin-configuration.md
new file mode 100644
index 00000000..895e0adc
--- /dev/null
+++ b/changelog/unreleased/2026-09-07-plugin-configuration.md
@@ -0,0 +1,48 @@
+# Plugin settings on the Settings dialog, the sandbox among them, and permissions per Session
+
+- **Date:** 2026-09-07
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `plugins`, `docs`
+- **PR:** [#769](https://github.com/Prism-Shadow/penguin-harness/pull/769)
+
+[中文版](2026-09-07-plugin-configuration.zh.md)
+
+A module, whether a plugin's or the harness's own, can declare the settings it needs, and an admin fills them in on a new **Plugins** page of the Settings dialog. The sandbox and its backends were the first to use it.
+
+## Declaring and reading settings
+
+- **A settings group is a contribution** to `PluginConfigProvider.groups`. It is manifest data, so a plugin's group lands in its generated `ifaces.json` and the page lists it without running the package. The contribution's id is the group's name. Its data is a title and description, with `…Zh` counterparts for the Chinese UI, and `properties`. Each field is a `string`, `secret`, `boolean`, `number`, `enum` (with `options`) or `list` (lines, with an optional `maxItems`), and carries a title, description, default, placeholder and `required`. A `number` may declare `minimum` and `maximum`, and a `string` or `list` a `pattern` (with `patternErrorMessage`) that every value, or every line, must match. A group may also set `parent`, which draws it inside another group's card, and `order`.
+- **Live notices** come from a code contribution to `PluginConfigPage.status`, for a group whose state changes at run time. It may also name enum options this machine cannot honour (`unavailable()`): they are drawn greyed out with the reason, and a save choosing one is refused. Its optional `saved()` runs after a save of the card and holds the PUT's answer until what it set in motion has settled. A malformed declaration drops that group with a warning, and the rest of the page still loads.
+- **A status can offer actions and report work in progress.** It may list `actions()`, drawn as buttons under the group's notices, and `run(id)` runs one through `POST /api/admin/plugin-config/action`. A notice may carry the `progress` tone: the page shows it with a spinner and reads the card again every two seconds until it is gone. When an action's work ends, the card that draws it settles as after a save, so a sandbox backend that could not load before loads without one. The WSL backend's card is the first to use both.
+- **Values are stored server-wide**, one document per group under `plugin-config:<group>` in the server settings, since plugins load once per process. A secret is masked at every API surface. Sending the mask back keeps the stored value, and an empty value clears it.
+- **The declaring module reads its own group.** It `requires` `PluginConfig` from `PluginConfigModule`: `get(name)` returns the stored values merged onto the declared defaults, `watch(name, cb)` fires after every save, and `saved(name)` tells a stored choice from a default.
+- **A data-only contribution does not order the boot.** The module tree creates a slot's owner after its contributors only when the slot takes code. A module can therefore declare a group and require `PluginConfig` in the same class.
+- **API.** `GET /api/admin/plugin-config` lists every declared group in order, with its schema, masked values, `parent` and notices. `PUT /api/admin/plugin-config {name, values}` saves one group. A refused field returns 400 `plugin_config_invalid` naming the field, and an unknown name returns 404 `plugin_config_unknown`.
+
+## The Plugins page
+
+- **The System settings dialog was renamed Settings** (系统设置 became 设置), in the sidebar user menu, the docs and the other unreleased entries. Its server group gained the Plugins page.
+- **The page is admin only**, with one card per group that has no parent and its child groups drawn inside. A secret field starts empty, with the stored mask and a clear checkbox under it. A boolean is a switch, an enum a select, and a list a box of lines.
+- **Each card saves on its own**, one PUT per changed group in it, carrying only the fields that changed, so an untouched default is never stored as a value. A field the server refuses is marked under that field.
+- **The plugin list's header** gained a gear button, for admins, that opens the dialog on this page.
+
+## The sandbox card
+
+- **The sandbox is a settings group**, drawn first on the page: the confinement mode (off, workspace-write or read-only), the network level (no network, local network — only this machine's localhost — or full access; local is greyed out and marked unsupported where no backend implements it, and a save choosing it is refused), whether the system temp directory stays writable (on by default, in either mode), and the absolute paths masked from confined commands. It is stored as `plugin-config:sandbox`. A change applies to the next command spawn without a restart, and survives one.
+- **A backend declares its own group** with `parent: "sandbox"`, beside its `SandboxModule.providers` contribution, and reads it through `PluginConfig` at each spawn. bwrap declares its program and a probe timeout of 1–30 seconds, and Seatbelt its program. A named program is used first; empty, bwrap falls back to the bubblewrap it ships and then a `bwrap` on PATH, and Seatbelt to `/usr/bin/sandbox-exec`. A changed program is probed again. A backend binds a loader (`SandboxProviderSource` now also accepts a function), so one that failed its check at boot, such as a wrong program path, loads again after the Sandbox card is saved, with no restart.
+- **The WSL backend's card** ([sandbox backends](2026-09-17-sandbox-backends.md)). Its group holds whether every Windows drive is shown read-only (off by default: only the Workspace is visible under `/mnt`), the base Linux (Ubuntu or Alpine), the package list, a package mirror for apt or apk, and the distro's name. The card says what the machine has, and offers the next step as a button, each showing its progress: Install WSL (one Windows consent prompt), Initialize sandbox distro, Check confinement, Remove distro.
+- **The card says what enforces the mode.** It lists the backends in use and the isolation each implements. A backend that failed its load-time check ([sandbox backends](2026-09-17-sandbox-backends.md)) is named with its reason. A backend for another platform is named only when no backend serves. When the saved mode needs isolation no usable backend implements, the card warns that every agent command will be refused. With no usable backend at all, it says every mode but off refuses every agent command.
+
+## Permissions per Session
+
+The sandbox policy belongs to a Session now. A Session takes the server's Sandbox settings when it is created and keeps them, so changing those settings no longer reaches an agent that is already running. The composer's approval control becomes a permission button that shows the level at a glance.
+
+- **The permission button** is an icon-only square, like the + button beside it, and the skills button now matches them: no text, no caret. The three sit as one tight cluster. It shows lucide's shield icon for the level, a different icon per level so the level never depends on colour alone. Red `shield-alert` is full access: full filesystem, full network access, every call approved. Amber `shield-half` is partial: some write permission with something still holding it back. Green `shield-check` is read-only: commands cannot write. Grey `shield-off` is off: every tool call is denied. The accessible name and the tooltip spell out the level and all three settings.
+- **A change of level is shown at once and animated.** The picked level shows immediately instead of after the save, and the button no longer dims while it saves, which together read as a flicker. The new icon turns and grows in; a refused save swaps back, with a toast saying why.
+- **The menu has three sections.** Filesystem picks read-only, workspace write, or full access. Network picks no network, local network (localhost only) or full access; local is greyed out with a note where this server cannot enforce it, and picking it is refused (400 `sandbox_unsupported`). Approval picks one of the four approval modes. For an administrator, a plain More… row opens the Settings page's Plugins tab scrolled to the Sandbox card. The draft page shows the same button, starting from the server's Sandbox settings, and the subagent panel edits its root Session's values.
+- **Settings are defaults now.** The Sandbox card on the Settings page says so. A policy change on a Session applies from that Session's next command. A subagent runs under its root Session's policy, a fork and a model switch carry the policy over, and a handoff to another Agent carries it too.
+- **An administrator's sandbox is still a ceiling for everyone else.** A non-admin may tighten a Session's policy but never pick a filesystem mode or network looser than the server's settings; the API answers `403 sandbox_forbidden`.
+- **API.** `SessionInfo.sandbox` reports `{ mode, network, localNetworkSupported }`, `network` being `open`, `local` or `none`. Session creation and `PATCH /api/sessions/:id` accept `sandbox`. `GET /api/projects/:p/chat-defaults` also serves the policy a new Session would start with. On the plugin side, `CreateAgentOptions.confineSpawn` is evaluated with the Session's coordinates, like `controlEnv`, and the sandbox service gains `confinerFor`.
+- **Known gap:** Filesystem and Network confine commands only. The file-writing tools are still governed by the approval mode alone, as before.
+
+A Session created before this change has no policy of its own. It takes the settings in force at its next command and keeps them from then on; until then its permission button shows the current settings.
diff --git a/changelog/unreleased/2026-09-07-plugin-configuration.zh.md b/changelog/unreleased/2026-09-07-plugin-configuration.zh.md
new file mode 100644
index 00000000..0bd8af30
--- /dev/null
+++ b/changelog/unreleased/2026-09-07-plugin-configuration.zh.md
@@ -0,0 +1,48 @@
+# 设置弹窗里的插件设置(沙盒是第一批用户),以及按会话保存的权限
+
+- **Date:** 2026-09-07
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `plugins`, `docs`
+- **PR:** [#769](https://github.com/Prism-Shadow/penguin-harness/pull/769)
+
+[English](2026-09-07-plugin-configuration.md)
+
+模块(无论是插件的还是 harness 自己的)可以声明自己需要的设置,管理员在设置弹窗新增的「**插件**」页里填写。沙盒与它的后端最先用上了这套机制。
+
+## 声明与读取设置
+
+- **设置分组是一条 contribution**,投给 `PluginConfigProvider.groups`。它是清单数据,因此插件的分组会写进生成的 `ifaces.json`,页面不运行包就能列出它。contribution 的 id 即分组名。数据包括标题、说明(带供中文界面使用的 `…Zh` 字段)以及 `properties`。每个字段是 `string`、`secret`、`boolean`、`number`、`enum`(带 `options`)或 `list`(按行,可选 `maxItems`)之一,各带标题、说明、缺省值、占位文字与 `required`。`number` 可声明 `minimum` 与 `maximum`,`string` 与 `list` 可声明 `pattern`(配 `patternErrorMessage`),每个值或每一行都须匹配。分组还可以设置 `parent`,画进另一个分组的卡片里,以及 `order`。
+- **实时提示行**来自投给 `PluginConfigPage.status` 的代码 contribution,用于运行时状态会变化的分组。它还可以列出本机无法支持的枚举选项(`unavailable()`):这些选项置灰显示并附原因,保存时选中即被拒绝。可选的 `saved()` 在卡片保存后执行,PUT 的应答会等它引发的工作完成后才返回。声明写错时只丢弃那个分组并告警,页面其余部分照常加载。
+- **提示行可以提供操作,并报告进行中的工作。** 它可列出 `actions()`,画成分组提示行下方的按钮,`run(id)` 经 `POST /api/admin/plugin-config/action` 执行其中一个。提示行可带 `progress` 语气:页面以旋转图标显示它,并每两秒重新读取该卡片,直到它消失。操作启动的工作结束后,绘制它的卡片会像保存后一样完成收尾,于是此前无法加载的沙盒后端无需保存即可加载。WSL 后端的卡片最先用上这两项。
+- **值在服务端全局存储**,每个分组一份文档,存在服务端设置的 `plugin-config:<分组名>` 下,因为插件按进程只加载一次。密钥在所有 API 返回中都以掩码显示。原样送回掩码即保留存储值,送空值即清除。
+- **由声明分组的模块自己读取。** 模块 `requires` 来自 `PluginConfigModule` 的 `PluginConfig`:`get(name)` 返回合并到声明缺省值上的存储值,`watch(name, cb)` 在每次保存后触发,`saved(name)` 区分已保存的选择与缺省值。
+- **纯数据的 contribution 不决定启动顺序。** 模块树只在槽接收代码时,才让槽的所有者晚于投稿者创建。因此同一个类可以既声明分组,又 requires `PluginConfig`。
+- **API。** `GET /api/admin/plugin-config` 按顺序列出每个已声明的分组,含 schema、掩码后的值、`parent` 与提示行。`PUT /api/admin/plugin-config {name, values}` 保存一个分组。字段被拒时返回 400 `plugin_config_invalid` 并点名该字段,名字不存在时返回 404 `plugin_config_unknown`。
+
+## 「插件」页
+
+- **「系统设置」弹窗更名为「设置」**(英文界面由 System settings 改为 Settings),侧边栏用户菜单、文档与其他未发布条目一并更新。服务器分组新增「插件」页。
+- **该页仅管理员可见**,每个没有 parent 的分组一张卡片,子分组画在卡片内。密钥字段初始为空,下方显示存储值的掩码与清除勾选。布尔值是开关,枚举是下拉框,列表是按行填写的文本框。
+- **每张卡片各自保存**,卡片内每个改动过的分组各发一次 PUT,只带改动过的字段,未动过的缺省值不会被存成值。服务端拒绝的字段在该字段下标出。
+- **插件列表的页头**新增齿轮按钮(仅管理员),直接打开设置弹窗的这一页。
+
+## 沙盒卡片
+
+- **沙盒是一个设置分组**,排在该页最前:封禁模式(关闭、仅工作区可写或只读)、网络档位(无网络、本地网络——只允许本机 localhost——或完全访问;没有后端实现本地网络时该项置灰并标注不支持,保存时选中即被拒绝)、系统临时目录是否可写(默认开启,两种模式都生效),以及对被封禁命令屏蔽的绝对路径。它存为 `plugin-config:sandbox`。改动对下一次命令启动生效,无需重启,重启后仍保留。
+- **后端声明自己的分组**,在 `SandboxModule.providers` contribution 旁设 `parent: "sandbox"`,并在每次启动命令时经 `PluginConfig` 读取。bwrap 声明了程序路径与 1–30 秒的探测超时,Seatbelt 声明了程序路径。填了程序路径时优先使用它;留空时,bwrap 依次回退到插件自带的 bubblewrap 与 PATH 上的 `bwrap`,Seatbelt 回退到 `/usr/bin/sandbox-exec`。换了程序会重新探测。后端绑定的是加载函数(`SandboxProviderSource` 现在也接受函数),因此启动时未通过自检的后端(例如程序路径写错)在沙盒卡片保存后会重新加载,无需重启。
+- **WSL 后端的卡片**([沙盒后端](2026-09-17-sandbox-backends.zh.md))。它的分组包括:是否以只读方式显示所有 Windows 磁盘(缺省关闭:`/mnt` 下只能看到工作区)、基础 Linux(Ubuntu 或 Alpine)、软件包列表、apt 或 apk 的软件包镜像,以及发行版名称。卡片说明本机现状,并以按钮提供下一步,每一步都显示进度:安装 WSL(一次 Windows 授权)、初始化沙盒发行版、检查隔离效果、移除发行版。
+- **卡片说明由谁实施封禁。** 卡片列出正在使用的后端及各自实现的隔离维度。未通过加载时自检([沙盒后端](2026-09-17-sandbox-backends.zh.md))的后端点名并给出原因。面向其他平台的后端只在没有任何后端可用时才点名。当保存的模式需要的隔离没有可用后端实现时,卡片警告 Agent 的每条命令都会被拒绝。一个可用后端都没有时,卡片说明除关闭外的任何模式都会拒绝 Agent 的每条命令。
+
+## 按会话保存的权限
+
+沙盒策略现在归属于会话。会话在创建时取服务端的沙盒设置并一直保留,因此修改这些设置不再影响已经在运行的 Agent。输入区的审批控件改为权限按钮,一眼即可看出权限等级。
+
+- **权限按钮**是纯图标的方形按钮,与旁边的加号按钮一致,技能按钮也随之统一:不显示文字、不带下拉箭头。三个按钮紧凑地排在一起。按钮使用 lucide 的盾牌图标表示等级,每个等级一个不同图标,不单靠颜色区分。红色 `shield-alert` 为完全访问:文件系统完全开放、网络完全访问、所有调用自动批准。琥珀色 `shield-half` 为部分权限:存在写权限,但仍有某项在约束。绿色 `shield-check` 为只读:命令无法写入。灰色 `shield-off` 为关闭:所有工具调用都被拒绝。无障碍名称与 tooltip 写明等级及三项取值。
+- **等级变化立即显示并带动画。** 选中的等级立即显示,不再等保存返回;保存期间按钮也不再变暗,二者合起来曾表现为闪烁。新图标旋转放大进入;保存被拒时切换回原等级,并以 toast 说明原因。
+- **菜单分三节。** 文件系统可选只读、仅工作区可写、完全访问。网络可选无网络、本地网络(仅 localhost)或完全访问;本服务端无法实施本地网络时该项置灰并附说明,选中即被拒绝(400 `sandbox_unsupported`)。审批可选四种审批模式之一。管理员另有一行不带图标的「更多…」,打开设置页的插件标签并滚动到沙盒卡片。草稿页使用同一按钮,初值取服务端沙盒设置;子智能体面板修改的是根会话的取值。
+- **设置变为缺省值。** 设置页的沙盒卡片已如此说明。修改某个会话的策略,从该会话的下一条命令起生效。子智能体沿用根会话的策略;分叉、切换模型与交接给其他 Agent 时都会带上原策略。
+- **管理员的沙盒对其他人仍是上限。** 非管理员可以收紧会话策略,但不能选择比服务端设置更宽的文件系统模式或网络;API 返回 `403 sandbox_forbidden`。
+- **API。** `SessionInfo.sandbox` 返回 `{ mode, network, localNetworkSupported }`,`network` 为 `open`、`local` 或 `none`。创建会话与 `PATCH /api/sessions/:id` 接受 `sandbox`。`GET /api/projects/:p/chat-defaults` 同时返回新会话的初始策略。插件侧,`CreateAgentOptions.confineSpawn` 与 `controlEnv` 一样按会话坐标求值,沙盒服务新增 `confinerFor`。
+- **已知缺口:** 文件系统与网络只约束命令执行,文件写入工具仍与此前一样只由审批模式把关。
+
+本次改动之前创建的会话没有自己的策略:它在下一条命令执行时取当时生效的设置并从此保留;在那之前,权限按钮显示当前设置。
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 0d3d06fb..822ca53d 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -148,9 +148,10 @@ export interface CreateAgentOptions {
* 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.
+ * Sessions. Evaluated with the Session's coordinates, like `controlEnv`, so a host can
+ * keep a policy per Session. Absent = commands spawn unconfined.
*/
- confineSpawn?: () => SpawnConfiner | null;
+ confineSpawn?: (ctx: ControlEnvContext) => SpawnConfiner | null;
/**
* What a host adds to every Session this Agent assembles — see {@link AgentAssembly}.
* Host policy like
@@ -396,8 +397,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,
+ /** See {@link CreateAgentOptions.confineSpawn}; evaluated per Session with that Session's coordinates. */
+ private readonly confineSpawn?: (ctx: ControlEnvContext) => SpawnConfiner | null,
/** See {@link CreateAgentOptions.assembly}; read at every Session creation. */
private readonly assembly?: AgentAssembly,
) {}
@@ -1202,7 +1203,18 @@ export class Agent {
}
: {}),
...(this.pathPrepend ? { pathPrepend: this.pathPrepend } : {}),
- ...(this.confineSpawn ? { confineSpawn: this.confineSpawn } : {}),
+ // Bound to THIS Session's coordinates like controlEnv: the host may confine each
+ // Session under its own policy, and the getter is still re-read at every spawn.
+ ...(this.confineSpawn
+ ? {
+ confineSpawn: () =>
+ this.confineSpawn!({
+ projectId: this.state.projectId,
+ agentId: this.state.agentId,
+ sessionId,
+ }),
+ }
+ : {}),
});
// The tool_call_id uniqueness registry is shared by every context's LLM object: its
diff --git a/packages/core/src/kernel/module.ts b/packages/core/src/kernel/module.ts
index 049e919a..95031e4d 100644
--- a/packages/core/src/kernel/module.ts
+++ b/packages/core/src/kernel/module.ts
@@ -4,8 +4,10 @@
* A module is a manifest ({@link Manifest}) plus one `create`. Boot runs {@link checkTree}
* over the manifests first — nothing is created while a problem stands — then creates
* modules in dependency order: a module boots after everything it `requires` and after
- * every module that CONTRIBUTES to one of its slots (the code half of a contribution is
- * the contributor's `bind[id]`, which exists only once the contributor is created).
+ * every module that contributes to one of its slots WITH A CODE HALF (that half is the
+ * contributor's `bind[id]`, which exists only once the contributor is created). A data-only
+ * contribution is manifest data, there before anything is created, so it orders nothing — a
+ * module may declare data on a slot and require the slot's owner.
*
* The tree shape is scope, not order: siblings are created in whatever order their
* edges allow, and a cycle is a boot error naming the modules in it.
@@ -481,7 +483,7 @@ export async function bootModules(root: ModuleDef, opts: BootModulesOptions): Pr
};
// Edges: a module comes after what it requires (resolved through exports to the node
- // that provides it), after what contributes to it, and after its children.
+ // that provides it), after what contributes code to it, and after its children.
const after = new Map<string, Set<string>>();
for (const n of nodes) after.set(n.def.manifest.name, new Set());
for (const n of nodes) {
@@ -490,8 +492,12 @@ export async function bootModules(root: ModuleDef, opts: BootModulesOptions): Pr
if (byName.has(w.from)) after.get(name)!.add(exportTarget(w.from, w.alias).module);
}
for (const slotKey of Object.keys(n.def.manifest.contributes)) {
- const target = splitSlotKey(slotKey)!.module;
- if (byName.has(target)) after.get(target)!.add(name);
+ const split = splitSlotKey(slotKey)!;
+ if (!byName.has(split.module)) continue;
+ const slotDecl = Object.values(provides[split.module] ?? {})
+ .map((d) => d.slots[split.slot])
+ .find((s) => s !== undefined);
+ if (slotDecl?.code !== undefined) after.get(split.module)!.add(name);
}
for (const child of n.childrenDefs) after.get(name)!.add(child.manifest.name);
}
diff --git a/packages/core/src/plugin/sandbox.ts b/packages/core/src/plugin/sandbox.ts
index 54c451d7..81ff802c 100644
--- a/packages/core/src/plugin/sandbox.ts
+++ b/packages/core/src/plugin/sandbox.ts
@@ -134,7 +134,14 @@ export interface SandboxProvider {
}
/** A provider, or a promise of one: backends load asynchronously (dynamic imports, probes). */
-export type SandboxProviderSource = SandboxProvider | PromiseLike<SandboxProvider | null> | null;
+export type SandboxProviderLoad = SandboxProvider | PromiseLike<SandboxProvider | null> | null;
+
+/**
+ * What a backend binds: a load, or a loader that produces one. A loader is called at boot and
+ * again after its failure whenever the sandbox's settings are saved — so a backend whose check
+ * failed on a setting (a wrong program path) recovers once that setting is fixed, no restart.
+ */
+export type SandboxProviderSource = SandboxProviderLoad | (() => SandboxProviderLoad);
/**
* The active confinement settings, resolved per spawn. A type literal with plain
@@ -145,4 +152,6 @@ export type SandboxSettings = {
mode: SandboxMode;
network?: SandboxNetwork;
maskPaths?: string[];
+ /** Grant the system temp directory writable (SandboxPolicy.writableTemp). Absent = granted. */
+ writableTemp?: boolean;
};
diff --git a/packages/core/test/kernel-modules.test.ts b/packages/core/test/kernel-modules.test.ts
index 642c70cd..7d6d0950 100644
--- a/packages/core/test/kernel-modules.test.ts
+++ b/packages/core/test/kernel-modules.test.ts
@@ -336,6 +336,45 @@ describe("bootModules", () => {
booted.dispose();
});
+ it("a data-only contribution orders nothing: its contributor may require the slot's owner", async () => {
+ const Registry: IfaceDecl = {
+ name: "Registry",
+ methods: { names: { params: [], returns: { data: "string[]" } } },
+ slots: { entries: { data: { title: "string" } } },
+ };
+ const t: IfaceTable = { ...table, "registry#Registry": Registry, "user#Registry": Registry };
+ const registry = manifest({ name: "registry", provides: { registry: "Registry" } });
+ const user = manifest({
+ name: "user",
+ requires: { registry: { iface: "Registry", from: "registry" } },
+ contributes: { "registry.entries": [{ id: "user.entry", title: "User" }] },
+ });
+ const order: string[] = [];
+ const root = defineModule(manifest({ name: "platform", children: ["registry", "user"] }), {
+ create: () => ({ api: {} }),
+ children: [
+ defineModule(user, {
+ create(ctx) {
+ order.push("user");
+ expect((ctx.use.registry as { names(): string[] }).names()).toEqual(["User"]);
+ return { api: {} };
+ },
+ }),
+ defineModule(registry, {
+ create(ctx) {
+ order.push("registry");
+ const names = (ctx.contributions.entries ?? []).map((c) => c.data.title as string);
+ expect(ctx.contributions.entries?.[0]).not.toHaveProperty("code");
+ return { api: { registry: { names: () => names } } };
+ },
+ }),
+ ],
+ });
+ const booted = await bootModules(root, { ifaces: t, resources });
+ expect(order).toEqual(["registry", "user"]);
+ booted.dispose();
+ });
+
it("refuses a declared-but-unbound contribution", async () => {
const root = defineModule(platform, {
create: () => ({ api: {} }),
diff --git a/packages/docs/content/chat.en.md b/packages/docs/content/chat.en.md
index a9bee60e..00390981 100644
--- a/packages/docs/content/chat.en.md
+++ b/packages/docs/content/chat.en.md
@@ -67,7 +67,7 @@ Limits apply at two moments:
- When you pick or drop a file: a file over the per-file size (100MB by default) or an image over 20MB is refused before anything is read, and the message names the limit in force.
- When you send: a message carries at most 20 files and 120MB in total by default. Over that, the send fails with "Too many files attached to one message." or "The request is too large."
-An admin can change both sizes under [System settings › Upload limits](/settings#upload-limits). The 20MB cap for images placed inline does not follow them: an inline image enters the conversation and the Trace, where its size is paid again on every history page and every Session resume.
+An admin can change both sizes under [Settings › Upload limits](/settings#upload-limits). The 20MB cap for images placed inline does not follow them: an inline image enters the conversation and the Trace, where its size is paid again on every history page and every Session resume.
On send, attached files are written into the Session's scratchpad, which is deleted with the Session. The conversation shows an "Attached files" notice; the file contents never enter the conversation, and the model opens each file by path with its file tools. On a model without image input, images are saved to the scratchpad the same way and passed as file paths, and a hint above the composer says so.
@@ -197,7 +197,7 @@ The fork is a new Session with the same agent, model, Workspace and approval mod
- **Text** renders as it streams, and thinking blocks can be collapsed.
- **Steps**, meaning thinking and tool calls, are grouped under a **Running** or **Done** header with the step count and time. The group is open while it runs, closes when it is done, and opens again when a call in it needs approval.
-- **Tool cards** expand to show arguments and output, with a live timer while running. A card is headed by the description the model wrote or a shortened file path. Built-in tools go by short names (`read_file` reads as "read", with the full name in the tooltip); turn this off with **Tool short names** under [System settings › Appearance](/settings#appearance). Other tools, MCP tools included, always use their own names.
+- **Tool cards** expand to show arguments and output, with a live timer while running. A card is headed by the description the model wrote or a shortened file path. Built-in tools go by short names (`read_file` reads as "read", with the full name in the tooltip); turn this off with **Tool short names** under [Settings › Appearance](/settings#appearance). Other tools, MCP tools included, always use their own names.
- **Compaction** leaves a row whose title is its status: **Compacting** while it runs and **Compacted** when it ends (**Clearing** and **Cleared** for a context clear), with its time. While it runs, the row opens a thinking section once the request's thinking arrives, and a result section when the summary starts; both are collapsed by default, each with its own time. The row folds back to one line when the compaction ends. A failed compaction keeps the title **Compaction** (or **Clear**) over a one-line reason.
- **MCP connect**, the first connection to the agent's MCP servers, leaves a row with the number of tools found and the names of unavailable servers. It expands into one group per server, with its status, tool count and connect time, and each group opens to its tool list or the error.
- **Subagents** each leave a row with their avatar, name, short Session id, a spinner while running, and an amber dot while one of their tool calls awaits approval. Selecting the row opens the **Agents panel**: a call graph of that Task at the top, with each node's elapsed time, and the selected subagent's live conversation below. Nested tool cards and approvals work as in the main chat, the subagent has a composer of its own, and **Jump to this session** opens it as a full conversation. When the current Task starts a subagent, the Agents panel opens by itself, once per Task.
@@ -239,7 +239,7 @@ Good to know:
- Near the top or bottom of the conversation, the fan shortens to what fits.
- Drag the button up or down along the edge; a short press is still a click. It springs back to the edge, never rests over the toolbar or the composer, and keeps its position in this browser for every conversation.
- While the right sidebar is closed and a subagent awaits approval, the button and its Agents panel entry show the amber dot.
-- **Hide launcher** puts the button away for good, and a message says where to turn it back on: the **Shortcuts launcher** switch under [System settings › Appearance](/settings#appearance).
+- **Hide launcher** puts the button away for good, and a message says where to turn it back on: the **Shortcuts launcher** switch under [Settings › Appearance](/settings#appearance).
### Use a terminal
diff --git a/packages/docs/content/chat.zh.md b/packages/docs/content/chat.zh.md
index 1fff501a..6560a132 100644
--- a/packages/docs/content/chat.zh.md
+++ b/packages/docs/content/chat.zh.md
@@ -67,7 +67,7 @@ Session 创建后,模型和 Workspace 就锁定了。之后想换模型,见[
- 选择或拖入文件时:超过单个文件大小上限(默认 100MB)的文件,或超过 20MB 的图片,会在读取之前被拒绝,提示中写明当前生效的上限。
- 发送时:一条消息默认最多 20 个文件、合计 120MB,超出时发送失败,提示「一条消息附加的文件过多。」或「请求体过大。」
-管理员可以在[系统设置 › 上传限制](/settings#上传限制)中修改这两个大小。嵌入对话的图片另有 20MB 上限,不随它们变化:这类图片会进入对话和 Trace,此后每次翻阅历史、每次恢复 Session,都要再付出一次它的体积。
+管理员可以在[设置 › 上传限制](/settings#上传限制)中修改这两个大小。嵌入对话的图片另有 20MB 上限,不随它们变化:这类图片会进入对话和 Trace,此后每次翻阅历史、每次恢复 Session,都要再付出一次它的体积。
发送时,附件写入 Session 的 scratchpad,随 Session 一起删除。对话中显示一条「附加文件」提示;文件内容本身不进入对话,模型用文件工具按路径逐个读取。如果模型不支持图片输入,图片也会这样存进 scratchpad、以文件路径传给模型,输入框上方会给出提示。
@@ -197,7 +197,7 @@ Session 的模型是锁定的,点击模型名称会提示「输入 /model 切
- **文字**随生成逐步显示,思考块可以折叠。
- **步骤**,即思考和工具调用,归在一个标着**运行中**或**运行完毕**的分组下,显示步数和用时。分组运行时展开、结束后收起,组内有调用需要审批时会再次展开。
-- **工具卡片**可以展开查看参数和输出,运行时有实时计时。卡片标题是模型写的说明,或缩短后的文件路径。内置工具用短名显示(`read_file` 显示为「读取」,完整名称在悬停提示里),可以在[系统设置 › 外观](/settings#外观)中关闭**工具短名**。其他工具(含 MCP 工具)始终显示原名。
+- **工具卡片**可以展开查看参数和输出,运行时有实时计时。卡片标题是模型写的说明,或缩短后的文件路径。内置工具用短名显示(`read_file` 显示为「读取」,完整名称在悬停提示里),可以在[设置 › 外观](/settings#外观)中关闭**工具短名**。其他工具(含 MCP 工具)始终显示原名。
- **压缩**会留下一行,标题就是状态:进行中为**压缩中**,结束后为**压缩完毕**(清空上下文时为**清空中**、**清空完毕**),并带用时。进行期间,这一行在请求的思考内容到达后出现思考部分,摘要开始生成时出现结果部分,两部分默认折叠,各有自己的用时。压缩结束后这一行收回成一行。压缩失败时,标题保持为**压缩**(或**清空**),下面一行写明原因。
- **MCP 连接**,即首次连接 MCP 服务器,会留下一行,显示发现的工具数,并列出不可用的服务器。展开后每个服务器一组,显示状态、工具数和连接用时;再展开可以看到工具列表或失败原因。
- **子 Agent** 各自留下一行,显示头像、名称、短 Session id,运行中带转圈动画,有工具调用待审批时带琥珀色圆点。点击这一行会打开**智能体面板**:上方是该 Task 的调用图,每个节点显示运行时长;下方是所选子 Agent 的实时对话。嵌套的工具卡片和审批与主对话完全一致,子 Agent 还有自己的输入框,**跳转到该会话**可以把它作为完整对话打开。当前 Task 派生子 Agent 时,智能体面板会自动打开,每个 Task 只自动打开一次。
@@ -239,7 +239,7 @@ Session 的模型是锁定的,点击模型名称会提示「输入 /model 切
- 靠近对话区顶部或底部时,这圈入口会缩短,只显示放得下的部分。
- 按钮可以沿右缘上下拖动,短按仍是点击。松手后按钮贴回边缘,不会停在工具栏或输入框上;它的位置记在当前浏览器里,所有对话共用。
- 右侧栏关闭时,如果有子 Agent 在等待审批,按钮和其中的智能体面板入口上都会出现琥珀色圆点。
-- **隐藏悬浮球**会让按钮不再出现,同时提示在哪里重新打开:[系统设置 › 外观](/settings#外观)中的**快捷方式悬浮球**开关。
+- **隐藏悬浮球**会让按钮不再出现,同时提示在哪里重新打开:[设置 › 外观](/settings#外观)中的**快捷方式悬浮球**开关。
### 使用终端
diff --git a/packages/docs/content/company-mode.en.md b/packages/docs/content/company-mode.en.md
index 2cd3d2e7..484177ec 100644
--- a/packages/docs/content/company-mode.en.md
+++ b/packages/docs/content/company-mode.en.md
@@ -21,10 +21,10 @@ Development mode is one person talking to one agent. Company mode, the Web App's
- You need an admin account. Company mode is off by default on every server, and only admins see its server switch.
-1. Open **System settings** › Server › **Company mode**, and turn on **Enable company mode**. The change is saved at once.
+1. Open **Settings** › Server › **Company mode**, and turn on **Enable company mode**. The change is saved at once.
2. At the top left of the sidebar, the mode switch reads **Development** | **Company**, with a **Beta** tag. Select **Company**.
-To go back, select **Development**. Every user sees the mode switch while the server switch is on. To hide it for yourself only, turn off **Company mode** under **System settings** › Personal › **General**; organizations keep running. See [Switches and lifecycle](#switches-and-lifecycle).
+To go back, select **Development**. Every user sees the mode switch while the server switch is on. To hide it for yourself only, turn off **Company mode** under **Settings** › Personal › **General**; organizations keep running. See [Switches and lifecycle](#switches-and-lifecycle).
## Create an organization
@@ -276,8 +276,8 @@ The organization settings include **Working language**, **Approval mode** and **
| Switch | Where | Effect |
| --- | --- | --- |
-| Server | **System settings** › Server › **Company mode** (admins only; off by default) | Off stops the organization scheduler: nothing fires, and nothing is backfilled when it is turned back on. Every organization route answers 404, and the mode switch disappears for everyone. |
-| Personal | **System settings** › Personal › **General** › **Company mode** (shown only while the server switch is on) | Hides the mode switch for you only. Organizations keep running. |
+| Server | **Settings** › Server › **Company mode** (admins only; off by default) | Off stops the organization scheduler: nothing fires, and nothing is backfilled when it is turned back on. Every organization route answers 404, and the mode switch disappears for everyone. |
+| Personal | **Settings** › Personal › **General** › **Company mode** (shown only while the server switch is on) | Hides the mode switch for you only. Organizations keep running. |
| Organization | **Pause organization** in the organization settings | Stops all of the organization's automatic triggers. People can still open any desk and talk to it. |
**There is no delete.** An organization is either running or paused, and that is its whole lifecycle. Deleting one would throw away the only way back to its conversations, employees, desks and tickets, while a paused organization costs nothing to keep: it fires nothing, and every desk is still there to talk to.
diff --git a/packages/docs/content/company-mode.zh.md b/packages/docs/content/company-mode.zh.md
index 3173cd6e..983e5356 100644
--- a/packages/docs/content/company-mode.zh.md
+++ b/packages/docs/content/company-mode.zh.md
@@ -21,10 +21,10 @@ description: 把一句话的使命变成一个由 Agent 组成的组织:它靠
- 需要管理员账号。公司模式在每台服务器上都默认关闭,只有管理员能看到服务器开关。
-1. 打开**系统设置** › 服务器 › **公司模式**,开启**启用公司模式**。改动会立即保存。
+1. 打开**设置** › 服务器 › **公司模式**,开启**启用公司模式**。改动会立即保存。
2. 侧边栏左上角的模式切换显示为**开发** | **公司**,并带有**内测版**标记。选择**公司**。
-要切回去,选择**开发**。服务器开关开着时,所有用户都能看到模式切换。只想对自己隐藏,就在**系统设置** › 个人 › **通用**里关闭**公司模式**,组织照常运转。见[开关与生命周期](#开关与生命周期)。
+要切回去,选择**开发**。服务器开关开着时,所有用户都能看到模式切换。只想对自己隐藏,就在**设置** › 个人 › **通用**里关闭**公司模式**,组织照常运转。见[开关与生命周期](#开关与生命周期)。
## 创建组织
@@ -276,8 +276,8 @@ penguin org finance # spend per employee (cumulati
| 开关 | 位置 | 效果 |
| --- | --- | --- |
-| 服务器 | **系统设置** › 服务器 › **公司模式**(仅管理员可见,默认关闭) | 关闭即停止组织调度器:不再触发任何东西,重新打开时也不补发。所有组织路由返回 404,模式切换对所有人消失。 |
-| 个人 | **系统设置** › 个人 › **通用** › **公司模式**(仅在服务器开关打开时显示) | 只对你自己隐藏模式切换,组织照常运转。 |
+| 服务器 | **设置** › 服务器 › **公司模式**(仅管理员可见,默认关闭) | 关闭即停止组织调度器:不再触发任何东西,重新打开时也不补发。所有组织路由返回 404,模式切换对所有人消失。 |
+| 个人 | **设置** › 个人 › **通用** › **公司模式**(仅在服务器开关打开时显示) | 只对你自己隐藏模式切换,组织照常运转。 |
| 组织 | 组织设置里的**暂停组织** | 停止这个组织的一切自动触发。真人仍可打开任意工位直接对话。 |
**没有删除。** 组织只有运行和暂停两种状态,这就是它的全部生命周期。删除会丢掉回到它的对话、员工、工位和工单的唯一途径;而暂停的组织留着不花任何成本:它不触发任何东西,每个工位也都还在,随时可以对话。
diff --git a/packages/docs/content/concepts.en.md b/packages/docs/content/concepts.en.md
index 600d7660..f7431041 100644
--- a/packages/docs/content/concepts.en.md
+++ b/packages/docs/content/concepts.en.md
@@ -198,7 +198,7 @@ See [Cost Center](/usage).
## Company mode
-Company mode is a beta work mode of the Web App in which a Project's agents run as a company. It is off until an admin turns it on in **System settings**.
+Company mode is a beta work mode of the Web App in which a Project's agents run as a company. It is off until an admin turns it on in **Settings**.
### Organization
diff --git a/packages/docs/content/concepts.zh.md b/packages/docs/content/concepts.zh.md
index 4b1ba8a9..0f6ebd03 100644
--- a/packages/docs/content/concepts.zh.md
+++ b/packages/docs/content/concepts.zh.md
@@ -198,7 +198,7 @@ Token 是模型计量文本的单位。用量和成本都按 Token 计算,成
## 公司模式
-公司模式是 Web App 的一种 Beta 工作模式,让一个 Project 的 Agent 像一家公司那样自行运转。它默认关闭,需要管理员在**系统设置**里开启。
+公司模式是 Web App 的一种 Beta 工作模式,让一个 Project 的 Agent 像一家公司那样自行运转。它默认关闭,需要管理员在**设置**里开启。
### 组织
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index d4c33799..7439849f 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -42,7 +42,7 @@ Notes:
Commands an agent runs with `exec_command` inherit the host environment, with these changes:
- **Removed:** `PORT`, `HOST`, `FORCE_COLOR`, `CLICOLOR_FORCE` and every `PENGUIN_*` variable. They configure PenguinHarness itself, not the command. Without this, a dev server started by `exec_command` would read `PORT` and try to bind the port meant for PenguinHarness instead of choosing its own.
-- **Proxy:** in Sessions the server runs, the **Agent environment uses the proxy** switch in [System settings](/settings#proxy-options) decides the proxy variables. Off removes `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY`; on injects the configured proxy address, or passes the host's variables through when no address is set.
+- **Proxy:** in Sessions the server runs, the **Agent environment uses the proxy** switch in [Settings](/settings#proxy-options) decides the proxy variables. Off removes `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY`; on injects the configured proxy address, or passes the host's variables through when no address is set.
- **Vault:** the agent's [Vault](#vault) is applied on top, so setting `PORT` or a `PENGUIN_*` variable there does reach commands.
- **Control variables:** a server-driven Session then injects `PENGUIN_API_URL`, `PENGUIN_API_TOKEN`, `PENGUIN_PROJECT_ID`, `PENGUIN_AGENT_ID` and `PENGUIN_SESSION_ID` (plus `PENGUIN_ORG_ID` in company mode), so the agent's own `penguin` calls reach the server that runs it. These override Vault entries of the same name. See [CLI Reference](/cli).
- **Forced:** `GIT_EDITOR`, `GIT_TERMINAL_PROMPT`, `TERM`, `NO_COLOR`, `PAGER` and `GIT_PAGER` always get fixed values, so a command cannot hang waiting on an editor, a credential prompt or a pager. Nothing overrides them, the Vault included.
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index aca43b48..b417e8db 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -42,7 +42,7 @@ CLI 和服务器启动时会从工作目录加载 `.env` 文件。
Agent 用 `exec_command` 运行的命令继承宿主环境,但有以下改动:
- **移除:** `PORT`、`HOST`、`FORCE_COLOR`、`CLICOLOR_FORCE` 以及所有 `PENGUIN_*` 变量。这些变量配置的是 PenguinHarness 本身,不是命令。如果不移除,`exec_command` 启动的开发服务器会读到 `PORT`,试图绑定本应留给 PenguinHarness 的端口,而不是自己另选。
-- **代理:** 在服务器运行的 Session 中,由[系统设置](/settings#代理选项)里的 **Agent 环境使用代理** 开关决定代理变量。关闭时移除 `HTTP_PROXY`、`HTTPS_PROXY` 和 `ALL_PROXY`;开启时注入已配置的代理地址,没有配置地址时透传宿主的变量。
+- **代理:** 在服务器运行的 Session 中,由[设置](/settings#代理选项)里的 **Agent 环境使用代理** 开关决定代理变量。关闭时移除 `HTTP_PROXY`、`HTTPS_PROXY` 和 `ALL_PROXY`;开启时注入已配置的代理地址,没有配置地址时透传宿主的变量。
- **密钥保险柜:** 之后再叠加 Agent 的[密钥保险柜](#vault),所以在保险柜里设置的 `PORT` 或 `PENGUIN_*` 变量确实能传给命令。
- **控制变量:** 由服务器驱动的 Session 随后注入 `PENGUIN_API_URL`、`PENGUIN_API_TOKEN`、`PENGUIN_PROJECT_ID`、`PENGUIN_AGENT_ID` 和 `PENGUIN_SESSION_ID`(公司模式下还有 `PENGUIN_ORG_ID`),Agent 自己发起的 `penguin` 调用因此能到达运行它的服务器。这些变量会覆盖密钥保险柜里的同名条目。见 [CLI 参考](/cli)。
- **强制:** `GIT_EDITOR`、`GIT_TERMINAL_PROMPT`、`TERM`、`NO_COLOR`、`PAGER` 和 `GIT_PAGER` 始终取固定值,命令不会因为等待编辑器、凭证提示或分页器而卡住。任何来源都无法覆盖它们,密钥保险柜也不例外。
diff --git a/packages/docs/content/quickstart-desktop.en.md b/packages/docs/content/quickstart-desktop.en.md
index 146e929d..8dadf689 100644
--- a/packages/docs/content/quickstart-desktop.en.md
+++ b/packages/docs/content/quickstart-desktop.en.md
@@ -32,7 +32,7 @@ The macOS builds are Developer ID signed and notarized, and the Windows installe
> chmod +x penguin-desktop-linux-x86_64.AppImage
> ```
-The app opens signed in. The window signs itself in, so there is no password to type or to change: in the app's window, **System settings** has no **Account** page with **Change password**.
+The app opens signed in. The window signs itself in, so there is no password to type or to change: in the app's window, **Settings** has no **Account** page with **Change password**.
## Configure a model
diff --git a/packages/docs/content/quickstart-desktop.zh.md b/packages/docs/content/quickstart-desktop.zh.md
index e255d1cc..e5235cbc 100644
--- a/packages/docs/content/quickstart-desktop.zh.md
+++ b/packages/docs/content/quickstart-desktop.zh.md
@@ -32,7 +32,7 @@ macOS 安装包已经过 Developer ID 签名和公证,Windows 安装程序已
> chmod +x penguin-desktop-linux-x86_64.AppImage
> ```
-应用打开即已登录。窗口自己完成登录,既没有要输入的密码,也没有可修改的密码,所以应用窗口里的**系统设置**没有带**修改密码**的**账户**页面。
+应用打开即已登录。窗口自己完成登录,既没有要输入的密码,也没有可修改的密码,所以应用窗口里的**设置**没有带**修改密码**的**账户**页面。
## 配置模型
diff --git a/packages/docs/content/remote-control.en.md b/packages/docs/content/remote-control.en.md
index b81434d6..abaf5ccc 100644
--- a/packages/docs/content/remote-control.en.md
+++ b/packages/docs/content/remote-control.en.md
@@ -168,7 +168,7 @@ A connected conversation shows a paper-plane icon on its row in the sidebar. Poi
- A message to the bot starts a Task in the conversation, just like a message typed in the Web App. The agent is not told that the message came from a chat app.
- If the agent is busy, the message waits in the queue and runs next.
-- On Feishu, Telegram and WeChat, images and files you send are attached to the message. Each image can be up to 20 MB, and one connection accepts up to 40 MB of images per 10 minutes. Files follow the upload limits in [System settings](/settings); Telegram also caps bot downloads at 20 MB.
+- On Feishu, Telegram and WeChat, images and files you send are attached to the message. Each image can be up to 20 MB, and one connection accepts up to 40 MB of images per 10 minutes. Files follow the upload limits in [Settings](/settings); Telegram also caps bot downloads at 20 MB.
- Stickers are not supported, and neither are voice and video messages on Feishu and Telegram. The bot replies that only text, image and file messages are supported.
- On Feishu, Telegram and WeChat, messages sent while the connection is off are not delivered later.
diff --git a/packages/docs/content/remote-control.zh.md b/packages/docs/content/remote-control.zh.md
index 884d364a..949895a3 100644
--- a/packages/docs/content/remote-control.zh.md
+++ b/packages/docs/content/remote-control.zh.md
@@ -168,7 +168,7 @@ description: 把对话连接到飞书、Telegram、QQ 或微信机器人,在
- 发给机器人的消息会在对话里启动一个 Task,和在 Web App 里输入的消息一样。Agent 不会知道这条消息来自聊天应用。
- Agent 正忙时,消息会先排队,等轮到它再运行。
-- 在飞书、Telegram 和微信上,你发送的图片和文件会以附件形式随消息进入对话。每张图片最大 20 MB,同一个连接每 10 分钟最多接收 40 MB 图片。文件遵循[系统设置](/settings)里的上传限制;Telegram 另外把机器人能下载的文件限制在 20 MB。
+- 在飞书、Telegram 和微信上,你发送的图片和文件会以附件形式随消息进入对话。每张图片最大 20 MB,同一个连接每 10 分钟最多接收 40 MB 图片。文件遵循[设置](/settings)里的上传限制;Telegram 另外把机器人能下载的文件限制在 20 MB。
- 不支持贴纸,飞书和 Telegram 上的语音、视频消息也不支持。遇到这些消息,机器人会回复「目前仅支持文本、图片和文件消息。」
- 在飞书、Telegram 和微信上,连接关闭期间发给机器人的消息,之后也不会补发。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index c2c045a3..0628875f 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -106,7 +106,7 @@ In desktop mode (a server spawned by the desktop app), every route in this group
## Server Settings (admin only)
-Server-wide proxy, attachment and company-mode settings.
+Server-wide proxy, attachment and company-mode settings, and the settings groups plugins declare.
| Method | Path | Description |
| --- | --- | --- |
@@ -114,6 +114,9 @@ Server-wide proxy, attachment and company-mode settings.
| PUT | `/api/admin/settings` | Updates settings; omitted fields keep their current value, and an invalid field rejects the whole PUT. Returns the full updated settings |
| GET | `/api/admin/settings/proxy-probe` | The reachability probe's targets: `{targets: [{provider, url}]}`. Makes no request |
| POST | `/api/admin/settings/proxy-probe/:provider` | Probes one target over the server's outbound path, sending no credential: `{probe: {provider, url, outcome, ms, status?}}` |
+| GET | `/api/admin/plugin-config` | Every settings group modules declare, the sandbox's first: `{plugins: [{name, configuration, values, parent?, notices?}]}`. See [Plugin settings](#plugin-settings) |
+| PUT | `/api/admin/plugin-config` | Saves one group's values: `{name, values}`. Returns every group, as GET does |
+| POST | `/api/admin/plugin-config/action` | Runs one of a group's actions: `{name, action}`. Returns what happened, with every group as it stands afterwards |
A probe's `outcome` is `reachable` for any HTTP answer, and otherwise `timeout`, `dns`, `refused`, `tls` or `network`. A `:provider` that is not in the target list returns `404` `probe_target_not_found`.
@@ -160,6 +163,14 @@ Two limits cannot be changed: the number of files per message (20) and the inlin
`companyMode` is the server's **Enable company mode** switch, off by default. A change applies without a restart: while the switch is off, every organization route returns `404` `company_mode_off` and the organization scheduler fires nothing.
+### Plugin settings
+
+A settings group is a contribution to `PluginConfigProvider.groups`; the sandbox's comes first. Each group in the list carries its schema (`configuration`), its stored values merged onto the defaults with secrets masked, the group whose card it is drawn inside (`parent`), and live status lines (`notices`).
+
+Field types are `string`, `secret`, `boolean`, `number`, `enum` (with `options`) and `list` (one value per line, optional `maxItems`). A `number` may declare `minimum` and `maximum`, and a `string` or `list` a `pattern` (with `patternErrorMessage`) that every value or line must match.
+
+On PUT, fields the request omits keep their value, `null` or `""` clears one, and a secret sent back as its mask keeps the stored value. A refused field returns `400` `plugin_config_invalid` naming it; a name no group answers to returns `404` `plugin_config_unknown`. The declaring module picks the change up itself, through its watch or at its next read, with no restart.
+
## Machines (admin only)
Installs this server's build on other hosts over ssh and manages the connections to them.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index fe7bb6eb..8bb023c2 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -106,7 +106,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
## 服务器设置(仅管理员)
-服务器全局的代理、附件和公司模式设置。
+服务器全局的代理、附件和公司模式设置,以及插件声明的设置分组。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
@@ -114,6 +114,9 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| PUT | `/api/admin/settings` | 更新设置;省略的字段保持当前值,任何字段非法都会拒绝整个 PUT。返回更新后的完整设置 |
| GET | `/api/admin/settings/proxy-probe` | 可达性探测的目标:`{targets: [{provider, url}]}`。不发起任何请求 |
| POST | `/api/admin/settings/proxy-probe/:provider` | 经服务器的出站链路探测其中一个目标,不发送任何凭证:`{probe: {provider, url, outcome, ms, status?}}` |
+| GET | `/api/admin/plugin-config` | 模块声明的每个设置分组,沙盒的排在最前:`{plugins: [{name, configuration, values, parent?, notices?}]}`。见[插件设置](#插件设置) |
+| PUT | `/api/admin/plugin-config` | 保存一个分组的值:`{name, values}`。返回全部分组,与 GET 相同 |
+| POST | `/api/admin/plugin-config/action` | 执行某个分组的一个动作:`{name, action}`。返回执行结果,以及执行后的全部分组 |
只要有 HTTP 响应返回,探测的 `outcome` 就是 `reachable`,否则为 `timeout`、`dns`、`refused`、`tls` 或 `network`。`:provider` 不在目标列表里时返回 `404` `probe_target_not_found`。
@@ -160,6 +163,14 @@ PUT 按如下规则校验:
`companyMode` 是服务器的**启用公司模式**开关,默认关闭。修改无需重启即生效:开关关闭期间,所有组织路由都返回 `404` `company_mode_off`,组织的调度器也不会触发任何事件。
+### 插件设置
+
+设置分组是投给 `PluginConfigProvider.groups` 的 contribution,沙盒的排在最前。列表中的每个分组带有它的 schema(`configuration`)、合并到缺省值上的存储值(密钥掩码)、它被画在哪个分组的卡片里(`parent`),以及实时状态行(`notices`)。
+
+字段类型有 `string`、`secret`、`boolean`、`number`、`enum`(带 `options`)和 `list`(每行一个值,可选 `maxItems`)。`number` 可声明 `minimum` 与 `maximum`;`string` 与 `list` 可声明每个值或每一行都须匹配的 `pattern`(配 `patternErrorMessage`)。
+
+PUT 时,请求省略的字段保持原值,`null` 或 `""` 清除该字段,密钥按掩码原样送回即保持存储值。被拒的字段返回 `400` `plugin_config_invalid` 并点名该字段;没有分组叫这个名字时返回 `404` `plugin_config_unknown`。声明它的模块自己经 watch 或下次读取拿到改动,无需重启。
+
## 机器(仅管理员)
通过 ssh 在其他主机上安装本服务器的构建,并管理与这些主机的连接。
diff --git a/packages/docs/content/sessions-and-traces.en.md b/packages/docs/content/sessions-and-traces.en.md
index f64ecf2f..84f57dfb 100644
--- a/packages/docs/content/sessions-and-traces.en.md
+++ b/packages/docs/content/sessions-and-traces.en.md
@@ -170,6 +170,6 @@ The approval mechanism itself is covered in [Tools & Approval](/tools).
### Moving Trace files across deployments
- **Export:** in a conversation's Trace panel, **Export** downloads the selected file verbatim as JSONL.
-- **Import:** in [System settings](/settings#import-a-trace) → **General**, **Import Trace** adds a file to the Project and agent you choose, as a new conversation. Files can be up to 14 MB.
+- **Import:** in [Settings](/settings#import-a-trace) → **General**, **Import Trace** adds a file to the Project and agent you choose, as a new conversation. Files can be up to 14 MB.
An import whose session id already exists anywhere in this installation is rejected, so an imported file always becomes index 001 of a new Session.
diff --git a/packages/docs/content/sessions-and-traces.zh.md b/packages/docs/content/sessions-and-traces.zh.md
index 13eeac1a..4255b99c 100644
--- a/packages/docs/content/sessions-and-traces.zh.md
+++ b/packages/docs/content/sessions-and-traces.zh.md
@@ -170,6 +170,6 @@ Web App 的 Trace 视图和用量、成本统计都来自这份数据,不存
### 跨部署迁移 Trace 文件
- **导出:** 在对话的 Trace 面板中,**导出**会把选中的文件原样下载为 JSONL。
-- **导入:** 在[系统设置](/settings#导入-trace) → **通用**中,**导入 Trace** 会把文件添加到你选择的 Project 和 Agent,成为一个新对话。文件最大 14 MB。
+- **导入:** 在[设置](/settings#导入-trace) → **通用**中,**导入 Trace** 会把文件添加到你选择的 Project 和 Agent,成为一个新对话。文件最大 14 MB。
如果文件的 session id 已在本安装的任何位置存在,导入即失败,因此导入的文件总是成为新 Session 的 001 号文件。
diff --git a/packages/docs/content/settings.en.md b/packages/docs/content/settings.en.md
index a204b3e4..030a8777 100644
--- a/packages/docs/content/settings.en.md
+++ b/packages/docs/content/settings.en.md
@@ -1,17 +1,17 @@
---
title: Settings
-description: Manage your profile, preferences and password, and, as an admin, users, the proxy, upload limits and company mode.
+description: Manage your profile, preferences and password, and, as an admin, users, the proxy, upload limits, company mode and plugins.
---
-**System settings** is one dialog for the settings that belong to neither a Project nor an agent: your profile, your interface preferences and password, and, for an admin, the server's users, proxy, upload limits and company mode.
+**Settings** is one dialog for the settings that belong to neither a Project nor an agent: your profile, your interface preferences and password, and, for an admin, the server's users, proxy, upload limits, company mode and plugins, the sandbox among them.
- Your own settings: [Profile](#profile), [General](#general), [Appearance](#appearance) and [Account](#account).
-- Server settings, for admins: [Users](#users), [Proxy options](#proxy-options), [Upload limits](#upload-limits) and [Company mode](#company-mode).
+- Server settings, for admins: [Users](#users), [Proxy options](#proxy-options), [Upload limits](#upload-limits), [Company mode](#company-mode) and [Plugins](#plugins).
-## Open System settings
+## Open Settings
1. At the bottom of the sidebar, select your user row, or your avatar when the sidebar is collapsed. The account menu opens.
-2. Select **System settings**.
+2. Select **Settings**.
## How the dialog is organized
@@ -29,6 +29,7 @@ The rail is grouped into **Personal** and **Server**:
| [Proxy options](#proxy-options) | Server | Admin only |
| [Upload limits](#upload-limits) | Server | Admin only |
| [Company mode](#company-mode) | Server | Admin only |
+| [Plugins](#plugins) | Server | Admin only |
Personal preferences apply the moment they are touched. There is no Save button and nothing to lose by closing the dialog. The nickname on the Profile page is the one exception: typed text needs a commit, and its **Save** sits beside the field rather than under the page.
@@ -240,3 +241,22 @@ Turning it off stops the organization scheduler and every organization route, an
> [!NOTE]
> Company mode is a beta. See [Company mode](/company-mode).
+
+## Plugins
+
+The **Plugins** page is admin-only and server-global. It shows the options each loaded plugin declares, as a form drawn from the plugin's own schema. A plugin that declares no options has no card here. A save reaches the plugin at once, with no restart.
+
+### Sandbox
+
+The sandbox is the first card on the page. It sets the confinement every agent command is spawned under:
+
+- **Confinement mode**: off (full access), workspace write only, or read-only.
+- **Network**: full access, local network (localhost only), or no network. The local level needs a backend that can enforce it.
+- **Temporary directory**: whether it stays writable. On by default, in either confining mode, because shells and most tools cannot start without one.
+- **Masked paths**: paths hidden from a confined command, one absolute path per line, at most 64.
+
+A sandbox backend installed as a plugin (bwrap, Seatbelt, DSH) enforces the mode. The card lists the mounted backends and the isolation each one implements, and says so when there is none. Without a backend, every mode but off refuses every agent command.
+
+A backend's own options, such as bwrap's program and its probe timeout of 1–30 seconds, or Seatbelt's program, are drawn inside the same card, and the card's one **Save** stores both. A backend that failed its check, for example on a wrong program path, is loaded again by that save, with no restart.
+
+The settings apply to Sessions created after the save; each Session keeps the policy it was created with. A restart keeps the settings.
diff --git a/packages/docs/content/settings.zh.md b/packages/docs/content/settings.zh.md
index 8254e796..ff369df4 100644
--- a/packages/docs/content/settings.zh.md
+++ b/packages/docs/content/settings.zh.md
@@ -1,17 +1,17 @@
---
-title: 系统设置
-description: 管理个人资料、偏好设置和密码;管理员还可以管理用户、代理、上传限制和公司模式。
+title: 设置
+description: 管理个人资料、偏好设置和密码;管理员还可以管理用户、代理、上传限制、公司模式和插件。
---
-**系统设置**把不属于 Project 也不属于 Agent 的设置集中在一个对话框里:你的个人资料、界面偏好和密码;管理员还能在这里管理服务器的用户、代理、上传限制和公司模式。
+**设置**把不属于 Project 也不属于 Agent 的设置集中在一个对话框里:你的个人资料、界面偏好和密码;管理员还能在这里管理服务器的用户、代理、上传限制、公司模式和插件(包括沙盒)。
- 个人设置:[个人资料](#个人资料)、[通用](#通用)、[外观](#外观)和[账户](#账户)。
-- 服务器设置,仅管理员:[用户管理](#用户管理)、[代理选项](#代理选项)、[上传限制](#上传限制)和[公司模式](#公司模式)。
+- 服务器设置,仅管理员:[用户管理](#用户管理)、[代理选项](#代理选项)、[上传限制](#上传限制)、[公司模式](#公司模式)和[插件](#插件)。
-## 打开系统设置
+## 打开设置
1. 在侧边栏底部点击你的用户行;侧边栏收起时,点击你的头像。账户菜单随即打开。
-2. 选择**系统设置**。
+2. 选择**设置**。
## 对话框的结构
@@ -29,6 +29,7 @@ description: 管理个人资料、偏好设置和密码;管理员还可以管
| [代理选项](#代理选项) | 服务器 | 仅管理员 |
| [上传限制](#上传限制) | 服务器 | 仅管理员 |
| [公司模式](#公司模式) | 服务器 | 仅管理员 |
+| [插件](#插件) | 服务器 | 仅管理员 |
个人偏好改动即生效,没有保存按钮,关掉对话框也不会丢失什么。唯一的例外是个人资料页的昵称:输入的文字需要显式提交,它的**保存**按钮就在输入框旁边,不在页面底部。
@@ -240,3 +241,22 @@ Trace 会成为该 Agent 的一段新对话。如果该 Agent 下已有相同 id
> [!NOTE]
> 公司模式是内测功能。见[公司模式](/company-mode)。
+
+## 插件
+
+**插件**页仅管理员可见,作用于整台服务器。页面列出每个已装载插件声明的选项,表单按插件自己的 schema 生成;没有声明选项的插件不会出现。保存后立即送达插件,无需重启。
+
+### 沙盒
+
+沙盒是页面上的第一张卡片,设置 Agent 执行每条命令时所处的封禁:
+
+- **封禁模式**:关闭(完全访问)、仅工作区可写或只读。
+- **网络**:完全访问、本地网络(仅本机 localhost)或无网络。本地网络需要能实施它的后端。
+- **临时目录**:是否保持可写。默认开启,两种封禁模式下都生效,因为 Shell 与大多数工具没有它就无法启动。
+- **屏蔽路径**:对被封禁命令隐藏的路径,每行一个绝对路径,最多 64 条。
+
+真正实施封禁的是以插件形式安装的沙盒后端(bwrap、Seatbelt、DSH)。卡片列出已挂载的后端及各自实现的隔离维度,一个都没有时会明确说明。没有后端时,除关闭外的任何模式都会拒绝 Agent 的每条命令。
+
+后端自己的选项(例如 bwrap 的程序路径与 1–30 秒的探测超时,Seatbelt 的程序路径)画在同一张卡片里,卡片的一个**保存**一并存下。未通过自检的后端(例如程序路径写错)会在这次保存后重新加载,无需重启。
+
+设置对保存之后创建的 Session 生效;每个 Session 保留它创建时的策略。重启后设置仍然保留。
diff --git a/packages/docs/content/updates.en.md b/packages/docs/content/updates.en.md
index b5a34322..65fd57f1 100644
--- a/packages/docs/content/updates.en.md
+++ b/packages/docs/content/updates.en.md
@@ -17,7 +17,7 @@ Check which version of PenguinHarness you are running, and update it in the way
In the Web App:
- The new-chat page shows the running version on a version line such as `vX.Y.Z · Last updated Jul 26`. The release workflow stamps the date into the build, so it is shown without any network access. Dev builds and releases from before the stamping, v0.1.2 and earlier, show no date.
-- In the sidebar user menu, the update row directly under **System settings** shows the running version, muted, on its right.
+- In the sidebar user menu, the update row directly under **Settings** shows the running version, muted, on its right.
In a terminal:
@@ -32,7 +32,7 @@ Updating works the way an app updater does, from one dialog.
Two entries open the dialog:
-- The update row directly under **System settings** in the sidebar user menu. The row says where things stand: **Check for updates**, **Checking…**, **New version vX available**, **Downloading vX 42%** or **Restart to update to vX**. Whatever it says, it opens the dialog.
+- The update row directly under **Settings** in the sidebar user menu. The row says where things stand: **Check for updates**, **Checking…**, **New version vX available**, **Downloading vX 42%** or **Restart to update to vX**. Whatever it says, it opens the dialog.
- The small superscript on the new-chat page's version line. It reads **New version available** when a release is offered, **Downloading update** while a download runs, and **Restart to update** once the download is ready.
### Run the update
diff --git a/packages/docs/content/updates.zh.md b/packages/docs/content/updates.zh.md
index bf257df2..1bc88846 100644
--- a/packages/docs/content/updates.zh.md
+++ b/packages/docs/content/updates.zh.md
@@ -17,7 +17,7 @@ description: 查看正在运行的版本,并更新桌面应用、CLI 安装或
在 Web App 里:
- 新对话页的版本行会显示正在运行的版本,形如 `vX.Y.Z · 最近更新日期 7月26日`。日期由发布流程在构建时写入,所以不联网也能显示。开发构建,以及引入日期写入之前的发布版(v0.1.2 及更早)没有日期。
-- 在侧边栏的用户菜单里,紧贴**系统设置**下方的更新行会在右侧以浅色显示当前运行的版本。
+- 在侧边栏的用户菜单里,紧贴**设置**下方的更新行会在右侧以浅色显示当前运行的版本。
在终端里:
@@ -32,7 +32,7 @@ description: 查看正在运行的版本,并更新桌面应用、CLI 安装或
有两个入口可以打开更新弹窗:
-- 侧边栏用户菜单里紧贴**系统设置**下方的更新行。这一行会显示更新到了哪一步:**检查更新**、**检查中…**、**新版本 vX 可用**、**正在下载 vX 42%** 或**重启以更新到 vX**。无论显示哪种状态,点击都会打开弹窗。
+- 侧边栏用户菜单里紧贴**设置**下方的更新行。这一行会显示更新到了哪一步:**检查更新**、**检查中…**、**新版本 vX 可用**、**正在下载 vX 42%** 或**重启以更新到 vX**。无论显示哪种状态,点击都会打开弹窗。
- 新对话页版本行上的小上标。有新版本时显示**有新版本可用**,下载中显示**正在下载更新**,下载就绪后显示**重启以更新**。
### 执行更新
diff --git a/packages/docs/content/usage.en.md b/packages/docs/content/usage.en.md
index 9bfb00b0..518f4ae5 100644
--- a/packages/docs/content/usage.en.md
+++ b/packages/docs/content/usage.en.md
@@ -29,7 +29,7 @@ The same range and agent filter decide which rows the server error panel lists,
Three cards show totals: **Today**, **Last 7 days**, and **Total** for the selected date range. All three follow the agent and model filters. Each card lists the Tokens, the number of requests and the cost.
-Prices are shown in the display currency you choose under [System settings › General](/settings#general). Only models with configured pricing count toward cost. When some records have no price, an asterisk appears beside **Cost** and a note at the bottom of the page says so.
+Prices are shown in the display currency you choose under [Settings › General](/settings#general). Only models with configured pricing count toward cost. When some records have no price, an asterisk appears beside **Cost** and a note at the bottom of the page says so.
## Read the charts
diff --git a/packages/docs/content/usage.zh.md b/packages/docs/content/usage.zh.md
index 77a21854..cbc428a0 100644
--- a/packages/docs/content/usage.zh.md
+++ b/packages/docs/content/usage.zh.md
@@ -29,7 +29,7 @@ description: 按 Agent、模型和时间范围查看 Token 用量、成本与服
三张卡片分别汇总**今日**、**近 7 天**和**累计**的数据,其中**累计**统计的是所选日期范围。三张卡片都受 Agent 和模型筛选影响,每张列出 Token 用量、请求数和成本。
-价格按你在[系统设置 › 通用](/settings#通用)中选择的币种显示。只有配置了价格的模型才计入成本;部分记录没有价格时,**成本**旁会出现星号,页面底部也有一行说明。
+价格按你在[设置 › 通用](/settings#通用)中选择的币种显示。只有配置了价格的模型才计入成本;部分记录没有价格时,**成本**旁会出现星号,页面底部也有一行说明。
## 查看图表
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index 45d19386..218db0ab 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -32,7 +32,7 @@ The initial account is `admin`, and it starts with no password of its own. Until
1. Start the server with `penguin web`.
2. Find the framed notice in the server output. It contains the first-login link.
3. Open the link in your browser. You are signed in as `admin`.
-4. Set a password: select **Change now** on the banner that appears, or go to **System settings** › **Account**. This first session needs no current password.
+4. Set a password: select **Change now** on the banner that appears, or go to **Settings** › **Account**. This first session needs no current password.
> [!NOTE]
> The link can be opened again. It lasts 30 days, or until a password is set. A restart prints a new link and the old one stops working. A link that no longer works lands on the login page with an explanation.
@@ -43,7 +43,7 @@ The desktop app does not print the notice. The server also skips it while a pass
The login page asks for a **Username** and a **Password**, and has language and theme switches in its corner.
-There is no self-registration. An admin creates accounts on the **Users** page of System settings. Every new user automatically gets an independent initial Project named `<userId>-default_project`.
+There is no self-registration. An admin creates accounts on the **Users** page of Settings. Every new user automatically gets an independent initial Project named `<userId>-default_project`.
While the initial password is still in use, a banner prompts the user to change it, with a **Change now** link. Closing the banner hides it for good.
@@ -99,7 +99,7 @@ From top to bottom, the sidebar holds:
- The conversation list, with search and grouping by Workspace, agent or time. See [Chat](/chat).
- Your user row at the bottom. It opens the account menu:
- - **System settings**. See [Settings](/settings).
+ - **Settings**. See [Settings](/settings).
- The update row, which names where an update stands and opens the update dialog. See [Updates](/updates).
- **Sign out**.
@@ -132,7 +132,7 @@ Two parts of the app have no sidebar entry.
### Language and theme
-The interface language (English / 中文 / System) and the theme (Light / Dark / System) can be switched at any time in [System settings](/settings), and on the login page. Both are saved per browser.
+The interface language (English / 中文 / System) and the theme (Light / Dark / System) can be switched at any time in [Settings](/settings), and on the login page. Both are saved per browser.
## Projects and members
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index 2d1812dd..a82e4f4b 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -32,7 +32,7 @@ penguin web
1. 用 `penguin web` 启动服务。
2. 在服务的输出里找到带边框的提示,其中有首次登录链接。
3. 在浏览器中打开链接,即以 `admin` 身份登录。
-4. 设置密码:点击随后出现的横幅上的**去修改**,或进入**系统设置** › **账户**。这次登录后设置密码,不需要输入当前密码。
+4. 设置密码:点击随后出现的横幅上的**去修改**,或进入**设置** › **账户**。这次登录后设置密码,不需要输入当前密码。
> [!NOTE]
> 链接可以重复打开,有效期 30 天,设置密码后即失效。重启服务会打印新链接,旧链接随之作废。打开已失效的链接会跳到登录页,并显示说明。
@@ -43,7 +43,7 @@ penguin web
登录页要求填写**用户名**和**密码**,页面一角有语言和主题的切换。
-系统不开放自助注册:账号由管理员在系统设置的**用户管理**页创建。每个新用户都会自动获得一个独立的初始 Project,名为 `<userId>-default_project`。
+系统不开放自助注册:账号由管理员在设置的**用户管理**页创建。每个新用户都会自动获得一个独立的初始 Project,名为 `<userId>-default_project`。
仍在使用初始密码时,页面顶部会显示横幅,提醒尽快修改,并附有**去修改**链接。关闭横幅后,它就不再出现。
@@ -99,7 +99,7 @@ penguin web
- 对话列表,可以搜索,可以按 Workspace、Agent 或时间分组。见[对话](/chat)。
- 底部是你的用户行,点击打开账户菜单:
- - **系统设置**,见[系统设置](/settings)。
+ - **设置**,见[设置](/settings)。
- 更新行,显示更新进行到哪一步,点击打开更新对话框,见[更新 PenguinHarness](/updates)。
- **登出**。
@@ -132,7 +132,7 @@ penguin web
### 语言与主题
-界面语言(English / 中文 / 跟随系统)和主题(浅色 / 深色 / 跟随系统)随时可以在[系统设置](/settings)中切换,登录页上也能切换。两者都按浏览器保存。
+界面语言(English / 中文 / 跟随系统)和主题(浅色 / 深色 / 跟随系统)随时可以在[设置](/settings)中切换,登录页上也能切换。两者都按浏览器保存。
## Project 与成员
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index af477735..1601d837 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -929,6 +929,11 @@ export interface ChatDefaultsDto {
* "none" — only the selectable tiers.
*/
thinkingLevel?: Exclude<ThinkingLevelName, "none">;
+ /**
+ * Read-only, GET only: the sandbox policy a new Session starts with — the server's Sandbox
+ * settings. Not part of the Project's block; PUT ignores it.
+ */
+ sandbox?: SessionSandbox;
}
// ---------------------------------------------------------------------------
@@ -1365,6 +1370,30 @@ export interface MemoryImportResponse {
// Session
// ---------------------------------------------------------------------------
+/** How far a Session's commands may reach the filesystem (the sandbox's confinement mode). */
+export type SessionSandboxMode = "read-only" | "workspace-write" | "danger-full-access";
+
+/**
+ * The part of a Session's sandbox policy a person picks from the composer: the filesystem
+ * mode and the network level. The Session keeps its own copy — taken from the server's
+ * Sandbox settings when it was created — so editing those settings only changes what NEW
+ * Sessions start with.
+ */
+export interface SessionSandbox {
+ mode: SessionSandboxMode;
+ /** `open` = unrestricted, `local` = only the host's localhost, `none` = no network. */
+ network: SessionSandboxNetwork;
+ /**
+ * Response only, ignored in requests: whether a sandbox backend on this server can enforce
+ * the `local` level. When false the composer shows it greyed out, and picking it is refused
+ * (400 `sandbox_unsupported`).
+ */
+ localNetworkSupported?: boolean;
+}
+
+/** The network levels, widest first. */
+export type SessionSandboxNetwork = "open" | "local" | "none";
+
export interface SessionInfo {
sessionId: string;
projectId: string;
@@ -1375,6 +1404,8 @@ export interface SessionInfo {
modelId: string;
workspace: string;
approvalMode: ApprovalMode;
+ /** The Session's own sandbox policy (see {@link SessionSandbox}). */
+ sandbox: SessionSandbox;
/**
* Thinking level pinned for this Session (set via PATCH; the Web App's in-chat picker).
* Unset = never pinned: each model context the Session opens reads the Agent config's
@@ -1543,6 +1574,11 @@ export interface SessionCreateRequest {
workspace?: string;
/** Defaults to allow-all. */
approvalMode?: ApprovalMode;
+ /**
+ * The Session's sandbox policy; either half omitted takes the server's Sandbox settings.
+ * A non-admin may not pick anything looser than those settings (403 `sandbox_forbidden`).
+ */
+ sandbox?: Partial<SessionSandbox>;
/**
* Creating-client hint stored on the Session row: "cli" when the CLI creates the
* Session through the API, "org" when the organization runtime opened it (a desk or a
@@ -1593,6 +1629,11 @@ export interface SessionResponse {
export interface SessionPatchRequest {
approvalMode?: ApprovalMode;
+ /**
+ * Change this Session's sandbox policy; applies from its next command. A non-admin may not
+ * pick anything looser than the server's Sandbox settings (403 `sandbox_forbidden`).
+ */
+ sandbox?: Partial<SessionSandbox>;
/**
* Pin this Session's thinking level (`none | low | medium | high | xhigh | max`, anything else
* is a 400). It replaces the Agent-config fallback for this Session and applies from the
@@ -4811,6 +4852,123 @@ export interface ContributionsResponse {
sessionTabs: WebContribution[];
}
+/**
+ * One field of a settings group a module declares (its `PluginConfigProvider.groups`
+ * contribution's `properties.<name>`): what the Settings dialog draws for it. `secret` is
+ * drawn as a password field and masked on the way out; `enum` is a choice among `options`;
+ * `list` is a list of strings, drawn one per line.
+ */
+export interface PluginConfigField {
+ type: "string" | "secret" | "boolean" | "number" | "enum" | "list";
+ title: string;
+ titleZh?: string;
+ description?: string;
+ descriptionZh?: string;
+ placeholder?: string;
+ /** The value a package with nothing stored reads; also what an empty field falls back to. */
+ default?: string | number | boolean | string[];
+ /** A save that would leave this field empty is refused. */
+ required?: boolean;
+ /** `enum` only: the values it may take, in display order. */
+ options?: PluginConfigOption[];
+ /** `list` only: the most entries a save may leave (after trimming and de-duplicating). */
+ maxItems?: number;
+ /** `number` only: the smallest and largest value a save may store. */
+ minimum?: number;
+ maximum?: number;
+ /** `string` / `list` only: a regular expression every value (every line) must match. */
+ pattern?: string;
+ /** What a save refused by `pattern` says, after the field's name (e.g. "must be an absolute path"). */
+ patternErrorMessage?: string;
+}
+
+/** One choice of an `enum` field. */
+export interface PluginConfigOption {
+ value: string;
+ title: string;
+ titleZh?: string;
+}
+
+/** A declared configuration: a titled group of fields, in declaration order. */
+export interface PluginConfiguration {
+ title?: string;
+ titleZh?: string;
+ description?: string;
+ descriptionZh?: string;
+ properties: Record<string, PluginConfigField>;
+}
+
+/** A line of live status a contributed group reports beside its fields (e.g. that nothing can enforce it). */
+export interface PluginConfigNotice {
+ /**
+ * `progress` = work the group started is still running (an install, a download): the page
+ * reads the groups again every few seconds while any notice says so, and the text is the
+ * step it is on.
+ */
+ tone: "attention" | "muted" | "progress";
+ text: string;
+ textZh?: string;
+}
+
+/** One settings group (GET /api/admin/plugin-config): its schema and its values, secrets masked. */
+export interface PluginConfigEntry {
+ /** The group's name — the id of the contribution that declared it; also the store key. */
+ name: string;
+ configuration: PluginConfiguration;
+ /** Stored values merged onto the defaults; a secret arrives masked (`first4…last4` or `***`), never in the clear. */
+ values: Record<string, unknown>;
+ /** Drawn inside that entry's card and saved with it (a sandbox backend's options inside the sandbox's). */
+ parent?: string;
+ /** Live status beside the fields; absent when there is none. */
+ notices?: PluginConfigNotice[];
+ /** What this group can DO once, on the machine, drawn as buttons beneath its notices. */
+ actions?: PluginConfigActionDecl[];
+ /** Enum options this machine cannot honour now: drawn greyed out with the reason; a save choosing one is refused. */
+ unavailable?: PluginConfigUnavailableDecl[];
+}
+
+/** One enum option a settings group cannot honour on this machine, and why. */
+export interface PluginConfigUnavailableDecl {
+ field: string;
+ value: string;
+ reason: string;
+ reasonZh?: string;
+}
+
+/** One button under a settings group: what it is called, and what pressing it will do. */
+export interface PluginConfigActionDecl {
+ id: string;
+ title: string;
+ titleZh?: string;
+ description?: string;
+ descriptionZh?: string;
+}
+
+/** POST /api/admin/plugin-config/action — what running one reported. */
+export interface PluginConfigActionResponse {
+ ok: boolean;
+ message: string;
+ messageZh?: string;
+ /** The groups as they stand after it ran: a setup that worked changes what the page says. */
+ plugins: PluginConfigEntry[];
+}
+
+export interface PluginConfigResponse {
+ plugins: PluginConfigEntry[];
+}
+
+/**
+ * PUT /api/admin/plugin-config — one group's update. Every named field is validated
+ * against its type; an omitted field keeps its stored value; a secret sent as the masked
+ * value keeps the stored one, and `null` or `""` clears any field. 400 `plugin_config_invalid`
+ * (with `field`) on a value that does not fit or a required field left empty; 404
+ * `plugin_config_unknown` for a name no group answers to.
+ */
+export interface PluginConfigUpdateRequest {
+ name: string;
+ values: Record<string, unknown>;
+}
+
/** One plugin a Project lists (GET /api/projects/:projectId/plugins/installed). */
export interface InstalledPlugin {
/** The package specifier as written in the file. */
diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.ts
index 7afd5008..14338f82 100644
--- a/packages/server/src/db/database.ts
+++ b/packages/server/src/db/database.ts
@@ -65,6 +65,7 @@ export function openDatabase(dbPath: string): DatabaseSync {
ensureColumn(db, "sessions", "has_trace", "INTEGER NOT NULL DEFAULT 0");
ensureColumn(db, "sessions", "fork_count", "INTEGER NOT NULL DEFAULT 0");
ensureColumn(db, "sessions", "thinking_level", "TEXT");
+ ensureColumn(db, "sessions", "sandbox", "TEXT");
// A v0.2.0 web.db has auth_sessions without `via`; CREATE TABLE IF NOT EXISTS never adds a
// column, so every INSERT would fail "no column named via" until this runs.
ensureColumn(db, "auth_sessions", "via", "TEXT");
diff --git a/packages/server/src/db/migrations.ts b/packages/server/src/db/migrations.ts
index e88a84dc..ede57777 100644
--- a/packages/server/src/db/migrations.ts
+++ b/packages/server/src/db/migrations.ts
@@ -491,6 +491,22 @@ export const MIGRATIONS: readonly Migration[] = [
db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
},
},
+ {
+ version: 11,
+ name: "sessions-sandbox",
+ // The Session's own sandbox policy (JSON), snapshotted from the server's settings when
+ // the Session is created, so a later settings change leaves running Sessions alone.
+ // NULL = a row from before this column: it takes the settings in force at its next
+ // command and keeps them from then on. Swap-safe: a pushed platform boots against the
+ // runtime's already-open database, so the column has to arrive by a migration.
+ swapSafe: true,
+ up(db) {
+ ensureColumn(db, "sessions", "sandbox", "TEXT");
+ },
+ // Not a DROP: schema.ts declares the column, and dropping it would put every Session
+ // back under whatever the settings say.
+ down() {},
+ },
];
/** The highest version this build knows how to reach. */
diff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.ts
index b51717b9..a9534b9b 100644
--- a/packages/server/src/db/repos/sessions.ts
+++ b/packages/server/src/db/repos/sessions.ts
@@ -4,6 +4,7 @@
*/
import type { ThinkingLevelName } from "@prismshadow/penguin-core/interfaces";
import type { ApprovalMode } from "../../api/types.js";
+import type { SandboxSettings } from "@prismshadow/penguin-core/plugin";
import { Component, Use } from "@prismshadow/penguin-core/kernel";
import type { Db } from "../../hmr/capabilities.js";
import type { SessionIndex } from "../../mechanisms/sessions.js";
@@ -54,6 +55,33 @@ export interface SessionRow {
*/
lastActiveAt: string;
createdAt: string;
+ /**
+ * The Session's own sandbox policy, snapshotted from the server's settings at creation.
+ * NULL = a row from before the column: it takes the settings at its next command.
+ */
+ sandbox?: SandboxSettings | null;
+}
+
+/** A stored policy, or null when the column is empty or holds something unreadable. */
+function parseSandbox(raw: unknown): SandboxSettings | null {
+ if (typeof raw !== "string" || raw === "") return null;
+ try {
+ const value = JSON.parse(raw) as Partial<SandboxSettings> | null;
+ const modes = ["read-only", "workspace-write", "danger-full-access"];
+ if (value === null || typeof value !== "object" || !modes.includes(value.mode as string)) {
+ return null;
+ }
+ return {
+ mode: value.mode as SandboxSettings["mode"],
+ ...(value.network === "none" || value.network === "local" ? { network: value.network } : {}),
+ ...(Array.isArray(value.maskPaths)
+ ? { maskPaths: value.maskPaths.filter((p): p is string => typeof p === "string") }
+ : {}),
+ ...(typeof value.writableTemp === "boolean" ? { writableTemp: value.writableTemp } : {}),
+ };
+ } catch {
+ return null;
+ }
}
function mapRow(r: Record<string, unknown>): SessionRow {
@@ -74,6 +102,7 @@ function mapRow(r: Record<string, unknown>): SessionRow {
// somehow inserted as NULL (degrades to createdAt instead of surfacing undefined).
lastActiveAt: (r.last_active_at as string | null) ?? (r.created_at as string),
createdAt: r.created_at as string,
+ sandbox: parseSandbox(r.sandbox),
};
}
@@ -130,8 +159,8 @@ export class SessionsRepo implements SessionIndex {
private runInsert(verb: "INSERT" | "INSERT OR IGNORE", row: SessionRow): void {
this.db
.prepare(
- `${verb} INTO sessions (session_id, project_id, agent_id, provider, model_id, workspace, approval_mode, title, client, has_trace, last_active_at, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, ?), ?)`,
+ `${verb} INTO sessions (session_id, project_id, agent_id, provider, model_id, workspace, approval_mode, title, client, has_trace, last_active_at, created_at, sandbox)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, ?), ?, ?)`,
)
.run(
row.sessionId,
@@ -147,6 +176,7 @@ export class SessionsRepo implements SessionIndex {
row.lastActiveAt ?? null,
row.createdAt,
row.createdAt,
+ row.sandbox ? JSON.stringify(row.sandbox) : null,
);
}
@@ -229,6 +259,13 @@ export class SessionsRepo implements SessionIndex {
.run(mode, sessionId);
}
+ /** Replace the Session's sandbox policy snapshot (applies from its next command). */
+ updateSandbox(sessionId: string, sandbox: SandboxSettings): void {
+ this.db
+ .prepare("UPDATE sessions SET sandbox = ? WHERE session_id = ?")
+ .run(JSON.stringify(sandbox), sessionId);
+ }
+
/** Pin the session's thinking level (runs without one of their own then use it). */
updateThinkingLevel(sessionId: string, level: ThinkingLevelName): void {
this.db
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index 5d779f68..23b65c60 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -90,6 +90,7 @@ CREATE TABLE IF NOT EXISTS sessions (
client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace); NULL = legacy row, treated as web
has_trace INTEGER NOT NULL DEFAULT 0, -- cache: a Trace record exists (set at task start / adoption / subagent registration; lazily backfilled by list hydration)
fork_count INTEGER NOT NULL DEFAULT 0, -- monotonically allocated child-fork number for this source Session; never decremented when a fork is deleted
+ sandbox TEXT, -- the Session's sandbox policy snapshot (JSON SandboxSettings); NULL = legacy row, snapshotted at its next command
last_active_at TEXT, -- last activity this server drove for the session (ISO; stamped once when a run starts and once when it ends, initialized to created_at); monotonic, never moves backwards; NULL only before openDatabase's one-time backfill
created_at TEXT NOT NULL
); -- the subagent/schedule/benchmark SOURCE is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); "client" is a different, DB-only axis (who created the row)
diff --git a/packages/server/src/http/routes/admin-plugin-config.ts b/packages/server/src/http/routes/admin-plugin-config.ts
new file mode 100644
index 00000000..f79a6056
--- /dev/null
+++ b/packages/server/src/http/routes/admin-plugin-config.ts
@@ -0,0 +1,66 @@
+/**
+ * Admin plugin-configuration routes (admin only, 403 for non-admins):
+ * GET /api/admin/plugin-config — every declared settings group, its schema and its values
+ * (secrets masked); PUT /api/admin/plugin-config { name, values } — one group's update,
+ * validated against its schema (see plugin/config.ts applyUpdate), stored, and handed to the
+ * declaring module's watchers so it applies without a restart; POST
+ * /api/admin/plugin-config/action { name, action } — runs one group's action (what a deployment
+ * must DO on the machine, like creating the Windows sandbox's local accounts) and answers what
+ * happened, together with the groups as they stand afterwards.
+ */
+import { Hono } from "hono";
+import type { PluginConfigActionResponse, PluginConfigResponse } from "../../api/types.js";
+import type { AppEnv } from "../../auth/middleware.js";
+import { PluginConfigError } from "../../plugin/config.js";
+import type { PluginConfigAdmin } from "../../plugin/config.js";
+import { HttpError } from "../errors.js";
+import { badRequest, readJson, requireString } from "../validate.js";
+
+export function adminPluginConfigRoutes(store: PluginConfigAdmin): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ app.use("*", async (c, next) => {
+ if (!c.var.user.isAdmin) {
+ throw new HttpError(403, "admin_required", "Only an admin can perform this operation.");
+ }
+ await next();
+ });
+
+ app.get("/", (c) => c.json({ plugins: store.describe() } satisfies PluginConfigResponse));
+
+ app.put("/", async (c) => {
+ const body = await readJson(c);
+ const name = requireString(body, "name", { minLen: 1, maxLen: 214 });
+ const values = (body as { values?: unknown }).values;
+ if (values === null || typeof values !== "object" || Array.isArray(values)) {
+ throw badRequest("values must be an object of fields.");
+ }
+ try {
+ await store.set(name, values as Record<string, unknown>);
+ } catch (err) {
+ if (err instanceof PluginConfigError) {
+ if (err.field === null) throw new HttpError(404, "plugin_config_unknown", err.message);
+ throw new HttpError(400, "plugin_config_invalid", err.message);
+ }
+ throw err;
+ }
+ return c.json({ plugins: store.describe() } satisfies PluginConfigResponse);
+ });
+
+ app.post("/action", async (c) => {
+ const body = await readJson(c);
+ const name = requireString(body, "name", { minLen: 1, maxLen: 214 });
+ const action = requireString(body, "action", { minLen: 1, maxLen: 214 });
+ try {
+ const result = await store.run(name, action);
+ return c.json({ ...result, plugins: store.describe() } satisfies PluginConfigActionResponse);
+ } catch (err) {
+ if (err instanceof PluginConfigError) {
+ throw new HttpError(404, "plugin_config_unknown", err.message);
+ }
+ throw err;
+ }
+ });
+
+ return app;
+}
diff --git a/packages/server/src/http/routes/admin.ts b/packages/server/src/http/routes/admin.ts
index 76bcfa01..0b1abefa 100644
--- a/packages/server/src/http/routes/admin.ts
+++ b/packages/server/src/http/routes/admin.ts
@@ -13,6 +13,8 @@ import { pathParam, readJson, requireString } from "../validate.js";
import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
import type { Desktop, Proxy } from "../../hmr/capabilities.js";
import { adminSettingsRoutes } from "./admin-settings.js";
+import { adminPluginConfigRoutes } from "./admin-plugin-config.js";
+import { PluginConfigAdmin } from "../../plugin/config.js";
import type { Admin } from "../../mechanisms/identity.js";
import type { Settings } from "../../mechanisms/settings.js";
@@ -75,6 +77,12 @@ export function adminUsersRoutes(deps: AdminRouteDeps): Hono<AppEnv> {
auth: "user",
order: 40,
},
+ {
+ id: "admin-api.plugin-config",
+ prefix: "/api/admin/plugin-config",
+ auth: "user",
+ order: 45,
+ },
],
},
})
@@ -83,9 +91,12 @@ export class AdminRoutes {
@Use() private readonly desktop!: Desktop;
@Use() private readonly proxy!: Proxy;
@Use() private readonly settings!: Settings;
+ @Use() private readonly pluginConfigAdmin!: PluginConfigAdmin;
@Bind("admin-api.users") usersRoutes!: Hono<AppEnv>;
@Bind("admin-api.settings") settingsRoutes!: Hono<AppEnv>;
+ @Bind("admin-api.plugin-config") pluginConfigRoutes!: Hono<AppEnv>;
setup() {
+ this.pluginConfigRoutes = adminPluginConfigRoutes(this.pluginConfigAdmin);
this.usersRoutes = adminUsersRoutes({
adminService: this.admin,
desktop: this.desktop.current() as DesktopService | null,
diff --git a/packages/server/src/http/routes/chat-defaults.ts b/packages/server/src/http/routes/chat-defaults.ts
index 6a037b48..9356bb8c 100644
--- a/packages/server/src/http/routes/chat-defaults.ts
+++ b/packages/server/src/http/routes/chat-defaults.ts
@@ -7,7 +7,7 @@
*/
import { Hono } from "hono";
import { DEFAULT_CHAT_THINKING_LEVELS, isValidId } from "@prismshadow/penguin-core";
-import type { ChatDefaultsDto } from "../../api/types.js";
+import type { ChatDefaultsDto, SessionSandbox } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import { HttpError } from "../errors.js";
import { optionalEnum, optionalString, readJson, requireValidId } from "../validate.js";
@@ -20,6 +20,8 @@ export interface ChatDefaultsRouteDeps {
agentConfigService: AgentConfig;
projectConfigService: ProjectConfigStore;
access: Access;
+ /** The sandbox policy a new Session starts with (the server's settings), served beside the block. */
+ sandboxDefaults?: () => SessionSandbox;
}
export function chatDefaultsRoutes(deps: ChatDefaultsRouteDeps): Hono<AppEnv> {
@@ -29,7 +31,12 @@ export function chatDefaultsRoutes(deps: ChatDefaultsRouteDeps): Hono<AppEnv> {
// Defensive id validation.
const projectId = requireValidId(c, "projectId");
deps.access.requireProjectAccess(c.var.user.userId, projectId);
- return c.json(await deps.projectConfigService.getChatDefaults(projectId));
+ const defaults = await deps.projectConfigService.getChatDefaults(projectId);
+ const sandbox = deps.sandboxDefaults?.();
+ return c.json({
+ ...defaults,
+ ...(sandbox !== undefined ? { sandbox } : {}),
+ } satisfies ChatDefaultsDto);
});
app.put("/", async (c) => {
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index e43815ce..7c0bd131 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -39,6 +39,7 @@ import type {
SubagentMessageResponse,
RetryNowResponse,
TaskCreateResponse,
+ SessionSandbox,
} from "../../api/types.js";
import { compactionThresholdFor } from "../../services/context-breakdown.js";
import { decodeCursor } from "../../services/message-window.js";
@@ -141,6 +142,32 @@ const SESSION_TITLE_MAX = 120;
const STAT_MAX_PATHS = 100;
const STAT_MAX_PATH_LEN = 512;
+/** The composer's sandbox picks from a request body: absent, or a checked partial. */
+function parseSandboxPick(body: unknown): Partial<SessionSandbox> | undefined {
+ const raw = (body as Record<string, unknown>).sandbox;
+ if (raw === undefined) return undefined;
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
+ throw badRequest("sandbox must be an object with mode and/or network.");
+ }
+ const pick: Partial<SessionSandbox> = {};
+ const mode = optionalEnum(raw as Record<string, unknown>, "mode", [
+ "read-only",
+ "workspace-write",
+ "danger-full-access",
+ ] as const);
+ const network = optionalEnum(raw as Record<string, unknown>, "network", [
+ "open",
+ "local",
+ "none",
+ ] as const);
+ if (mode !== undefined) pick.mode = mode;
+ if (network !== undefined) pick.network = network;
+ if (mode === undefined && network === undefined) {
+ throw badRequest("sandbox must set mode and/or network.");
+ }
+ return pick;
+}
+
/** The four approval modes (shared with the chat-defaults route's validation). */
export const APPROVAL_MODES: readonly ApprovalMode[] = [
"allow-all",
@@ -545,6 +572,7 @@ export function agentSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
);
}
const approvalMode = optionalEnum(body, "approvalMode", APPROVAL_MODES);
+ const sandbox = parseSandboxPick(body);
// Creating-client hint stored on the row ("cli" from the CLI; default "web").
// Informational provenance only — lists serve every row regardless.
const client = optionalEnum(body, "client", ["web", "cli"] as const);
@@ -563,6 +591,7 @@ export function agentSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
...(provider !== undefined ? { provider } : {}),
...(workspace !== undefined ? { workspace } : {}),
...(approvalMode !== undefined ? { approvalMode } : {}),
+ ...(sandbox !== undefined ? { sandbox, isAdmin: c.var.user.isAdmin } : {}),
...(client !== undefined ? { client } : {}),
...(source !== undefined ? { source } : {}),
});
@@ -617,6 +646,7 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
const body = await readJson(c);
const approvalMode = optionalEnum(body, "approvalMode", APPROVAL_MODES);
const thinkingLevel = optionalEnum(body, "thinkingLevel", THINKING_LEVEL_NAMES);
+ const sandbox = parseSandboxPick(body);
const archivedRaw = (body as Record<string, unknown>).archived;
const archived = typeof archivedRaw === "boolean" ? archivedRaw : undefined;
const titleRaw = (body as Record<string, unknown>).title;
@@ -636,6 +666,7 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
}
if (
approvalMode === undefined &&
+ sandbox === undefined &&
thinkingLevel === undefined &&
archived === undefined &&
title === undefined
@@ -643,7 +674,7 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
throw new HttpError(
400,
"no_update",
- "No updatable field provided (approvalMode / thinkingLevel / archived / title).",
+ "No updatable field provided (approvalMode / sandbox / thinkingLevel / archived / title).",
);
}
let updated: SessionRow = { ...row };
@@ -657,6 +688,11 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
deps.sessionsRepo.updateApprovalMode(row.sessionId, approvalMode);
updated = { ...updated, approvalMode };
}
+ if (sandbox !== undefined) {
+ // Takes effect at the Session's next command: its confiner reads the row at every spawn.
+ const next = deps.sessionService.updateSandbox(row, sandbox, c.var.user.isAdmin);
+ updated = { ...updated, sandbox: next };
+ }
if (thinkingLevel !== undefined) {
// The row is what the loader applies at load; a runtime already loaded is assigned
// here. Soft-limited: core applies it from the Session's very next LLM request (the
@@ -713,6 +749,8 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
modelId: row.modelId,
workspace: row.workspace,
approvalMode: row.approvalMode,
+ // A fork carries the source's policy on, as it carries its approval mode.
+ sandbox: row.sandbox ?? null,
// insertFork replaces this with the source's current title plus its persistent number.
title: null,
client: "web",
@@ -1762,6 +1800,7 @@ export class SessionApiRoutes {
agentConfigService,
projectConfigService,
access,
+ sandboxDefaults: () => sessionService.sandboxView(sessionService.defaultSandbox()),
});
this.commandPolicyRoutes = commandPolicyRoutes({ projectConfigService, access });
this.agentsRoutes = agentsRoutes({
diff --git a/packages/server/src/mechanisms/sessions.ts b/packages/server/src/mechanisms/sessions.ts
index da378050..411d55f0 100644
--- a/packages/server/src/mechanisms/sessions.ts
+++ b/packages/server/src/mechanisms/sessions.ts
@@ -6,6 +6,7 @@ import type { Opaque } from "@prismshadow/penguin-core/kernel";
import type { SessionSource, ApprovalMode } from "../api/types.js";
import type { SessionRow } from "../db/repos/sessions.js";
import type { ThinkingLevelName } from "@prismshadow/penguin-core";
+import type { SandboxSettings } from "@prismshadow/penguin-core/plugin";
import type { ScheduleStateRow } from "../db/repos/schedules.js";
import type { ScheduleFileCache } from "../runtime/schedule-store.js";
import type { ScheduleEntryView } from "../runtime/scheduler.js";
@@ -23,6 +24,7 @@ export abstract class SessionIndex extends Interface<{
listByAgent(projectId: string, agentId: string): SessionRow[];
listByProject(projectId: string): SessionRow[];
updateApprovalMode(sessionId: string, mode: ApprovalMode): void;
+ updateSandbox(sessionId: string, sandbox: SandboxSettings): void;
updateThinkingLevel(sessionId: string, level: ThinkingLevelName): void;
updateTitle(sessionId: string, title: string): void;
updateTitleIfNull(sessionId: string, title: string): void;
diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.ts
index a1f81877..0c9868a9 100644
--- a/packages/server/src/platform.ts
+++ b/packages/server/src/platform.ts
@@ -46,6 +46,12 @@ import { QQTransportProvider } from "./runtime/messaging/qq-connector.js";
import { QQScanTransportProvider } from "./runtime/messaging/qq-scan.js";
import { WeChatTransportProvider } from "./runtime/messaging/wechat-connector.js";
import { WeChatScanTransportProvider } from "./runtime/messaging/wechat-scan.js";
+import {
+ PluginConfig,
+ PluginConfigAdmin,
+ PluginConfigPage,
+ PluginConfigProvider,
+} from "./plugin/config.js";
import {
CoreSessionLoaders,
DefaultTitleGenerators,
@@ -103,6 +109,7 @@ import { MemoryService } from "./services/memory-service.js";
import { BenchmarkService } from "./services/benchmark-service.js";
import { ProjectsRoutes } from "./http/routes/dirs.js";
import { SandboxModule } from "./sandbox/service.js";
+import { SandboxSettings, SandboxSettingsStatus } from "./sandbox/settings-store.js";
import { SchedulerRoutes } from "./http/routes/schedules.js";
import { Machines, MachinesModule } from "./machines/service.js";
import { OrganizationModule, OrgScheduler, OrgService } from "./runtime/organization/service.js";
@@ -323,6 +330,28 @@ export class SessionRuntimeModule {}
})
export class SettingsModule {}
+/**
+ * Plugin configuration as a group of its own, beside the settings it is stored in: a plugin
+ * that stands in for the settings group replaces the store, not the schema-and-watch layer
+ * over it, and a plugin's manifest names this module as where `PluginConfig` comes from.
+ */
+@Module({
+ children: [PluginConfigProvider, PluginConfigPage],
+ exports: [PluginConfig, PluginConfigAdmin],
+})
+export class PluginConfigModule {}
+
+/**
+ * Sandbox settings as a group of their own: the sandbox service boots on the capability-free
+ * floor, while its settings group and the node applying it need plugin configuration (and
+ * through it the database), so they sit above it.
+ */
+@Module({
+ children: [SandboxSettings, SandboxSettingsStatus],
+ exports: [],
+})
+export class SandboxSettingsModule {}
+
@Module({
children: [ErrorsRepo, ErrorRecorder, UsageRepo, UsageRecorder, UsageService],
exports: [ErrorLog, Errors, UsageStore, UsageRecording, UsageQueries],
@@ -409,6 +438,7 @@ export class ApiModule {}
children: [
RuntimeModule,
SettingsModule,
+ PluginConfigModule,
IdentityModule,
ProjectsModule,
SessionRuntimeModule,
@@ -420,6 +450,7 @@ export class ApiModule {}
CompanyModule,
ApiModule,
SandboxModule,
+ SandboxSettingsModule,
TerminalModule,
MachinesModule,
Startup,
diff --git a/packages/server/src/plugin/config.ts b/packages/server/src/plugin/config.ts
new file mode 100644
index 00000000..f7ceea05
--- /dev/null
+++ b/packages/server/src/plugin/config.ts
@@ -0,0 +1,618 @@
+/**
+ * Plugin configuration: the settings a module DECLARES and the values an admin gives them on
+ * the Settings dialog's Plugins page, stored server-wide and read back by the declaring module
+ * itself through the `PluginConfig` mechanism (a module `requires` it from `PluginConfigModule`).
+ *
+ * A declaration is a contribution to `PluginConfigProvider.groups`: pure manifest data, so a
+ * plugin's lands in its generated `ifaces.json` beside every other contribution, and the page
+ * can list and validate it without running the package. Its shape is VS Code's
+ * `contributes.configuration` cut down to what a settings page can draw without knowing the
+ * module — a titled group of fields (a string, a secret, a boolean, a number, a choice among
+ * options, or a list of lines) — plus a `parent` that draws the group inside another's card.
+ * The group's name is the contribution's id. A group whose status changes at run time (the
+ * sandbox's backends) contributes that as code to `PluginConfigPage.status`.
+ *
+ * Values live in `server_settings` under `plugin-config:<group>`, one JSON document per group
+ * — server-global, like the proxy: plugins load once per process (the closure over every
+ * Project's list, PRFC-0010), so their options are the process's too. A secret is stored in
+ * the clear beside the other settings the server keeps and is masked at every API surface; a
+ * masked value sent back keeps the stored one, the models-page rule.
+ *
+ * Delivery is a pull. The module that declared a group reads it: `get` merges what is stored
+ * onto the declared defaults, so a first boot reads a complete document; `watch` fires after
+ * every save, which is how a module applies an edit without a restart or a re-assembly of the
+ * App. Nothing else carries the values on its behalf, so each reader turns the document into
+ * its own typed settings at its own boundary. Declaring data on the slot does not order the
+ * boot (a data-only contribution), which is what lets one module both declare and require.
+ *
+ * Two nodes, for the same ordering reason. `PluginConfigProvider` holds the values and takes
+ * the declarations; `PluginConfigPage` is what the admin API reads — the entries with their
+ * live notices — and takes the status code. A status contributor (the sandbox's, which reads
+ * the sandbox service) is created before the page, and a sandbox backend reading its own
+ * group is created after the provider: one node for both would close that circle.
+ */
+import { Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";
+import type { ClassCtx, Slot } from "@prismshadow/penguin-core/kernel";
+import type {
+ PluginConfigEntry,
+ PluginConfigField,
+ PluginConfigNotice,
+ PluginConfiguration,
+} from "../api/types.js";
+import { Settings } from "../mechanisms/settings.js";
+import { maskApiKey } from "../services/project-config-service.js";
+
+export type { PluginConfigField, PluginConfigNotice, PluginConfiguration } from "../api/types.js";
+
+const FIELD_TYPES = new Set<PluginConfigField["type"]>([
+ "string",
+ "secret",
+ "boolean",
+ "number",
+ "enum",
+ "list",
+]);
+
+/** A field name: what the manifest and the stored document are keyed by. */
+const FIELD_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;
+
+/**
+ * Validates a declared configuration. Undefined when there is none; a malformed one throws,
+ * naming where it was declared — a schema the page cannot draw is
+ * a load failure of that plugin, not something to guess at.
+ */
+export function parsePluginConfiguration(
+ doc: unknown,
+ where: string,
+): PluginConfiguration | undefined {
+ if (doc === undefined) return undefined;
+ if (doc === null || typeof doc !== "object" || Array.isArray(doc)) {
+ throw new Error(`${where}: configuration must be an object`);
+ }
+ const d = doc as Record<string, unknown>;
+ const str = (key: string): string | undefined => {
+ const v = d[key];
+ if (v === undefined) return undefined;
+ if (typeof v !== "string") throw new Error(`${where}: configuration.${key} must be a string`);
+ return v;
+ };
+ if (d.properties === null || typeof d.properties !== "object" || Array.isArray(d.properties)) {
+ throw new Error(`${where}: configuration.properties must be an object of fields`);
+ }
+ const properties: Record<string, PluginConfigField> = {};
+ for (const [name, raw] of Object.entries(d.properties as Record<string, unknown>)) {
+ if (!FIELD_NAME.test(name)) {
+ throw new Error(`${where}: configuration field "${name}" is not a valid name`);
+ }
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
+ throw new Error(`${where}: configuration.properties.${name} must be an object`);
+ }
+ const f = raw as Record<string, unknown>;
+ const type = f.type;
+ if (typeof type !== "string" || !FIELD_TYPES.has(type as PluginConfigField["type"])) {
+ throw new Error(
+ `${where}: configuration.properties.${name}.type must be one of ${[...FIELD_TYPES].join(", ")}`,
+ );
+ }
+ if (typeof f.title !== "string" || f.title === "") {
+ throw new Error(`${where}: configuration.properties.${name}.title is required`);
+ }
+ const field: PluginConfigField = { type: type as PluginConfigField["type"], title: f.title };
+ for (const key of ["titleZh", "description", "descriptionZh", "placeholder"] as const) {
+ const v = f[key];
+ if (v === undefined) continue;
+ if (typeof v !== "string") {
+ throw new Error(`${where}: configuration.properties.${name}.${key} must be a string`);
+ }
+ field[key] = v;
+ }
+ if (field.type === "enum") {
+ const options = f.options;
+ if (!Array.isArray(options) || options.length === 0) {
+ throw new Error(`${where}: configuration.properties.${name}.options must list the choices`);
+ }
+ field.options = options.map((o, i) => {
+ const opt = (o ?? {}) as Record<string, unknown>;
+ if (typeof opt.value !== "string" || typeof opt.title !== "string") {
+ throw new Error(
+ `${where}: configuration.properties.${name}.options[${i}] needs a string value and title`,
+ );
+ }
+ return {
+ value: opt.value,
+ title: opt.title,
+ ...(typeof opt.titleZh === "string" ? { titleZh: opt.titleZh } : {}),
+ };
+ });
+ }
+ if (field.type === "list" && f.maxItems !== undefined) {
+ if (typeof f.maxItems !== "number" || !Number.isInteger(f.maxItems) || f.maxItems < 1) {
+ throw new Error(
+ `${where}: configuration.properties.${name}.maxItems must be a positive integer`,
+ );
+ }
+ field.maxItems = f.maxItems;
+ }
+ if (field.type === "number") {
+ for (const key of ["minimum", "maximum"] as const) {
+ const v = f[key];
+ if (v === undefined) continue;
+ if (typeof v !== "number" || !Number.isFinite(v)) {
+ throw new Error(`${where}: configuration.properties.${name}.${key} must be a number`);
+ }
+ field[key] = v;
+ }
+ }
+ if ((field.type === "string" || field.type === "list") && f.pattern !== undefined) {
+ if (typeof f.pattern !== "string") {
+ throw new Error(`${where}: configuration.properties.${name}.pattern must be a string`);
+ }
+ try {
+ new RegExp(f.pattern, "u");
+ } catch {
+ throw new Error(
+ `${where}: configuration.properties.${name}.pattern is not a valid regular expression`,
+ );
+ }
+ field.pattern = f.pattern;
+ if (f.patternErrorMessage !== undefined) {
+ if (typeof f.patternErrorMessage !== "string") {
+ throw new Error(
+ `${where}: configuration.properties.${name}.patternErrorMessage must be a string`,
+ );
+ }
+ field.patternErrorMessage = f.patternErrorMessage;
+ }
+ }
+ if (f.required !== undefined) {
+ if (typeof f.required !== "boolean") {
+ throw new Error(`${where}: configuration.properties.${name}.required must be a boolean`);
+ }
+ field.required = f.required;
+ }
+ if (f.default !== undefined) {
+ if (!valueFits(field, f.default) || valueViolation(name, field, f.default) !== undefined) {
+ throw new Error(
+ `${where}: configuration.properties.${name}.default does not fit a ${field.type} field`,
+ );
+ }
+ field.default = f.default as PluginConfigField["default"];
+ }
+ properties[name] = field;
+ }
+ return {
+ ...(str("title") !== undefined ? { title: str("title")! } : {}),
+ ...(str("titleZh") !== undefined ? { titleZh: str("titleZh")! } : {}),
+ ...(str("description") !== undefined ? { description: str("description")! } : {}),
+ ...(str("descriptionZh") !== undefined ? { descriptionZh: str("descriptionZh")! } : {}),
+ properties,
+ };
+}
+
+/** Whether a value is of a field's type (a Project is named by its id, a string). */
+export function valueFits(field: PluginConfigField, value: unknown): boolean {
+ switch (field.type) {
+ case "boolean":
+ return typeof value === "boolean";
+ case "number":
+ return typeof value === "number" && Number.isFinite(value);
+ case "enum":
+ return typeof value === "string" && (field.options ?? []).some((o) => o.value === value);
+ case "list":
+ return Array.isArray(value) && value.every((v) => typeof v === "string");
+ default:
+ return typeof value === "string";
+ }
+}
+
+/**
+ * Why a value of the right type is still refused — outside the field's range, or a value (a
+ * list's line) that does not match its pattern — or undefined when it is accepted.
+ */
+export function valueViolation(
+ name: string,
+ field: PluginConfigField,
+ value: unknown,
+): string | undefined {
+ if (typeof value === "number") {
+ if (field.minimum !== undefined && value < field.minimum) {
+ return `"${name}" must be at least ${field.minimum}`;
+ }
+ if (field.maximum !== undefined && value > field.maximum) {
+ return `"${name}" must be at most ${field.maximum}`;
+ }
+ return undefined;
+ }
+ if (field.pattern === undefined) return undefined;
+ const pattern = new RegExp(field.pattern, "u");
+ const bad = (Array.isArray(value) ? value : [value]).find(
+ (v) => typeof v === "string" && !pattern.test(v),
+ );
+ if (bad === undefined) return undefined;
+ return field.patternErrorMessage !== undefined
+ ? `"${name}" ${field.patternErrorMessage}: ${bad}`
+ : `"${name}" does not match ${field.pattern}: ${bad}`;
+}
+
+/** The schema's defaults, as the document a plugin with nothing stored reads. */
+export function defaultsOf(schema: PluginConfiguration): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ for (const [name, field] of Object.entries(schema.properties)) {
+ if (field.default !== undefined) out[name] = field.default;
+ }
+ return out;
+}
+
+/** A stored document as it may leave the server: every secret masked, everything else as is. */
+export function maskValues(
+ schema: PluginConfiguration,
+ values: Record<string, unknown>,
+): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ for (const [name, field] of Object.entries(schema.properties)) {
+ const v = values[name];
+ if (v === undefined) continue;
+ out[name] = field.type === "secret" && typeof v === "string" && v !== "" ? maskApiKey(v) : v;
+ }
+ return out;
+}
+
+/** What `set` refuses, with the field it refuses. */
+export class PluginConfigError extends Error {
+ constructor(
+ readonly field: string | null,
+ message: string,
+ ) {
+ super(message);
+ this.name = "PluginConfigError";
+ }
+}
+
+/**
+ * One update, validated against the schema and folded onto the stored document.
+ *
+ * Every field the request names is checked for its type; a secret sent as the masked value
+ * the page read keeps what is stored, an empty string or null clears it; a required field
+ * may not end up empty. Fields the request omits keep their stored value, so a page can
+ * save one field at a time.
+ */
+export function applyUpdate(
+ schema: PluginConfiguration,
+ stored: Record<string, unknown>,
+ update: Record<string, unknown>,
+): Record<string, unknown> {
+ const next = { ...stored };
+ for (const [name, value] of Object.entries(update)) {
+ const field = schema.properties[name];
+ if (field === undefined)
+ throw new PluginConfigError(name, `"${name}" is not a field of this configuration`);
+ if (value === null || value === "") {
+ delete next[name];
+ continue;
+ }
+ if (field.type === "secret" && typeof value === "string") {
+ const current = stored[name];
+ if (typeof current === "string" && current !== "" && value === maskApiKey(current)) continue;
+ }
+ if (!valueFits(field, value)) {
+ throw new PluginConfigError(
+ name,
+ field.type === "enum"
+ ? `"${name}" must be one of ${(field.options ?? []).map((o) => o.value).join(", ")}`
+ : field.type === "list"
+ ? `"${name}" must be a list of strings`
+ : `"${name}" must be a ${field.type}`,
+ );
+ }
+ if (field.type === "list") {
+ const items = [...new Set((value as string[]).map((v) => v.trim()).filter((v) => v !== ""))];
+ if (field.maxItems !== undefined && items.length > field.maxItems) {
+ throw new PluginConfigError(name, `"${name}" may hold at most ${field.maxItems} entries`);
+ }
+ const violation = valueViolation(name, field, items);
+ if (violation !== undefined) throw new PluginConfigError(name, violation);
+ if (items.length === 0) delete next[name];
+ else next[name] = items;
+ continue;
+ }
+ next[name] = typeof value === "string" ? value.trim() : value;
+ if (next[name] === "") {
+ delete next[name];
+ continue;
+ }
+ const violation = valueViolation(name, field, next[name]);
+ if (violation !== undefined) throw new PluginConfigError(name, violation);
+ }
+ for (const [name, field] of Object.entries(schema.properties)) {
+ if (field.required === true && next[name] === undefined && field.default === undefined) {
+ throw new PluginConfigError(name, `"${name}" is required`);
+ }
+ }
+ return next;
+}
+
+/** A settings group as a module declares it: a configuration, and where the page draws it. */
+export interface SettingsGroupDecl extends PluginConfiguration {
+ /** Another group's name (its contribution id): this one is drawn inside that card and saved with it. */
+ parent?: string;
+ /** Position among the groups: lower first (absent = 100), then declaration order. */
+ order?: number;
+}
+
+/** One settings group as the store holds it: named by its contribution id. */
+export interface SettingsGroup {
+ name: string;
+ configuration: PluginConfiguration;
+ parent?: string;
+}
+
+/**
+ * The code half of a `status` contribution: a group's live notices, asked per read, and the
+ * ACTIONS it offers.
+ *
+ * An action is for what a person cannot express as a field: something the deployment must DO
+ * once, on the machine, before the settings above mean anything — the Windows sandbox's local
+ * accounts, which need an administrator's consent. Naming the command in a notice puts the work
+ * on whoever reads it; an action lets the module do it and report back.
+ */
+export interface SettingsGroupStatus {
+ notices(): PluginConfigNotice[];
+ /**
+ * After a save of this group or of one drawn inside its card: does what that save sets in
+ * motion beyond the group's own watchers, and resolves once it has settled, so the notices
+ * the save answers with are current.
+ */
+ saved?(): Promise<void>;
+ /** What this group offers to do, drawn as buttons beneath its notices. */
+ actions?(): PluginConfigAction[];
+ /**
+ * Enum options this machine cannot honour right now: drawn greyed out with the reason, and a
+ * save choosing one is refused. Asked per read, like the notices.
+ */
+ unavailable?(): PluginConfigUnavailable[];
+ /** Runs one, by its id. Told what happened, in words the page shows as they are. */
+ run?(action: string): Promise<PluginConfigActionResult>;
+}
+
+/** One enum option a settings group cannot honour on this machine, and why. */
+export interface PluginConfigUnavailable {
+ field: string;
+ value: string;
+ reason: string;
+ reasonZh?: string;
+}
+
+/** One thing a settings group can do, named for the button that runs it. */
+export interface PluginConfigAction {
+ id: string;
+ title: string;
+ titleZh?: string;
+ /** What pressing it will do, shown beside the button — a person consents to what they read. */
+ description?: string;
+ descriptionZh?: string;
+}
+
+/** What an action reports: whether it did what it said, and what to tell the person. */
+export interface PluginConfigActionResult {
+ ok: boolean;
+ message: string;
+ messageZh?: string;
+ /**
+ * Work the action started and did not wait for, reported through `progress` notices; it
+ * resolves when that work ends. The page node then settles the card the way a save does (a
+ * sandbox backend the work made usable loads again). Never sent to the page.
+ */
+ settled?: Promise<void>;
+}
+
+/** What a module reads: the group it declared, and a watch on it. */
+@Interface()
+export abstract class PluginConfig {
+ /** The stored values merged onto the declared defaults; `{}` for a name no group answers to. */
+ abstract get(name: string): Record<string, unknown>;
+ /** Fires with the new document after every save of `name`; returns the unsubscribe. */
+ abstract watch(name: string, cb: (values: Record<string, unknown>) => void): () => void;
+ /** Whether anything was ever saved under `name` — what tells a default from a choice. */
+ abstract saved(name: string): boolean;
+}
+
+export interface PluginConfigSlots {
+ /** A settings group, as data: its id is its name, the data its configuration. */
+ groups: Slot<SettingsGroupDecl>;
+}
+
+/** The entries as stored, before any live notice: what the page node builds on. */
+@Interface()
+export abstract class PluginConfigEntries {
+ abstract describe(): PluginConfigEntry[];
+ abstract set(name: string, update: Record<string, unknown>): PluginConfigEntry;
+}
+
+/** What the settings page reads and writes. */
+@Interface()
+export abstract class PluginConfigAdmin {
+ /** Every declared group, in order, with its live notices; values masked. */
+ abstract describe(): PluginConfigEntry[];
+ /** Validates and stores one update; answers that entry, masked, with its notices once its card's status has settled. */
+ abstract set(name: string, update: Record<string, unknown>): Promise<PluginConfigEntry>;
+ /** Runs one group's action and says what happened; throws PluginConfigError for an unknown one. */
+ abstract run(name: string, action: string): Promise<PluginConfigActionResult>;
+}
+
+export interface PluginConfigAdminSlots {
+ /** Live notices for a group that has any (`group` names it). */
+ status: Slot<{ group: string }, SettingsGroupStatus>;
+}
+
+export interface PluginConfigStoreDeps {
+ settings: Pick<Settings, "get" | "set">;
+ groups: () => readonly SettingsGroup[];
+}
+
+export class PluginConfigStore {
+ private readonly watchers = new Map<string, Set<(values: Record<string, unknown>) => void>>();
+
+ constructor(private readonly deps: PluginConfigStoreDeps) {}
+
+ private group(name: string): SettingsGroup | undefined {
+ return this.deps.groups().find((g) => g.name === name);
+ }
+
+ private stored(name: string): Record<string, unknown> {
+ const raw = this.deps.settings.get(`plugin-config:${name}`);
+ if (raw === null) return {};
+ try {
+ const doc = JSON.parse(raw) as unknown;
+ return doc !== null && typeof doc === "object" && !Array.isArray(doc)
+ ? (doc as Record<string, unknown>)
+ : {};
+ } catch {
+ return {};
+ }
+ }
+
+ get(name: string): Record<string, unknown> {
+ const group = this.group(name);
+ if (group === undefined) return {};
+ return { ...defaultsOf(group.configuration), ...this.stored(name) };
+ }
+
+ saved(name: string): boolean {
+ return this.deps.settings.get(`plugin-config:${name}`) !== null;
+ }
+
+ watch(name: string, cb: (values: Record<string, unknown>) => void): () => void {
+ const set = this.watchers.get(name) ?? new Set();
+ set.add(cb);
+ this.watchers.set(name, set);
+ return () => void set.delete(cb);
+ }
+
+ describe(): PluginConfigEntry[] {
+ return this.deps.groups().map((g) => this.entry(g));
+ }
+
+ set(name: string, update: Record<string, unknown>): PluginConfigEntry {
+ const group = this.group(name);
+ if (group === undefined) {
+ throw new PluginConfigError(null, `no settings group named "${name}"`);
+ }
+ const next = applyUpdate(group.configuration, this.stored(name), update);
+ this.deps.settings.set(`plugin-config:${name}`, JSON.stringify(next));
+ const merged = { ...defaultsOf(group.configuration), ...next };
+ for (const cb of this.watchers.get(name) ?? []) {
+ try {
+ cb(merged);
+ } catch {
+ // A watcher's failure is its own; the save has happened.
+ }
+ }
+ return this.entry(group);
+ }
+
+ private entry(group: SettingsGroup): PluginConfigEntry {
+ const { name, configuration } = group;
+ return {
+ name,
+ configuration,
+ values: maskValues(configuration, { ...defaultsOf(configuration), ...this.stored(name) }),
+ ...(group.parent !== undefined ? { parent: group.parent } : {}),
+ };
+ }
+}
+
+/** The store as a node: values in the settings repo, groups from the declarations on its slot. */
+@Module()
+export class PluginConfigProvider {
+ @Use() private readonly settings!: Settings;
+ @Provide() pluginConfig!: PluginConfig;
+ @Provide() pluginConfigEntries!: PluginConfigEntries;
+ setup({ contributions }: ClassCtx) {
+ const declared: Array<SettingsGroup & { order: number; index: number }> = [];
+ for (const [index, c] of (contributions.groups ?? []).entries()) {
+ const { parent, order, ...configuration } = c.data as unknown as SettingsGroupDecl;
+ try {
+ const parsed = parsePluginConfiguration(configuration, `${c.from}: group "${c.id}"`)!;
+ declared.push({
+ name: c.id,
+ configuration: parsed,
+ ...(typeof parent === "string" ? { parent } : {}),
+ order: typeof order === "number" ? order : 100,
+ index,
+ });
+ } catch (err) {
+ // One malformed declaration drops that group, not the page.
+ console.warn(`[plugin-config] ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+ declared.sort((a, b) => a.order - b.order || a.index - b.index);
+ const groups: SettingsGroup[] = declared.map(({ name, configuration, parent }) => ({
+ name,
+ configuration,
+ ...(parent !== undefined ? { parent } : {}),
+ }));
+ const store = new PluginConfigStore({ settings: this.settings, groups: () => groups });
+ this.pluginConfig = store;
+ this.pluginConfigEntries = store;
+ }
+}
+
+/** The page's view: the stored entries with the live notices their status contributors report. */
+@Module()
+export class PluginConfigPage {
+ @Use() private readonly entries!: PluginConfigEntries;
+ @Provide() pluginConfigAdmin!: PluginConfigAdmin;
+ setup({ contributions }: ClassCtx) {
+ const entries = this.entries;
+ const status = new Map<string, SettingsGroupStatus>();
+ for (const c of contributions.status ?? []) {
+ status.set(c.data.group as string, c.code as SettingsGroupStatus);
+ }
+ const withStatus = (entry: PluginConfigEntry): PluginConfigEntry => {
+ const group = status.get(entry.name);
+ const notices = group?.notices() ?? [];
+ const actions = group?.actions?.() ?? [];
+ const unavailable = group?.unavailable?.() ?? [];
+ return {
+ ...entry,
+ ...(notices.length > 0 ? { notices } : {}),
+ ...(actions.length > 0 ? { actions } : {}),
+ ...(unavailable.length > 0 ? { unavailable } : {}),
+ };
+ };
+ this.pluginConfigAdmin = {
+ describe: () => entries.describe().map(withStatus),
+ set: async (name, update) => {
+ // An option this machine cannot honour is refused like an invalid value, naming it.
+ for (const u of status.get(name)?.unavailable?.() ?? []) {
+ if (update[u.field] === u.value) {
+ throw new PluginConfigError(
+ u.field,
+ `"${u.field}" cannot be "${u.value}" here: ${u.reason}`,
+ );
+ }
+ }
+ const saved = entries.set(name, update);
+ await status.get(saved.parent ?? name)?.saved?.();
+ return withStatus(saved);
+ },
+ run: async (name, action) => {
+ const group = status.get(name);
+ const offered = group?.actions?.() ?? [];
+ if (group?.run === undefined || !offered.some((a) => a.id === action)) {
+ throw new PluginConfigError(null, `"${name}" offers no action "${action}".`);
+ }
+ const { settled, ...result } = await group.run(action);
+ // What the action changed on the machine is settled like a save of its card: the
+ // owner's status runs its follow-up (a backend that failed its check loads again).
+ const owner = entries.describe().find((e) => e.name === name)?.parent ?? name;
+ const settle = async () => {
+ await status.get(owner)?.saved?.();
+ };
+ if (settled === undefined) await settle();
+ else void settled.then(settle, settle).catch(() => {});
+ return result;
+ },
+ };
+ }
+}
diff --git a/packages/server/src/plugin/index.ts b/packages/server/src/plugin/index.ts
index 1deb2173..96e2aa9d 100644
--- a/packages/server/src/plugin/index.ts
+++ b/packages/server/src/plugin/index.ts
@@ -16,5 +16,12 @@ export type { Sessions, SessionServiceIface } from "../runtime/session-manager.j
export type { AgentService } from "../services/agent-service.js";
export type { AgentConfigService } from "../services/agent-config-service.js";
export type { Messaging, MessagingSlots } from "../runtime/messaging/bridge.js";
+export type {
+ PluginConfig,
+ PluginConfigField,
+ PluginConfiguration,
+ PluginConfigSlots,
+ SettingsGroupDecl,
+} from "./config.js";
export type { Http, HttpSlots } from "../http/app.js";
export type { WebShell, WebShellSlots } from "../http/routes/contributions.js";
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index a467a550..e9cb622d 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -261,7 +261,7 @@ export function createCoreSessionLoader(
proxyEnv?: () => ProxyEnvPolicy | null;
controlEnv?: (ctx: ControlEnvContext) => Record<string, string>;
pathPrepend?: () => string[];
- confineSpawn?: () => SpawnConfiner | null;
+ confineSpawn?: (ctx: ControlEnvContext) => SpawnConfiner | null;
assembly?: AgentAssembly;
} = {},
): SessionLoader {
@@ -639,6 +639,17 @@ function isPlainText(role: "user" | "assistant") {
export class SessionManager {
private readonly entries = new Map<string, RuntimeEntry>();
+ /**
+ * Each registered subagent Session's ROOT Session: a subagent runs under its root's
+ * sandbox policy, as it runs under its root's approval mode, so a change the person makes
+ * in the composer reaches the children already running.
+ */
+ private readonly childRoots = new Map<string, string>();
+
+ /** The Session whose policy governs `sessionId`: its root for a subagent, else itself. */
+ rootSessionOf(sessionId: string): string {
+ return this.childRoots.get(sessionId) ?? sessionId;
+ }
/** Per-Session mutex (serializes get-or-load and status flips); auto-cleaned once the chain drains. */
private readonly locks = new Map<string, Promise<unknown>>();
private readonly log: (line: string) => void;
@@ -2077,6 +2088,8 @@ export class SessionManager {
// row deliberately stores no source column.
const source = asSessionSource(p.source) ?? "subagent";
this.deps.sources.set(childSid, source);
+ const root = this.rootSessionOf(entry.sessionId);
+ this.childRoots.set(childSid, root);
const createdAt = this.now().toISOString();
// A sub-session of an organization's Session is company mode's own as much as the desk
// or ticket session that spawned it: it inherits the durable "org" stamp, which is the
@@ -2095,6 +2108,9 @@ export class SessionManager {
// A subagent's approvals are inherited from the parent Session; the index row is
// inserted with defaults (matches the convention for Sessions discovered by the CLI).
approvalMode: "allow-all",
+ // The root's policy at registration, so the child row stands on its own if it is ever
+ // resumed directly; while registered it follows the root (see rootSessionOf).
+ sandbox: this.deps.sessions.findById(root)?.sandbox ?? null,
title: null,
...(parentClient === "org" ? { client: "org" as const } : {}),
// Its Trace exists by construction.
@@ -2298,6 +2314,8 @@ export abstract class SessionServiceIface extends Interface<
| "listSessions"
| "sessionStats"
| "createSession"
+ | "defaultSandbox"
+ | "updateSandbox"
| "latestTracePath"
| "adoptUnmanagedTraceSessions"
>
@@ -2309,7 +2327,7 @@ export abstract class SessionEnv extends Interface<{
controlEnv(ctx: ControlEnvContext): Record<string, string>;
/** The directories at the FRONT of every command's PATH: the harness's own CLI shim (see CreateAgentOptions.pathPrepend). */
pathPrepend(): string[];
- confineSpawn(): SpawnConfiner | null;
+ confineSpawn(ctx: ControlEnvContext): SpawnConfiner | null;
}>() {}
@Module()
@@ -2397,7 +2415,18 @@ export class SessionsModule {
// this field publishes a config without it and wrote no shim either: no field, no
// directory, feature off, rather than a push declined over a PATH entry.
pathPrepend: (): string[] => (config.cliEntry ? [cliShimDir(config.root)] : []),
- confineSpawn: () => sandbox.confiner(),
+ // Each Session confines under its OWN policy — the snapshot on its row, its root's for a
+ // subagent — so a settings change reaches only Sessions created after it. A row from
+ // before snapshots takes the settings at its first command and keeps them from then on.
+ confineSpawn: (ctx: ControlEnvContext) =>
+ sandbox.confinerFor(() => {
+ const root = manager.rootSessionOf(ctx.sessionId);
+ const row = sessionsRepo.findById(root);
+ if (row?.sandbox) return row.sandbox;
+ const snapshot = sandbox.currentSettings();
+ if (row !== null) sessionsRepo.updateSandbox(root, snapshot);
+ return snapshot;
+ }),
};
const notifyProjectUsers = (projectId: string, event: ServerEvent): void => {
@@ -2464,6 +2493,9 @@ export class SessionsModule {
pathPrepend: env.pathPrepend,
confineSpawn: env.confineSpawn,
assembly,
+ sandboxDefaults: () => sandbox.currentSettings(),
+ sandboxLocalNetwork: () =>
+ sandbox.backends().some((b) => b.dimensions.includes("network-local")),
});
this.manager = manager;
this.sessionService = sessionService;
diff --git a/packages/server/src/sandbox/service.ts b/packages/server/src/sandbox/service.ts
index e7b41896..bf92f152 100644
--- a/packages/server/src/sandbox/service.ts
+++ b/packages/server/src/sandbox/service.ts
@@ -28,19 +28,43 @@ interface MountedProvider {
provider: SandboxProvider;
}
+/** How one registration's latest load settled. */
+type LoadOutcome = { provider: SandboxProvider } | { declined: true } | { error: string };
+
+interface Registration {
+ name: string;
+ source: SandboxProviderSource;
+ outcome?: LoadOutcome;
+ /** Counts the loads started; only the latest one's outcome is recorded. */
+ attempts: number;
+}
+
+/** Settles one load: a provider, a decline (null), or the failure's message. */
+function settle(source: SandboxProviderSource): Promise<LoadOutcome> {
+ return Promise.resolve()
+ .then(() => (typeof source === "function" ? source() : source))
+ .then(
+ (provider): LoadOutcome =>
+ provider === null || provider === undefined ? { declined: true } : { provider },
+ (err: unknown): LoadOutcome => ({ error: err instanceof Error ? err.message : String(err) }),
+ );
+}
+
export class SandboxService {
- private readonly mounted: MountedProvider[] = [];
+ private mounted: MountedProvider[] = [];
/**
* name → why it FAILED: it could not load, or failed its check on a host it is meant for —
- * never silently absent. Surfaced in the fail-closed message.
+ * never silently absent. Surfaced in the fail-closed message and on the settings card.
*/
- private readonly loadErrors = new Map<string, string>();
+ private loadErrors = new Map<string, string>();
/**
* The backends that declined: this host is not theirs (a Linux backend on Windows). Nothing
* is wrong with a deployment that installs one backend per platform, so a decline is not a
* failure — it is listed only when NO backend serves, where it is the explanation.
*/
- private readonly declinedNames: string[] = [];
+ private declinedNames: string[] = [];
+ /** Every registration in routing order, with how its latest load settled. */
+ private readonly registrations: Registration[];
/**
* Ships with confinement OFF (`danger-full-access`): the default flips to
* workspace-write together with the deployment-facing config surface, so a
@@ -58,27 +82,64 @@ export class SandboxService {
* exists for deployments flipping the mode in the first milliseconds after boot.
*/
constructor(registrations: Iterable<[string, SandboxProviderSource]> = []) {
+ const loads: Registration[] = [...registrations].map(([name, source]) => ({
+ name,
+ source,
+ attempts: 1,
+ }));
+ this.registrations = loads;
// Every source is settled at once (a backend's check runs while the others load, and a
// rejection is handled the moment it happens); the results are recorded in registration
// order, which is routing order.
- const settled = [...registrations].map(([name, source]) => ({
- name,
- result: Promise.resolve(source).then(
- (provider) => ({ provider }),
- (err: unknown) => ({ error: err instanceof Error ? err.message : String(err) }),
- ),
- }));
+ const settled = loads.map((r) => settle(r.source));
this.ready = (async () => {
- for (const { name, result } of settled) {
- const outcome = await result;
- if ("error" in outcome) this.loadErrors.set(name, outcome.error);
- else if (outcome.provider === null || outcome.provider === undefined) {
- this.declinedNames.push(name);
- } else this.mounted.push({ name, provider: outcome.provider });
+ for (const [i, result] of settled.entries()) {
+ loads[i]!.outcome = await result;
+ this.record();
}
})();
}
+ /** Rebuilds the mounted / failed / declined views from the registrations, in routing order. */
+ private record(): void {
+ const mounted: MountedProvider[] = [];
+ const errors = new Map<string, string>();
+ const declined: string[] = [];
+ for (const { name, outcome } of this.registrations) {
+ if (outcome === undefined) continue;
+ if ("provider" in outcome) mounted.push({ name, provider: outcome.provider });
+ else if ("error" in outcome) errors.set(name, outcome.error);
+ else declined.push(name);
+ }
+ this.mounted = mounted;
+ this.loadErrors = errors;
+ this.declinedNames = declined;
+ }
+
+ /**
+ * Loads again every backend whose load failed and that registered a loader (a bare promise
+ * cannot be re-run). Called after the sandbox's settings are saved: a backend whose check
+ * failed on its own setting mounts once that setting is fixed. Resolves when those settle.
+ */
+ retryFailed(): Promise<void> {
+ return this.ready.then(async () => {
+ await Promise.all(
+ this.registrations
+ .filter((r) => r.outcome !== undefined && "error" in r.outcome)
+ .filter((r) => typeof r.source === "function")
+ .map(async (r) => {
+ // Saves in quick succession each probe their own setting; an older probe that
+ // settles last must not overwrite the newer outcome.
+ const attempt = ++r.attempts;
+ const outcome = await settle(r.source);
+ if (r.attempts !== attempt) return;
+ r.outcome = outcome;
+ this.record();
+ }),
+ );
+ });
+ }
+
/** Resolves when every registered backend has loaded (or failed to). */
whenReady(): Promise<void> {
return this.ready;
@@ -104,12 +165,27 @@ export class SandboxService {
*/
parkedSettings(): SandboxSettings | undefined {
const s = this.settings;
- if (s.mode === "danger-full-access" && s.network === undefined && s.maskPaths === undefined) {
+ if (
+ s.mode === "danger-full-access" &&
+ s.network === undefined &&
+ s.maskPaths === undefined &&
+ s.writableTemp === undefined
+ ) {
return undefined;
}
return copySettings(s);
}
+ /** The backends that failed to load, each with why (diagnostics / the config surface). */
+ failures(): Array<{ name: string; reason: string }> {
+ return [...this.loadErrors].map(([name, reason]) => ({ name, reason }));
+ }
+
+ /** The backends that declined because this host is not theirs (the config surface). */
+ declined(): string[] {
+ return [...this.declinedNames];
+ }
+
/** The mounted backends and what each implements (diagnostics / the config surface). */
backends(): Array<{ name: string; dimensions: readonly SandboxDimension[] }> {
return this.mounted.map(({ name, provider }) => ({
@@ -124,8 +200,16 @@ export class SandboxService {
* serving during a hot-swap freeze window.
*/
confiner(): SpawnConfiner {
+ return this.confinerFor(() => this.settings);
+ }
+
+ /**
+ * The same closure under a policy the caller keeps — a Session's own snapshot. The
+ * backends are still this service's, so a backend change reaches every Session.
+ */
+ confinerFor(policyOf: () => SandboxSettings): SpawnConfiner {
return (argv, opts) => {
- const settings = this.settings;
+ const settings = policyOf();
const required = requestedDimensions(settings);
// Full access with nothing else asked (no network cut, no masked paths) is genuinely
// unconfined — spawn as-is. But full access that STILL cuts the network or masks a path
@@ -142,8 +226,8 @@ export class SandboxService {
...(settings.maskPaths !== undefined && settings.maskPaths.length > 0
? { maskPaths: settings.maskPaths }
: {}),
- // Always: without a writable temp directory a shell cannot start.
- writableTemp: true,
+ // On unless turned off: without a writable temp directory a shell cannot start.
+ ...(settings.writableTemp !== false ? { writableTemp: true } : {}),
};
// ConfinedArgv also carries enforcement / denialSignatures / runnerFailureRules;
// the classification consumer (denial vs runner failure) lands with escalation.
@@ -186,6 +270,7 @@ function copySettings(settings: SandboxSettings): SandboxSettings {
mode: settings.mode,
...(settings.network !== undefined ? { network: settings.network } : {}),
...(settings.maskPaths !== undefined ? { maskPaths: [...settings.maskPaths] } : {}),
+ ...(settings.writableTemp !== undefined ? { writableTemp: settings.writableTemp } : {}),
};
}
@@ -193,7 +278,16 @@ function copySettings(settings: SandboxSettings): SandboxSettings {
export abstract class Sandbox extends Interface<
Pick<
SandboxService,
- "configure" | "currentSettings" | "parkedSettings" | "backends" | "confiner" | "whenReady"
+ | "configure"
+ | "currentSettings"
+ | "parkedSettings"
+ | "backends"
+ | "failures"
+ | "declined"
+ | "retryFailed"
+ | "confiner"
+ | "confinerFor"
+ | "whenReady"
>
>() {}
@@ -213,6 +307,7 @@ export interface SandboxSlots {
mode: "'read-only'|'workspace-write'|'danger-full-access'",
"network?": "'none'|'local'",
"maskPaths?": "string[]",
+ "writableTemp?": "boolean",
},
},
},
diff --git a/packages/server/src/sandbox/settings-store.ts b/packages/server/src/sandbox/settings-store.ts
new file mode 100644
index 00000000..1208a6c7
--- /dev/null
+++ b/packages/server/src/sandbox/settings-store.ts
@@ -0,0 +1,215 @@
+/**
+ * Sandbox settings, as a settings group: the confinement every agent command spawns under is
+ * declared on `PluginConfigProvider.groups` like any module's settings, drawn on the Settings
+ * dialog's Plugins page and stored under `plugin-config:sandbox`, so a restart keeps it. A
+ * sandbox backend that has settings of its own declares its own group with `parent: "sandbox"`
+ * and reads it itself; nothing here carries a backend's values.
+ *
+ * `SandboxSettings` declares the group and applies what is stored to the service — on boot
+ * and after every save. The service stays on the capability-free floor (a bare kernel boots
+ * it with no database), and its parked context still carries the settings across a hot swap:
+ * on boot a saved document wins, and with none saved the service keeps what the swap carried.
+ * `SandboxSettingsStatus` reports, as live notices, whether the saved policy can be enforced,
+ * which backends are in use, and why each other one is not — a backend that failed to load,
+ * failed its check or runs on another platform is named with its reason, never left out. It is
+ * a code contribution, so it must not require plugin configuration itself.
+ */
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { SandboxMode, SandboxSettings as Policy } from "@prismshadow/penguin-core/plugin";
+import type { PluginConfigNotice } from "../api/types.js";
+import { PluginConfig } from "../plugin/config.js";
+import type { SettingsGroupStatus } from "../plugin/config.js";
+import { Sandbox, SandboxModule } from "./service.js";
+import { requestedDimensions } from "./dimensions.js";
+
+/** The sandbox's group name (its contribution id), and the parent a backend's group names. */
+export const SANDBOX_GROUP = "sandbox";
+
+const MODES: readonly SandboxMode[] = ["read-only", "workspace-write", "danger-full-access"];
+
+/** A stored document (defaults merged) as the service's policy. */
+export function sandboxPolicyOf(doc: Record<string, unknown>): Policy {
+ const mode = MODES.includes(doc.mode as SandboxMode)
+ ? (doc.mode as SandboxMode)
+ : "danger-full-access";
+ const maskPaths = Array.isArray(doc.maskPaths)
+ ? doc.maskPaths.filter((p): p is string => typeof p === "string" && p !== "")
+ : [];
+ return {
+ mode,
+ ...(doc.network === "none" || doc.network === "local" ? { network: doc.network } : {}),
+ ...(maskPaths.length > 0 ? { maskPaths } : {}),
+ ...(doc.writableTemp === false ? { writableTemp: false } : {}),
+ };
+}
+
+@Component({
+ contributes: {
+ "PluginConfigProvider.groups": [
+ {
+ id: "sandbox",
+ order: 0,
+ title: "Sandbox",
+ titleZh: "沙盒",
+ description:
+ "The confinement new sessions start with, enforced by a sandbox backend plugin. A session keeps the policy it started with; change it from that session's permission button.",
+ descriptionZh:
+ "新建会话的初始封禁策略,由沙盒后端插件实施。已有会话保留创建时的策略,可在该会话的权限按钮中修改。",
+ properties: {
+ mode: {
+ type: "enum",
+ title: "Confinement mode",
+ titleZh: "封禁模式",
+ default: "danger-full-access",
+ options: [
+ {
+ value: "danger-full-access",
+ title: "Off (full access)",
+ titleZh: "关闭(完全访问)",
+ },
+ { value: "workspace-write", title: "Workspace write only", titleZh: "仅工作区可写" },
+ { value: "read-only", title: "Read-only", titleZh: "只读" },
+ ],
+ },
+ network: {
+ type: "enum",
+ title: "Network",
+ titleZh: "网络",
+ description:
+ "What a confined command may reach. Local network allows only this machine's localhost, and needs a backend that can enforce it.",
+ descriptionZh:
+ "被封禁的命令能访问的网络。本地网络只允许访问本机 localhost,需要能实施它的后端。",
+ default: "open",
+ options: [
+ { value: "open", title: "Full access", titleZh: "完全访问" },
+ {
+ value: "local",
+ title: "Local network (localhost only)",
+ titleZh: "本地网络(仅本机 localhost)",
+ },
+ { value: "none", title: "No network", titleZh: "无网络" },
+ ],
+ },
+ writableTemp: {
+ type: "boolean",
+ title: "Temporary directory writable",
+ titleZh: "临时目录可写",
+ description:
+ "Confined commands may write the system temp directory, in either mode. Shells and most tools need one to start; off keeps it read-only too.",
+ descriptionZh:
+ "被封禁的命令在两种模式下都可以写系统临时目录。Shell 与大多数工具需要它才能启动;关闭后临时目录同样只读。",
+ default: true,
+ },
+ maskPaths: {
+ type: "list",
+ title: "Masked paths",
+ titleZh: "屏蔽路径",
+ description:
+ "One absolute path per line, hidden from confined commands (reads included).",
+ descriptionZh: "每行一个绝对路径,对被封禁的命令隐藏(包括读取)。",
+ maxItems: 64,
+ // POSIX `/…`, Windows `C:\…` or `C:/…`, or a UNC `\\server\…`.
+ pattern: "^(?:/|[A-Za-z]:[\\\\/]|\\\\\\\\)",
+ patternErrorMessage: "must list absolute paths",
+ },
+ },
+ },
+ ],
+ },
+})
+export class SandboxSettings {
+ @Use() private readonly pluginConfig!: PluginConfig;
+ @Use(SandboxModule) private readonly sandbox!: Sandbox;
+ setup() {
+ const { pluginConfig, sandbox } = this;
+ // A saved document wins; with none saved the service keeps what the swap carried —
+ // applying the defaults here would un-confine a deployment on every hot update.
+ if (pluginConfig.saved(SANDBOX_GROUP)) {
+ sandbox.configure(sandboxPolicyOf(pluginConfig.get(SANDBOX_GROUP)));
+ }
+ pluginConfig.watch(SANDBOX_GROUP, (doc) => sandbox.configure(sandboxPolicyOf(doc)));
+ }
+}
+
+/**
+ * The sandbox card's live notices: a warning when the saved mode needs isolation no usable
+ * backend implements (every command would be refused), the backends in use, and each backend
+ * that failed to load, with its reason. A backend that declined because this host is not its
+ * platform is no fault of the deployment — it is named only when nothing else serves, where
+ * it explains why.
+ */
+@Component({
+ contributes: {
+ "PluginConfigPage.status": [{ id: "sandbox.status", group: "sandbox" }],
+ },
+})
+export class SandboxSettingsStatus {
+ @Use(SandboxModule) private readonly sandbox!: Sandbox;
+ @Bind("sandbox.status") status!: SettingsGroupStatus;
+ setup() {
+ const sandbox = this.sandbox;
+ this.status = {
+ // A backend reads its own group (drawn inside this card) at load: after a save of the
+ // card, one that failed its check — a wrong program path — loads again, no restart.
+ saved: () => sandbox.retryFailed(),
+ // The local level needs a backend that declares it; where none does, the option is
+ // shown greyed out and a save choosing it is refused.
+ unavailable: () =>
+ sandbox.backends().some((b) => b.dimensions.includes("network-local"))
+ ? []
+ : [
+ {
+ field: "network",
+ value: "local",
+ reason: "no sandbox backend on this host supports it",
+ reasonZh: "本机的沙盒后端不支持",
+ },
+ ],
+ notices: (): PluginConfigNotice[] => {
+ const notices: PluginConfigNotice[] = [];
+ const backends = sandbox.backends();
+ const settings = sandbox.currentSettings();
+ if (settings.mode !== "danger-full-access") {
+ const required = requestedDimensions(settings);
+ const served = backends.some((b) => required.every((d) => b.dimensions.includes(d)));
+ if (!served) {
+ const needs = required.join(" + ");
+ notices.push({
+ tone: "attention",
+ text: `The saved mode needs ${needs}, and no usable backend implements it: every agent command is refused until one does.`,
+ textZh: `当前保存的模式需要 ${needs},但没有可用的后端实现它:在有后端能实施之前,Agent 的每条命令都会被拒绝。`,
+ });
+ }
+ }
+ if (backends.length === 0) {
+ const declined = sandbox.declined();
+ const elsewhere =
+ declined.length === 0
+ ? ""
+ : ` ${declined.join(", ")} ${declined.length === 1 ? "is" : "are"} installed, but for another platform.`;
+ const elsewhereZh =
+ declined.length === 0 ? "" : `已安装 ${declined.join("、")},但它们适用于其他平台。`;
+ notices.push({
+ tone: "attention",
+ text: `This deployment has no usable sandbox backend: until one for this platform is installed from the Plugins page, every mode but Off refuses every agent command.${elsewhere}`,
+ textZh: `当前部署没有可用的沙盒后端:在插件页安装适用于本平台的后端之前,除「关闭」外的任何模式都会拒绝 Agent 的每条命令。${elsewhereZh}`,
+ });
+ } else {
+ const list = backends.map((b) => `${b.name} (${b.dimensions.join(", ")})`).join(" · ");
+ notices.push({ tone: "muted", text: `Backends: ${list}`, textZh: `后端:${list}` });
+ }
+ // A failure while another backend serves is worth saying, but it is not the card's
+ // headline — confinement works. With nothing serving it is the headline.
+ const tone = backends.length === 0 ? "attention" : "muted";
+ for (const { name, reason } of sandbox.failures()) {
+ notices.push({
+ tone,
+ text: `${name} is not in use: ${reason}`,
+ textZh: `${name} 未启用:${reason}`,
+ });
+ }
+ return notices;
+ },
+ };
+ }
+}
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index 8b8ed630..862a84b7 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -27,6 +27,7 @@ import type {
SessionCategory,
SessionCategoryCounts,
SessionInfo,
+ SessionSandbox,
SessionSource,
} from "../api/types.js";
import { HttpError, isMissingCredential, modelCredentialMissing } from "../http/errors.js";
@@ -39,6 +40,75 @@ import { matchesWorkspaceGroup } from "./workspace-group.js";
import type { TraceIndex, TraceIndexStore } from "../mechanisms/traces.js";
import type { SessionIndex, SessionOrigins } from "../mechanisms/sessions.js";
import type { ProjectConfigStore } from "../mechanisms/projects.js";
+import type { SandboxSettings } from "@prismshadow/penguin-core/plugin";
+
+const SANDBOX_MODE_RANK: Record<SandboxSettings["mode"], number> = {
+ "read-only": 0,
+ "workspace-write": 1,
+ "danger-full-access": 2,
+};
+
+const SANDBOX_NETWORK_RANK: Record<SessionSandbox["network"], number> = {
+ none: 0,
+ local: 1,
+ open: 2,
+};
+
+/** A stored policy's network level as the composer names it. */
+function networkOf(policy: SandboxSettings): SessionSandbox["network"] {
+ return policy.network ?? "open";
+}
+
+/** A stored policy as the composer sees it, with whether this server can enforce `local`. */
+export function sessionSandboxOf(
+ policy: SandboxSettings,
+ localNetworkSupported = false,
+): SessionSandbox {
+ return { mode: policy.mode, network: networkOf(policy), localNetworkSupported };
+}
+
+/**
+ * `base` with the composer's picks laid over it — the mask paths and the temp directory stay
+ * what the snapshot holds. A non-admin may tighten but never loosen past the server's settings
+ * (`defaults`): the admin's sandbox is the ceiling for everyone else, per Session or not.
+ */
+export function applySandboxPick(
+ base: SandboxSettings,
+ pick: Partial<SessionSandbox>,
+ defaults: SandboxSettings,
+ isAdmin: boolean,
+ localNetworkSupported = false,
+): SandboxSettings {
+ const mode = pick.mode ?? base.mode;
+ const network = pick.network ?? networkOf(base);
+ // Picking a level no backend here can enforce would make every command fail closed; say so
+ // now instead. A policy that already holds it (a backend went away) fails at the command.
+ if (pick.network === "local" && !localNetworkSupported) {
+ throw new HttpError(
+ 400,
+ "sandbox_unsupported",
+ "No sandbox backend on this server can limit the network to localhost.",
+ );
+ }
+ if (!isAdmin) {
+ if (SANDBOX_MODE_RANK[mode] > SANDBOX_MODE_RANK[defaults.mode]) {
+ throw new HttpError(
+ 403,
+ "sandbox_forbidden",
+ `Only an administrator can give a Session more filesystem access than the server's sandbox settings (${defaults.mode}).`,
+ );
+ }
+ if (SANDBOX_NETWORK_RANK[network] > SANDBOX_NETWORK_RANK[networkOf(defaults)]) {
+ throw new HttpError(
+ 403,
+ "sandbox_forbidden",
+ `Only an administrator can give a Session more network access than the server's sandbox settings (${networkOf(defaults)}).`,
+ );
+ }
+ }
+ const { network: _dropped, ...rest } = base;
+ return { ...rest, mode, ...(network === "open" ? {} : { network }) };
+}
const SESSION_ID_TS_RE = /^session-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-[0-9a-f]{8}$/;
@@ -102,14 +172,51 @@ export interface SessionServiceDeps {
orgIdOfSession?: (sessionId: string) => string | undefined;
orgIdsOfProject?: (projectId: string) => ReadonlyMap<string, string>;
/** Spawn-confinement getter (the sandbox module's), forwarded into core beside proxyEnv. */
- confineSpawn?: () => SpawnConfiner | null;
+ confineSpawn?: (ctx: ControlEnvContext) => SpawnConfiner | null;
+ /** The server's Sandbox settings: what a new Session's policy is snapshotted from. */
+ sandboxDefaults?: () => SandboxSettings;
/** Host-owned model-request hooks, forwarded to core for every Session LLM. */
assembly?: AgentAssembly;
+ /** Whether a mounted sandbox backend implements the `local` network level. */
+ sandboxLocalNetwork?: () => boolean;
}
export class SessionService {
constructor(private readonly deps: SessionServiceDeps) {}
+ /** The policy a new Session starts with: the server's Sandbox settings. */
+ defaultSandbox(): SandboxSettings {
+ return this.deps.sandboxDefaults?.() ?? { mode: "danger-full-access" };
+ }
+
+ /** Whether this server can enforce the `local` network level right now. */
+ localNetworkSupported(): boolean {
+ return this.deps.sandboxLocalNetwork?.() ?? false;
+ }
+
+ /** A policy as the composer sees it, with this server's support for `local`. */
+ sandboxView(policy: SandboxSettings): SessionSandbox {
+ return sessionSandboxOf(policy, this.localNetworkSupported());
+ }
+
+ /** A Session's policy: its snapshot, or — for a row from before snapshots — the settings. */
+ sandboxOf(row: SessionRow): SandboxSettings {
+ return row.sandbox ?? this.defaultSandbox();
+ }
+
+ /** Changes one Session's policy (its next command runs under it); returns the new policy. */
+ updateSandbox(row: SessionRow, pick: Partial<SessionSandbox>, isAdmin: boolean): SandboxSettings {
+ const next = applySandboxPick(
+ this.sandboxOf(row),
+ pick,
+ this.defaultSandbox(),
+ isAdmin,
+ this.localNetworkSupported(),
+ );
+ this.deps.sessions.updateSandbox(row.sessionId, next);
+ return next;
+ }
+
/**
* DB row -> SessionInfo (run status and pending approval count come from session-manager).
* Async because `source` is derived from session_meta: a registry miss (Session predating
@@ -136,6 +243,7 @@ export class SessionService {
modelId: row.modelId,
workspace: row.workspace,
approvalMode: row.approvalMode,
+ sandbox: this.sandboxView(this.sandboxOf(row)),
...(row.thinkingLevel ? { thinkingLevel: row.thinkingLevel } : {}),
...(row.title !== null ? { title: row.title } : {}),
...(source !== undefined ? { source } : {}),
@@ -388,6 +496,10 @@ export class SessionService {
provider?: string;
workspace?: string;
approvalMode?: ApprovalMode;
+ /** The composer's sandbox picks; omitted halves take the server's settings. */
+ sandbox?: Partial<SessionSandbox>;
+ /** Whether the creator is an administrator (may loosen past the settings). Default false. */
+ isAdmin?: boolean;
/**
* Session source marker: `schedule` when triggered by a scheduled task, `benchmark` when
* created by a Benchmark evaluation or optimization (the only value a client may send);
@@ -407,6 +519,8 @@ export class SessionService {
"modelId and provider must be given together as a (provider, modelId) pair: specify both, or neither to use the Project's default model.",
);
}
+ // Checked before anything is created: a refused pick must not leave a Session behind.
+ const sandbox = this.snapshotSandbox(args);
let modelId: string;
let provider: string;
if (args.modelId !== undefined && args.provider !== undefined) {
@@ -472,6 +586,7 @@ export class SessionService {
modelId: session.modelId,
workspace: session.workspaceDir,
approvalMode: args.approvalMode ?? "allow-all",
+ sandbox,
title: null,
// The creator's hint: "cli" when the CLI created this Session through the API,
// "org" when the organization runtime opened a desk or a ticket session, otherwise
@@ -483,9 +598,27 @@ export class SessionService {
};
this.deps.sessions.insert(row);
this.deps.manager.adopt(row, session);
+
return this.toInfo(row, false);
}
+ /** A new Session's snapshot: the settings, with the creator's picks (checked) on top. */
+ private snapshotSandbox(args: {
+ sandbox?: Partial<SessionSandbox>;
+ isAdmin?: boolean;
+ }): SandboxSettings {
+ const defaults = this.defaultSandbox();
+ return args.sandbox === undefined
+ ? defaults
+ : applySandboxPick(
+ defaults,
+ args.sandbox,
+ defaults,
+ args.isAdmin ?? false,
+ this.localNetworkSupported(),
+ );
+ }
+
/**
* Absolute path of a Session's **latest** Trace file (the current context shard);
* undefined when no Trace exists. Costs a directory walk, so only the single-session
diff --git a/packages/server/test/db-migrations.test.ts b/packages/server/test/db-migrations.test.ts
index 06cb83ef..1250b93f 100644
--- a/packages/server/test/db-migrations.test.ts
+++ b/packages/server/test/db-migrations.test.ts
@@ -569,8 +569,12 @@ describe("migration 8 → current: model-promotions", () => {
)
.get();
try {
- expect(migrate(db).applied).toEqual(["model-promotions", "model-provider-auth-tokens"]);
- expect(schemaVersion(db)).toBe(10);
+ expect(migrate(db).applied).toEqual([
+ "model-promotions",
+ "model-provider-auth-tokens",
+ "sessions-sandbox",
+ ]);
+ expect(schemaVersion(db)).toBe(11);
expect(promotionsTableExists()).toEqual({ "1": 1 });
expect(authTokensTableExists()).toEqual({ "1": 1 });
@@ -589,8 +593,9 @@ describe("migration 8 → current: model-promotions", () => {
expect(migrate(db, { swapPath: true }).applied).toEqual([
"model-promotions",
"model-provider-auth-tokens",
+ "sessions-sandbox",
]);
- expect(schemaVersion(db)).toBe(10);
+ expect(schemaVersion(db)).toBe(11);
} finally {
db.close();
}
@@ -607,8 +612,8 @@ describe("migration 9 → current: model-provider-auth-tokens", () => {
)
.get();
try {
- expect(migrate(db).applied).toEqual(["model-provider-auth-tokens"]);
- expect(schemaVersion(db)).toBe(10);
+ expect(migrate(db).applied).toEqual(["model-provider-auth-tokens", "sessions-sandbox"]);
+ expect(schemaVersion(db)).toBe(11);
expect(tableExists()).toEqual({ "1": 1 });
db.exec(
"INSERT INTO users (user_id, password_hash, is_admin, created_at)" +
diff --git a/packages/server/test/plugin-config.test.ts b/packages/server/test/plugin-config.test.ts
new file mode 100644
index 00000000..90373e9a
--- /dev/null
+++ b/packages/server/test/plugin-config.test.ts
@@ -0,0 +1,345 @@
+/**
+ * Plugin configuration: a module DECLARES a settings group as a contribution (manifest data),
+ * an admin fills it in on the Plugins page through /api/admin/plugin-config, and the module
+ * reads the document back through the PluginConfig mechanism — defaults merged in, secrets
+ * masked at the API and kept when the mask is sent back, every save handed to the watchers.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { parseManifest } from "@prismshadow/penguin-core/kernel";
+import type { PluginConfigResponse } from "../src/api/types.js";
+import {
+ PluginConfigError,
+ PluginConfigPage,
+ PluginConfigStore,
+ applyUpdate,
+ parsePluginConfiguration,
+} from "../src/plugin/config.js";
+import { PluginHost } from "../src/plugin/host.js";
+import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const SCHEMA = parsePluginConfiguration(
+ {
+ title: "Acme",
+ titleZh: "Acme 机器人",
+ properties: {
+ token: { type: "secret", title: "Token", required: true },
+ project: { type: "string", title: "Project" },
+ agent: { type: "string", title: "Agent", default: "default_agent" },
+ enabled: { type: "boolean", title: "Enabled", default: true },
+ limit: { type: "number", title: "Limit" },
+ },
+ },
+ "acme/package.json",
+)!;
+
+describe("parsePluginConfiguration", () => {
+ it("reads a declared schema and leaves an undeclared one undefined", () => {
+ expect(parsePluginConfiguration(undefined, "x")).toBeUndefined();
+ expect(SCHEMA.title).toBe("Acme");
+ expect(Object.keys(SCHEMA.properties)).toEqual([
+ "token",
+ "project",
+ "agent",
+ "enabled",
+ "limit",
+ ]);
+ expect(SCHEMA.properties.agent).toEqual({
+ type: "string",
+ title: "Agent",
+ default: "default_agent",
+ });
+ });
+
+ it("refuses a schema the page could not draw, naming the file", () => {
+ const bad = (properties: unknown) => () =>
+ parsePluginConfiguration({ properties }, "acme/package.json");
+ // A Project picker is not a field type: a Project is named by its id, a string.
+ expect(bad({ a: { type: "project", title: "A" } })).toThrow(/\.a\.type must be one of/);
+ expect(bad({ a: { type: "colour", title: "A" } })).toThrow(
+ /acme\/package.json.*\.a\.type must be one of/,
+ );
+ expect(bad({ a: { type: "string" } })).toThrow(/\.a\.title is required/);
+ expect(bad({ "bad name": { type: "string", title: "A" } })).toThrow(
+ /"bad name" is not a valid name/,
+ );
+ expect(bad({ a: { type: "number", title: "A", default: "1" } })).toThrow(
+ /\.a\.default does not fit a number/,
+ );
+ expect(bad([])).toThrow(/properties must be an object/);
+ expect(bad({ a: { type: "enum", title: "A" } })).toThrow(/\.a\.options must list the choices/);
+ expect(bad({ a: { type: "enum", title: "A", options: [{ value: "x" }] } })).toThrow(
+ /options\[0\] needs a string value and title/,
+ );
+ expect(
+ bad({ a: { type: "enum", title: "A", options: [{ value: "x", title: "X" }], default: "y" } }),
+ ).toThrow(/\.a\.default does not fit a enum/);
+ expect(bad({ a: { type: "list", title: "A", maxItems: 0 } })).toThrow(
+ /maxItems must be a positive integer/,
+ );
+ expect(bad({ a: { type: "number", title: "A", maximum: "30" } })).toThrow(
+ /\.a\.maximum must be a number/,
+ );
+ expect(bad({ a: { type: "number", title: "A", maximum: 3, default: 5 } })).toThrow(
+ /\.a\.default does not fit/,
+ );
+ expect(bad({ a: { type: "string", title: "A", pattern: "(" } })).toThrow(
+ /\.a\.pattern is not a valid regular expression/,
+ );
+ });
+});
+
+describe("applyUpdate", () => {
+ it("checks types, keeps a secret sent back masked, clears on null or empty, and enforces required", () => {
+ const stored = { token: "secret-token-value", project: "p" };
+ const next = applyUpdate(SCHEMA, stored, { token: "secr…alue", agent: " a1 ", limit: 3 });
+ expect(next).toEqual({ token: "secret-token-value", project: "p", agent: "a1", limit: 3 });
+ expect(applyUpdate(SCHEMA, next, { agent: null, limit: "" })).toEqual({
+ token: "secret-token-value",
+ project: "p",
+ });
+ expect(() => applyUpdate(SCHEMA, stored, { limit: "3" })).toThrow(
+ new PluginConfigError("limit", '"limit" must be a number'),
+ );
+ expect(() => applyUpdate(SCHEMA, stored, { colour: "red" })).toThrow(/"colour" is not a field/);
+ expect(() => applyUpdate(SCHEMA, stored, { token: null })).toThrow(/"token" is required/);
+ // A required field with a default is never missing.
+ expect(() => applyUpdate(SCHEMA, {}, { token: "t" })).not.toThrow();
+ });
+
+ it("holds an enum to its choices and a list to trimmed, distinct lines under its cap", () => {
+ const schema = parsePluginConfiguration(
+ {
+ properties: {
+ mode: {
+ type: "enum",
+ title: "Mode",
+ options: [
+ { value: "a", title: "A" },
+ { value: "b", title: "B" },
+ ],
+ },
+ paths: { type: "list", title: "Paths", maxItems: 2 },
+ },
+ },
+ "x",
+ )!;
+ expect(applyUpdate(schema, {}, { mode: "b", paths: [" /x ", "/x", "", "/y"] })).toEqual({
+ mode: "b",
+ paths: ["/x", "/y"],
+ });
+ expect(() => applyUpdate(schema, {}, { mode: "c" })).toThrow('"mode" must be one of a, b');
+ expect(() => applyUpdate(schema, {}, { paths: "/x" })).toThrow(
+ '"paths" must be a list of strings',
+ );
+ expect(() => applyUpdate(schema, {}, { paths: ["/a", "/b", "/c"] })).toThrow(
+ '"paths" may hold at most 2 entries',
+ );
+ // An empty list clears the field.
+ expect(applyUpdate(schema, { paths: ["/x"] }, { paths: [] })).toEqual({});
+ });
+
+ it("holds a number to its range and every line of a patterned field to its pattern", () => {
+ const schema = parsePluginConfiguration(
+ {
+ properties: {
+ seconds: { type: "number", title: "Seconds", minimum: 1, maximum: 30, default: 5 },
+ paths: {
+ type: "list",
+ title: "Paths",
+ pattern: "^/",
+ patternErrorMessage: "must list absolute paths",
+ },
+ host: { type: "string", title: "Host", pattern: "^[a-z]+$" },
+ },
+ },
+ "x",
+ )!;
+ expect(applyUpdate(schema, {}, { seconds: 30, paths: ["/a"], host: "box" })).toEqual({
+ seconds: 30,
+ paths: ["/a"],
+ host: "box",
+ });
+ expect(() => applyUpdate(schema, {}, { seconds: 0 })).toThrow('"seconds" must be at least 1');
+ expect(() => applyUpdate(schema, {}, { seconds: 600 })).toThrow('"seconds" must be at most 30');
+ expect(() => applyUpdate(schema, {}, { paths: ["/a", " .ssh "] })).toThrow(
+ '"paths" must list absolute paths: .ssh',
+ );
+ expect(() => applyUpdate(schema, {}, { host: "Box" })).toThrow(
+ '"host" does not match ^[a-z]+$: Box',
+ );
+ // Clearing is never a violation.
+ expect(applyUpdate(schema, { host: "box" }, { host: "" })).toEqual({});
+ });
+});
+
+describe("PluginConfigStore", () => {
+ it("merges defaults, stores under the package's key, masks, and fires the watchers", () => {
+ const kv = new Map<string, string>();
+ const store = new PluginConfigStore({
+ settings: { get: (k) => kv.get(k) ?? null, set: (k, v) => void kv.set(k, v) },
+ groups: () => [{ name: "@acme/bot", configuration: SCHEMA }],
+ });
+ expect(store.saved("@acme/bot")).toBe(false);
+ expect(store.get("@acme/bot")).toEqual({ agent: "default_agent", enabled: true });
+ expect(store.get("@acme/other")).toEqual({});
+ const seen: Record<string, unknown>[] = [];
+ const off = store.watch("@acme/bot", (v) => seen.push(v));
+ const entry = store.set("@acme/bot", { token: "secret-token-value", enabled: false });
+ expect(entry.values).toEqual({ token: "secr…alue", agent: "default_agent", enabled: false });
+ expect(store.saved("@acme/bot")).toBe(true);
+ expect(kv.get("plugin-config:@acme/bot")).toBe(
+ '{"token":"secret-token-value","enabled":false}',
+ );
+ expect(seen).toEqual([{ token: "secret-token-value", agent: "default_agent", enabled: false }]);
+ off();
+ store.set("@acme/bot", { agent: "x" });
+ expect(seen).toHaveLength(1);
+ expect(() => store.set("@acme/other", {})).toThrow(/no settings group named "@acme\/other"/);
+ expect(store.describe().map((e) => e.name)).toEqual(["@acme/bot"]);
+ });
+});
+
+describe("/api/admin/plugin-config", () => {
+ let t: TestApp;
+ let admin: ReturnType<typeof apiClient>;
+
+ beforeEach(async () => {
+ const host = new PluginHost();
+ host.use({
+ specifier: "@acme/bot",
+ modules: [
+ {
+ // A plugin module declaring its group: pure data, the way a generated ifaces.json carries it.
+ manifest: parseManifest({
+ name: "AcmeBot",
+ requires: {},
+ provides: {},
+ contributes: { "PluginConfigProvider.groups": [{ id: "acme-bot", ...SCHEMA }] },
+ children: [],
+ }),
+ create: () => ({ api: {} }),
+ },
+ ],
+ replaces: [],
+ });
+ t = await createTestApp({ plugins: host });
+ admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ it("lists the declared groups, and is for admins only", async () => {
+ const res = await admin.get("/api/admin/plugin-config");
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as PluginConfigResponse;
+ // The sandbox's group is ordered ahead of the rest.
+ expect(body.plugins[0]!.name).toBe("sandbox");
+ expect(body.plugins.slice(1)).toEqual([
+ {
+ name: "acme-bot",
+ configuration: SCHEMA,
+ values: { agent: "default_agent", enabled: true },
+ },
+ ]);
+ const member = apiClient(t.app, (await provisionUser(t.app, "member")).cookie);
+ expect((await member.get("/api/admin/plugin-config")).status).toBe(403);
+ expect(
+ (await member.put("/api/admin/plugin-config", { name: "acme-bot", values: {} })).status,
+ ).toBe(403);
+ });
+
+ it("saves one package's values, masks the secret, and refuses what the schema refuses", async () => {
+ const saved = await admin.put("/api/admin/plugin-config", {
+ name: "acme-bot",
+ values: { token: "secret-token-value", project: "default_project" },
+ });
+ expect(saved.status).toBe(200);
+ const body = (await saved.json()) as PluginConfigResponse;
+ expect(body.plugins.find((e) => e.name === "acme-bot")!.values).toEqual({
+ token: "secr…alue",
+ project: "default_project",
+ agent: "default_agent",
+ enabled: true,
+ });
+ expect(JSON.stringify(body)).not.toContain("secret-token-value");
+
+ const invalid = await admin.put("/api/admin/plugin-config", {
+ name: "acme-bot",
+ values: { limit: "many" },
+ });
+ expect(invalid.status).toBe(400);
+ expect(await invalid.json()).toMatchObject({
+ error: { code: "plugin_config_invalid", message: '"limit" must be a number' },
+ });
+ const unknown = await admin.put("/api/admin/plugin-config", {
+ name: "acme-plain",
+ values: {},
+ });
+ expect(unknown.status).toBe(404);
+ expect(await unknown.json()).toMatchObject({ error: { code: "plugin_config_unknown" } });
+ const shapeless = await admin.put("/api/admin/plugin-config", {
+ name: "acme-bot",
+ values: [],
+ });
+ expect(shapeless.status).toBe(400);
+ });
+});
+
+describe("PluginConfigPage actions", () => {
+ /** A page node over one sandbox card and a backend card drawn inside it. */
+ function page(run: () => Promise<{ ok: boolean; message: string; settled?: Promise<void> }>) {
+ const saves: string[] = [];
+ const node = new PluginConfigPage() as unknown as {
+ entries: unknown;
+ pluginConfigAdmin: {
+ run(name: string, action: string): Promise<Record<string, unknown>>;
+ };
+ setup(ctx: unknown): void;
+ };
+ node.entries = {
+ describe: () => [
+ { name: "sandbox", configuration: { properties: {} }, values: {} },
+ { name: "backend", parent: "sandbox", configuration: { properties: {} }, values: {} },
+ ],
+ set: () => {
+ throw new Error("unused");
+ },
+ };
+ node.setup({
+ contributions: {
+ status: [
+ {
+ data: { group: "sandbox" },
+ code: { notices: () => [], saved: async () => void saves.push("sandbox") },
+ },
+ {
+ data: { group: "backend" },
+ code: { notices: () => [], actions: () => [{ id: "go", title: "Go" }], run },
+ },
+ ],
+ },
+ });
+ return { admin: node.pluginConfigAdmin, saves };
+ }
+
+ it("settles the card that draws the group once an action returns, as a save would", async () => {
+ const { admin, saves } = page(async () => ({ ok: true, message: "done" }));
+ expect(await admin.run("backend", "go")).toEqual({ ok: true, message: "done" });
+ expect(saves).toEqual(["sandbox"]);
+ });
+
+ it("settles only when started work ends, and never sends the promise to the page", async () => {
+ let finish!: () => void;
+ const settled = new Promise<void>((resolve) => (finish = resolve));
+ const { admin, saves } = page(async () => ({ ok: true, message: "started", settled }));
+ const result = await admin.run("backend", "go");
+ expect(result).toEqual({ ok: true, message: "started" });
+ expect(saves).toEqual([]);
+ finish();
+ await settled;
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(saves).toEqual(["sandbox"]);
+ });
+});
diff --git a/packages/server/test/project-chat-defaults.test.ts b/packages/server/test/project-chat-defaults.test.ts
index edec71da..2dc93a43 100644
--- a/packages/server/test/project-chat-defaults.test.ts
+++ b/packages/server/test/project-chat-defaults.test.ts
@@ -25,6 +25,11 @@ import type {
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
+/** What GET serves beside the block: the sandbox policy a new Session starts with (read-only). */
+const SERVED = {
+ sandbox: { mode: "danger-full-access", network: "open", localNetworkSupported: false },
+};
+
describe("project chat defaults", () => {
let t: TestApp;
let owner: ReturnType<typeof apiClient>;
@@ -58,7 +63,7 @@ describe("project chat defaults", () => {
it("any member reads; an absent block is an empty object; a non-member gets 404", async () => {
const res = await member.get(url);
expect(res.status).toBe(200);
- expect(await res.json()).toEqual({});
+ expect(await res.json()).toEqual(SERVED);
expect((await outsider.get(url)).status).toBe(404);
});
@@ -72,7 +77,7 @@ describe("project chat defaults", () => {
const put = await owner.put(url, body);
expect(put.status).toBe(200);
expect(await put.json()).toEqual(body);
- expect(await (await member.get(url)).json()).toEqual(body);
+ expect(await (await member.get(url)).json()).toEqual({ ...body, ...SERVED });
const toml = await fs.readFile(path.join(t.root, projectId, ".project_config.toml"), "utf8");
expect(toml).toContain("[default_chat]");
@@ -87,7 +92,7 @@ describe("project chat defaults", () => {
// Replace with a different subset: the previous keys must be gone.
const second = await owner.put(url, { thinkingLevel: "low" });
expect(await second.json()).toEqual({ thinkingLevel: "low" });
- expect(await (await owner.get(url)).json()).toEqual({ thinkingLevel: "low" });
+ expect(await (await owner.get(url)).json()).toEqual({ ...{ thinkingLevel: "low" }, ...SERVED });
// Empty body: the block disappears from the toml entirely.
expect(await (await owner.put(url, {})).json()).toEqual({});
const toml = await fs.readFile(path.join(t.root, projectId, ".project_config.toml"), "utf8");
@@ -97,7 +102,7 @@ describe("project chat defaults", () => {
it("owner only: a member PUT gets 403, a non-member 404 (existence is not leaked)", async () => {
expect((await member.put(url, { thinkingLevel: "low" })).status).toBe(403);
expect((await outsider.put(url, { thinkingLevel: "low" })).status).toBe(404);
- expect(await (await owner.get(url)).json()).toEqual({});
+ expect(await (await owner.get(url)).json()).toEqual({ ...{}, ...SERVED });
});
it("agentId must reference an existing Agent of the Project (400 unknown_agent)", async () => {
@@ -106,7 +111,7 @@ describe("project chat defaults", () => {
expect(((await res.json()) as ErrorBody).error.code).toBe("unknown_agent");
// An id that is not even shaped like one gets the same 400 before any path is built.
expect((await owner.put(url, { agentId: "../escape" })).status).toBe(400);
- expect(await (await owner.get(url)).json()).toEqual({});
+ expect(await (await owner.get(url)).json()).toEqual({ ...{}, ...SERVED });
});
it("rejects invalid enum values with 400 — including thinkingLevel 'none'", async () => {
@@ -114,7 +119,7 @@ describe("project chat defaults", () => {
// "none" is a valid per-turn wire value but never a project default.
expect((await owner.put(url, { thinkingLevel: "none" })).status).toBe(400);
expect((await owner.put(url, { thinkingLevel: 3 })).status).toBe(400);
- expect(await (await owner.get(url)).json()).toEqual({});
+ expect(await (await owner.get(url)).json()).toEqual({ ...{}, ...SERVED });
});
it("keeps models, credentials and the name — the write is read-modify-write", async () => {
@@ -146,7 +151,10 @@ describe("project chat defaults", () => {
// the [default_chat] table must end up below the re-appended scalar keys.
expect((await owner.put(url, { workspace: "/srv/data" })).status).toBe(200);
expect((await owner.patch(`/api/projects/${projectId}`, { name: "Renamed" })).status).toBe(200);
- expect(await (await owner.get(url)).json()).toEqual({ workspace: "/srv/data" });
+ expect(await (await owner.get(url)).json()).toEqual({
+ ...{ workspace: "/srv/data" },
+ ...SERVED,
+ });
const toml = await fs.readFile(path.join(t.root, projectId, ".project_config.toml"), "utf8");
expect(toml).toContain('name = "Renamed"');
});
diff --git a/packages/server/test/sandbox-settings.test.ts b/packages/server/test/sandbox-settings.test.ts
new file mode 100644
index 00000000..9fc4c5e1
--- /dev/null
+++ b/packages/server/test/sandbox-settings.test.ts
@@ -0,0 +1,365 @@
+/**
+ * Sandbox settings are a settings group: the sandbox's policy is listed, validated and stored
+ * through /api/admin/plugin-config like any module's settings and applied at the next spawn,
+ * surviving a restart. A backend with settings of its own declares its own group inside the
+ * sandbox's and reads it itself through PluginConfig — nothing hands it a bag of values.
+ */
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { parseManifest } from "@prismshadow/penguin-core/kernel";
+import type { ModuleDef } from "@prismshadow/penguin-core/kernel";
+import type { SandboxPolicy } from "@prismshadow/penguin-core/plugin";
+import type { PluginConfigResponse } from "../src/api/types.js";
+import type { PluginConfig } from "../src/plugin/config.js";
+import { PluginHost } from "../src/plugin/host.js";
+import type { SandboxService } from "../src/sandbox/service.js";
+import { apiClient, createTestApp, loginAdmin } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+/** What the backend saw at each confine: the policy, and the runner it read from its own group. */
+interface Seen {
+ policy: SandboxPolicy;
+ runner: unknown;
+}
+
+/** A backend declaring a group inside the sandbox's and reading it at each confine. */
+function backend(seen: Seen[]): ModuleDef {
+ return {
+ manifest: parseManifest({
+ name: "TestBackend",
+ requires: {
+ config: { iface: "@prismshadow/penguin-server#PluginConfig", from: "PluginConfigModule" },
+ },
+ provides: {},
+ contributes: {
+ "SandboxModule.providers": [
+ {
+ id: "test.provider",
+ name: "test-backend",
+ dimensions: ["fs-write", "network", "mask-paths"],
+ },
+ // Installed for another platform: it declines here, and says nothing on the card.
+ { id: "elsewhere.provider", name: "other-platform", dimensions: ["fs-write"] },
+ ],
+ "PluginConfigProvider.groups": [
+ {
+ id: "sandbox-test",
+ parent: "sandbox",
+ title: "Test backend",
+ properties: { runner: { type: "string", title: "Runner", default: "runner-a" } },
+ },
+ ],
+ },
+ children: [],
+ }),
+ create({ use }) {
+ const config = use.config as PluginConfig;
+ return {
+ api: {},
+ bind: {
+ "elsewhere.provider": Promise.resolve(null),
+ "test.provider": {
+ dimensions: ["fs-write", "network", "mask-paths"],
+ confine(argv: readonly string[], policy: SandboxPolicy) {
+ seen.push({ policy, runner: config.get("sandbox-test").runner });
+ return {
+ argv: ["confined", ...argv],
+ enforcement: "full",
+ denialSignatures: [],
+ runnerFailureRules: [],
+ };
+ },
+ },
+ },
+ };
+ },
+ };
+}
+
+async function appWith(seen: Seen[], dbPath?: string) {
+ const host = new PluginHost();
+ host.use({ specifier: "test-backend", modules: [backend(seen)], replaces: [] });
+ const t = await createTestApp({ plugins: host, ...(dbPath ? { config: { dbPath } } : {}) });
+ const admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ const sandbox = t.deps.tree.api<SandboxService>("SandboxModule", "sandbox");
+ await sandbox.whenReady();
+ const spawn = () => sandbox.confiner()(["true"], { workspaceDir: "/w" } as never);
+ const list = async () =>
+ ((await (await admin.get("/api/admin/plugin-config")).json()) as PluginConfigResponse).plugins;
+ return { t, admin, sandbox, spawn, list };
+}
+
+describe("sandbox settings group", () => {
+ const apps: TestApp[] = [];
+ afterEach(async () => {
+ for (const t of apps.splice(0)) await t.cleanup();
+ });
+
+ it("lists the sandbox with its backends' notice (a backend for another platform is not a notice), and a backend's group inside it", async () => {
+ const { t, list } = await appWith([]);
+ apps.push(t);
+ const entries = await list();
+ const sandbox = entries.find((e) => e.name === "sandbox")!;
+ expect(entries[0]).toBe(sandbox);
+ expect(sandbox.values).toEqual({
+ mode: "danger-full-access",
+ network: "open",
+ writableTemp: true,
+ });
+ expect(sandbox.notices).toEqual([
+ expect.objectContaining({
+ tone: "muted",
+ text: "Backends: test-backend (fs-write, network, mask-paths)",
+ }),
+ ]);
+ const child = entries.find((e) => e.name === "sandbox-test")!;
+ expect(child.parent).toBe("sandbox");
+ expect(child.values).toEqual({ runner: "runner-a" });
+ });
+
+ it("lists the local network level as unavailable where no backend supports it, and refuses saving it", async () => {
+ const { t, admin, list, sandbox } = await appWith([]);
+ apps.push(t);
+ const entry = (await list()).find((e) => e.name === "sandbox")!;
+ expect(entry.unavailable).toEqual([
+ expect.objectContaining({ field: "network", value: "local" }),
+ ]);
+ const refused = await admin.put("/api/admin/plugin-config", {
+ name: "sandbox",
+ values: { mode: "workspace-write", network: "local" },
+ });
+ expect(refused.status).toBe(400);
+ expect(await refused.text()).toContain("network");
+ // Nothing was stored: the service still runs the defaults.
+ expect(sandbox.currentSettings()).toEqual({ mode: "danger-full-access" });
+ });
+
+ it("applies a saved policy to the next spawn; the backend reads its own saved group", async () => {
+ const seen: Seen[] = [];
+ const { t, admin, spawn, sandbox } = await appWith(seen);
+ apps.push(t);
+ const saved = await admin.put("/api/admin/plugin-config", {
+ name: "sandbox",
+ values: { mode: "workspace-write", network: "none", maskPaths: [" /etc/x ", "/etc/x", ""] },
+ });
+ expect(saved.status).toBe(200);
+ expect(sandbox.currentSettings()).toEqual({
+ mode: "workspace-write",
+ network: "none",
+ maskPaths: ["/etc/x"],
+ });
+ expect(
+ (
+ await admin.put("/api/admin/plugin-config", {
+ name: "sandbox-test",
+ values: { runner: "runner-b" },
+ })
+ ).status,
+ ).toBe(200);
+ expect(spawn()).toEqual({ argv: ["confined", "true"] });
+ expect(seen.at(-1)).toEqual({
+ policy: {
+ mode: "workspace-write",
+ workspaceRoot: "/w",
+ network: "none",
+ maskPaths: ["/etc/x"],
+ writableTemp: true,
+ },
+ runner: "runner-b",
+ });
+
+ await admin.put("/api/admin/plugin-config", {
+ name: "sandbox",
+ values: { mode: "read-only", network: "open", maskPaths: [], writableTemp: false },
+ });
+ expect(sandbox.currentSettings()).toEqual({ mode: "read-only", writableTemp: false });
+ spawn();
+ expect(seen.at(-1)?.policy).toEqual({ mode: "read-only", workspaceRoot: "/w" });
+ expect(sandbox.parkedSettings()).toEqual({ mode: "read-only", writableTemp: false });
+
+ const refused = await admin.put("/api/admin/plugin-config", {
+ name: "sandbox",
+ values: { mode: "wide-open" },
+ });
+ expect(refused.status).toBe(400);
+ // A relative masked path would resolve against the server's working directory.
+ const relative = await admin.put("/api/admin/plugin-config", {
+ name: "sandbox",
+ values: { maskPaths: ["/etc/x", ".ssh"] },
+ });
+ expect(relative.status).toBe(400);
+ expect(sandbox.currentSettings().maskPaths).toBeUndefined();
+ expect(sandbox.currentSettings().mode).toBe("read-only");
+ });
+
+ it("names a failed backend with its reason and the ones meant for another platform, and warns when the saved mode cannot be enforced", async () => {
+ const host = new PluginHost();
+ host.use({
+ specifier: "wrong-platform",
+ modules: [
+ {
+ manifest: parseManifest({
+ name: "WrongPlatformBackend",
+ requires: {},
+ provides: {},
+ contributes: {
+ "SandboxModule.providers": [
+ { id: "wrong.provider", name: "wrong-backend", dimensions: ["fs-write"] },
+ { id: "elsewhere.provider", name: "other-platform", dimensions: ["fs-write"] },
+ ],
+ },
+ children: [],
+ }),
+ create: () => ({
+ api: {},
+ bind: {
+ "wrong.provider": Promise.reject(new Error("'bwrap' is missing")),
+ // A backend for another platform declines: not a failure, and not named on its own.
+ "elsewhere.provider": Promise.resolve(null),
+ },
+ }),
+ },
+ ],
+ replaces: [],
+ });
+ const t = await createTestApp({ plugins: host });
+ apps.push(t);
+ const admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ await t.deps.tree.api<SandboxService>("SandboxModule", "sandbox").whenReady();
+ await admin.put("/api/admin/plugin-config", {
+ name: "sandbox",
+ values: { mode: "workspace-write" },
+ });
+ const entries = (
+ (await (await admin.get("/api/admin/plugin-config")).json()) as PluginConfigResponse
+ ).plugins;
+ const notices = entries
+ .find((e) => e.name === "sandbox")!
+ .notices!.map((n) => [n.tone, n.text]);
+ expect(notices).toEqual([
+ [
+ "attention",
+ "The saved mode needs fs-write, and no usable backend implements it: every agent command is refused until one does.",
+ ],
+ [
+ "attention",
+ "This deployment has no usable sandbox backend: until one for this platform is installed from the Plugins page, every mode but Off refuses every agent command. other-platform is installed, but for another platform.",
+ ],
+ ["attention", "wrong-backend is not in use: 'bwrap' is missing"],
+ ]);
+ });
+
+ it("loads a backend that failed its check again when its group is saved, and answers with the outcome", async () => {
+ const host = new PluginHost();
+ host.use({
+ specifier: "probed-backend",
+ modules: [
+ {
+ manifest: parseManifest({
+ name: "ProbedBackend",
+ requires: {
+ config: {
+ iface: "@prismshadow/penguin-server#PluginConfig",
+ from: "PluginConfigModule",
+ },
+ },
+ provides: {},
+ contributes: {
+ "SandboxModule.providers": [
+ { id: "probed.provider", name: "probed", dimensions: ["fs-write"] },
+ ],
+ "PluginConfigProvider.groups": [
+ {
+ id: "sandbox-probed",
+ parent: "sandbox",
+ title: "Probed backend",
+ properties: {
+ runner: { type: "string", title: "Runner", default: "/opt/bwarp" },
+ },
+ },
+ ],
+ },
+ children: [],
+ }),
+ create({ use }) {
+ const config = use.config as PluginConfig;
+ return {
+ api: {},
+ bind: {
+ // A loader, the way bwrap binds one: it checks the runner its group names.
+ "probed.provider": async () => {
+ const runner = config.get("sandbox-probed").runner;
+ if (runner !== "/usr/bin/bwrap")
+ throw new Error(`'${String(runner)}' is missing`);
+ return {
+ confine: (argv: readonly string[]) => ({
+ argv: ["probed", ...argv],
+ enforcement: "full" as const,
+ denialSignatures: [],
+ runnerFailureRules: [],
+ }),
+ };
+ },
+ },
+ };
+ },
+ },
+ ],
+ replaces: [],
+ });
+ const t = await createTestApp({ plugins: host });
+ apps.push(t);
+ const admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ const sandbox = t.deps.tree.api<SandboxService>("SandboxModule", "sandbox");
+ await sandbox.whenReady();
+ expect(sandbox.failures()).toEqual([{ name: "probed", reason: "'/opt/bwarp' is missing" }]);
+
+ const saved = await admin.put("/api/admin/plugin-config", {
+ name: "sandbox-probed",
+ values: { runner: "/usr/bin/bwrap" },
+ });
+ expect(saved.status).toBe(200);
+ const card = ((await saved.json()) as PluginConfigResponse).plugins.find(
+ (e) => e.name === "sandbox",
+ )!;
+ expect(card.notices?.map((n) => n.text)).toEqual(["Backends: probed (fs-write)"]);
+ expect(sandbox.failures()).toEqual([]);
+ sandbox.configure({ mode: "read-only" });
+ expect(sandbox.confiner()(["true"], { workspaceDir: "/w" } as never).argv).toEqual([
+ "probed",
+ "true",
+ ]);
+ });
+
+ it("keeps what was saved across a restart", async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-sandbox-settings-"));
+ const dbPath = path.join(dir, "web.db");
+ let second: Awaited<ReturnType<typeof appWith>> | undefined;
+ try {
+ const first = await appWith([], dbPath);
+ await first.admin.put("/api/admin/plugin-config", {
+ name: "sandbox",
+ values: { mode: "read-only" },
+ });
+ await first.admin.put("/api/admin/plugin-config", {
+ name: "sandbox-test",
+ values: { runner: "runner-c" },
+ });
+ await first.t.cleanup();
+
+ const seen: Seen[] = [];
+ second = await appWith(seen, dbPath);
+ expect(second.sandbox.currentSettings()).toEqual({ mode: "read-only" });
+ second.spawn();
+ expect(seen.at(-1)?.runner).toBe("runner-c");
+ } finally {
+ // The database lives outside either app's root, so it is only removable once the app
+ // holding it is closed: Windows refuses to unlink an open file (EBUSY on web.db-shm),
+ // and fs.rm retries that past the test's timeout.
+ await second?.t.cleanup();
+ await fs.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ }
+ });
+});
diff --git a/packages/server/test/sandbox.test.ts b/packages/server/test/sandbox.test.ts
index c0e37380..a02f9c1f 100644
--- a/packages/server/test/sandbox.test.ts
+++ b/packages/server/test/sandbox.test.ts
@@ -15,6 +15,7 @@ import type {
SandboxDimension,
SandboxPolicy,
SandboxProvider,
+ SandboxProviderSource,
} from "@prismshadow/penguin-core/plugin";
const ARGV = ["bash", "-lc", "echo hi"] as const;
@@ -38,9 +39,7 @@ function fake(label: string, dimensions?: readonly SandboxDimension[]) {
return { provider, calls };
}
-async function service(
- entries: Array<[string, SandboxProvider | PromiseLike<SandboxProvider | null> | null]>,
-): Promise<SandboxService> {
+async function service(entries: Array<[string, SandboxProviderSource]>): Promise<SandboxService> {
const svc = new SandboxService(entries);
await svc.whenReady();
return svc;
@@ -76,12 +75,70 @@ describe("sandbox service — the built-in interface and its optional dimensions
["loud", Promise.reject(new Error("'bwrap' is missing"))],
]);
expect(svc.backends()).toEqual([]);
+ expect(svc.declined()).toEqual(["quiet"]);
+ expect(svc.failures()).toEqual([{ name: "loud", reason: "'bwrap' is missing" }]);
svc.configure({ mode: "read-only" });
expect(() => svc.confiner()([...ARGV], OPTS)).toThrow(
/loud \('bwrap' is missing\); quiet \(not for this host\)/,
);
});
+ it("a failed loader loads again on retry and mounts in its routing place; a failed promise cannot", async () => {
+ const bwrap = fake("bwrap", ["fs-write", "network"]);
+ const dsh = fake("dsh");
+ let runner = "/opt/bwarp";
+ const loader = vi.fn(async () => {
+ if (runner !== "bwrap") throw new Error(`'${runner}' is missing`);
+ return bwrap.provider;
+ });
+ const svc = await service([
+ ["bwrap", loader],
+ ["gone", Promise.reject(new Error("MODULE_NOT_FOUND"))],
+ ["dsh-local", dsh.provider],
+ ]);
+ expect(svc.failures().map((f) => f.name)).toEqual(["bwrap", "gone"]);
+ runner = "bwrap";
+ await svc.retryFailed();
+ expect(loader).toHaveBeenCalledTimes(2);
+ expect(svc.failures()).toEqual([{ name: "gone", reason: "MODULE_NOT_FOUND" }]);
+ // Registration order is routing order: the recovered backend comes before dsh-local.
+ expect(svc.backends().map((b) => b.name)).toEqual(["bwrap", "dsh-local"]);
+ svc.configure({ mode: "read-only" });
+ expect(svc.confiner()([...ARGV], OPTS).argv[0]).toBe("bwrap");
+ // A mounted backend is not loaded again.
+ await svc.retryFailed();
+ expect(loader).toHaveBeenCalledTimes(2);
+ });
+
+ it("of two retries in flight, the later one's outcome stands even if it settles first", async () => {
+ const good = fake("bwrap");
+ const pending: Array<(p: SandboxProvider | null) => void> = [];
+ const rejecting: Array<(e: Error) => void> = [];
+ let calls = 0;
+ const svc = await service([
+ [
+ "bwrap",
+ () => {
+ calls += 1;
+ if (calls === 1) return Promise.reject(new Error("'/opt/bwarp' is missing"));
+ return new Promise<SandboxProvider | null>((resolve, reject) => {
+ pending.push(resolve);
+ rejecting.push(reject);
+ });
+ },
+ ],
+ ]);
+ const older = svc.retryFailed();
+ const newer = svc.retryFailed();
+ await vi.waitFor(() => expect(pending).toHaveLength(2));
+ pending[1]!(good.provider);
+ await newer;
+ rejecting[0]!(new Error("'/opt/bwarp' is missing"));
+ await older;
+ expect(svc.failures()).toEqual([]);
+ expect(svc.backends().map((b) => b.name)).toEqual(["bwrap"]);
+ });
+
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.
diff --git a/packages/server/test/session-sandbox.test.ts b/packages/server/test/session-sandbox.test.ts
new file mode 100644
index 00000000..cba5bfcd
--- /dev/null
+++ b/packages/server/test/session-sandbox.test.ts
@@ -0,0 +1,231 @@
+/**
+ * A Session's sandbox policy is its own: snapshotted at creation, changed only on that Session,
+ * and bounded for non-admins by the server's settings. Editing the settings afterwards must
+ * not reach a Session that already exists.
+ */
+import { describe, expect, it } from "vitest";
+import { wire } from "@prismshadow/penguin-core/kernel";
+import type { SandboxProvider, SandboxSettings } from "@prismshadow/penguin-core/plugin";
+import { openDatabase } from "../src/db/database.js";
+import { migrate } from "../src/db/migrations.js";
+import { SCHEMA_SQL } from "../src/db/schema.js";
+import { SessionsRepo } from "../src/db/repos/sessions.js";
+import type { SessionRow } from "../src/db/repos/sessions.js";
+import { SandboxService } from "../src/sandbox/index.js";
+import { applySandboxPick, sessionSandboxOf } from "../src/services/session-service.js";
+
+const sqlite = process.getBuiltinModule("node:sqlite");
+
+const ROW: SessionRow = {
+ sessionId: "session-1",
+ projectId: "p",
+ agentId: "a",
+ provider: "prov",
+ modelId: "m",
+ workspace: "/w",
+ approvalMode: "allow-all",
+ title: null,
+ lastActiveAt: "t",
+ createdAt: "t",
+};
+
+describe("picking a Session's sandbox from the composer", () => {
+ const settings: SandboxSettings = {
+ mode: "workspace-write",
+ network: "none",
+ maskPaths: ["/secret"],
+ writableTemp: false,
+ };
+
+ it("keeps the snapshot's mask paths and temp choice, and lays the picks over it", () => {
+ const next = applySandboxPick(settings, { mode: "read-only" }, settings, false);
+ expect(next).toEqual({ ...settings, mode: "read-only" });
+ expect(sessionSandboxOf(next)).toEqual({
+ mode: "read-only",
+ network: "none",
+ localNetworkSupported: false,
+ });
+ });
+
+ it("a non-admin cannot loosen past the server's settings, in either dimension", () => {
+ expect(() =>
+ applySandboxPick(settings, { mode: "danger-full-access" }, settings, false),
+ ).toThrow(/Only an administrator/);
+ expect(() => applySandboxPick(settings, { network: "open" }, settings, false)).toThrow(
+ /Only an administrator/,
+ );
+ });
+
+ it("the local level is refused where no backend supports it, and ranks between none and open", () => {
+ expect(() => applySandboxPick(settings, { network: "local" }, settings, true)).toThrow(
+ /localhost/,
+ );
+ const open: SandboxSettings = { mode: "workspace-write" };
+ const local = applySandboxPick(open, { network: "local" }, open, false, true);
+ expect(local.network).toBe("local");
+ expect(sessionSandboxOf(local, true)).toEqual({
+ mode: "workspace-write",
+ network: "local",
+ localNetworkSupported: true,
+ });
+ // Under settings of "local", a non-admin may cut the network but not open it.
+ const localDefaults: SandboxSettings = { mode: "workspace-write", network: "local" };
+ expect(
+ applySandboxPick(localDefaults, { network: "none" }, localDefaults, false, true).network,
+ ).toBe("none");
+ expect(() =>
+ applySandboxPick(localDefaults, { network: "open" }, localDefaults, false, true),
+ ).toThrow(/Only an administrator/);
+ // Under settings of "none", "local" is already looser.
+ expect(() => applySandboxPick(settings, { network: "local" }, settings, false, true)).toThrow(
+ /Only an administrator/,
+ );
+ });
+
+ it("a non-admin who tightened may come back to the settings; an admin may go past them", () => {
+ const tightened = applySandboxPick(settings, { mode: "read-only" }, settings, false);
+ expect(applySandboxPick(tightened, { mode: "workspace-write" }, settings, false).mode).toBe(
+ "workspace-write",
+ );
+ const opened = applySandboxPick(
+ settings,
+ { mode: "danger-full-access", network: "open" },
+ settings,
+ true,
+ );
+ expect(opened.mode).toBe("danger-full-access");
+ expect(opened.network).toBeUndefined();
+ });
+});
+
+describe("the snapshot on the Session's row", () => {
+ it("round-trips, updates in place, and reads as absent on a row from before the column", () => {
+ const db = openDatabase(":memory:");
+ try {
+ const repo = wire(SessionsRepo, { db });
+ repo.insert({ ...ROW, sandbox: { mode: "read-only", network: "none" } });
+ expect(repo.findById("session-1")?.sandbox).toEqual({ mode: "read-only", network: "none" });
+ repo.updateSandbox("session-1", { mode: "danger-full-access" });
+ expect(repo.findById("session-1")?.sandbox).toEqual({ mode: "danger-full-access" });
+ repo.insert({ ...ROW, sessionId: "session-legacy" });
+ expect(repo.findById("session-legacy")?.sandbox).toBeNull();
+ } finally {
+ db.close();
+ }
+ });
+
+ it("grows the column on the swap path, so a pushed platform can write it", () => {
+ const db = new sqlite.DatabaseSync(":memory:");
+ try {
+ db.exec(SCHEMA_SQL);
+ db.exec("ALTER TABLE sessions DROP COLUMN sandbox");
+ db.exec("PRAGMA user_version = 8");
+ migrate(db, { swapPath: true });
+ const cols = db.prepare("PRAGMA table_info(sessions)").all() as { name: string }[];
+ expect(cols.some((c) => c.name === "sandbox")).toBe(true);
+ } finally {
+ db.close();
+ }
+ });
+});
+
+describe("confining under a Session's own policy", () => {
+ it("a settings change does not reach a confiner bound to the Session's snapshot", async () => {
+ const seen: string[] = [];
+ const provider: SandboxProvider = {
+ dimensions: ["fs-write", "network"],
+ confine(argv, policy) {
+ seen.push(`${policy.mode}/${policy.network ?? "open"}`);
+ return {
+ argv: ["runner", ...argv],
+ enforcement: "full",
+ denialSignatures: [],
+ runnerFailureRules: [],
+ };
+ },
+ };
+ const svc = new SandboxService([["fake", provider]]);
+ await svc.whenReady();
+ let snapshot: SandboxSettings = { mode: "workspace-write", network: "none" };
+ const sessionConfiner = svc.confinerFor(() => snapshot);
+ const opts = { cwd: "/w", workspaceDir: "/w" };
+
+ svc.configure({ mode: "danger-full-access" });
+ expect(sessionConfiner(["true"], opts).argv[0]).toBe("runner");
+ expect(seen).toEqual(["workspace-write/none"]);
+ // The settings' own confiner follows the settings; the Session's does not.
+ expect(svc.confiner()(["true"], opts).argv).toEqual(["true"]);
+
+ snapshot = { mode: "danger-full-access" };
+ expect(sessionConfiner(["true"], opts).argv).toEqual(["true"]);
+ });
+});
+
+describe("the API: settings seed new Sessions, and never reach existing ones", () => {
+ it("snapshots at creation, keeps the snapshot across a settings change, and bounds non-admins", async () => {
+ const { apiClient, createTestApp, loginAdmin, provisionUser } = await import("./helpers.js");
+ const t = await createTestApp();
+ try {
+ const admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ const owner = apiClient(t.app, (await provisionUser(t.app, "owner")).cookie);
+ const project = (await (
+ await owner.post("/api/projects", { projectId: "owner-sandbox", name: "project" })
+ ).json()) as { project: { projectId: string } };
+ const projectId = project.project.projectId;
+ await owner.put(`/api/projects/${projectId}/models`, {
+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },
+ models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],
+ });
+ const settings = (values: Record<string, unknown>) =>
+ admin.put("/api/admin/plugin-config", { name: "sandbox", values });
+ const create = async (body: Record<string, unknown> = {}) =>
+ owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, body);
+ type Created = { session: { sessionId: string; sandbox: unknown } };
+
+ expect((await settings({ mode: "workspace-write", network: "none" })).status).toBe(200);
+ const first = (await (await create()).json()) as Created;
+ expect(first.session.sandbox).toEqual({
+ mode: "workspace-write",
+ network: "none",
+ localNetworkSupported: false,
+ });
+
+ // The settings change: a new Session starts from it, the existing one does not move.
+ expect((await settings({ mode: "read-only", network: "open" })).status).toBe(200);
+ const again = (await (
+ await owner.get(`/api/sessions/${first.session.sessionId}`)
+ ).json()) as Created;
+ expect(again.session.sandbox).toEqual({
+ mode: "workspace-write",
+ network: "none",
+ localNetworkSupported: false,
+ });
+ const second = (await (await create()).json()) as Created;
+ expect(second.session.sandbox).toEqual({
+ mode: "read-only",
+ network: "open",
+ localNetworkSupported: false,
+ });
+
+ // A non-admin tightens freely, and may not loosen past the settings.
+ const tightened = await owner.patch(`/api/sessions/${first.session.sessionId}`, {
+ sandbox: { mode: "read-only" },
+ });
+ expect(tightened.status).toBe(200);
+ expect(((await tightened.json()) as Created).session.sandbox).toEqual({
+ mode: "read-only",
+ network: "none",
+ localNetworkSupported: false,
+ });
+ const loosened = await owner.patch(`/api/sessions/${second.session.sessionId}`, {
+ sandbox: { mode: "danger-full-access" },
+ });
+ expect(loosened.status).toBe(403);
+ expect(await loosened.json()).toMatchObject({ error: { code: "sandbox_forbidden" } });
+ expect((await create({ sandbox: { mode: "workspace-write" } })).status).toBe(403);
+ expect((await create({ sandbox: { mode: "nope" } })).status).toBe(400);
+ } finally {
+ await t.cleanup();
+ }
+ });
+});
diff --git a/packages/web/e2e/draft.spec.mjs b/packages/web/e2e/draft.spec.mjs
index 529f0a3c..38ea10ee 100644
--- a/packages/web/e2e/draft.spec.mjs
+++ b/packages/web/e2e/draft.spec.mjs
@@ -91,10 +91,14 @@ test("draft: pick model/approval -> reload restores them -> send creates the ses
await page.getByPlaceholder(/搜索模型/).fill("mini");
await page.getByRole("button", { name: /claude-4-8-mini/ }).click();
- // Switch the approval mode to read-only (the trigger button shows the Chinese description).
- await page.getByRole("button", { name: "审批模式" }).click();
- await page.getByRole("button", { name: /放行只读/ }).click();
- await expect(page.getByRole("button", { name: "审批模式" })).toContainText("放行只读");
+ // Switch the approval mode to read-only from the permission button's Approval section (the
+ // button is icon-only; its title spells out the three values).
+ await page.getByRole("button", { name: /^权限/ }).click();
+ await page.getByRole("menuitemradio", { name: /放行只读/ }).click();
+ await expect(page.getByRole("button", { name: /^权限/ })).toHaveAttribute(
+ "title",
+ /审批: 放行只读/,
+ );
// Conversation-time thinking level (backed by the Agent settings): the picker shows the
// seeded default (medium); the menu carries a title bar and the rows 低/中/高/极高/最高
@@ -142,7 +146,10 @@ test("draft: pick model/approval -> reload restores them -> send creates the ses
)
.toBe(true);
await expect(page.getByRole("button", { name: "选择模型" })).toContainText("claude-4-8-mini");
- await expect(page.getByRole("button", { name: "审批模式" })).toContainText("放行只读");
+ await expect(page.getByRole("button", { name: /^权限/ })).toHaveAttribute(
+ "title",
+ /审批: 放行只读/,
+ );
// The thinking level is NOT draft state: it restores from the Agent config (written through above), not the cache.
await expect(page.getByRole("button", { name: "思考等级" })).toContainText("高 (high)");
// Send: the Session is only created now, and the selections land faithfully in its meta.
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 732a5f9d..f06f73ae 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -160,6 +160,9 @@ import type {
SessionProcessesResponse,
SessionResponse,
PluginIndexResponse,
+ PluginConfigResponse,
+ PluginConfigActionResponse,
+ PluginConfigUpdateRequest,
PluginReadmeResponse,
SessionsResponse,
SessionTracesResponse,
@@ -260,6 +263,21 @@ export const adminDeleteUser = (userId: string) =>
/** Server-global settings (admin only): currently the "use system HTTP proxy" switch. */
export const adminGetSettings = () => apiFetch<ServerSettingsResponse>("/api/admin/settings");
+/** Every loaded plugin that declares a configuration, with its schema and masked values (admin). */
+export const adminGetPluginConfig = () =>
+ apiFetch<PluginConfigResponse>("/api/admin/plugin-config");
+
+/** One package's update (admin): omitted fields keep their value, a masked secret sent back keeps the stored one. */
+export const adminPutPluginConfig = (body: PluginConfigUpdateRequest) =>
+ apiFetch<PluginConfigResponse>("/api/admin/plugin-config", { method: "PUT", body });
+
+/** Runs one settings group's action (admin): what a deployment must DO on the machine, once. */
+export const adminRunPluginConfigAction = (body: { name: string; action: string }) =>
+ apiFetch<PluginConfigActionResponse>("/api/admin/plugin-config/action", {
+ method: "POST",
+ body,
+ });
+
/** Omitted fields keep their current value; applies immediately (no restart). */
export const adminPutSettings = (body: ServerSettingsUpdateRequest) =>
apiFetch<ServerSettingsResponse>("/api/admin/settings", { method: "PUT", body });
@@ -1801,7 +1819,7 @@ export const getDesktopTray = () => apiFetch<DesktopTrayStatusResponse>("/api/de
export const setDesktopTray = (patch: DesktopTrayPatch) =>
apiFetch<void>("/api/desktop/tray", { method: "PUT", body: patch });
-// ---- The plugins a Project asks for ----
+// ---- The plugins a Project asks for, and the confinement agent commands run under ----
/**
* A Project's plugin list. Project-scoped because machines are lent to Projects, so this is
* what says which machines a plugin has to reach; what the process RUNS is the union over
diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsx
index e4fddfe2..58d8de54 100644
--- a/packages/web/src/components/layout/app-layout.tsx
+++ b/packages/web/src/components/layout/app-layout.tsx
@@ -305,7 +305,7 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
)}
</nav>
{/* The account menu opens here, on the rail, instead of the avatar expanding the sidebar
- first: appearance and System settings, the update row and signing out all stay one
+ first: appearance and Settings, the update row and signing out all stay one
click away while collapsed. Same component as the pinned sidebar's (user-menu.tsx). */}
<UserMenu
className="mt-auto shrink-0"
diff --git a/packages/web/src/components/layout/user-menu.tsx b/packages/web/src/components/layout/user-menu.tsx
index 2a5c444b..c3fb3b3d 100644
--- a/packages/web/src/components/layout/user-menu.tsx
+++ b/packages/web/src/components/layout/user-menu.tsx
@@ -1,7 +1,7 @@
/**
* The account menu, shared by both avatars that open one: the pinned sidebar's user row and
* the collapsed rail's avatar. One component rather than a copy per anchor — the rows
- * (System settings, the update entry, sign out) and the dialog behind the first of them must
+ * (Settings, the update entry, sign out) and the dialog behind the first of them must
* stay the same menu from either side, and a second copy is how two menus drift apart.
*
* Only the trigger differs, so the trigger is the caller's: it is handed the menu's own open
@@ -89,7 +89,7 @@ export function UserMenu({
</div>
</div>
)}
- {/* System settings dialog: everyone gets the row — the dialog always has the
+ {/* Settings dialog: everyone gets the row — the dialog always has the
personal pages, and the server-global ones inside it stay gated by the
section registry rather than by this row. The preference rows that used to
stack here live on its pages now. */}
@@ -101,7 +101,7 @@ export function UserMenu({
setSettingsOpen(true);
}}
>
- {S.settings.systemSettings}
+ {S.settings.title}
</button>
{/* Update entry, directly under the settings entry rather than on a page inside
it: one row for both backends (the server release here, the shell's own
diff --git a/packages/web/src/components/ui/paged-dialog.tsx b/packages/web/src/components/ui/paged-dialog.tsx
index 12ef030f..52ad1b62 100644
--- a/packages/web/src/components/ui/paged-dialog.tsx
+++ b/packages/web/src/components/ui/paged-dialog.tsx
@@ -1,6 +1,6 @@
/**
* PagedDialog: a large modal whose left rail switches sub-pages — the shared shell for
- * multi-page settings surfaces (System settings today; Project settings converges on the
+ * multi-page settings surfaces (Settings today; Project settings converges on the
* same shell). Purely presentational: the caller owns which pages exist, which one is
* active, and what the pane renders; the shell draws the rail (grouped, icon + label,
* solid-fill active row — the sidebar's convention), the pane heading, and the close
diff --git a/packages/web/src/features/admin/admin-users-page.tsx b/packages/web/src/features/admin/admin-users-page.tsx
index 8b597e34..8e2f2cbe 100644
--- a/packages/web/src/features/admin/admin-users-page.tsx
+++ b/packages/web/src/features/admin/admin-users-page.tsx
@@ -1,6 +1,6 @@
/**
* User management (admin only): user list + create / reset password / delete. Rendered as
- * a page of the System settings dialog rather than a routed page of its own.
+ * a page of the Settings dialog rather than a routed page of its own.
* Registration is closed: new users are created here, with the initial password set by the admin and
* communicated offline; deleting a user also deletes all their Projects (including data directories),
* with a confirmation dialog.
diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsx
index 6f6acd3f..0bbba416 100644
--- a/packages/web/src/features/chat/chat-input.tsx
+++ b/packages/web/src/features/chat/chat-input.tsx
@@ -83,6 +83,7 @@ import type {
PendingFollowUpInfo,
PendingSteeringInfo,
RecalledMessageResponse,
+ SessionSandbox,
SessionStatus,
SkillMetadataItem,
TaskInputPart,
@@ -95,6 +96,7 @@ import { agentDisplayName } from "../../state/project";
import { AgentAvatar } from "../../components/ui/agent-avatar";
import { Button } from "../../components/ui/button";
import { Dropdown } from "../../components/ui/dropdown";
+import { PermissionSelect } from "./permission-select";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { CheckIcon, ChevronDown } from "../../components/ui/icons";
import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
@@ -132,111 +134,6 @@ import { splitBySize } from "../../lib/upload-limits";
import type { ComposerReference } from "../../lib/workspace-tree";
import { ReferenceChip } from "./reference-chip";
-const APPROVAL_MODES: ApprovalMode[] = ["always-ask", "read-only", "allow-all", "deny-all"];
-
-/**
- * Illustrative icon for each approval mode (24x24 line art, grayscale via currentColor, no
- * color-coding): allow-all uses a warning triangle — it permits everything at the user's own
- * risk, the shape hints at it visually without rendering tension through color; deny-all is a
- * no-entry sign, read-only is an eye, always-ask is a question-mark circle.
- */
-const APPROVAL_MODE_ICONS: Record<ApprovalMode, string> = {
- "allow-all":
- "M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0zM12 9v4m0 4h.01",
- "deny-all": "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM5.64 5.64l12.72 12.72",
- "read-only":
- "M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z",
- "always-ask":
- "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM9.1 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3m.07 4h.01",
-};
-
-/**
- * Approval mode selector (custom-drawn dropdown, not the browser's native select): small,
- * grayscale.
- * Popup direction depends on context: for the draft card, vertically centered with room below
- * -> opens downward; for the chat input area docked at the bottom of the screen, where opening
- * downward would overflow the viewport with nowhere to scroll -> opens upward.
- */
-function ApprovalModeSelect({
- value,
- onChange,
- disabled,
- direction = "up",
-}: {
- value: ApprovalMode;
- onChange: (mode: ApprovalMode) => void;
- disabled: boolean;
- direction?: "up" | "down";
-}) {
- const [open, setOpen] = useState(false);
- return (
- <Dropdown
- open={open}
- setOpen={setOpen}
- // w-max: width exactly wraps the longest line (no wrapping within a line), avoiding an
- // overly wide panel. Placement is portal-driven (the toolbar scrolls horizontally on
- // phones, which would otherwise clip the panel); only size classes belong here.
- menuClass="w-max"
- portal={{ direction, align: "left" }}
- button={
- // Button styling matches the model selector (h-8 / rounded-md / solid hover background).
- <button
- type="button"
- aria-label={S.chat.approvalMode}
- title={`${S.chat.approvalMode}:${S.chat.approvalModeNames[value] ?? value}`}
- disabled={disabled}
- onClick={() => setOpen((v) => !v)}
- className="flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
- >
- {/* Icon changes with the current mode (allow-all = warning triangle, grayscale, no color-coding) */}
- <GlyphIcon d={APPROVAL_MODE_ICONS[value]} />
- {/* Button shows only the description (the mode id is spelled out in the menu); when the card is narrower than @md, only the icon remains (title shows the full name). */}
- <span className="hidden min-w-0 truncate @md:block">
- {S.chat.approvalModeNames[value] ?? value}
- </span>
- <ChevronDown size={ICON_SIZE.caretDense} />
- </button>
- }
- >
- {APPROVAL_MODES.map((m) => (
- <button
- key={m}
- type="button"
- onClick={() => {
- onChange(m);
- setOpen(false);
- }}
- className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${
- m === value
- ? "font-medium text-gray-900 dark:text-gray-100"
- : "text-gray-600 dark:text-gray-400"
- }`}
- >
- <svg
- width="13"
- height="13"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.7"
- strokeLinecap="round"
- strokeLinejoin="round"
- aria-hidden
- className="shrink-0 text-gray-400 dark:text-gray-500"
- >
- <path d={APPROVAL_MODE_ICONS[m]} />
- </svg>
- {/* Description first, mode id after (copy in strings); single line, no wrapping, selected checkmark at line end. */}
- <span className="min-w-0 flex-1 truncate whitespace-nowrap">
- {S.chat.approvalModes[m] ?? m}
- </span>
- <span className="w-3 shrink-0 text-center">{m === value ? "✓" : ""}</span>
- </button>
- ))}
- </Dropdown>
- );
-}
-
/**
* Agent candidate panel for the `/agent` switch picker — the agent-side counterpart of
* ModelMenuList, and now literally the same panel (PickerList: search, scroll cap, keyboard
@@ -522,18 +419,16 @@ function SkillSelect({
disabled={disabled}
// The panel is unmounted while closed, so its search box starts empty on every open.
onClick={() => setOpen(!open)}
- className="flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ // Icon only, the + button's square; the selected count rides the corner.
+ className="relative flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
>
- <GlyphIcon d={BOOK_ICON} className="shrink-0" />
- {/* When the card is narrower than @md, only the icon + badge remain (title shows the full name). */}
- <span className="hidden min-w-0 truncate @md:block">{S.chat.skillsSelect}</span>
+ <GlyphIcon d={BOOK_ICON} size={15} className="shrink-0" />
{/* Selected-count badge (the chip row above the input mirrors the selection too). */}
{selected.length > 0 && (
- <span className="shrink-0 rounded-full bg-gray-200/80 px-1.5 py-px font-mono text-[10px] font-semibold text-gray-700 dark:bg-gray-700/60 dark:text-gray-200">
+ <span className="absolute -top-0.5 -right-0.5 min-w-3.5 rounded-full bg-gray-200 px-1 text-center font-mono text-[9px] leading-3.5 font-semibold text-gray-700 dark:bg-gray-700 dark:text-gray-200">
{selected.length}
</span>
)}
- <ChevronDown size={ICON_SIZE.caretDense} />
</button>
}
>
@@ -828,6 +723,8 @@ export function ChatInput({
vision,
approvalMode,
onChangeApprovalMode,
+ sandbox,
+ onChangeSandbox,
modeSaving,
autoFocus,
agents,
@@ -992,7 +889,11 @@ export function ChatInput({
/** Whether the current model supports image input (models config's vision; assumed supported by default). */
vision: boolean;
approvalMode: ApprovalMode;
- onChangeApprovalMode: (mode: ApprovalMode) => void;
+ /** A returned promise keeps the permission button's pick on screen until the save settles. */
+ onChangeApprovalMode: (mode: ApprovalMode) => void | Promise<unknown>;
+ /** The Session's own sandbox policy (the draft's pick before there is a Session). */
+ sandbox: SessionSandbox;
+ onChangeSandbox: (pick: Partial<SessionSandbox>) => void | Promise<unknown>;
modeSaving: boolean;
autoFocus?: boolean;
/** Agent list of the current Project: the `/agent` command's candidates (without any, the command isn't offered). */
@@ -2662,70 +2563,76 @@ export function ChatInput({
className="hidden"
onChange={onPickAttachments}
/>
- {/* "+" extension menu, leading the row: input add-ons (image upload, file
+ {/* The three icon buttons — +, permission, skills — sit as one tight cluster: the
+ row's wider gap would read them as unrelated controls. */}
+ <div className="flex shrink-0 items-center gap-0.5">
+ {/* "+" extension menu, leading the row: input add-ons (image upload, file
attachment, goal mode) plus the input settings footer (mid-run send mode —
usable while running, which is exactly when it matters, so the button itself
never disables). The uploads live in here rather than as their own toolbar
buttons: one 8x8 slot instead of three, which is the difference between the
phone row scrolling and not. */}
- {variant === "session" && (
- <PlusMenu
- items={[
- {
- key: "image",
- icon: IMAGE_ICON,
- label: S.chat.uploadImage,
- // Without vision the images still send — as scratchpad file paths — so the
- // entry stays usable and the hint says what will happen instead. Goal mode
- // changes nothing here: a goal's images ride its first message as ordinary
- // image input, so the model's vision decides how they arrive, exactly as
- // for any other send.
- desc: vision ? S.chat.uploadImageDesc : S.chat.imagesAsPathHint,
- active: images.length > 0,
- onSelect: () => imageInputRef.current?.click(),
- },
- {
- key: "file",
- icon: PAPERCLIP_ICON,
- label: S.chat.uploadFile,
- // The description doubles as the explanation of where the file ends up:
- // it is filed into the session scratchpad and reached by path, never
- // inlined into the conversation.
- desc: S.chat.uploadFileDesc,
- active: attachments.length > 0,
- // Unlike images, a file cannot ride a goal: the server refuses file
- // attachments on a goal request.
- disabled: goalOn,
- onSelect: () => attachmentInputRef.current?.click(),
- },
- {
- key: "goal",
- icon: GOAL_ICON,
- label: S.chat.goalMode,
- desc: S.chat.goalModeDesc,
- active: goalOn,
- disabled: running || compacting || busy,
- onSelect: () => toggleGoal(!goalOn),
- },
- ]}
- footer={<SteerModeRow steerMode={steerMode} onChangeSteerMode={setSteerMode} />}
+ {variant === "session" && (
+ <PlusMenu
+ items={[
+ {
+ key: "image",
+ icon: IMAGE_ICON,
+ label: S.chat.uploadImage,
+ // Without vision the images still send — as scratchpad file paths — so the
+ // entry stays usable and the hint says what will happen instead. Goal mode
+ // changes nothing here: a goal's images ride its first message as ordinary
+ // image input, so the model's vision decides how they arrive, exactly as
+ // for any other send.
+ desc: vision ? S.chat.uploadImageDesc : S.chat.imagesAsPathHint,
+ active: images.length > 0,
+ onSelect: () => imageInputRef.current?.click(),
+ },
+ {
+ key: "file",
+ icon: PAPERCLIP_ICON,
+ label: S.chat.uploadFile,
+ // The description doubles as the explanation of where the file ends up:
+ // it is filed into the session scratchpad and reached by path, never
+ // inlined into the conversation.
+ desc: S.chat.uploadFileDesc,
+ active: attachments.length > 0,
+ // Unlike images, a file cannot ride a goal: the server refuses file
+ // attachments on a goal request.
+ disabled: goalOn,
+ onSelect: () => attachmentInputRef.current?.click(),
+ },
+ {
+ key: "goal",
+ icon: GOAL_ICON,
+ label: S.chat.goalMode,
+ desc: S.chat.goalModeDesc,
+ active: goalOn,
+ disabled: running || compacting || busy,
+ onSelect: () => toggleGoal(!goalOn),
+ },
+ ]}
+ footer={<SteerModeRow steerMode={steerMode} onChangeSteerMode={setSteerMode} />}
+ direction={models && onChangeModel ? "down" : "up"}
+ />
+ )}
+ <PermissionSelect
+ approvalMode={approvalMode}
+ sandbox={sandbox}
+ onChangeApprovalMode={onChangeApprovalMode}
+ onChangeSandbox={onChangeSandbox}
+ disabled={modeSaving}
direction={models && onChangeModel ? "down" : "up"}
/>
- )}
- <ApprovalModeSelect
- value={approvalMode}
- onChange={onChangeApprovalMode}
- disabled={modeSaving}
- direction={models && onChangeModel ? "down" : "up"}
- />
- {/* Multi-select skills dropdown (after approval mode): selected state is conveyed via the button badge. */}
- <SkillSelect
- skills={skills}
- selected={selectedSkills}
- onToggle={toggleSkill}
- disabled={running || compacting || busy}
- direction={models && onChangeModel ? "down" : "up"}
- />
+ {/* Multi-select skills dropdown (after approval mode): selected state is conveyed via the button badge. */}
+ <SkillSelect
+ skills={skills}
+ selected={selectedSkills}
+ onToggle={toggleSkill}
+ disabled={running || compacting || busy}
+ direction={models && onChangeModel ? "down" : "up"}
+ />
+ </div>
{/* Help text: shown only when the card is wide enough (@lg); it never competes for
space on phones, where the group scrolls instead. */}
<span
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index fe1f89f6..3e908354 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -26,6 +26,7 @@ import type {
ModelsResponse,
SessionInfo,
SessionPatchRequest,
+ SessionSandbox,
SessionProcessInfo,
SessionStatus,
SkillMetadataItem,
@@ -1175,6 +1176,7 @@ export function ChatPage() {
modelId: ref.modelId,
workspace: selected.workspace,
approvalMode: selected.approvalMode,
+ sandbox: selected.sandbox,
});
createdId = created.session.sessionId;
const res = await api.postTask(createdId, { input: [origin, ...input] });
@@ -1215,6 +1217,7 @@ export function ChatPage() {
try {
const created = await api.createSession(projectId, target.agentId, {
approvalMode: selected.approvalMode,
+ sandbox: selected.sandbox,
});
createdId = created.session.sessionId;
const res = await api.postTask(createdId, { input: [origin, ...input] });
@@ -1409,7 +1412,8 @@ export function ChatPage() {
(mode: ApprovalMode) => {
if (!selected || modeSaving) return;
setModeSaving(true);
- void api
+ // Returned so the permission button keeps the pick on screen until the save settles.
+ return api
.patchSession(selected.sessionId, { approvalMode: mode })
.then((res) => replace(res.session))
.catch((e: unknown) => {
@@ -1420,6 +1424,25 @@ export function ChatPage() {
[selected, modeSaving, replace],
);
+ // The Session's own sandbox policy: saved on the Session and applied from its next command.
+ // The same save shape as the approval mode — a refused change (a non-admin loosening past
+ // the server's settings) is a toast, and the button keeps showing what the server has.
+ const onChangeSandbox = useCallback(
+ (pick: Partial<SessionSandbox>) => {
+ if (!selected || modeSaving) return;
+ setModeSaving(true);
+ // Returned so the permission button keeps the pick on screen until the save settles.
+ return api
+ .patchSession(selected.sessionId, { sandbox: pick })
+ .then((res) => replace(res.session))
+ .catch((e: unknown) => {
+ toastError(apiErrorText(e));
+ })
+ .finally(() => setModeSaving(false));
+ },
+ [selected, modeSaving, replace],
+ );
+
// Starts a context compaction — the single path to the server for it (the composer's
// /compact command and the thinking-switch dialog's "compact, then switch" both come
// through here). Returns whether the request was ACCEPTED: the endpoint answers 202 and
@@ -1681,6 +1704,7 @@ export function ChatPage() {
models={models?.models ?? []}
approvalMode={selected.approvalMode}
onChangeApprovalMode={onChangeApprovalMode}
+ onChangeSandbox={onChangeSandbox}
modeSaving={modeSaving}
parentThinkingLevel={sessionThinkingLevel(turnThinkingLevel, agentThinkingLevel)}
/>
@@ -1833,6 +1857,8 @@ export function ChatPage() {
vision={vision}
approvalMode={selected.approvalMode}
onChangeApprovalMode={onChangeApprovalMode}
+ sandbox={selected.sandbox}
+ onChangeSandbox={onChangeSandbox}
modeSaving={modeSaving}
autoFocus
agents={agents}
diff --git a/packages/web/src/features/chat/draft-cache.ts b/packages/web/src/features/chat/draft-cache.ts
index 91be0b98..4243ce8b 100644
--- a/packages/web/src/features/chat/draft-cache.ts
+++ b/packages/web/src/features/chat/draft-cache.ts
@@ -10,7 +10,7 @@
* succession and the key only contains the Project/Session ID, the later user would recover the
* previous user's text, Workspace, model selection, and handoff target — a cross-account information leak.
*/
-import type { ApprovalMode } from "@prismshadow/penguin-server/api";
+import type { ApprovalMode, SessionSandbox } from "@prismshadow/penguin-server/api";
const APPROVAL_MODES: ApprovalMode[] = ["always-ask", "read-only", "allow-all", "deny-all"];
@@ -19,6 +19,8 @@ export interface DraftCache {
agentId?: string;
workspace?: string;
approvalMode?: ApprovalMode;
+ /** The draft's own permission picks; a half left out follows the server's sandbox settings. */
+ sandbox?: Partial<SessionSandbox>;
/**
* The model selected in the draft (a paired reference; (provider, modelId) is the unique key):
* load validates the object shape; the old string-typed modelId field is simply dropped
@@ -124,6 +126,21 @@ export function draftFromUnknown(parsed: unknown): DraftCache {
) {
out.approvalMode = o.approvalMode as ApprovalMode;
}
+ if (typeof o.sandbox === "object" && o.sandbox !== null) {
+ const raw = o.sandbox as Record<string, unknown>;
+ const sandbox: Partial<SessionSandbox> = {};
+ if (
+ raw.mode === "read-only" ||
+ raw.mode === "workspace-write" ||
+ raw.mode === "danger-full-access"
+ ) {
+ sandbox.mode = raw.mode;
+ }
+ if (raw.network === "open" || raw.network === "local" || raw.network === "none") {
+ sandbox.network = raw.network;
+ }
+ if (Object.keys(sandbox).length > 0) out.sandbox = sandbox;
+ }
return out;
}
diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsx
index 9b654aab..4b28b1ed 100644
--- a/packages/web/src/features/chat/draft-view.tsx
+++ b/packages/web/src/features/chat/draft-view.tsx
@@ -47,11 +47,13 @@ import type {
ModelRefDto,
ModelsResponse,
SessionCreateRequest,
+ SessionSandbox,
SkillMetadataItem,
TaskInputPart,
} from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
+import { UNCONFINED } from "../../lib/permission-level";
import { formatMonthDay } from "../../lib/format";
import { apiErrorText } from "../../lib/api-error";
import { useAuth } from "../../state/auth";
@@ -199,6 +201,9 @@ export function DraftView({
const [approvalMode, setApprovalMode] = useState<ApprovalMode>(
cached.approvalMode ?? "allow-all",
);
+ // Only what the person picked: the rest follows the server's sandbox settings, which the
+ // chat-defaults response carries, so the button shows what the Session would start with.
+ const [sandboxPick, setSandboxPick] = useState<Partial<SessionSandbox>>(cached.sandbox ?? {});
const [modelRef, setModelRef] = useState<ModelRefDto | null>(cached.modelRef ?? null);
const textRef = useRef(cached.text ?? "");
/**
@@ -493,6 +498,7 @@ export function DraftView({
cancelPendingSave();
if (!userId) return;
const data: DraftCache = { text: textRef.current, workspace, approvalMode };
+ if (Object.keys(sandboxPick).length > 0) data.sandbox = sandboxPick;
if (agentId) data.agentId = agentId;
if (modelRef) data.modelRef = modelRef;
if (skillsRef.current.length > 0) data.skills = skillsRef.current;
@@ -513,6 +519,7 @@ export function DraftView({
agentId,
workspace,
approvalMode,
+ sandboxPick,
modelRef,
cached.source,
]);
@@ -638,6 +645,9 @@ export function DraftView({
touchedRef.current.approval = true;
setApprovalMode(mode);
}, []);
+ const changeSandbox = useCallback((pick: Partial<SessionSandbox>) => {
+ setSandboxPick((prev) => ({ ...prev, ...pick }));
+ }, []);
// Synchronous in-flight guard for the one send entry point (the composer): a second
// submission while one is running would create a second Session with its own first task and
@@ -655,6 +665,7 @@ export function DraftView({
let createdId: string | null = null;
try {
const body: SessionCreateRequest = { approvalMode };
+ if (Object.keys(sandboxPick).length > 0) body.sandbox = sandboxPick;
// Model reference is submitted as a pair (provider + modelId; falls back to the Project default when not set).
if (modelRef) {
body.modelId = modelRef.modelId;
@@ -695,6 +706,7 @@ export function DraftView({
projectId,
agentId,
approvalMode,
+ sandboxPick,
modelRef,
workspace,
cached.source,
@@ -790,6 +802,8 @@ export function DraftView({
vision={vision}
approvalMode={approvalMode}
onChangeApprovalMode={changeApprovalMode}
+ sandbox={{ ...(chatDefaults?.sandbox ?? UNCONFINED), ...sandboxPick }}
+ onChangeSandbox={changeSandbox}
modeSaving={false}
autoFocus
agents={agents}
diff --git a/packages/web/src/features/chat/permission-select.tsx b/packages/web/src/features/chat/permission-select.tsx
new file mode 100644
index 00000000..94ad485b
--- /dev/null
+++ b/packages/web/src/features/chat/permission-select.tsx
@@ -0,0 +1,243 @@
+/**
+ * The composer's permission button: an icon-only square like the + button, wearing lucide's
+ * shield icon for the level (see lib/permission-level.ts) — a different icon per level, coloured
+ * by it, so the level never depends on colour alone. The menu has three sections — Filesystem, Network and Approval — and, for an
+ * administrator, More…, which opens the Settings page's Sandbox card.
+ *
+ * Filesystem and Network edit the Session's own sandbox policy: a Session keeps the policy it
+ * was created with, so the Settings page only decides what NEW Sessions start from.
+ *
+ * Popup direction depends on context: the draft card has room below and opens downward; the
+ * chat input docked at the bottom of the screen opens upward.
+ */
+import { useState } from "react";
+import type { ReactNode } from "react";
+import type { ApprovalMode, SessionSandbox } from "@prismshadow/penguin-server/api";
+import { S } from "../../lib/strings";
+import { Dropdown } from "../../components/ui/dropdown";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { toneInk } from "../../lib/tone";
+import {
+ PERMISSION_LEVEL_GLYPH,
+ PERMISSION_LEVEL_TONE,
+ permissionLevel,
+} from "../../lib/permission-level";
+import { useAuth } from "../../state/auth";
+import { SettingsDialog } from "../settings/settings-dialog";
+
+const APPROVAL_MODES: ApprovalMode[] = ["always-ask", "read-only", "allow-all", "deny-all"];
+const FS_MODES: SessionSandbox["mode"][] = ["read-only", "workspace-write", "danger-full-access"];
+const NETWORK_MODES: SessionSandbox["network"][] = ["open", "local", "none"];
+
+/** A section's small heading inside the panel. */
+function Heading({ children }: { children: ReactNode }) {
+ return (
+ <div className="px-3 pt-2 pb-1 text-[11px] font-medium text-gray-400 dark:text-gray-500">
+ {children}
+ </div>
+ );
+}
+
+/**
+ * One choice row: its text, and a check when it is the current value. An unavailable choice
+ * stays listed, greyed out, with a short note saying why (`unavailable`).
+ */
+function Choice({
+ label,
+ selected,
+ onPick,
+ unavailable,
+}: {
+ label: string;
+ selected: boolean;
+ onPick: () => void;
+ unavailable?: string;
+}) {
+ const off = unavailable !== undefined;
+ return (
+ <button
+ type="button"
+ role="menuitemradio"
+ aria-checked={selected}
+ aria-disabled={off || undefined}
+ disabled={off}
+ title={unavailable}
+ onClick={onPick}
+ className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 ${
+ off
+ ? "cursor-not-allowed text-gray-400 dark:text-gray-600"
+ : `hover:bg-gray-100 dark:hover:bg-gray-800 ${
+ selected
+ ? "font-medium text-gray-900 dark:text-gray-100"
+ : "text-gray-600 dark:text-gray-400"
+ }`
+ }`}
+ >
+ <span className="min-w-0 flex-1 truncate whitespace-nowrap">{label}</span>
+ {off && <span className="shrink-0 text-[10px]">{S.chat.permission.unsupported}</span>}
+ <span className="w-3 shrink-0 text-center">{selected ? "✓" : ""}</span>
+ </button>
+ );
+}
+
+/** A pick not yet confirmed by its save: shown at once, dropped when the save settles. */
+interface PendingPick {
+ approvalMode?: ApprovalMode;
+ sandbox?: Partial<SessionSandbox>;
+}
+
+export function PermissionSelect({
+ approvalMode: savedApprovalMode,
+ sandbox: savedSandbox,
+ onChangeApprovalMode,
+ onChangeSandbox,
+ disabled,
+ direction = "up",
+}: {
+ approvalMode: ApprovalMode;
+ sandbox: SessionSandbox;
+ /** A save that returns a promise keeps the pick on screen until it settles. */
+ onChangeApprovalMode: (mode: ApprovalMode) => void | Promise<unknown>;
+ onChangeSandbox: (pick: Partial<SessionSandbox>) => void | Promise<unknown>;
+ /** Blocks a second pick while one saves; deliberately NOT drawn dimmed (that read as a flicker). */
+ disabled: boolean;
+ direction?: "up" | "down";
+}) {
+ const [open, setOpen] = useState(false);
+ // The pick shows the moment it is made: waiting for the server's row would draw the old
+ // level, then the new one — the flicker. When the save settles the saved values take over
+ // (on a refusal those are the old ones, and the toast says why).
+ const [pending, setPending] = useState<PendingPick | null>(null);
+ const approvalMode = pending?.approvalMode ?? savedApprovalMode;
+ const sandbox: SessionSandbox = { ...savedSandbox, ...pending?.sandbox };
+ const [settingsOpen, setSettingsOpen] = useState(false);
+ // The Sandbox card lives on the Plugins page, which only an administrator can open.
+ const isAdmin = useAuth().user?.isAdmin === true;
+ const P = S.chat.permission;
+ const level = permissionLevel(approvalMode, sandbox);
+ // The swap animation plays only for a CHANGE of level, never on the first paint — React's
+ // "adjust state while rendering" pattern for information from the previous render.
+ const [shownLevel, setShownLevel] = useState(level);
+ const [animate, setAnimate] = useState(false);
+ if (shownLevel !== level) {
+ setShownLevel(level);
+ setAnimate(true);
+ }
+ const levelName = P.levels[level] ?? level;
+ const summary = [
+ `${P.fs}: ${P.fsModes[sandbox.mode] ?? sandbox.mode}`,
+ `${P.network}: ${P.networkModes[sandbox.network] ?? sandbox.network}`,
+ `${P.approval}: ${S.chat.approvalModeNames[approvalMode] ?? approvalMode}`,
+ ].join(" · ");
+ const pick = (next: PendingPick, save: () => void | Promise<unknown>) => {
+ setOpen(false);
+ setPending(next);
+ const saved = save();
+ if (saved instanceof Promise) void saved.finally(() => setPending(null));
+ else setPending(null);
+ };
+ return (
+ <>
+ <Dropdown
+ open={open}
+ setOpen={setOpen}
+ menuClass="w-max min-w-44"
+ portal={{ direction, align: "left" }}
+ button={
+ <button
+ type="button"
+ aria-label={`${P.label}: ${levelName}`}
+ title={`${P.label}:${levelName}\n${summary}`}
+ data-level={level}
+ disabled={disabled}
+ onClick={() => setOpen((v) => !v)}
+ // Icon only, the + button's square: the level is in the icon's shape and colour, and
+ // spelled out in the accessible name and the title.
+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ {/* Keyed by level: a new level mounts a new icon, which swaps in. */}
+ <span key={level} className={animate ? "anim-icon-swap" : undefined}>
+ <GlyphIcon
+ d={PERMISSION_LEVEL_GLYPH[level]}
+ size={15}
+ className={toneInk[PERMISSION_LEVEL_TONE[level]]}
+ />
+ </span>
+ </button>
+ }
+ >
+ <div role="menu" aria-label={P.label} className="pb-1">
+ <Heading>{P.fs}</Heading>
+ {FS_MODES.map((mode) => (
+ <Choice
+ key={mode}
+ label={P.fsModes[mode] ?? mode}
+ selected={sandbox.mode === mode}
+ onPick={() =>
+ mode === sandbox.mode
+ ? setOpen(false)
+ : pick({ sandbox: { mode } }, () => onChangeSandbox({ mode }))
+ }
+ />
+ ))}
+ <Heading>{P.network}</Heading>
+ {NETWORK_MODES.map((network) => (
+ <Choice
+ key={network}
+ label={P.networkModes[network] ?? network}
+ selected={sandbox.network === network}
+ // The local level needs a backend that can enforce it on this server.
+ {...(network === "local" && sandbox.localNetworkSupported !== true
+ ? { unavailable: P.localUnsupported }
+ : {})}
+ onPick={() =>
+ network === sandbox.network
+ ? setOpen(false)
+ : pick({ sandbox: { network } }, () => onChangeSandbox({ network }))
+ }
+ />
+ ))}
+ <Heading>{P.approval}</Heading>
+ {APPROVAL_MODES.map((mode) => (
+ <Choice
+ key={mode}
+ label={S.chat.approvalModes[mode] ?? mode}
+ selected={approvalMode === mode}
+ onPick={() =>
+ mode === approvalMode
+ ? setOpen(false)
+ : pick({ approvalMode: mode }, () => onChangeApprovalMode(mode))
+ }
+ />
+ ))}
+ {isAdmin && (
+ <>
+ <div className="my-1 border-t border-gray-100 dark:border-gray-800" />
+ {/* More…: the rest of the sandbox (masked paths, the temp directory, the backend)
+ is on the Settings page's Sandbox card, where this opens. */}
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => {
+ setOpen(false);
+ setSettingsOpen(true);
+ }}
+ className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-gray-600 transition-colors duration-150 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800"
+ >
+ <span className="min-w-0 flex-1 truncate whitespace-nowrap">{P.more}</span>
+ </button>
+ </>
+ )}
+ </div>
+ </Dropdown>
+ {isAdmin && (
+ <SettingsDialog
+ open={settingsOpen}
+ onClose={() => setSettingsOpen(false)}
+ section="plugins"
+ pluginFocus="sandbox"
+ />
+ )}
+ </>
+ );
+}
diff --git a/packages/web/src/features/chat/subagents-view.tsx b/packages/web/src/features/chat/subagents-view.tsx
index 5e475d22..9d080698 100644
--- a/packages/web/src/features/chat/subagents-view.tsx
+++ b/packages/web/src/features/chat/subagents-view.tsx
@@ -25,6 +25,7 @@ import type { RefObject } from "react";
import { useNavigate } from "react-router";
import type {
ApprovalMode,
+ SessionSandbox,
ModelInfo,
SessionInfo,
SessionPatchRequest,
@@ -79,6 +80,7 @@ export function SubagentsView({
models,
approvalMode,
onChangeApprovalMode,
+ onChangeSandbox,
modeSaving,
parentThinkingLevel,
}: {
@@ -99,6 +101,8 @@ export function SubagentsView({
/** The PARENT session's approval mode — child approvals are judged by it (the same value the main composer edits). */
approvalMode: ApprovalMode;
onChangeApprovalMode: (mode: ApprovalMode) => void;
+ /** Edits the PARENT session's sandbox policy — a child runs under its root's. */
+ onChangeSandbox: (pick: Partial<SessionSandbox>) => void;
modeSaving: boolean;
/** The parent session's effective thinking level ("" = unknown): the child composer's display fallback — a child inherits it at spawn unless the spawning call pinned its own. */
parentThinkingLevel: string;
@@ -297,6 +301,8 @@ export function SubagentsView({
models={models}
approvalMode={approvalMode}
onChangeApprovalMode={onChangeApprovalMode}
+ sandbox={session.sandbox}
+ onChangeSandbox={onChangeSandbox}
modeSaving={modeSaving}
fallbackThinkingLevel={activeNode?.spawnThinkingLevel ?? parentThinkingLevel}
/>
@@ -339,6 +345,8 @@ function SubagentComposer({
models,
approvalMode,
onChangeApprovalMode,
+ sandbox,
+ onChangeSandbox,
modeSaving,
fallbackThinkingLevel,
}: {
@@ -353,6 +361,10 @@ function SubagentComposer({
models: ModelInfo[];
approvalMode: ApprovalMode;
onChangeApprovalMode: (mode: ApprovalMode) => void;
+ /** The PARENT session's sandbox policy. */
+ sandbox: SessionSandbox;
+ /** Edits the PARENT session's sandbox policy — a child runs under its root's. */
+ onChangeSandbox: (pick: Partial<SessionSandbox>) => void;
modeSaving: boolean;
/** Display fallback for the thinking picker while the user hasn't picked: the spawn call's explicit level, else the parent session's effective level (what the child inherited). */
fallbackThinkingLevel: string;
@@ -454,6 +466,8 @@ function SubagentComposer({
vision={false}
approvalMode={approvalMode}
onChangeApprovalMode={onChangeApprovalMode}
+ sandbox={sandbox}
+ onChangeSandbox={onChangeSandbox}
modeSaving={modeSaving}
agents={[]}
skills={skills}
diff --git a/packages/web/src/features/plugins/plugins-page.tsx b/packages/web/src/features/plugins/plugins-page.tsx
index 58f4c5af..d66ad995 100644
--- a/packages/web/src/features/plugins/plugins-page.tsx
+++ b/packages/web/src/features/plugins/plugins-page.tsx
@@ -63,7 +63,7 @@ import { AgentAvatar } from "../../components/ui/agent-avatar";
import { Button } from "../../components/ui/button";
import { Chevron } from "../../components/ui/chevron";
import { GlyphIcon } from "../../components/ui/glyph-icon";
-import { NAV_ICONS, PLUGIN_ICON } from "../../components/ui/icons";
+import { GEAR_ICON, NAV_ICONS, PLUGIN_ICON } from "../../components/ui/icons";
import { Modal } from "../../components/ui/modal";
import { TRASH_ICON } from "../../components/ui/session-row-menu";
import { StatusIcon } from "../../components/ui/status-icon";
@@ -77,6 +77,7 @@ import { draftKey, loadDraft, saveDraft } from "../chat/draft-cache";
import { prepareNewChatDraft } from "../chat/new-chat";
import { localizedShortText, localizedText } from "../chat/skill-use";
import { PluginDetailModal } from "./plugin-detail";
+import { SettingsDialog } from "../settings/settings-dialog";
import { formatRelativeDate } from "../../lib/format";
import { SkillTile } from "../skills/skill-icon-view";
import { InfoPopover } from "../../components/ui/info-popover";
@@ -225,6 +226,7 @@ export function PluginsPage() {
/** The specifier whose install or removal is running: the list is written one verb at a time. */
const [pendingSpecifier, setPendingSpecifier] = useState<string | null>(null);
const isAdmin = user?.isAdmin === true;
+ const [settingsOpen, setSettingsOpen] = useState(false);
/** Free text over name, specifier and description. */
const [query, setQuery] = useState("");
/** The filter column's choices: a row shows when it carries one selected category and every selected tag. */
@@ -555,7 +557,26 @@ export function PluginsPage() {
{S.plugins.pageTitle}
<InfoPopover label={S.plugins.pageTitle}>{S.plugins.pageDesc}</InfoPopover>
</h1>
+ {/* The options loaded plugins declare live on the Settings dialog's Plugins page, an
+ admin's page; this opens the dialog there rather than sending anyone through the
+ user menu to find it. */}
+ {isAdmin && (
+ <Button
+ size="sm"
+ className="h-8 w-8 shrink-0 justify-center p-0"
+ aria-label={S.plugins.openSettings}
+ title={S.plugins.openSettings}
+ onClick={() => setSettingsOpen(true)}
+ >
+ <GlyphIcon d={GEAR_ICON} size={ICON_SIZE.iconButton} />
+ </Button>
+ )}
</div>
+ <SettingsDialog
+ open={settingsOpen}
+ onClose={() => setSettingsOpen(false)}
+ section="plugins"
+ />
{/* Last stop on the plugins trail: what the sidebar's dot was pointing at, the control
that takes all of it in one press, and the way to clear it for someone who has looked
and decided to stay on the installed copies. A plugin is never NEW here — one nobody
diff --git a/packages/web/src/features/settings/account-section.tsx b/packages/web/src/features/settings/account-section.tsx
index 3d030870..889989ea 100644
--- a/packages/web/src/features/settings/account-section.tsx
+++ b/packages/web/src/features/settings/account-section.tsx
@@ -1,5 +1,5 @@
/**
- * Account page of System settings: the credentials the signed-in account can change. Only
+ * Account page of the Settings dialog: the credentials the signed-in account can change. Only
* mounted where a password exists to change — the desktop shell's own window signs in
* through a one-shot token and is filtered out by the section registry (see
* offersChangePassword for the full rule).
diff --git a/packages/web/src/features/settings/general-section.tsx b/packages/web/src/features/settings/general-section.tsx
index 937fd287..5d18055a 100644
--- a/packages/web/src/features/settings/general-section.tsx
+++ b/packages/web/src/features/settings/general-section.tsx
@@ -1,5 +1,5 @@
/**
- * General page of System settings: per-account preferences that are neither appearance nor
+ * General page of the Settings dialog: per-account preferences that are neither appearance nor
* credentials. Everything applies the moment it is touched — the stores persist each value
* (language, currency and task-completion notifications per browser) — so the page carries
* no Save button and no draft state to lose.
diff --git a/packages/web/src/features/settings/plugins-section.tsx b/packages/web/src/features/settings/plugins-section.tsx
new file mode 100644
index 00000000..45b2adfa
--- /dev/null
+++ b/packages/web/src/features/settings/plugins-section.tsx
@@ -0,0 +1,548 @@
+/**
+ * Plugin options (admin only, server-global): one card per settings entry — a group a module
+ * contributes (the sandbox) or a loaded plugin's declared configuration — drawn from its
+ * schema: a string, a secret, a boolean, a number, a choice or a list of
+ * lines per field, so the page knows nothing about any particular entry. An entry naming a
+ * `parent` is drawn inside that card (a sandbox backend's own options inside the sandbox's) and
+ * saved with it; notices the entry reports sit under its title. Each card saves on its own;
+ * nothing is written until its Save, which sends each changed entry of the card in one PUT. A secret field always starts empty and shows
+ * the stored value's mask under it: blank keeps what is stored, typing replaces it, and the
+ * clear checkbox drops it. The server validates against the same schema and answers a
+ * rejected field by name, which renders under that field.
+ *
+ * Values hydrate when the section mounts and the saved response is adopted as the new
+ * baseline, the proxy page's rule; the plugin picks the change up through its watch, so
+ * nothing here says "restart".
+ */
+import { useEffect, useRef, useState } from "react";
+import type { PluginConfigEntry, PluginConfigField } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { ApiError } from "../../api/client";
+import { S } from "../../lib/strings";
+import { useLocale } from "../../state/locale";
+import { localizedText } from "../chat/skill-use";
+import { apiErrorText } from "../../lib/api-error";
+import { Button } from "../../components/ui/button";
+import { Input, Textarea } from "../../components/ui/input";
+import { PasswordInput } from "../../components/ui/password-input";
+import { Select } from "../../components/ui/select";
+import { Switch } from "../../components/ui/switch";
+import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";
+import { toneInk, toneStrip } from "../../lib/tone";
+import { SectionShell } from "./section-shell";
+
+/**
+ * A field's draft: strings and numbers as typed (a number stays the string in the box until
+ * Save, so "1." or "-" survives the keystroke), booleans as values; a secret's clear box
+ * beside it.
+ */
+type Draft = Record<string, unknown>;
+
+/** The draft a plugin's form starts from: every non-secret value as stored, every secret empty. */
+function draftOf(entry: PluginConfigEntry): Draft {
+ const out: Draft = {};
+ for (const [name, field] of Object.entries(entry.configuration.properties)) {
+ if (field.type === "secret") continue;
+ const v = entry.values[name];
+ if (v === undefined) continue;
+ out[name] =
+ field.type === "number"
+ ? String(v)
+ : field.type === "list"
+ ? (Array.isArray(v) ? v : []).join("\n")
+ : v;
+ }
+ return out;
+}
+
+/** The value a draft sends for a field: a number parsed from its box, a list split into lines, everything else as is. */
+function valueOf(field: PluginConfigField, draft: unknown): unknown {
+ if (field.type === "list") {
+ const lines = (typeof draft === "string" ? draft : "")
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line !== "");
+ return lines.length === 0 ? null : lines;
+ }
+ if (field.type !== "number") return draft ?? null;
+ const text = typeof draft === "string" ? draft.trim() : "";
+ return text === "" ? null : Number(text);
+}
+
+/** Whether two field values are the same (lists compared by content). */
+const sameValue = (a: unknown, b: unknown) =>
+ JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
+
+/**
+ * Brings one card into view once the list has loaded — an opening that names a card (the
+ * composer's permission menu names `sandbox`) lands on it rather than on the top of the page.
+ * Once per opening: scrolling away afterwards is the person's choice.
+ */
+function FocusCard({ focus, ready }: { focus: string | undefined; ready: boolean }) {
+ const anchor = useRef<HTMLSpanElement>(null);
+ const done = useRef(false);
+ useEffect(() => {
+ if (focus === undefined || !ready || done.current) return;
+ const card = anchor.current?.parentElement?.querySelector(
+ `[data-plugin-config="${CSS.escape(focus)}"]`,
+ );
+ if (card) {
+ card.scrollIntoView({ block: "start" });
+ done.current = true;
+ }
+ }, [focus, ready]);
+ return <span ref={anchor} hidden />;
+}
+
+export function PluginsSection({ focus }: { focus?: string } = {}) {
+ const { locale } = useLocale();
+ const localized = (en: string | undefined, zhText: string | undefined) =>
+ en === undefined ? undefined : localizedText(locale, en, zhText);
+ const [entries, setEntries] = useState<PluginConfigEntry[] | null>(null);
+ const [drafts, setDrafts] = useState<Record<string, Draft>>({});
+ /** Secret fields whose stored value the next Save drops, keyed `<plugin>\0<field>`. */
+ const [clearing, setClearing] = useState<Set<string>>(new Set());
+ const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
+ const [busy, setBusy] = useState<string | null>(null);
+
+ const adopt = (list: PluginConfigEntry[]) => {
+ setEntries(list);
+ setDrafts(Object.fromEntries(list.map((e) => [e.name, draftOf(e)])));
+ setClearing(new Set());
+ };
+
+ /** One plugin's saved entry becomes its new baseline; every other form keeps its draft. */
+ const adoptOne = (saved: PluginConfigEntry) => {
+ setEntries((prev) => (prev ?? []).map((e) => (e.name === saved.name ? saved : e)));
+ setDrafts((prev) => ({ ...prev, [saved.name]: draftOf(saved) }));
+ setClearing((prev) => new Set([...prev].filter((k) => !k.startsWith(`${saved.name}\0`))));
+ };
+ const clearErrorsOf = (plugin: string) =>
+ setFieldErrors((prev) =>
+ Object.fromEntries(Object.entries(prev).filter(([k]) => !k.startsWith(`${plugin}\0`))),
+ );
+
+ useEffect(() => {
+ let cancelled = false;
+ void api.adminGetPluginConfig().then(
+ (config) => {
+ if (!cancelled) adopt(config.plugins);
+ },
+ (e: unknown) => {
+ if (!cancelled) toastError(apiErrorText(e));
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ /**
+ * While any group reports work in progress (an install it started), its notices and actions
+ * are read again every few seconds — only those: a draft being typed elsewhere on the page is
+ * not replaced, and a group that finished gets its new notices and buttons the same way.
+ */
+ const inProgress = (entries ?? []).some((e) =>
+ (e.notices ?? []).some((n) => n.tone === "progress"),
+ );
+ useEffect(() => {
+ if (!inProgress) return;
+ let cancelled = false;
+ const timer = setTimeout(() => {
+ void api.adminGetPluginConfig().then(
+ (config) => {
+ if (cancelled) return;
+ setEntries((prev) =>
+ (prev ?? []).map((e) => {
+ const next = config.plugins.find((p) => p.name === e.name);
+ if (next === undefined) return e;
+ const { notices: _n, actions: _a, ...rest } = e;
+ return {
+ ...rest,
+ ...(next.notices !== undefined ? { notices: next.notices } : {}),
+ ...(next.actions !== undefined ? { actions: next.actions } : {}),
+ };
+ }),
+ );
+ },
+ () => {
+ // A failed read leaves the card as it was; the next change of `entries` does not
+ // come, so try again on the same schedule.
+ if (!cancelled) setEntries((prev) => (prev === null ? prev : [...prev]));
+ },
+ );
+ }, 2000);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [entries, inProgress]);
+
+ /**
+ * The update one entry's draft makes, or `null` when it changes nothing; `false` when a
+ * number box does not parse (its error is set, and nothing in the card is sent).
+ */
+ const updateOf = (entry: PluginConfigEntry): Record<string, unknown> | null | false => {
+ const draft = drafts[entry.name] ?? {};
+ const values: Record<string, unknown> = {};
+ let changed = false;
+ for (const [name, field] of Object.entries(entry.configuration.properties)) {
+ if (field.type === "secret") {
+ const typed = typeof draft[name] === "string" ? (draft[name] as string).trim() : "";
+ if (typed !== "") {
+ values[name] = typed;
+ changed = true;
+ } else if (clearing.has(`${entry.name}\0${name}`)) {
+ values[name] = null;
+ changed = true;
+ }
+ continue;
+ }
+ const v = valueOf(field, draft[name]);
+ if (typeof v === "number" && !Number.isFinite(v)) {
+ setFieldErrors((prev) => ({
+ ...prev,
+ [`${entry.name}\0${name}`]: S.settings.pluginFieldNotNumber,
+ }));
+ return false;
+ }
+ // Only what changed: sending an untouched field would store its default as a value,
+ // pinning it against a later change of the default.
+ if (sameValue(v, entry.values[name])) continue;
+ values[name] = v;
+ changed = true;
+ }
+ return changed ? values : null;
+ };
+
+ /** Saves a card: its entry and the entries drawn inside it, each changed one in its own PUT. */
+ const save = async (card: PluginConfigEntry, members: PluginConfigEntry[]) => {
+ if (busy !== null) return;
+ const updates: Array<[PluginConfigEntry, Record<string, unknown>]> = [];
+ for (const entry of members) {
+ const update = updateOf(entry);
+ if (update === false) return;
+ if (update !== null) updates.push([entry, update]);
+ }
+ if (updates.length === 0) {
+ toastInfo(S.common.noChangesToSave);
+ return;
+ }
+ setBusy(card.name);
+ for (const [entry] of updates) clearErrorsOf(entry.name);
+ try {
+ for (const [entry, values] of updates) {
+ try {
+ const res = await api.adminPutPluginConfig({ name: entry.name, values });
+ const saved = res.plugins.find((e) => e.name === entry.name);
+ if (saved !== undefined) adoptOne(saved);
+ else adopt(res.plugins);
+ } catch (e) {
+ // A rejected field is named in the message as `"field" …`; it renders under that field.
+ const named =
+ e instanceof ApiError && e.code === "plugin_config_invalid"
+ ? /^"([^"]+)"/.exec(e.message)?.[1]
+ : undefined;
+ if (named !== undefined) {
+ setFieldErrors({ [`${entry.name}\0${named}`]: apiErrorText(e) });
+ } else toastError(apiErrorText(e));
+ return;
+ }
+ }
+ toastSuccess(S.common.saved);
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ /**
+ * Runs a group's action: what the deployment must DO once on the machine (the Windows
+ * sandbox's local accounts). The result's own words are what the person sees — the module
+ * knows what happened, this page does not — and the groups it answers with replace ours,
+ * because a setup that worked changes what the card says about itself.
+ */
+ const runAction = async (entry: PluginConfigEntry, action: string) => {
+ setBusy(`${entry.name}\0${action}`);
+ try {
+ const res = await api.adminRunPluginConfigAction({ name: entry.name, action });
+ adopt(res.plugins);
+ const message = localized(res.message, res.messageZh) ?? res.message;
+ if (res.ok) toastSuccess(message);
+ else toastError(message);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ if (entries === null) return <SectionShell>{null}</SectionShell>;
+
+ const patch = (plugin: string, name: string, value: unknown) => {
+ setDrafts((prev) => ({ ...prev, [plugin]: { ...(prev[plugin] ?? {}), [name]: value } }));
+ setFieldErrors((prev) => {
+ const next = { ...prev };
+ delete next[`${plugin}\0${name}`];
+ return next;
+ });
+ };
+
+ const control = (entry: PluginConfigEntry, name: string, field: PluginConfigField) => {
+ const draft = drafts[entry.name] ?? {};
+ const key = `${entry.name}\0${name}`;
+ const error = fieldErrors[key];
+ const label = localized(field.title, field.titleZh) ?? name;
+ const hint = localized(field.description, field.descriptionZh);
+ const disabled = busy !== null;
+ switch (field.type) {
+ case "enum":
+ return (
+ <Select
+ key={name}
+ size="sm"
+ label={label}
+ {...(hint !== undefined ? { hint } : {})}
+ {...(error !== undefined ? { error } : {})}
+ value={typeof draft[name] === "string" ? (draft[name] as string) : ""}
+ disabled={disabled}
+ onChange={(e) => patch(entry.name, name, e.target.value)}
+ >
+ {(field.options ?? []).map((option) => {
+ // An option this machine cannot honour stays listed, greyed out, with the reason.
+ const off = entry.unavailable?.find(
+ (u) => u.field === name && u.value === option.value,
+ );
+ const title = localized(option.title, option.titleZh);
+ return (
+ <option key={option.value} value={option.value} disabled={off !== undefined}>
+ {off === undefined
+ ? title
+ : S.settings.pluginOptionUnavailable(
+ title ?? option.value,
+ localized(off.reason, off.reasonZh) ?? off.reason,
+ )}
+ </option>
+ );
+ })}
+ </Select>
+ );
+ case "list":
+ return (
+ <Textarea
+ key={name}
+ label={label}
+ rows={3}
+ {...(hint !== undefined ? { hint } : {})}
+ {...(error !== undefined ? { error } : {})}
+ value={typeof draft[name] === "string" ? (draft[name] as string) : ""}
+ placeholder={field.placeholder ?? ""}
+ disabled={disabled}
+ onChange={(e) => patch(entry.name, name, e.target.value)}
+ />
+ );
+ case "boolean":
+ return (
+ <div key={name} className="flex items-center justify-between gap-3">
+ <div className="min-w-0">
+ <p className="text-sm font-medium">{label}</p>
+ {hint !== undefined && (
+ <p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400">{hint}</p>
+ )}
+ </div>
+ <Switch
+ checked={draft[name] === true}
+ onChange={(v) => patch(entry.name, name, v)}
+ disabled={disabled}
+ />
+ </div>
+ );
+ case "secret": {
+ const masked = typeof entry.values[name] === "string" ? (entry.values[name] as string) : "";
+ const typed = typeof draft[name] === "string" ? (draft[name] as string) : "";
+ return (
+ <div key={name} className="space-y-1">
+ <PasswordInput
+ size="sm"
+ label={label}
+ {...(hint !== undefined ? { hint } : {})}
+ {...(error !== undefined ? { error } : {})}
+ value={typed}
+ placeholder={
+ masked !== "" ? S.settings.pluginSecretKeepHint : (field.placeholder ?? "")
+ }
+ disabled={disabled}
+ autoComplete="off"
+ onChange={(e) => {
+ patch(entry.name, name, e.target.value);
+ setClearing((prev) => {
+ const next = new Set(prev);
+ next.delete(key);
+ return next;
+ });
+ }}
+ />
+ {masked !== "" && typed === "" && (
+ <label className="flex items-center gap-x-3 text-xs text-gray-500 dark:text-gray-400">
+ <span className="font-mono">{masked}</span>
+ <span className="flex items-center gap-1.5">
+ <input
+ type="checkbox"
+ checked={clearing.has(key)}
+ disabled={disabled}
+ onChange={(e) =>
+ setClearing((prev) => {
+ const next = new Set(prev);
+ if (e.target.checked) next.add(key);
+ else next.delete(key);
+ return next;
+ })
+ }
+ />
+ {S.settings.pluginSecretClear}
+ </span>
+ </label>
+ )}
+ </div>
+ );
+ }
+ case "number":
+ return (
+ <Input
+ key={name}
+ size="sm"
+ type="number"
+ label={label}
+ {...(hint !== undefined ? { hint } : {})}
+ {...(error !== undefined ? { error } : {})}
+ value={typeof draft[name] === "string" ? (draft[name] as string) : ""}
+ placeholder={field.placeholder ?? ""}
+ disabled={disabled}
+ onChange={(e) => patch(entry.name, name, e.target.value)}
+ />
+ );
+ default:
+ return (
+ <Input
+ key={name}
+ size="sm"
+ label={label}
+ {...(hint !== undefined ? { hint } : {})}
+ {...(error !== undefined ? { error } : {})}
+ value={typeof draft[name] === "string" ? (draft[name] as string) : ""}
+ placeholder={field.placeholder ?? ""}
+ disabled={disabled}
+ autoComplete="off"
+ onChange={(e) => patch(entry.name, name, e.target.value)}
+ />
+ );
+ }
+ };
+
+ /** An entry's title, its store name, its description and its notices. */
+ const heading = (entry: PluginConfigEntry, nested: boolean) => {
+ const description = localized(
+ entry.configuration.description,
+ entry.configuration.descriptionZh,
+ );
+ return (
+ <div className="space-y-1.5">
+ <div>
+ <p className={nested ? "text-[13px] font-semibold" : "text-sm font-semibold"}>
+ {localized(entry.configuration.title, entry.configuration.titleZh) ?? entry.name}
+ </p>
+ <p className="font-mono text-xs text-gray-500 dark:text-gray-400">{entry.name}</p>
+ {description !== undefined && (
+ <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">{description}</p>
+ )}
+ </div>
+ {(entry.actions ?? []).length > 0 && (
+ <div className="space-y-2">
+ {(entry.actions ?? []).map((action) => {
+ const description = localized(action.description, action.descriptionZh);
+ return (
+ <div key={action.id} className="flex items-start gap-3">
+ <Button
+ size="sm"
+ variant="secondary"
+ disabled={busy !== null}
+ onClick={() => void runAction(entry, action.id)}
+ >
+ {localized(action.title, action.titleZh) ?? action.title}
+ </Button>
+ {description !== undefined && (
+ <p className="text-xs text-gray-500 dark:text-gray-400">{description}</p>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ {(entry.notices ?? []).map((notice, i) =>
+ notice.tone === "progress" ? (
+ <p key={i} className={`flex items-center gap-2 text-xs ${toneInk.busy}`}>
+ <span
+ aria-hidden
+ className="inline-block size-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent"
+ />
+ <span className="min-w-0 break-words">{localized(notice.text, notice.textZh)}</span>
+ </p>
+ ) : notice.tone === "attention" ? (
+ <p key={i} className={`rounded-md px-3 py-2 text-xs ${toneStrip.attention}`}>
+ {localized(notice.text, notice.textZh)}
+ </p>
+ ) : (
+ <p key={i} className="text-xs text-gray-500 dark:text-gray-400">
+ {localized(notice.text, notice.textZh)}
+ </p>
+ ),
+ )}
+ </div>
+ );
+ };
+
+ // A card per entry with no parent on the page; an entry whose parent is not listed stands
+ // on its own rather than disappearing.
+ const names = new Set(entries.map((e) => e.name));
+ const cards = entries.filter((e) => e.parent === undefined || !names.has(e.parent));
+ return (
+ <SectionShell>
+ <FocusCard focus={focus} ready={entries.length > 0} />
+ {cards.map((card) => {
+ const children = entries.filter((e) => e.parent === card.name);
+ return (
+ <section
+ key={card.name}
+ data-plugin-config={card.name}
+ className="space-y-3 rounded-md border border-gray-200 p-4 dark:border-gray-800"
+ >
+ {heading(card, false)}
+ {Object.entries(card.configuration.properties).map(([name, field]) =>
+ control(card, name, field),
+ )}
+ {children.map((child) => (
+ <div
+ key={child.name}
+ className="space-y-3 border-t border-gray-100 pt-3 dark:border-gray-800/60"
+ >
+ {heading(child, true)}
+ {Object.entries(child.configuration.properties).map(([name, field]) =>
+ control(child, name, field),
+ )}
+ </div>
+ ))}
+ <div className="flex justify-end">
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy !== null}
+ onClick={() => void save(card, [card, ...children])}
+ >
+ {busy === card.name ? S.common.saving : S.common.save}
+ </Button>
+ </div>
+ </section>
+ );
+ })}
+ </SectionShell>
+ );
+}
diff --git a/packages/web/src/features/settings/profile-section.tsx b/packages/web/src/features/settings/profile-section.tsx
index 8a05db0d..6c172081 100644
--- a/packages/web/src/features/settings/profile-section.tsx
+++ b/packages/web/src/features/settings/profile-section.tsx
@@ -1,5 +1,5 @@
/**
- * Profile page of System settings: the avatar and nickname the account shows itself by.
+ * Profile page of Settings: the avatar and nickname the account shows itself by.
*
* Unlike the Account page beside it, this one exists in every session — the desktop shell's
* own token window included, which for a desktop install is the only session there is. A
diff --git a/packages/web/src/features/settings/section-shell.tsx b/packages/web/src/features/settings/section-shell.tsx
index 7fe73c23..ca852ae6 100644
--- a/packages/web/src/features/settings/section-shell.tsx
+++ b/packages/web/src/features/settings/section-shell.tsx
@@ -1,5 +1,5 @@
/**
- * Shared frame for a System settings page that saves explicitly: body, and a trailing
+ * Shared frame for a Settings page that saves explicitly: body, and a trailing
* action row. The dialog pane already draws the page heading and the "?" that discloses
* what the page is, so the shell adds no title, no explanatory line and no box of its own.
* Pages that apply on the spot pass no actions and the row is not drawn, so nothing on
diff --git a/packages/web/src/features/settings/setting-row.tsx b/packages/web/src/features/settings/setting-row.tsx
index 8de3c310..4c94a8b1 100644
--- a/packages/web/src/features/settings/setting-row.tsx
+++ b/packages/web/src/features/settings/setting-row.tsx
@@ -1,5 +1,5 @@
/**
- * Row primitives for the System settings dialog's pages: a labelled preference row —
+ * Row primitives for the Settings dialog's pages: a labelled preference row —
* title on the left, the control on the right — meant to be stacked inside a `divide-y`
* container so rows separate with rules rather than boxes. AccentPicker lives here too:
* the accent swatches moved out of the sidebar user menu together with the rows that used
diff --git a/packages/web/src/features/settings/settings-dialog.tsx b/packages/web/src/features/settings/settings-dialog.tsx
index 3b62755e..544cda92 100644
--- a/packages/web/src/features/settings/settings-dialog.tsx
+++ b/packages/web/src/features/settings/settings-dialog.tsx
@@ -1,5 +1,5 @@
/**
- * System settings dialog: one popup holding the settings that used to sit as separate rows
+ * Settings dialog: one popup holding the settings that used to sit as separate rows
* in the sidebar user menu, on the PagedDialog shell (left rail of pages, ChatGPT-style
* rows on the right). The rail is grouped — Personal for the viewer's own preferences,
* Server for the server-global settings an admin writes — and both the rail and the pane
@@ -27,6 +27,7 @@ import { AccountSection } from "./account-section";
import { ProxySection } from "./proxy-section";
import { UploadsSection } from "./uploads-section";
import { CompanySection } from "./company-section";
+import { PluginsSection } from "./plugins-section";
import { AdminUsersSection } from "../admin/admin-users-page";
/** Rail glyphs, on the shared 24x24 stroke grid (see NAV_ICONS' conventions). */
@@ -47,12 +48,27 @@ const SECTION_ICONS: Record<SettingsSectionKey, string> = {
uploads: "M12 15V4m0 0L7 9m5-5l5 5M4 20h16",
/** The building the mode switch wears: company mode. */
company: COMPANY_MODE_ICON,
+ /** Puzzle piece: plugins. */
+ plugins:
+ "M10 4a2 2 0 1 1 4 0v2h3a1 1 0 0 1 1 1v3h-2a2 2 0 1 0 0 4h2v3a1 1 0 0 1-1 1h-3v-2a2 2 0 1 0-4 0v2H7a1 1 0 0 1-1-1v-3h2a2 2 0 1 0 0-4H6V7a1 1 0 0 1 1-1h3V4z",
/** Two people: user management. */
users:
"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75",
};
-export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
+export function SettingsDialog({
+ open,
+ onClose,
+ section,
+ pluginFocus,
+}: {
+ open: boolean;
+ onClose: () => void;
+ /** The page an opening starts on; a page this viewer may not open falls back like any other. */
+ section?: SettingsSectionKey;
+ /** On the Plugins page: the card an opening scrolls to (e.g. `sandbox`). */
+ pluginFocus?: string;
+}) {
// uploadLimits feeds the Upload limits page's "?" (sectionInfo below); the rest pick pages.
const { user, desktopMode, sessionVia, uploadLimits } = useAuth();
const sections = visibleSettingsSections({
@@ -62,12 +78,13 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
});
const [active, setActive] = useState<SettingsSectionKey | null>(null);
- // Each opening starts on the viewer's first page: clearing the choice lets `current`
- // below resolve it against the live list. Deliberately keyed on `open` alone — re-running
- // on every sections identity change would yank the user off a page they navigated to.
+ // Each opening starts on the requested page, or the viewer's first: `current` below
+ // resolves the choice against the live list. Deliberately keyed on `open` (and the
+ // request) alone — re-running on every sections identity change would yank the user off a
+ // page they navigated to.
useEffect(() => {
- if (open) setActive(null);
- }, [open]);
+ if (open) setActive(section ?? null);
+ }, [open, section]);
const current = resolveSettingsSection(active, sections);
if (current === null) return null;
@@ -81,6 +98,7 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
proxy: S.settings.proxyTitle,
uploads: S.settings.uploadLimitsTitle,
company: S.settings.companyModeTitle,
+ plugins: S.settings.pluginsTitle,
users: S.admin.users,
};
const groupLabel: Record<SettingsGroupKey, string> = {
@@ -93,6 +111,7 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
proxy: S.settings.proxyInfo,
uploads: S.settings.uploadLimitsInfo(uploadLimits.attachmentMaxCount, uploadLimits.imageMaxMb),
company: S.settings.companyModeServerInfo,
+ plugins: S.settings.pluginsInfo,
};
const groups: Array<PagedDialogGroup<SettingsSectionKey>> = settingsGroups(sections).map(
@@ -114,7 +133,7 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
<PagedDialog
open={open}
onClose={onClose}
- title={S.settings.systemSettings}
+ title={S.settings.title}
groups={groups}
active={current}
onSelect={setActive}
@@ -126,6 +145,9 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
{current === "proxy" && <ProxySection />}
{current === "uploads" && <UploadsSection />}
{current === "company" && <CompanySection />}
+ {current === "plugins" && (
+ <PluginsSection {...(pluginFocus !== undefined ? { focus: pluginFocus } : {})} />
+ )}
{current === "users" && <AdminUsersSection />}
</PagedDialog>
);
diff --git a/packages/web/src/features/settings/trace-import-row.tsx b/packages/web/src/features/settings/trace-import-row.tsx
index 076f5c56..067a0037 100644
--- a/packages/web/src/features/settings/trace-import-row.tsx
+++ b/packages/web/src/features/settings/trace-import-row.tsx
@@ -1,5 +1,5 @@
/**
- * Trace import (System settings → General): a `.jsonl` Trace exported from another install
+ * Trace import (Settings → General): a `.jsonl` Trace exported from another install
* becomes a conversation of the chosen Agent.
*
* Both halves of the destination are picked here, Project included. The endpoint is
diff --git a/packages/web/src/lib/permission-level.ts b/packages/web/src/lib/permission-level.ts
new file mode 100644
index 00000000..91f196ff
--- /dev/null
+++ b/packages/web/src/lib/permission-level.ts
@@ -0,0 +1,59 @@
+/**
+ * A Session's permission level, as the composer's button shows it: one colour for how much the
+ * Agent may do on its own. Derived from the two knobs that decide it — the approval mode, and
+ * the Session's sandbox policy — never stored.
+ *
+ * - `off`: every tool call is denied.
+ * - `read-only`: commands cannot write anywhere.
+ * - `all`: nothing stands in the way — full filesystem access, the network open, and every
+ * tool call approved without asking.
+ * - `partial`: some write permission, with something still holding it back.
+ */
+import type { ApprovalMode, SessionSandbox } from "@prismshadow/penguin-server/api";
+import type { Tone } from "./tone";
+
+export type PermissionLevel = "all" | "partial" | "read-only" | "off";
+
+export function permissionLevel(approval: ApprovalMode, sandbox: SessionSandbox): PermissionLevel {
+ if (approval === "deny-all") return "off";
+ if (sandbox.mode === "read-only") return "read-only";
+ if (
+ approval === "allow-all" &&
+ sandbox.mode === "danger-full-access" &&
+ sandbox.network === "open"
+ ) {
+ return "all";
+ }
+ return "partial";
+}
+
+/** The tone each level reads in: the more the Agent may do unasked, the louder. */
+export const PERMISSION_LEVEL_TONE: Record<PermissionLevel, Tone> = {
+ all: "danger",
+ partial: "attention",
+ "read-only": "success",
+ off: "muted",
+};
+
+/** lucide `shield`: the outline the three shield icons below share. */
+export const SHIELD =
+ "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z";
+
+/**
+ * lucide's shield icons, one per level, so the level reads without colour: `shield-alert`
+ * (all), `shield-half` (partial), `shield-check` (read-only), `shield-off` (off). Each icon's
+ * `<path>` elements are joined into one `d` for GlyphIcon, a relative `m` rewritten as the
+ * same absolute move, since a joined path would otherwise start it from the previous subpath.
+ */
+export const PERMISSION_LEVEL_GLYPH: Record<PermissionLevel, string> = {
+ all: `${SHIELD}M12 8v4M12 16h.01`,
+ partial: `${SHIELD}M12 22V2`,
+ "read-only": `${SHIELD}M9 12l2 2 4-4`,
+ off:
+ "M2 2l20 20" +
+ "M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71" +
+ "M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",
+};
+
+/** What a Session starts from when the server has not said: confinement off, network open. */
+export const UNCONFINED: SessionSandbox = { mode: "danger-full-access", network: "open" };
diff --git a/packages/web/src/lib/settings-sections.ts b/packages/web/src/lib/settings-sections.ts
index 2cc59139..0ac4d9a6 100644
--- a/packages/web/src/lib/settings-sections.ts
+++ b/packages/web/src/lib/settings-sections.ts
@@ -1,5 +1,5 @@
/**
- * The System settings dialog's pages, and who may see each one.
+ * The Settings dialog's pages, and who may see each one.
*
* Server-global pages write through /api/admin/settings (or the admin user routes) and
* belong to admins alone; the personal pages are per-user preferences every signed-in user
@@ -23,9 +23,17 @@
import { offersChangePassword } from "./account-menu";
import type { AccountMenuSession } from "./account-menu";
-/** A page of the System settings dialog. */
+/** A page of the Settings dialog. */
export type SettingsSectionKey =
- "profile" | "general" | "appearance" | "account" | "proxy" | "uploads" | "company" | "users";
+ | "profile"
+ | "general"
+ | "appearance"
+ | "account"
+ | "proxy"
+ | "uploads"
+ | "company"
+ | "plugins"
+ | "users";
/** Rail heading a page sits under: the viewer's own preferences vs. the whole server's. */
export type SettingsGroupKey = "personal" | "server";
@@ -59,6 +67,8 @@ const SECTION_RULES: ReadonlyArray<SettingsSection & { visible(viewer: SettingsV
{ key: "uploads", group: "server", visible: (v) => v.isAdmin },
// The company-mode master switch: server-global like the proxy and upload limits.
{ key: "company", group: "server", visible: (v) => v.isAdmin },
+ // The sandbox, and the options loaded plugins declare (server-global, like the plugins themselves).
+ { key: "plugins", group: "server", visible: (v) => v.isAdmin },
// Single-user under the desktop shell: the server rejects the admin user routes there.
{ key: "users", group: "server", visible: (v) => v.isAdmin && !v.desktopMode },
];
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 8b10b624..250722ac 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -131,8 +131,8 @@ export const en: Strings = {
settings: {
language: "Language",
languageInfo: "Interface language; can follow the browser.",
- /** Sidebar user-menu row opening the System settings dialog. */
- systemSettings: "System settings",
+ /** Sidebar user-menu row opening the Settings dialog, and that dialog's title. */
+ title: "Settings",
/** Rail headings: the viewer's own preferences vs. the whole server's. */
groupPersonal: "Personal",
groupServer: "Server",
@@ -186,6 +186,18 @@ export const en: Strings = {
tls: "TLS handshake failed",
network: "Unreachable",
},
+ /** Admin-only sub-page (server-global): the options loaded plugins declare. */
+ pluginsTitle: "Plugins",
+ /** An enum option this machine cannot honour, listed greyed out. */
+ pluginOptionUnavailable: (title: string, reason: string) =>
+ `${title} (not supported: ${reason})`,
+ pluginsInfo:
+ "The options each loaded plugin declares in its package, drawn from the plugin's own schema. Server-global, like the plugins themselves; a save reaches the plugin at once, nothing to restart. A plugin that declares no options has no form here.",
+ /** A secret field with a stored value: submitting it empty keeps the stored one. */
+ pluginSecretKeepHint: "Leave empty to keep the saved value",
+ pluginSecretClear: "Clear stored value",
+ /** Under a number field whose box does not parse; the save is not sent. */
+ pluginFieldNotNumber: "Must be a number",
uploadLimitsTitle: "Upload limits",
/** Its two number fields, both in whole MB. */
attachmentMaxMb: "Max attachment size (MB)",
@@ -554,7 +566,7 @@ export const en: Strings = {
},
/**
- * The Profile page of System settings, and the avatar/nickname it writes. Visible in every
+ * The Profile page of Settings, and the avatar/nickname it writes. Visible in every
* session, the desktop shell's own window included: a profile needs no password to change.
*/
profile: {
@@ -1689,6 +1701,8 @@ export const en: Strings = {
applyConfirmRemove: (name: string) => `Remove ${name}?`,
applyConfirmBody: "Agent runs in progress in every Project will be stopped.",
pageTitle: "Plugins",
+ /** Header icon button opening the Settings dialog on its Plugins page (admin only). */
+ openSettings: "Plugin settings",
pageDesc:
"Every plugin in one list. The library's plugins ship with this build (skills and/or a hook package — quick-start a chat, or install to agents); the module plugins this Project asks for run in the server, and the rest of the registry can be installed for it.",
/** The list's header: how many plugins are installed — the library's (shipped, every Agent may use them) plus the module plugins this Project lists. */
@@ -2165,6 +2179,32 @@ Scenarios:
/** The same rule as `workspaceHint`, short enough to sit under a form field. */
workspaceHintShort: "Leave empty for a temporary workspace",
approvalMode: "Approval mode",
+ /** The composer's permission button: one colored shield for the level, a menu of Fs / Network / More. */
+ permission: {
+ label: "Permissions",
+ levels: {
+ all: "Full access",
+ partial: "Partial",
+ "read-only": "Read only",
+ off: "Off",
+ } as Record<string, string>,
+ fs: "Filesystem",
+ fsModes: {
+ "read-only": "Read only",
+ "workspace-write": "Workspace write",
+ "danger-full-access": "Full access",
+ } as Record<string, string>,
+ network: "Network",
+ networkModes: {
+ open: "Full access",
+ local: "Local network (localhost only)",
+ none: "No network",
+ } as Record<string, string>,
+ unsupported: "Not supported",
+ localUnsupported: "No sandbox backend on this machine can limit the network to localhost",
+ more: "More…",
+ approval: "Approval",
+ },
approvalModeNames: {
"allow-all": "Approve everything",
"deny-all": "Deny everything",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 7f710b16..0d04b6f6 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -152,8 +152,8 @@ export const zh = {
settings: {
language: "语言",
languageInfo: "界面语言,可跟随浏览器设置。",
- /** Sidebar user-menu row opening the System settings dialog. */
- systemSettings: "系统设置",
+ /** Sidebar user-menu row opening the Settings dialog, and that dialog's title. */
+ title: "设置",
/** Rail headings: the viewer's own preferences vs. the whole server's. */
groupPersonal: "个人",
groupServer: "服务器",
@@ -204,6 +204,17 @@ export const zh = {
tls: "TLS 握手失败",
network: "无法连接",
},
+ /** Admin-only sub-page (server-global): the options loaded plugins declare. */
+ pluginsTitle: "插件",
+ /** An enum option this machine cannot honour, listed greyed out. */
+ pluginOptionUnavailable: (title: string, reason: string) => `${title}(不支持:${reason})`,
+ pluginsInfo:
+ "各已装载插件在其包里声明的选项,表单按插件自己的 schema 生成。与插件本身一样是服务器全局的;保存后立即送达插件,无需重启。没有声明选项的插件不会出现在这里。",
+ /** A secret field with a stored value: submitting it empty keeps the stored one. */
+ pluginSecretKeepHint: "留空保持已保存的值不变",
+ pluginSecretClear: "清除已存值",
+ /** Under a number field whose box does not parse; the save is not sent. */
+ pluginFieldNotNumber: "必须是数字",
uploadLimitsTitle: "上传限制",
/** Its two number fields, both in whole MB. */
attachmentMaxMb: "单个附件上限(MB)",
@@ -559,7 +570,7 @@ export const zh = {
},
/**
- * The Profile page of System settings, and the avatar/nickname it writes. Visible in every
+ * The Profile page of Settings, and the avatar/nickname it writes. Visible in every
* session, the desktop shell's own window included: a profile needs no password to change.
*/
profile: {
@@ -1684,6 +1695,8 @@ export const zh = {
applyConfirmRemove: (name: string) => `移除 ${name}?`,
applyConfirmBody: "所有 Project 中正在进行的 Agent 运行都会被中止。",
pageTitle: "插件",
+ /** Header icon button opening the Settings dialog on its Plugins page (admin only). */
+ openSettings: "插件设置",
pageDesc:
"所有插件在一个列表里。插件库里的随本次构建自带(技能和/或钩子包——快捷调用,或安装到 Agent);当前 Project 要求的模块插件在服务端运行,市场里其余的可以为它安装。",
/** The list's header: how many plugins are installed — the library's (shipped, every Agent may use them) plus the module plugins this Project lists. */
@@ -2157,6 +2170,32 @@ Benchmark:
/** The same rule as `workspaceHint`, short enough to sit under a form field. */
workspaceHintShort: "留空自动创建临时工作区",
approvalMode: "审批模式",
+ /** The composer's permission button: one colored shield for the level, a menu of Fs / Network / More. */
+ permission: {
+ label: "权限",
+ levels: {
+ all: "完全访问",
+ partial: "部分权限",
+ "read-only": "只读",
+ off: "关闭",
+ } as Record<string, string>,
+ fs: "文件系统",
+ fsModes: {
+ "read-only": "只读",
+ "workspace-write": "仅工作区可写",
+ "danger-full-access": "完全访问",
+ } as Record<string, string>,
+ network: "网络",
+ networkModes: {
+ open: "完全访问",
+ local: "本地网络(仅 localhost)",
+ none: "无网络",
+ } as Record<string, string>,
+ unsupported: "不支持",
+ localUnsupported: "本机的沙盒后端不支持只允许 localhost",
+ more: "更多…",
+ approval: "审批",
+ },
/** Short description (the trigger button shows only the description, not the mode id). */
approvalModeNames: {
"allow-all": "全部放行",
diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsx
index 468379ee..d009034d 100644
--- a/packages/web/src/router.tsx
+++ b/packages/web/src/router.tsx
@@ -131,7 +131,7 @@ export function AppRouter() {
<Route path="channels/:channelId" element={<ChannelView />} />
<Route path="*" element={<Navigate to="overview" replace />} />
</Route>
- {/* System settings and user management live in the settings dialog now (see
+ {/* Settings and user management live in the settings dialog now (see
SettingsDialog); their old routes fall through to the catch-all. */}
<Route path="*" element={<Navigate to="/chat" replace />} />
</Route>
diff --git a/packages/web/src/styles.css b/packages/web/src/styles.css
index 2bf5ecb8..da3a2b57 100644
--- a/packages/web/src/styles.css
+++ b/packages/web/src/styles.css
@@ -223,6 +223,26 @@
.anim-pop {
animation: pop-in 120ms ease-out both;
}
+/* A status icon replaced by the next one (the composer's permission level): the new icon turns
+ and grows in from small, so the change is seen rather than blinked. */
+@keyframes icon-swap {
+ from {
+ opacity: 0;
+ transform: scale(0.4) rotate(-45deg);
+ }
+ 60% {
+ opacity: 1;
+ transform: scale(1.15) rotate(6deg);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1) rotate(0);
+ }
+}
+.anim-icon-swap {
+ display: block;
+ animation: icon-swap 260ms cubic-bezier(0.2, 0.7, 0.3, 1) both;
+}
/* Top toast overlay: slides in from above / slides up while fading out. */
@keyframes toast-in {
from {
diff --git a/packages/web/test/account-menu.test.ts b/packages/web/test/account-menu.test.ts
index 807cf50e..445d89d2 100644
--- a/packages/web/test/account-menu.test.ts
+++ b/packages/web/test/account-menu.test.ts
@@ -130,7 +130,7 @@ describe("the account menu", () => {
expect(source.indexOf("<ConfirmModal")).toBeGreaterThan(menuEnd);
});
- it("reaches the settings it no longer holds through one ungated System settings entry", () => {
+ it("reaches the settings it no longer holds through one ungated Settings entry", () => {
// The preference rows, change password and user management all moved into the settings
// dialog, whose own section registry decides which pages this viewer sees — so the row
// itself carries no isAdmin test, or a non-admin would lose the personal pages along
diff --git a/packages/web/test/draft-cache.test.ts b/packages/web/test/draft-cache.test.ts
index e204f662..91344630 100644
--- a/packages/web/test/draft-cache.test.ts
+++ b/packages/web/test/draft-cache.test.ts
@@ -33,6 +33,14 @@ function memStorage(): DraftStorage & { map: Map<string, string> } {
}
describe("parseDraft (field-by-field validation)", () => {
+ it("keeps the permission picks it recognizes and drops the rest", () => {
+ expect(
+ parseDraft(JSON.stringify({ sandbox: { mode: "read-only", network: "sideways" } })).sandbox,
+ ).toEqual({ mode: "read-only" });
+ expect(parseDraft(JSON.stringify({ sandbox: { mode: "bogus" } })).sandbox).toBeUndefined();
+ expect(parseDraft(JSON.stringify({ sandbox: "open" })).sandbox).toBeUndefined();
+ });
+
it("null / empty string / bad JSON / non-objects all yield an empty draft", () => {
expect(parseDraft(null)).toEqual({});
expect(parseDraft("")).toEqual({});
diff --git a/packages/web/test/info-popover.test.ts b/packages/web/test/info-popover.test.ts
index d641af40..9f7a0a78 100644
--- a/packages/web/test/info-popover.test.ts
+++ b/packages/web/test/info-popover.test.ts
@@ -87,7 +87,7 @@ describe("Field with an info popover", () => {
});
describe("PrefRow with an info popover", () => {
- // A System settings row titles a control it does not own, so its title is a <p> and the "?"
+ // A Settings row titles a control it does not own, so its title is a <p> and the "?"
// is safe beside it. An edit that made that title a <label> for the sake of click-to-toggle
// would hand the row to the trigger instead — the same trap Field carries two layouts to
// avoid, on the one row primitive that has no Field between it and the control.
diff --git a/packages/web/test/permission-level.test.ts b/packages/web/test/permission-level.test.ts
new file mode 100644
index 00000000..a0ad48e4
--- /dev/null
+++ b/packages/web/test/permission-level.test.ts
@@ -0,0 +1,48 @@
+/**
+ * The composer's permission level: one colour for how much the Agent may do on its own.
+ */
+import { describe, expect, it } from "vitest";
+import type { SessionSandbox } from "@prismshadow/penguin-server/api";
+import {
+ PERMISSION_LEVEL_GLYPH,
+ PERMISSION_LEVEL_TONE,
+ SHIELD,
+ permissionLevel,
+} from "../src/lib/permission-level";
+
+const FULL: SessionSandbox = { mode: "danger-full-access", network: "open" };
+
+describe("permission level", () => {
+ it("is all only when nothing holds the Agent back", () => {
+ expect(permissionLevel("allow-all", FULL)).toBe("all");
+ expect(permissionLevel("always-ask", FULL)).toBe("partial");
+ expect(permissionLevel("read-only", FULL)).toBe("partial");
+ expect(permissionLevel("allow-all", { ...FULL, network: "none" })).toBe("partial");
+ expect(permissionLevel("allow-all", { ...FULL, mode: "workspace-write" })).toBe("partial");
+ });
+
+ it("is read-only when commands cannot write, and off when every call is denied", () => {
+ expect(permissionLevel("allow-all", { mode: "read-only", network: "open" })).toBe("read-only");
+ expect(permissionLevel("deny-all", FULL)).toBe("off");
+ expect(permissionLevel("deny-all", { mode: "read-only", network: "none" })).toBe("off");
+ });
+
+ it("gives each level its own tone, loudest for the most access", () => {
+ expect(PERMISSION_LEVEL_TONE).toEqual({
+ all: "danger",
+ partial: "attention",
+ "read-only": "success",
+ off: "muted",
+ });
+ });
+
+ it("draws each level with its own mark, so the level never depends on colour alone", () => {
+ const glyphs = Object.values(PERMISSION_LEVEL_GLYPH);
+ expect(glyphs).toHaveLength(4);
+ expect(new Set(glyphs).size).toBe(4);
+ // lucide's shield family: the three that keep the whole outline start with it.
+ for (const level of ["all", "partial", "read-only"] as const) {
+ expect(PERMISSION_LEVEL_GLYPH[level].startsWith(SHIELD)).toBe(true);
+ }
+ });
+});
diff --git a/packages/web/test/pinned-sessions.test.ts b/packages/web/test/pinned-sessions.test.ts
index 8a28d2b2..6de99094 100644
--- a/packages/web/test/pinned-sessions.test.ts
+++ b/packages/web/test/pinned-sessions.test.ts
@@ -44,6 +44,7 @@ function session(
modelId: "claude-4-8",
workspace: "/w",
approvalMode: "allow-all",
+ sandbox: { mode: "danger-full-access", network: "open" },
createdAt: "2026-08-13T00:00:00.000Z",
lastActiveAt: "2026-08-13T00:00:00.000Z",
status: "idle",
diff --git a/packages/web/test/session-grouping.test.ts b/packages/web/test/session-grouping.test.ts
index d81d4151..0c451cc7 100644
--- a/packages/web/test/session-grouping.test.ts
+++ b/packages/web/test/session-grouping.test.ts
@@ -58,6 +58,7 @@ function session(
modelId: "claude-4-8",
workspace,
approvalMode: "allow-all",
+ sandbox: { mode: "danger-full-access", network: "open" },
createdAt,
lastActiveAt: over.lastActiveAt ?? createdAt,
status: "idle",
diff --git a/packages/web/test/session-project.test.ts b/packages/web/test/session-project.test.ts
index 0f9d4771..6e42703c 100644
--- a/packages/web/test/session-project.test.ts
+++ b/packages/web/test/session-project.test.ts
@@ -19,6 +19,7 @@ const SESSION: SessionInfo = {
modelId: "claude-sonnet-4",
workspace: "/workspace",
approvalMode: "allow-all",
+ sandbox: { mode: "danger-full-access", network: "open" },
createdAt: "2026-08-24T00:00:00.000Z",
lastActiveAt: "2026-08-24T00:00:00.000Z",
status: "idle",
diff --git a/packages/web/test/session-status-events.test.ts b/packages/web/test/session-status-events.test.ts
index 7a1c5de9..042b1c4d 100644
--- a/packages/web/test/session-status-events.test.ts
+++ b/packages/web/test/session-status-events.test.ts
@@ -35,6 +35,7 @@ function session(sessionId: string, over: Partial<SessionInfo> = {}): SessionInf
modelId: "claude-sonnet-4",
workspace: "/w",
approvalMode: "allow-all",
+ sandbox: { mode: "danger-full-access", network: "open" },
createdAt: CREATED,
lastActiveAt: LOOKED,
status: "idle",
diff --git a/packages/web/test/sessions-own-rows.test.ts b/packages/web/test/sessions-own-rows.test.ts
index 408473c0..26d6250d 100644
--- a/packages/web/test/sessions-own-rows.test.ts
+++ b/packages/web/test/sessions-own-rows.test.ts
@@ -34,6 +34,7 @@ function session(sessionId: string, over: Partial<SessionInfo> = {}): SessionInf
modelId: "claude-sonnet-4",
workspace: "/w",
approvalMode: "allow-all",
+ sandbox: { mode: "danger-full-access", network: "open" },
createdAt: "2026-09-16T09:00:00.000Z",
lastActiveAt: "2026-09-16T09:00:00.000Z",
status: "idle",
diff --git a/packages/web/test/settings-sections.test.ts b/packages/web/test/settings-sections.test.ts
index dbec93bb..664aac52 100644
--- a/packages/web/test/settings-sections.test.ts
+++ b/packages/web/test/settings-sections.test.ts
@@ -1,5 +1,5 @@
/**
- * settings-sections.ts unit tests: which System settings pages each viewer gets.
+ * settings-sections.ts unit tests: which Settings pages each viewer gets.
*
* The rule is pinned by value rather than by shape because both halves of it can fail
* silently and separately: a rail that shows a forbidden entry leaks that the setting
@@ -59,6 +59,7 @@ describe("visibleSettingsSections", () => {
"proxy",
"uploads",
"company",
+ "plugins",
"users",
]);
});
@@ -82,6 +83,7 @@ describe("visibleSettingsSections", () => {
"proxy",
"uploads",
"company",
+ "plugins",
]);
});
@@ -96,6 +98,7 @@ describe("visibleSettingsSections", () => {
"proxy",
"uploads",
"company",
+ "plugins",
]);
});
});
@@ -137,7 +140,7 @@ describe("resolveSettingsSection", () => {
});
});
-describe("the System settings dialog", () => {
+describe("the Settings dialog", () => {
const source = readFileSync(
resolve(
dirname(fileURLToPath(import.meta.url)),
diff --git a/plugins/sandbox-bwrap/README.md b/plugins/sandbox-bwrap/README.md
index 7b3adbe9..6b7e453b 100644
--- a/plugins/sandbox-bwrap/README.md
+++ b/plugins/sandbox-bwrap/README.md
@@ -19,7 +19,8 @@ skew between hosts, and no sandbox that is quietly off because a machine lacked
binary finds its library through an `$ORIGIN/../lib` rpath, which is what makes it usable from a
backend that only rewrites an argv and never sets an environment.
-Precedence, when a command is confined: the one shipped here, else a `bwrap` on PATH.
+Precedence, when a command is confined: the program named in the settings, else the one shipped
+here, else a `bwrap` on PATH.
## How the profile is built
@@ -40,6 +41,10 @@ would otherwise expose them. A path that does not exist is skipped — there is
hide, and materializing an empty directory there would change the filesystem view rather
than restrict it.
+## Settings
+
+On **Settings → Plugins**, inside the Sandbox card: the **bwrap program** (a path or a command on PATH; empty uses `bwrap`) and the **probe timeout** in seconds (1–30, default 5; the confine-time probe blocks the server while it runs). Both apply at the next command spawn; a changed program is probed afresh. If bwrap failed its check at boot (a wrong program, or bubblewrap installed later), saving the card loads it again, no restart.
+
## Install
It ships with the harness build. On the Plugins page, install it to the Project that should
diff --git a/plugins/sandbox-bwrap/src/index.ts b/plugins/sandbox-bwrap/src/index.ts
index fe54a0eb..825124f3 100644
--- a/plugins/sandbox-bwrap/src/index.ts
+++ b/plugins/sandbox-bwrap/src/index.ts
@@ -36,7 +36,7 @@ import { accessSync, constants, statSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { tmpdir } from "node:os";
-import { Bind, Component } from "@prismshadow/penguin-core/plugin";
+import { Bind, Component, Interface, Use } from "@prismshadow/penguin-core/plugin";
import type {
ConfinedArgv,
Plugin,
@@ -48,6 +48,14 @@ import type {
/** Default probe budget; a probe that hangs must not hang the first spawn forever. */
const PROBE_TIMEOUT_MS = 5_000;
+/** This backend's own settings, as it reads them from its group. */
+export interface BwrapSettings {
+ /** The bwrap program: a path or a command on PATH. */
+ runner: string;
+ /** How long the first check that the runner works may take. */
+ probeTimeoutMs: number;
+}
+
/**
* The bwrap this plugin SHIPS for the host it is running on, or "" when it carries none.
*
@@ -79,12 +87,42 @@ function executable(target: string): boolean {
}
}
-/** Test seams: inject the probe verdict and the runner name. */
+/** Its group's stored document (defaults merged) as settings; anything unusable falls back. */
+export function bwrapSettingsOf(
+ doc: Record<string, unknown>,
+ vendored: string = vendoredRunner(),
+): BwrapSettings {
+ const runner = typeof doc.runner === "string" ? doc.runner.trim() : "";
+ const seconds = doc.probeTimeoutSeconds;
+ return {
+ // What a deployment names wins; then the one shipped here; and only then a host's own.
+ runner: runner !== "" ? runner : vendored !== "" ? vendored : "bwrap",
+ probeTimeoutMs:
+ typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0
+ ? seconds * 1000
+ : PROBE_TIMEOUT_MS,
+ };
+}
+
+/** Test seams: inject the probe verdict, and the settings the provider reads at each confine. */
export interface PenguinBwrapInternals {
probe?: (timeoutMs: number, runner: string) => boolean;
runner?: string;
+ settings?: () => BwrapSettings;
}
+/**
+ * What this backend requires of plugin configuration: to read the group it declares. The
+ * interface is the consumer's own, so the package depends on no harness type.
+ */
+@Interface()
+export abstract class BwrapConfigReader {
+ abstract get(name: string): Record<string, unknown>;
+}
+
+/** The settings group this backend declares (its contribution id), drawn inside the Sandbox card. */
+export const BWRAP_GROUP = "sandbox-bwrap";
+
/**
* The writable roots a policy grants, canonical and deduplicated: the workspace under
* `workspace-write`, and the temp areas whenever the policy makes temp writable (either mode).
@@ -163,7 +201,8 @@ function probeAsync(timeoutMs: number, runner: string): Promise<boolean> {
* reason, when it cannot: it runs on Linux only, and needs a bwrap that accepts the base profile.
* A backend mounted without being able to serve would be routed policies and fail every command;
* one that declined without a reason would leave nobody able to tell why. The sandbox service
- * records the rejection and names it when a command fails closed.
+ * records the rejection and the settings page shows it, and loads it again after the next save
+ * of the sandbox card. The confine-time probe stays, for a runner changed while mounted.
*/
export async function loadPenguinBwrapProvider(
internals: PenguinBwrapInternals & { platform?: NodeJS.Platform } = {},
@@ -172,10 +211,13 @@ export async function loadPenguinBwrapProvider(
// Not this host's backend: a decline, not a failure — the deployment installed it for
// its Linux machines, and saying so on every Windows card would be noise.
if (platform !== "linux") return null;
- const runner = internals.runner ?? (vendoredRunner() || "bwrap");
+ const { runner, probeTimeoutMs } = internals.settings?.() ?? {
+ runner: internals.runner ?? (vendoredRunner() || "bwrap"),
+ probeTimeoutMs: PROBE_TIMEOUT_MS,
+ };
const usable = internals.probe
- ? internals.probe(PROBE_TIMEOUT_MS, runner)
- : await probeAsync(PROBE_TIMEOUT_MS, runner);
+ ? internals.probe(probeTimeoutMs, runner)
+ : await probeAsync(probeTimeoutMs, runner);
if (!usable) {
throw new Error(
`'${runner}' is missing or refuses the base profile (are unprivileged user namespaces enabled on this host? \`sysctl kernel.unprivileged_userns_clone\`)`,
@@ -185,19 +227,26 @@ export async function loadPenguinBwrapProvider(
}
/**
- * 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.
+ * The backend. It reads its settings at each confine, so an edit applies to the next spawn;
+ * the probe runs lazily (the first confine with a given runner) and is cached per runner: 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 ?? (vendoredRunner() || "bwrap");
const probe = internals.probe ?? defaultProbe;
- let usable: boolean | undefined;
+ const settings =
+ internals.settings ??
+ (() => ({
+ runner: internals.runner ?? (vendoredRunner() || "bwrap"),
+ probeTimeoutMs: PROBE_TIMEOUT_MS,
+ }));
+ const usable = new Map<string, boolean>();
return {
dimensions: ["fs-write", "network", "mask-paths"],
confine(argv, policy): ConfinedArgv {
- usable ??= probe(PROBE_TIMEOUT_MS, runner);
- if (!usable) {
+ const { runner, probeTimeoutMs } = settings();
+ if (!usable.has(runner)) usable.set(runner, probe(probeTimeoutMs, runner));
+ if (!usable.get(runner)) {
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 " +
@@ -233,13 +282,52 @@ export function createPenguinBwrapProvider(internals: PenguinBwrapInternals = {}
dimensions: ["fs-write", "network", "mask-paths"],
},
],
+ "PluginConfigProvider.groups": [
+ {
+ id: "sandbox-bwrap",
+ parent: "sandbox",
+ title: "Bubblewrap",
+ properties: {
+ runner: {
+ type: "string",
+ title: "bwrap program",
+ titleZh: "bwrap 程序",
+ description:
+ "A path or a command on PATH; empty uses the bubblewrap this plugin ships, falling back to one on PATH where it carries none for this host.",
+ descriptionZh:
+ "路径或 PATH 上的命令名;留空则使用本插件自带的 bubblewrap,若没有适配本机的自带版本,再回退到 PATH 上的。",
+ placeholder: "bwrap",
+ },
+ probeTimeoutSeconds: {
+ type: "number",
+ title: "Probe timeout (seconds)",
+ titleZh: "探测超时(秒)",
+ description:
+ "How long the first check that bwrap works may take before it counts as unusable (1–30).",
+ descriptionZh: "首次检查 bwrap 是否可用时最多等待多久(1–30),超时即视为不可用。",
+ default: 5,
+ // The confine-time probe blocks the server while it runs; a hanging runner must
+ // not stall it for longer than this.
+ minimum: 1,
+ maximum: 30,
+ },
+ },
+ },
+ ],
},
})
export class SandboxBwrap {
+ @Use() private readonly config!: BwrapConfigReader;
@Bind("sandbox-bwrap.provider") provider!: SandboxProviderSource;
setup() {
- this.provider = loadPenguinBwrapProvider();
+ const config = this.config;
+ // A loader, not a load: after a save of the sandbox card the service calls it again if the
+ // check failed, so a corrected program mounts the backend without a restart.
+ this.provider = () =>
+ loadPenguinBwrapProvider({
+ settings: () => bwrapSettingsOf(config.get(BWRAP_GROUP)),
+ });
}
}
diff --git a/plugins/sandbox-bwrap/test/profile.test.ts b/plugins/sandbox-bwrap/test/profile.test.ts
index a292d87a..74a43388 100644
--- a/plugins/sandbox-bwrap/test/profile.test.ts
+++ b/plugins/sandbox-bwrap/test/profile.test.ts
@@ -9,6 +9,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import {
bwrapProfileArgs,
+ bwrapSettingsOf,
createPenguinBwrapProvider,
loadPenguinBwrapProvider,
vendoredRunner,
@@ -169,6 +170,31 @@ describe("penguin-bwrap provider", () => {
expect(() => provider.confine([...ARGV], policy)).toThrow(/cannot confine on this host/);
expect(probes).toBe(1);
});
+
+ it("reads its settings at each confine, probing each runner once with the timeout set", () => {
+ const probed: Array<[number, string]> = [];
+ let doc: Record<string, unknown> = {};
+ const provider = createPenguinBwrapProvider({
+ probe: (timeoutMs, runner) => {
+ probed.push([timeoutMs, runner]);
+ return runner !== "/missing/bwrap";
+ },
+ // "" for the shipped binary: this is about the settings, not about what the package carries.
+ settings: () => bwrapSettingsOf(doc, ""),
+ });
+ const policy = { mode: "read-only", workspaceRoot: WS } as const;
+ expect(provider.confine([...ARGV], policy).argv[0]).toBe("bwrap");
+ doc = { runner: " /opt/bwrap ", probeTimeoutSeconds: 2 };
+ expect(provider.confine([...ARGV], policy).argv[0]).toBe("/opt/bwrap");
+ expect(provider.confine([...ARGV], policy).argv[0]).toBe("/opt/bwrap");
+ doc = { runner: "/missing/bwrap" };
+ expect(() => provider.confine([...ARGV], policy)).toThrow(/'\/missing\/bwrap' is missing/);
+ expect(probed).toEqual([
+ [5000, "bwrap"],
+ [2000, "/opt/bwrap"],
+ [5000, "/missing/bwrap"],
+ ]);
+ });
});
describe("bwrap on another platform", () => {
@@ -202,4 +228,12 @@ describe("the bwrap it runs", () => {
it("carries none for a host it has no binary for, and says so with an empty path", () => {
expect(vendoredRunner("win32", "x64", () => false)).toBe("");
});
+
+ it("what the deployment names wins; then the shipped one; then a bwrap on PATH", () => {
+ const shipped = "/pkg/vendor/linux-x64/bin/bwrap";
+ expect(bwrapSettingsOf({ runner: "/usr/bin/bwrap" }, shipped).runner).toBe("/usr/bin/bwrap");
+ expect(bwrapSettingsOf({}, shipped).runner).toBe(shipped);
+ expect(bwrapSettingsOf({ runner: " " }, shipped).runner).toBe(shipped);
+ expect(bwrapSettingsOf({}, "").runner).toBe("bwrap");
+ });
});
diff --git a/plugins/sandbox-seatbelt/README.md b/plugins/sandbox-seatbelt/README.md
index aadc7428..9a58af77 100644
--- a/plugins/sandbox-seatbelt/README.md
+++ b/plugins/sandbox-seatbelt/README.md
@@ -10,8 +10,8 @@ network isolation and path masking — as policy rules rather than mounts.
Apple's to distribute, not this project's — so unlike the Linux backend, which ships its own
bubblewrap, there is nothing here to vendor. What that buys elsewhere, this buys by naming the
absolute path rather than a bare command: a PATH without `/usr/bin`, or one that puts something
-else called `sandbox-exec` first, no longer decides what confines a command. A host where it does not work is caught by the
-load-time probe.
+else called `sandbox-exec` first, no longer decides what confines a command. The settings can
+still name another program, and a host where it does not work is caught by the load-time probe.
## Requirements
@@ -45,6 +45,10 @@ Paths are canonicalized before entering the profile. Seatbelt matches the real f
path, and on macOS `/tmp` and `/var` are symlinks into `/private`, so an uncanonicalized
subpath rule silently matches nothing.
+## Settings
+
+On **Settings → Plugins**, inside the Sandbox card: the **sandbox-exec program** (a path or a command on PATH; empty uses `sandbox-exec`). It applies at the next command spawn; a changed program is probed afresh. If Seatbelt failed its check at boot, saving the card loads it again, no restart.
+
## Install
It ships with the harness build. On the Plugins page, install it to the Project that should
diff --git a/plugins/sandbox-seatbelt/src/index.ts b/plugins/sandbox-seatbelt/src/index.ts
index f339593a..74082c2d 100644
--- a/plugins/sandbox-seatbelt/src/index.ts
+++ b/plugins/sandbox-seatbelt/src/index.ts
@@ -34,7 +34,7 @@ import { execFile, spawnSync } from "node:child_process";
import { existsSync, realpathSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
-import { Bind, Component } from "@prismshadow/penguin-core/plugin";
+import { Bind, Component, Interface, Use } from "@prismshadow/penguin-core/plugin";
import type {
ConfinedArgv,
Plugin,
@@ -49,6 +49,12 @@ 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"];
+/** This backend's own settings, as it reads them from its group. */
+export interface SeatbeltSettings {
+ /** The sandbox-exec program: a path or a command on PATH. */
+ runner: string;
+}
+
/**
* Where macOS keeps the program this backend runs.
*
@@ -66,12 +72,34 @@ export function defaultRunner(exists: (p: string) => boolean = existsSync): stri
return exists(SYSTEM_RUNNER) ? SYSTEM_RUNNER : "sandbox-exec";
}
-/** Test seams: inject the probe verdict and the runner name. */
+/** Its group's stored document as settings; an empty runner falls back to the OS's own. */
+export function seatbeltSettingsOf(
+ doc: Record<string, unknown>,
+ fallback: string = defaultRunner(),
+): SeatbeltSettings {
+ const runner = typeof doc.runner === "string" ? doc.runner.trim() : "";
+ return { runner: runner !== "" ? runner : fallback };
+}
+
+/** Test seams: inject the probe verdict, and the settings the provider reads at each confine. */
export interface SeatbeltInternals {
probe?: (timeoutMs: number, runner: string) => boolean;
runner?: string;
+ settings?: () => SeatbeltSettings;
}
+/**
+ * What this backend requires of plugin configuration: to read the group it declares. The
+ * interface is the consumer's own, so the package depends on no harness type.
+ */
+@Interface()
+export abstract class SeatbeltConfigReader {
+ abstract get(name: string): Record<string, unknown>;
+}
+
+/** The settings group this backend declares (its contribution id), drawn inside the Sandbox card. */
+export const SEATBELT_GROUP = "sandbox-seatbelt";
+
/** Canonical path (symlinks resolved), falling back to a lexical resolve for paths that do not exist yet. */
export function canonicalPath(target: string): string {
try {
@@ -166,8 +194,9 @@ function defaultProbe(timeoutMs: number, runner: string): boolean {
/**
* Loads the backend, checking first that it can serve on this host — and rejecting, with the
* reason, when it cannot: it runs on macOS only, and needs a sandbox-exec that accepts its
- * profile. The sandbox service records the rejection and names it when a command fails closed,
- * so the backend is never silently absent.
+ * profile. The sandbox service records the rejection and the settings page shows it, so the
+ * backend is never silently absent, and loads it again after the next save of the sandbox card;
+ * the confine-time probe stays, for a runner changed while mounted.
*/
export async function loadSeatbeltProvider(
internals: SeatbeltInternals & { platform?: NodeJS.Platform } = {},
@@ -175,7 +204,7 @@ export async function loadSeatbeltProvider(
const platform = internals.platform ?? process.platform;
// Not this host's backend: a decline, not a failure (see penguin-bwrap's loader).
if (platform !== "darwin") return null;
- const runner = internals.runner ?? defaultRunner();
+ const { runner } = internals.settings?.() ?? { runner: internals.runner ?? defaultRunner() };
const usable = internals.probe
? internals.probe(PROBE_TIMEOUT_MS, runner)
: await new Promise<boolean>((resolve) => {
@@ -191,18 +220,20 @@ export async function loadSeatbeltProvider(
}
/**
- * 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.
+ * The backend. It reads its settings at each confine; the probe runs lazily (the first
+ * confine with a given runner) and is cached per runner; an unusable Seatbelt throws —
+ * fail-closed — rather than degrading to a weaker profile.
*/
export function createSeatbeltProvider(internals: SeatbeltInternals = {}): SandboxProvider {
- const runner = internals.runner ?? defaultRunner();
const probe = internals.probe ?? defaultProbe;
- let usable: boolean | undefined;
+ const settings = internals.settings ?? (() => ({ runner: internals.runner ?? defaultRunner() }));
+ const usable = new Map<string, boolean>();
return {
dimensions: ["fs-write", "network", "network-local", "mask-paths"],
confine(argv, policy): ConfinedArgv {
- usable ??= probe(PROBE_TIMEOUT_MS, runner);
- if (!usable) {
+ const { runner } = settings();
+ if (!usable.has(runner)) usable.set(runner, probe(PROBE_TIMEOUT_MS, runner));
+ if (!usable.get(runner)) {
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.",
@@ -235,13 +266,38 @@ export function createSeatbeltProvider(internals: SeatbeltInternals = {}): Sandb
dimensions: ["fs-write", "network", "network-local", "mask-paths"],
},
],
+ "PluginConfigProvider.groups": [
+ {
+ id: "sandbox-seatbelt",
+ parent: "sandbox",
+ title: "Seatbelt",
+ properties: {
+ runner: {
+ type: "string",
+ title: "sandbox-exec program",
+ titleZh: "sandbox-exec 程序",
+ description:
+ "A path or a command on PATH; empty uses the macOS program at /usr/bin/sandbox-exec.",
+ descriptionZh:
+ "路径或 PATH 上的命令名;留空则使用 macOS 自带的 /usr/bin/sandbox-exec。",
+ placeholder: "/usr/bin/sandbox-exec",
+ },
+ },
+ },
+ ],
},
})
export class SandboxSeatbelt {
+ @Use() private readonly config!: SeatbeltConfigReader;
@Bind("sandbox-seatbelt.provider") provider!: SandboxProviderSource;
setup() {
- this.provider = loadSeatbeltProvider();
+ const config = this.config;
+ // A loader: after a save of the sandbox card a failed check runs again (see penguin-bwrap).
+ this.provider = () =>
+ loadSeatbeltProvider({
+ settings: () => seatbeltSettingsOf(config.get(SEATBELT_GROUP)),
+ });
}
}
diff --git a/plugins/sandbox-seatbelt/test/profile.test.ts b/plugins/sandbox-seatbelt/test/profile.test.ts
index 77049d43..c5007bf7 100644
--- a/plugins/sandbox-seatbelt/test/profile.test.ts
+++ b/plugins/sandbox-seatbelt/test/profile.test.ts
@@ -14,6 +14,7 @@ import {
defaultRunner,
loadSeatbeltProvider,
seatbeltProfile,
+ seatbeltSettingsOf,
SYSTEM_RUNNER,
writableRoots,
} from "../src/index.js";
@@ -194,4 +195,12 @@ describe("the sandbox-exec it runs", () => {
// and the load-time probe is what rejects a host where nothing answers.
expect(defaultRunner(() => false)).toBe("sandbox-exec");
});
+
+ it("what the deployment names wins over the OS's own", () => {
+ expect(seatbeltSettingsOf({ runner: " /opt/sandbox-exec " }, SYSTEM_RUNNER).runner).toBe(
+ "/opt/sandbox-exec",
+ );
+ expect(seatbeltSettingsOf({}, SYSTEM_RUNNER).runner).toBe(SYSTEM_RUNNER);
+ expect(seatbeltSettingsOf({ runner: "" }, "sandbox-exec").runner).toBe("sandbox-exec");
+ });
});
diff --git a/plugins/sandbox-wsl/README.md b/plugins/sandbox-wsl/README.md
index 54642dc3..8ce1487e 100644
--- a/plugins/sandbox-wsl/README.md
+++ b/plugins/sandbox-wsl/README.md
@@ -8,16 +8,16 @@ A Windows sandbox backend for PenguinHarness. Each agent command runs in a dedic
| network | `network: "none"` runs the command in an empty network namespace; `"local"` is not supported |
| mask-paths | A tmpfs over a directory, `/dev/null` over a file |
-Other Windows drives are hidden from a confined command. The mount that hides them is remounted read-only after the Workspace is bound, so a write to a path outside the Workspace is refused rather than landing in a tmpfs that vanishes with the command.
+Other Windows drives are hidden from a confined command unless **Show Windows drives read-only** is on. The mount that hides them is remounted read-only after the Workspace is bound, so a write to a path outside the Workspace is refused rather than landing in a tmpfs that vanishes with the command.
WSL keeps the generated `resolv.conf` outside the distro's root, at `/mnt/wsl/resolv.conf` or `/run/resolvconf/resolv.conf`, and `/etc/resolv.conf` is a symlink to it. Both are bound back read-only, or covering those directories would leave a reachable network where no host name resolves.
## Setup
-Setup is a few tasks the plugin exports, each reporting the step it is on while it runs. Until the distro exists, the backend declines to load and says so.
+Everything happens on the WSL card under **Settings → Plugins → Sandbox**, with its progress shown there:
1. **Install WSL**: raises the Windows consent prompt for `setup/install-wsl.ps1`, which runs `wsl --install --no-distribution`. Some machines need a restart afterwards. This is the only step that needs an administrator.
-2. **Initialize sandbox distro**: downloads the base rootfs (checked against its published sha256), imports it as its own distro, installs bubblewrap and the package list (`git` and `curl`), creates the `penguin` account, and switches Windows interop off.
+2. **Initialize sandbox distro**: downloads the base rootfs (checked against its published sha256), imports it as its own distro, installs bubblewrap and the **Packages** list, creates the `penguin` account, and switches Windows interop off.
3. **Check confinement**: runs real commands through the sandbox and lists what passed.
State lives in `%LOCALAPPDATA%\penguin\sandbox-wsl` (`state.json`, the downloaded rootfs, the distro's disk).
@@ -33,9 +33,11 @@ With interop on, a Windows program started inside bwrap is an ordinary host proc
| Ubuntu 24.04 LTS (default) | 29 MB | 84 MB | glibc: what prebuilt binaries, native npm modules and pip wheels expect |
| Alpine | 3.5 MB | 8.7 MB | musl: much smaller, and some prebuilt binaries and wheels do not run |
+The **Package mirror** setting points apt or apk at a mirror; the rootfs itself always comes from the distribution's own site.
+
## Limits
-- Commands run in Linux, not Git Bash. Windows toolchains cannot run confined; the distro carries Linux ones instead.
+- Commands run in Linux, not Git Bash. Windows toolchains cannot run confined; add Linux ones through **Packages** (for example `nodejs`, `npm`, `python3`).
- A Windows path in a command means nothing inside the distro. The Workspace is at `/mnt/<drive>/…`.
- A Workspace on a network share has no path inside the distro and cannot be confined.
- The Workspace is bound at its own path, so the empty directory chain above it (`/mnt/c/Users/…`) is visible even though every other drive is hidden.
diff --git a/plugins/sandbox-wsl/src/index.ts b/plugins/sandbox-wsl/src/index.ts
index 0fca1b13..123ed1d2 100644
--- a/plugins/sandbox-wsl/src/index.ts
+++ b/plugins/sandbox-wsl/src/index.ts
@@ -15,22 +15,21 @@
* WHAT MAKES IT A SANDBOX. WSL's interop lets a Linux process start a Windows program, and that
* program is an ordinary host process: inside bwrap with the network cut, `cmd.exe` still wrote
* to the Windows disk and reached the internet (measured on Windows 11, WSL 2.7). The distro
- * this backend sets up switches interop off in its /etc/wsl.conf, and `check` proves it stays
- * off. It is also why the distro is its own and not the person's Ubuntu.
+ * this backend sets up switches interop off in its /etc/wsl.conf, and the check on its card
+ * proves it stays off. It is also why the distro is its own and not the person's Ubuntu.
*
* WHAT IT COSTS. Commands run in Linux, not in Git Bash: Windows toolchains (node.exe, git.exe)
* cannot run confined, so the distro carries its own (the packages setting). A Windows path in
* a command means nothing there; the Workspace is at `/mnt/<drive>/…`.
*
- * SETUP. Installing WSL needs an administrator once: `installWsl` raises Windows' own consent
+ * SETUP. Installing WSL needs an administrator once — the card raises Windows' own consent
* prompt for the script shipped in setup/. Everything after that runs as the harness's own
- * user: `initialize` downloads the base rootfs (Ubuntu by default, Alpine as the small option),
- * imports it, installs bubblewrap and the packages, and switches interop off, and `check` runs
- * real commands through the sandbox. Each reports the step it is on while it runs. Until the
- * distro exists, the backend declines to load and says so.
+ * user: Initialize downloads the base rootfs (Ubuntu by default, Alpine as the small option),
+ * imports it, installs bubblewrap and the packages, and switches interop off. Each step shows on
+ * the card while it runs.
*/
import { fileURLToPath } from "node:url";
-import { Bind, Component } from "@prismshadow/penguin-core/plugin";
+import { Bind, Component, Interface, Use } from "@prismshadow/penguin-core/plugin";
import type {
ConfinedArgv,
Plugin,
@@ -39,8 +38,18 @@ import type {
SandboxProviderSource,
} from "@prismshadow/penguin-core/plugin";
import { readHost, readState } from "./host.js";
-import { launchJob, wslSettingsOf } from "./tasks.js";
-import type { WslSettings } from "./tasks.js";
+import {
+ BASE_TITLES,
+ Tasks,
+ TASK_TITLES,
+ check,
+ initialize,
+ installWsl,
+ launchJob,
+ remove,
+ wslSettingsOf,
+} from "./tasks.js";
+import type { TaskKind, WslSettings } from "./tasks.js";
export { bwrapArgs, chdirRoots, linuxProgram, toLinuxPath } from "./profile.js";
export {
@@ -55,6 +64,9 @@ export { Tasks, check, initialize, installWsl, remove } from "./tasks.js";
export type { BaseImage, CheckLine, TaskKind, TaskOutcome } from "./tasks.js";
export type { WslSettings } from "./tasks.js";
+/** The settings group this backend declares, drawn inside the Sandbox card. */
+export const WSL_GROUP = "sandbox-wsl";
+
/** Where the launcher lives, beside this module in the built package. */
export function launcherPath(): string {
return fileURLToPath(new URL("./launch.js", import.meta.url));
@@ -71,7 +83,7 @@ export interface WslInternals {
async function unavailable(settings: WslSettings): Promise<string | null> {
const state = readState();
if (state === null) {
- return "the sandbox distro is not initialized";
+ return "the sandbox distro is not initialized: open Settings → Plugins → Sandbox and use Initialize on the WSL card";
}
if (state.distro !== settings.distro) {
return `the distro setting names ${settings.distro}, but ${state.distro} is the one initialized: initialize again`;
@@ -87,7 +99,8 @@ async function unavailable(settings: WslSettings): Promise<string | null> {
/**
* Loads the backend: on Windows only (elsewhere it declines — another backend serves), and only
- * once the distro exists. Until then it rejects with what is missing.
+ * once the distro exists. Until then it rejects with what to do, which the Sandbox card shows;
+ * a task that finishes on this backend's card loads it again.
*/
export async function loadWslProvider(
settings: () => WslSettings,
@@ -125,6 +138,259 @@ export function createWslProvider(
};
}
+/** What this backend requires of plugin configuration: to read the group it declares. */
+@Interface()
+export abstract class WslConfigReader {
+ abstract get(name: string): Record<string, unknown>;
+}
+
+/** The card's live half, in the consumer's own shape (see the settings page's contract). */
+export interface SettingsGroupStatus {
+ notices(): Array<{ tone: "attention" | "muted" | "progress"; text: string; textZh?: string }>;
+ actions(): Array<{
+ id: string;
+ title: string;
+ titleZh?: string;
+ description?: string;
+ descriptionZh?: string;
+ }>;
+ run(action: string): Promise<{
+ ok: boolean;
+ message: string;
+ messageZh?: string;
+ settled?: Promise<void>;
+ }>;
+}
+
+const when = (at: number) => new Date(at).toLocaleString();
+
+/** What a finished task is called on the card. */
+const DONE_TITLES: Record<TaskKind, { en: string; zh: string }> = {
+ install: { en: "WSL install", zh: "WSL 安装" },
+ initialize: { en: "Initialize", zh: "初始化" },
+ check: { en: "Check", zh: "检查" },
+ remove: { en: "Remove", zh: "移除" },
+};
+
+/**
+ * The card: what this machine has (WSL, the distro, the last check), the button for the next
+ * step, and the step a running task is on.
+ */
+@Component({
+ contributes: {
+ "PluginConfigPage.status": [{ id: "sandbox-wsl.status", group: "sandbox-wsl" }],
+ },
+})
+export class SandboxWslStatus {
+ @Use() private readonly config!: WslConfigReader;
+ @Bind("sandbox-wsl.status") status!: SettingsGroupStatus;
+
+ setup() {
+ const config = this.config;
+ const settings = () => wslSettingsOf(config.get(WSL_GROUP));
+ const tasks = new Tasks();
+ const windows = process.platform === "win32";
+ if (windows) void tasks.refreshHost();
+
+ const initialized = () => {
+ const state = readState();
+ const host = tasks.host;
+ return (
+ state !== null &&
+ state.distro === settings().distro &&
+ host !== null &&
+ host.distros.some((d) => d.toLowerCase() === state.distro.toLowerCase())
+ );
+ };
+
+ const bodies: Record<TaskKind, () => Promise<void> | null> = {
+ install: () => tasks.start("install", (report) => installWsl(report)),
+ initialize: () =>
+ tasks.start("initialize", async (report) => {
+ const outcome = await initialize(settings(), report);
+ if (!outcome.ok) return outcome;
+ const verdict = await check(settings(), report);
+ tasks.lastCheck = { at: Date.now(), lines: verdict.lines };
+ return verdict.result.ok
+ ? outcome
+ : {
+ ok: false,
+ message: {
+ en: `${outcome.message.en} ${verdict.result.message.en}`,
+ zh: `${outcome.message.zh}${verdict.result.message.zh}`,
+ },
+ };
+ }),
+ check: () =>
+ tasks.start("check", async (report) => {
+ const verdict = await check(settings(), report);
+ tasks.lastCheck = { at: Date.now(), lines: verdict.lines };
+ return verdict.result;
+ }),
+ remove: () =>
+ tasks.start("remove", async (report) => {
+ tasks.lastCheck = null;
+ return remove(settings(), report);
+ }),
+ };
+
+ this.status = {
+ notices: () => {
+ if (!windows) return [];
+ tasks.touchHost();
+ const out: ReturnType<SettingsGroupStatus["notices"]> = [];
+ const running = tasks.running;
+ if (running !== null) {
+ const title = TASK_TITLES[running.kind];
+ const secs = Math.round((Date.now() - running.startedAt) / 1000);
+ out.push({
+ tone: "progress",
+ text: `${title.en} (${secs}s): ${running.step.en}`,
+ textZh: `${title.zh}(${secs} 秒):${running.step.zh}`,
+ });
+ }
+ const host = tasks.host;
+ const last = tasks.last;
+ if (last !== null && running === null) {
+ out.push({
+ tone: last.ok ? "muted" : "attention",
+ text: `${DONE_TITLES[last.kind].en} ${last.ok ? "finished" : "failed"} at ${when(last.at)}: ${last.message.en}`,
+ textZh: `${DONE_TITLES[last.kind].zh}——${last.ok ? "完成" : "失败"}于 ${when(last.at)}:${last.message.zh}`,
+ });
+ }
+ if (host === null) {
+ out.push({
+ tone: "muted",
+ text: "Reading WSL on this machine…",
+ textZh: "正在读取本机的 WSL…",
+ });
+ return out;
+ }
+ if (host.wsl === "missing") {
+ const restart = last?.kind === "install" && last.restart === true;
+ out.push(
+ restart
+ ? {
+ tone: "attention",
+ text: "Restart Windows to finish installing WSL, then initialize the sandbox distro here.",
+ textZh: "重启 Windows 以完成 WSL 安装,然后回到这里初始化沙盒发行版。",
+ }
+ : {
+ tone: "attention",
+ text: `WSL is not available on this machine${host.problem ? ` (${host.problem})` : ""}. Install it below: Windows asks for permission once, and may ask for a restart.`,
+ textZh: `这台机器上没有可用的 WSL${host.problem ? `(${host.problem})` : ""}。在下方安装:Windows 会请求一次授权,可能还需要重启。`,
+ },
+ );
+ return out;
+ }
+ const state = readState();
+ if (!initialized()) {
+ out.push({
+ tone: "attention",
+ text:
+ state !== null && state.distro !== settings().distro
+ ? `WSL ${host.version ?? ""} is installed, but the distro setting names ${settings().distro} while ${state.distro} was initialized. Initialize again below.`
+ : `WSL ${host.version ?? ""} is installed. Initialize the sandbox distro below: it downloads ${BASE_TITLES[settings().base]} (${settings().base === "ubuntu" ? "about 30 MB" : "a few MB"}), installs bubblewrap and the packages, and switches Windows interop off inside it.`,
+ textZh:
+ state !== null && state.distro !== settings().distro
+ ? `WSL ${host.version ?? ""} 已安装,但发行版设置为 ${settings().distro},而初始化的是 ${state.distro}。请在下方重新初始化。`
+ : `WSL ${host.version ?? ""} 已安装。在下方初始化沙盒发行版:它会下载 ${BASE_TITLES[settings().base]}(${settings().base === "ubuntu" ? "约 30 MB" : "几 MB"})、安装 bubblewrap 与软件包,并在其中关闭 Windows interop。`,
+ });
+ return out;
+ }
+ out.push({
+ tone: "muted",
+ text: `${state!.distro} (${BASE_TITLES[state!.base === "alpine" ? "alpine" : "ubuntu"]}${state!.version === "" ? "" : ` ${state!.version}`}) serves as user ${state!.user}; initialized ${when(Date.parse(state!.initializedAt))}; WSL ${host.version ?? ""}. Commands run in Linux: the Workspace is at its /mnt path, Windows programs cannot run.`,
+ textZh: `${state!.distro}(${BASE_TITLES[state!.base === "alpine" ? "alpine" : "ubuntu"]}${state!.version === "" ? "" : ` ${state!.version}`})以用户 ${state!.user} 提供服务;初始化于 ${when(Date.parse(state!.initializedAt))};WSL ${host.version ?? ""}。命令在 Linux 中执行:工作区位于其 /mnt 路径,Windows 程序无法运行。`,
+ });
+ const verdict = tasks.lastCheck;
+ if (verdict !== null && running === null) {
+ for (const line of verdict.lines) {
+ const mark = line.ok === true ? "✓" : line.ok === false ? "✗" : "·";
+ out.push({
+ tone: line.ok === false ? "attention" : "muted",
+ text: `${mark} ${line.name.en}${line.ok === false && line.detail ? ` — ${line.detail}` : ""}`,
+ textZh: `${mark} ${line.name.zh}${line.ok === false && line.detail ? `——${line.detail}` : ""}`,
+ });
+ }
+ }
+ return out;
+ },
+ actions: () => {
+ if (!windows || tasks.running !== null || tasks.host === null) return [];
+ if (tasks.host.wsl === "missing") {
+ return [
+ {
+ id: "install",
+ title: "Install WSL",
+ titleZh: "安装 WSL",
+ description:
+ "Windows asks for permission, then runs wsl --install --no-distribution. Its progress shows here; some machines need a restart afterwards.",
+ descriptionZh:
+ "Windows 会请求授权,然后运行 wsl --install --no-distribution。进度显示在这里;部分机器完成后需要重启。",
+ },
+ ];
+ }
+ const init = {
+ id: "initialize",
+ title: initialized() ? "Initialize again" : "Initialize sandbox distro",
+ titleZh: initialized() ? "重新初始化" : "初始化沙盒发行版",
+ description: initialized()
+ ? "Re-applies the configuration and installs the packages setting's list into the existing distro, then checks it."
+ : "Downloads the base Linux, imports it as its own WSL distro, installs bubblewrap and the packages, switches interop off, then checks it. No administrator needed.",
+ descriptionZh: initialized()
+ ? "对现有发行版重新应用配置并安装软件包设置中的列表,然后检查。"
+ : "下载基础 Linux,导入为独立的 WSL 发行版,安装 bubblewrap 与软件包,关闭 interop,然后检查。无需管理员权限。",
+ };
+ if (!initialized()) return [init];
+ return [
+ {
+ id: "check",
+ title: "Check confinement",
+ titleZh: "检查隔离效果",
+ description:
+ "Runs real commands through the sandbox: interop, Workspace writes, read-only mode, the Windows drives, the network, a masked path and temp.",
+ descriptionZh:
+ "通过沙盒执行真实命令:interop、工作区写入、只读模式、Windows 磁盘、网络、屏蔽路径与临时目录。",
+ },
+ init,
+ {
+ id: "remove",
+ title: "Remove distro",
+ titleZh: "移除发行版",
+ description:
+ "Unregisters the sandbox distro and deletes everything inside it (not your Workspaces). The backend stays off until you initialize again.",
+ descriptionZh:
+ "注销沙盒发行版并删除其中所有内容(不含你的工作区)。重新初始化前后端保持停用。",
+ },
+ ];
+ },
+ run: async (action) => {
+ const start = bodies[action as TaskKind];
+ const settled = start?.();
+ if (settled === undefined || settled === null) {
+ return {
+ ok: false,
+ message:
+ tasks.running !== null
+ ? "Another task is still running on this card."
+ : `No action ${action}.`,
+ messageZh:
+ tasks.running !== null ? "此卡片上还有任务在运行。" : `没有 ${action} 操作。`,
+ };
+ }
+ const title = TASK_TITLES[action as TaskKind];
+ return {
+ ok: true,
+ message: `${title.en}: its progress shows on the WSL card.`,
+ messageZh: `${title.zh}:进度显示在 WSL 卡片上。`,
+ settled,
+ };
+ },
+ };
+ }
+}
+
@Component({
contributes: {
"SandboxModule.providers": [
@@ -134,15 +400,94 @@ export function createWslProvider(
dimensions: ["fs-write", "network", "mask-paths"],
},
],
+ "PluginConfigProvider.groups": [
+ {
+ id: "sandbox-wsl",
+ parent: "sandbox",
+ title: "WSL",
+ properties: {
+ exposeWindowsDrives: {
+ type: "boolean",
+ title: "Show Windows drives read-only",
+ titleZh: "以只读方式显示 Windows 磁盘",
+ description:
+ "Off: a confined command sees only its Workspace under /mnt. On: every Windows drive is visible read-only, your profile included.",
+ descriptionZh:
+ "关闭:被隔离的命令在 /mnt 下只能看到自己的工作区。打开:所有 Windows 磁盘以只读方式可见,包括你的用户目录。",
+ default: false,
+ },
+ base: {
+ type: "enum",
+ title: "Base Linux",
+ titleZh: "基础 Linux",
+ description:
+ "What the sandbox distro is built from. Ubuntu is the ordinary Linux most tools, wheels and prebuilt binaries expect. Alpine downloads about a tenth as much, but it is musl: some native npm modules, pip wheels and downloaded binaries do not run on it.",
+ descriptionZh:
+ "沙盒发行版基于哪个 Linux。Ubuntu 是绝大多数工具、wheel 与预编译二进制所预期的常规 Linux;Alpine 的下载量只有前者的十分之一左右,但它用 musl:部分原生 npm 模块、pip wheel 与预编译二进制无法运行。",
+ options: [
+ {
+ value: "ubuntu",
+ title: "Ubuntu 24.04 LTS (about 30 MB)",
+ titleZh: "Ubuntu 24.04 LTS(约 30 MB)",
+ },
+ {
+ value: "alpine",
+ title: "Alpine (about 4 MB, musl)",
+ titleZh: "Alpine(约 4 MB,musl)",
+ },
+ ],
+ default: "ubuntu",
+ },
+ packages: {
+ type: "list",
+ title: "Packages",
+ titleZh: "软件包",
+ description:
+ "Packages Initialize installs besides bubblewrap, one per line (for example nodejs, npm, python3). They are apt packages on Ubuntu and apk packages on Alpine. Windows toolchains cannot run inside the sandbox.",
+ descriptionZh:
+ "初始化时除 bubblewrap 外安装的软件包,每行一个(例如 nodejs、npm、python3)。Ubuntu 上是 apt 包,Alpine 上是 apk 包。Windows 工具链无法在沙盒内运行。",
+ default: ["git", "curl"],
+ pattern: "^[a-z0-9][a-z0-9._+-]*$",
+ patternErrorMessage: "must be package names",
+ },
+ mirror: {
+ type: "string",
+ title: "Package mirror",
+ titleZh: "软件包镜像",
+ description:
+ "Where the packages come from, empty for the official archive: an Ubuntu mirror such as https://mirrors.tuna.tsinghua.edu.cn/ubuntu, or an Alpine one such as https://mirrors.tuna.tsinghua.edu.cn/alpine. The base rootfs itself always comes from the distribution's own site.",
+ descriptionZh:
+ "软件包的下载地址,留空即用官方源:Ubuntu 镜像如 https://mirrors.tuna.tsinghua.edu.cn/ubuntu,Alpine 镜像如 https://mirrors.tuna.tsinghua.edu.cn/alpine。基础 rootfs 始终从发行版官方站点下载。",
+ placeholder: "https://mirrors.tuna.tsinghua.edu.cn/ubuntu",
+ pattern: "^https?://\\S+$",
+ patternErrorMessage: "must be an http(s) URL",
+ },
+ distro: {
+ type: "string",
+ title: "Distro name",
+ titleZh: "发行版名称",
+ description: "The WSL distro this backend creates and runs commands in.",
+ descriptionZh: "本后端创建并在其中执行命令的 WSL 发行版。",
+ default: "penguin-sandbox",
+ pattern: "^[A-Za-z0-9][A-Za-z0-9._-]*$",
+ patternErrorMessage: "may use letters, digits, dot, dash and underscore",
+ },
+ },
+ },
+ ],
},
})
export class SandboxWsl {
+ @Use() private readonly config!: WslConfigReader;
@Bind("sandbox-wsl.provider") provider!: SandboxProviderSource;
setup() {
- this.provider = loadWslProvider(() => wslSettingsOf({}));
+ const config = this.config;
+ const settings = () => wslSettingsOf(config.get(WSL_GROUP));
+ // A loader: the service calls it again after this card's task ends or the Sandbox card is saved.
+ this.provider = () => loadWslProvider(settings);
}
}
-const plugin: Plugin = { modules: [SandboxWsl] };
+const plugin: Plugin = { modules: [SandboxWsl, SandboxWslStatus] };
export default plugin;