Skip to content

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

feat(core,server,web,plugins): Linux 沙盒在默认的 Ubuntu 上走 Landlock(上游 #978 移植)

lmlihengea92b3ec06ac
diff --git a/changelog/unreleased/2026-10-09-sandbox-landlock-floor.md b/changelog/unreleased/2026-10-09-sandbox-landlock-floor.md
new file mode 100644
index 00000000..d9f35447
--- /dev/null
+++ b/changelog/unreleased/2026-10-09-sandbox-landlock-floor.md
@@ -0,0 +1,42 @@
+# The Linux sandbox works on a default Ubuntu, through Landlock
+
+- **Date:** 2026-10-09
+- **Type:** feature
+- **Scope:** `server`, `web`, `plugins`, `core`, `docs`
+
+[中文版](2026-10-09-sandbox-landlock-floor.zh.md)
+
+Turning the sandbox on in Linux offered `@lmliheng/penguin-plugin-sandbox-bwrap` alone, and on Ubuntu 23.10 and later — where unprivileged user namespaces are granted only to AppArmor-profiled programs — bubblewrap was refused on every install but the desktop `.deb`, so every confining mode refused every command until someone did a root step. The card now installs `@lmliheng/penguin-plugin-sandbox-dsh` beside it. Where bubblewrap is refused, the DSH adaptor confines file writes through Landlock, which needs no namespace and no root; every built-in preset leaves the network open, so all of them are enforced with no host step.
+
+This is ported from upstream PenguinHarness (#978, commit `234183f5`).
+
+## Routing
+
+- Of the mounted backends covering a policy, the one implementing the most dimensions serves it; registration order only breaks ties. Where bubblewrap and the DSH adaptor both load, bubblewrap serves every policy, whatever order the plugin lists name them in.
+- A policy needing network isolation or masked paths with only the adaptor mounted still fails closed, naming what the adaptor covers and why bubblewrap is not in use.
+
+## The Sandbox card
+
+- The sandbox entry's `backend.recommended` became a list: `@lmliheng/penguin-plugin-sandbox-bwrap` and `@lmliheng/penguin-plugin-sandbox-dsh` on Linux, one package on macOS and Windows. Turning the switch on with no backend installed offers the whole list and installs it in order; when one install fails, the prompt closes, the failure is reported, and the card is read again. The Web App still reads the single string an older server reports (see [backward compatibility](2026-10-09-sandbox-recommended-backward-compatibility.md)).
+- The card's "Backends:" line was replaced by what the machine enforces and by what, for example `Enforced here: file writes, by Landlock (dsh-local). Not enforced here: network isolation, localhost-only network, masked paths and closing the temporary directory.` It names each backend that adds a dimension the ones before it lack. A collapsed **More info** under that line lists what the serving backends leave open on this host, then each installed backend that is not in use, with its reason and the note that saving the card checks it again. A settings notice may carry `details` / `detailsZh` for this.
+- A sandbox provider may declare `limits` (core's `SandboxProvider`), each with English and Chinese text. The DSH adaptor declares that the Session scratchpad is not writable under Workspace Write on any rung. On Landlock it adds that the temporary directory is the host's shared `/tmp`, and on a kernel older than Landlock ABI 5 it explains `(partial)`: ioctl on device files outside the Workspace is not restricted, nor, below ABI 3, is truncating a file.
+- With a backend serving and none isolating the network, No network is greyed out in the presets table, naming the backend in use, and a save choosing it is refused, like Localhost only.
+- Closing the temporary directory is a dimension, `closed-temp`, which bubblewrap, Seatbelt and WSL declare and the DSH adaptor does not, because every DSH rung grants a temporary directory under Workspace Write. A confining policy that turns **Temporary directory writable** off is routed only to a backend declaring `closed-temp`; with none mounted it fails closed instead of running with temp writable. With only the adaptor serving, the switch is held on with the reason under it, and a save turning it off is refused. A switch that already stands off stays movable. A settings group's `unavailable` may name a boolean field's position, `"true"` or `"false"`.
+- The warning that the saved policy cannot be enforced also covers full access that cuts the network or masks paths (a document saved before the presets).
+- A sandbox provider may declare `mechanism` (core's `SandboxProvider`): bubblewrap declares `bubblewrap`, and the DSH adaptor declares the rung its chain selected (`Landlock`, `bubblewrap`, `Seatbelt` or the Windows ACL runner, with `(partial)` for partial enforcement).
+
+## Backends
+
+- The DSH adaptor selects its rung when it loads. On Linux this runs the chain's probes, so a host where neither bubblewrap nor Landlock works fails the load with DSH's reason instead of mounting a backend that refuses every command. macOS and Windows have one rung each, which DSH selects without probing.
+- On a kernel older than Landlock ABI 5 (Ubuntu 24.04's 6.8 has ABI 4), the Landlock launcher prints `landlock-run: partial enforcement (older Landlock ABI)` on every run. The spawn now drops the lines a backend reports as informational (core's `ConfinedSpawn.runnerLines`) from the head of a command's or hook script's stderr. Later lines are not examined.
+- `@lmliheng/penguin-plugin-sandbox-dsh`, `sandbox-bwrap`, `sandbox-seatbelt` and `sandbox-wsl` are 0.2.3. A machine whose build does not ship them (an npm global install) installs them with npm into `<data root>/plugins/`, and npm publishes each version once: at an unchanged 0.2.2, a machine already holding 0.2.2 there would keep running it, without the `closed-temp` declarations.
+- bubblewrap's refusal carries what bwrap said (`setting up uid map: Permission denied`, or the spawn error), and states that the Ubuntu root step is optional and adds network isolation and masked paths.
+
+## The composer
+
+- A Session's sandbox view reports `maskPathsSupported` and, for a policy with masked paths, `masksPaths`. Where no backend masks paths, every preset is greyed out, saying the masked paths would refuse every command.
+- The No network reason says the sandbox on this machine confines files only. It and the masked-paths reason name the backends in use, which a Session's sandbox view reports as `backendsInUse`.
+
+## Docs
+
+- The CLI quickstart's **Sandbox on Ubuntu** section, the Settings and Server API pages, and both backends' READMEs describe the default: it works with no step, file writes only through Landlock, and the root step only adds network isolation and masked paths.
diff --git a/changelog/unreleased/2026-10-09-sandbox-landlock-floor.zh.md b/changelog/unreleased/2026-10-09-sandbox-landlock-floor.zh.md
new file mode 100644
index 00000000..ea1fe982
--- /dev/null
+++ b/changelog/unreleased/2026-10-09-sandbox-landlock-floor.zh.md
@@ -0,0 +1,42 @@
+# Linux 沙盒在默认的 Ubuntu 上通过 Landlock 工作
+
+- **Date:** 2026-10-09
+- **Type:** feature
+- **Scope:** `server`, `web`, `plugins`, `core`, `docs`
+
+[English](2026-10-09-sandbox-landlock-floor.md)
+
+此前在 Linux 上打开沙盒只会提示安装 `@lmliheng/penguin-plugin-sandbox-bwrap`。Ubuntu 23.10 及以后的版本只把非特权 user namespace 交给带有 AppArmor profile 的程序,除桌面 `.deb` 外的每种安装上 bubblewrap 都被拒绝,于是在有人完成 root 操作之前,每种封禁模式都会拒绝每条命令。现在卡片会在它旁边一并安装 `@lmliheng/penguin-plugin-sandbox-dsh`。bubblewrap 被拒绝时,DSH 适配器通过 Landlock 约束文件写入,既不需要 namespace,也不需要 root;内置预设都不限制网络,因此无需任何主机操作,全部可以实施。
+
+本移植自上游 PenguinHarness(#978,提交 `234183f5`)。
+
+## 路由
+
+- 在覆盖某条策略的已挂载后端中,实现维度最多的那个负责,注册顺序只用于打破平局。bubblewrap 与 DSH 适配器都加载时,每条策略都由 bubblewrap 负责,与插件列表里的先后顺序无关。
+- 只挂载了适配器时,需要网络隔离或屏蔽路径的策略仍按 fail-closed 拒绝,并写明适配器覆盖什么、bubblewrap 为何未启用。
+
+## 沙盒卡片
+
+- 沙盒条目的 `backend.recommended` 改为列表:Linux 上是 `@lmliheng/penguin-plugin-sandbox-bwrap` 与 `@lmliheng/penguin-plugin-sandbox-dsh`,macOS 与 Windows 各一个包。没有安装后端时打开开关,会提示安装整个列表,并依次安装;其中一个安装失败时,提示框关闭,报告失败,并重新读取卡片。Web App 仍能读取较旧服务端报告的单个字符串(见[向后兼容](2026-10-09-sandbox-recommended-backward-compatibility.zh.md))。
+- 卡片的「Backends:」一行改为写明本机实施什么、由什么实施,例如 `本机实施:文件写入,由 Landlock (dsh-local) 实施。本机不实施:网络隔离、仅本机网络、屏蔽路径、关闭临时目录。`它列出每个补上了前面后端所缺维度的后端。这一行下方折叠的**更多信息**先列出在用后端在本机留下的缺口,再列出每个已安装但未启用的后端,附原因,并说明保存卡片会重新检查。设置提示为此可以带 `details` / `detailsZh`。
+- 沙盒后端可以声明 `limits`(core 的 `SandboxProvider`),每条带中英文。DSH 适配器声明:无论哪一级,仅工作区可写下 Session scratchpad 都不可写。在 Landlock 下还说明临时目录就是宿主共享的 `/tmp`;在 Landlock ABI 低于 5 的内核上解释 `(partial)`:工作区外设备文件上的 ioctl 不受限制,ABI 低于 3 时截断文件也不受限制。
+- 有后端在用、但没有后端能隔离网络时,预设表里的「无网络」显示为灰色并写明在用的后端,保存时选择它会被拒绝,与「仅本机」一致。
+- 关闭临时目录成为一个维度 `closed-temp`:bubblewrap、Seatbelt 与 WSL 声明它,DSH 适配器不声明,因为 DSH 的每一级在仅工作区可写下都会放开一个临时目录。关闭了**临时目录可写**的封禁策略只路由给声明 `closed-temp` 的后端;一个都没挂载时按 fail-closed 拒绝,而不是在临时目录可写的情况下运行。只有适配器在用时,该开关保持开启并在下方写明原因,保存时关闭它会被拒绝;已经处于关闭的开关仍可拨动。设置分组的 `unavailable` 可以指明布尔字段的一个取值,`"true"` 或 `"false"`。
+- 「已保存的策略无法实施」的警告也覆盖断开网络或带屏蔽路径的完全访问(在预设之前保存的设置)。
+- 沙盒后端可以声明 `mechanism`(core 的 `SandboxProvider`):bubblewrap 声明 `bubblewrap`,DSH 适配器声明其链条选中的一级(`Landlock`、`bubblewrap`、`Seatbelt` 或 Windows ACL 运行器,部分实施时带 `(partial)`)。
+
+## 后端
+
+- DSH 适配器在加载时选定所用的一级。在 Linux 上这会运行链条的探测,因此在 bubblewrap 与 Landlock 都不可用的主机上,加载会带着 DSH 的原因失败,而不是挂载一个拒绝每条命令的后端。macOS 与 Windows 各只有一级,DSH 不经探测直接选用。
+- 在 Landlock ABI 低于 5 的内核上(Ubuntu 24.04 的 6.8 为 ABI 4),Landlock 启动器每次运行都会打印 `landlock-run: partial enforcement (older Landlock ABI)`。现在 spawn 会从命令与钩子脚本 stderr 的开头去掉后端报告为提示性的行(core 的 `ConfinedSpawn.runnerLines`),之后的输出不做检查。
+- `@lmliheng/penguin-plugin-sandbox-dsh`、`sandbox-bwrap`、`sandbox-seatbelt` 与 `sandbox-wsl` 升为 0.2.3。构建不随包带它们的机器(npm 全局安装)用 npm 把它们装进 `<数据根>/plugins/`,而 npm 上每个版本只能发布一次:若版本仍是 0.2.2,已在那里装有 0.2.2 的机器会继续运行旧内容,拿不到 `closed-temp` 声明。
+- bubblewrap 的拒绝原因带上 bwrap 的输出(`setting up uid map: Permission denied`,或启动错误),并说明 Ubuntu 上的 root 操作是可选的,只增加网络隔离与屏蔽路径。
+
+## 输入框
+
+- 会话的沙盒视图报告 `maskPathsSupported`,策略带屏蔽路径时还报告 `masksPaths`。没有后端能屏蔽路径时,每个预设都显示为灰色,说明屏蔽路径会让每条命令被拒绝。
+- 「无网络」的原因改为说明本机的沙盒只封禁文件。它与屏蔽路径的原因都会点名在用的后端,会话的沙盒视图以 `backendsInUse` 报告它们。
+
+## 文档
+
+- CLI 快速开始的「Ubuntu 上的沙盒」一节、设置与 Server API 页面,以及两个后端的 README 都改为描述默认情形:无需任何操作即可工作,通过 Landlock 只约束文件写入,root 操作只增加网络隔离与屏蔽路径。
diff --git a/changelog/unreleased/2026-10-09-sandbox-recommended-backward-compatibility.md b/changelog/unreleased/2026-10-09-sandbox-recommended-backward-compatibility.md
new file mode 100644
index 00000000..2f9b2e9b
--- /dev/null
+++ b/changelog/unreleased/2026-10-09-sandbox-recommended-backward-compatibility.md
@@ -0,0 +1,19 @@
+# Backward compatibility: a remote machine reporting one recommended sandbox backend
+
+- **Date:** 2026-10-09
+- **Type:** feature
+- **Scope:** `web`
+
+[中文版](2026-10-09-sandbox-recommended-backward-compatibility.zh.md)
+
+[The Sandbox card](2026-10-09-sandbox-landlock-floor.md) reads `backend.recommended` from the machine it shows as a list of packages. A server from before this change reports a single package as a bare string.
+
+This is ported from upstream PenguinHarness (#978, commit `234183f5`).
+
+## The old shape: `recommended` as a string
+
+When the card shows a remote machine running an older server, the Web App reads the string as a one-package list, and turning the switch on offers that package. Without this, the string would be split into its characters and each offered as a package. Only the Web App is affected; nothing is stored. **A user is not required to do anything.**
+
+## When this can be removed
+
+The fallback is `recommendedOf` in `packages/web/src/lib/sandbox-backend-prompt.ts`, marked `TODO(recommended-string-compat)`. It can be removed once every machine a Web App can show runs a server that reports the list form, that is, once releases before this change are no longer supported for remote machines.
diff --git a/changelog/unreleased/2026-10-09-sandbox-recommended-backward-compatibility.zh.md b/changelog/unreleased/2026-10-09-sandbox-recommended-backward-compatibility.zh.md
new file mode 100644
index 00000000..b58f2e16
--- /dev/null
+++ b/changelog/unreleased/2026-10-09-sandbox-recommended-backward-compatibility.zh.md
@@ -0,0 +1,19 @@
+# 向后兼容:只报告一个推荐沙盒后端的远程机器
+
+- **Date:** 2026-10-09
+- **Type:** feature
+- **Scope:** `web`
+
+[English](2026-10-09-sandbox-recommended-backward-compatibility.md)
+
+[沙盒卡片](2026-10-09-sandbox-landlock-floor.zh.md)把所显示机器的 `backend.recommended` 读作包的列表。此改动之前的服务端只报告一个包,形式为单个字符串。
+
+本移植自上游 PenguinHarness(#978,提交 `234183f5`)。
+
+## 旧形态:`recommended` 为字符串
+
+卡片显示一台运行较旧服务端的远程机器时,Web App 把该字符串读作只含一个包的列表,打开开关时提示安装这个包。没有这层处理,字符串会被拆成单个字符,每个字符都被当作一个包提示安装。只影响 Web App,不涉及任何存储。**用户无需任何操作。**
+
+## 何时可以移除
+
+兜底是 `packages/web/src/lib/sandbox-backend-prompt.ts` 中的 `recommendedOf`,标有 `TODO(recommended-string-compat)`。当 Web App 能显示的每台机器都运行报告列表形式的服务端时,即不再为远程机器支持此改动之前的版本时,即可移除。
diff --git a/docs/FORK-PROGRESS.md b/docs/FORK-PROGRESS.md
index 0765face..2e707fbc 100644
--- a/docs/FORK-PROGRESS.md
+++ b/docs/FORK-PROGRESS.md
@@ -271,9 +271,11 @@
结论:我们自己的跨机子系统已经不小,缺的不是地基而是
上游那批修复与「公司模式跑在别的机器上」;而**「这台 Linux 指挥 Windows 生成台」在今天的两侧代码里
都还不可能**(Windows 机器连不上,见评估)。价值仍在,但要按评估里的顺序走。
-- [ ] 5.4 **沙箱体系**(上游已进 main:Landlock 让默认 Ubuntu 可用 `234183f5`、权限菜单命名预设
+- [x] 5.4 **沙箱体系**(上游已进 main:Landlock 让默认 Ubuntu 可用 `234183f5`、权限菜单命名预设
`9b170c61`、`sandbox-dsh` 在 Windows 走 pwsh `c03e58c4`、建沙箱前先建 scratchpad `cba091e3`、
后端拆成 npm 包 `1ba104c9`)。我们有四个后端,缺的是「体系」:公司模式下一群 agent 在跑命令。
+ **2026-10-09 第二十九轮落地最后一块 `234183f5`(#978)**,见该节;只剩 `1ba104c9`(拆 npm 包),
+ 它属 4.x 的发布链路。
- **第一块已落地(2026-10-08,第十八轮,提交见该节)**:**建沙箱前先建 Session scratchpad**
(上游 `cba091e3`)——`workspace-write` 下服务端在每次受约束的 spawn 之前 `mkdir -p` 那个目录,
建不出来就 fail-closed 拒掉这条命令;`SandboxPolicy.writableRoots` 的契约文档一并跟上。
@@ -315,6 +317,7 @@
**2026-10-09 第二十八轮把 #975 也落了**(见下条),所以本条(`234183f5` / #978)现在
**前置齐了**:它要改的 `packages/server/src/sandbox/settings-status.ts` 已在树里 —— 它是
5.4 剩下的唯一一块(`1ba104c9` 属 4.x),但仍是「一组提交的顶端」,得单独一轮。
+ **2026-10-09 第二十九轮已落地**(提交见该节)——5.4 的代码面到此清零,只剩 `1ba104c9`。
落 #961 时 `git apply -3 --check` 是干净的(三处冲突都是 import 区的包 scope 与本仓的两处
本地新增,见「第二十七轮」一节)。
2. `9b170c61`(权限菜单命名预设)**它自己一次就 6068 增 / 924 删**(设置页的插件配置表整片重写,
@@ -925,6 +928,7 @@ v0.2.2」——它只加台账里 v0.2.2 那一节与两行表格,**跟本轮
| 2026-10-09 | 5.4(Ubuntu userns 那一步) | **Ubuntu 23.10+ 上「怎么让默认 Ubuntu 也能跑 bwrap」这一步成文**(上游 `45885985` `#977` 移植,照改动落、不是合分支;就排在第十八轮已落的 `cba091e3` `#976` 之后):CLI 快速开始(中英双份)新增 **Ubuntu 上的沙盒** 一节 —— 一份要 root 的 AppArmor profile(`/etc/apparmor.d/adelie-sandbox-bwrap`,路径模式 `@{HOME}/.adelie/**/plugins/node_modules/@lmliheng/penguin-plugin-sandbox-bwrap/vendor/linux-*/bin/bwrap` 覆盖随包带 / 下载到数据根 / 热推送三处)、两种替代做法(换 root 拥有的 bwrap,或全机调低开关)与数据根不在 `~/.adelie` 时的做法;`plugins/sandbox-bwrap/src/index.ts` 的拒绝理由在 Debian 的开关旁点名 Ubuntu 的开关并指向这一节(注释补写「为什么这一处要给指针」);插件 README 写明要求;`profile.test.ts` 两条用例(两个开关都点名 / 指针)—— 第二条是本轮新行为,**缺了指针的实现在它上面会红**(实测)。**本地化**:包名 `@penguinharness/sandbox-bwrap` → `@lmliheng/penguin-plugin-sandbox-bwrap`、路径 `~/.penguin` → `~/.adelie`、`PENGUIN_HOME` → `ADELIE_HOME`(旧名仍读)、profile 名 `penguin-sandbox-bwrap` → `adelie-sandbox-bwrap`;**并去掉上游那句「桌面 `.deb` 会装这份 profile」**(本树 `packages/desktop/build/linux/after-install.tpl` 要复制的 `resources/apparmor-profile` 全仓没人产出,见本节末) | 插件 `typecheck` 过 · `pnpm --filter …sandbox-bwrap test` **27 通过**(profile 20 + live 7,`EXIT=0`)· 反向取证:把新加的指针从源码里去掉,`-t` 点名跑那条新用例 **1 失败**(19 跳过),恢复后 27 全绿 · 六包 `typecheck` **`EXIT=0`**(六个 `Done`,`ifaces.json unchanged` 187 接口 / 535 类型)· `pnpm lint` **0 警告 0 错误**(2073 文件)· `pnpm format:check` 干净 · 五包 test 逐包 `EXIT=0`:core **1359**/5 跳过(65 文件)· ui **1007**(127)· cli **506**(34)· web **2963**/2 跳过(241)· server **185 文件 / 2690 通过 / 4 跳过** —— **0 失败**;另跑 `@lmliheng/penguin-docs` **62 通过**(8 文件,本轮改到它的内容)· 文档站本机 `vite`(7471,临时起、看完即关)真开浏览器:中英两版标题分别是 `ubuntu-上的沙盒` / `sandbox-on-ubuntu`(与仓库自己的 `slugifyHeading` 算出来的一致)、节内链接 `/settings#沙盒`、`/settings#sandbox` 指向设置页既有标题、**代码块整段完整**、console 无 error、无 4xx,截图见 scratchpad | `493b9160` |
| 2026-10-09 | 5.4(`#975` 的前置) | **停靠面可以拉到最大,每个停靠面板都是一条注册表定义**(上游 `1eb13325` `#961` 移植,照改动落、不是合分支;24 文件 / +2125 −554):右侧与底部停靠栏都能经头部的**全屏**按钮、或把边界拖过最大值进入全屏 —— 停在对话工具栏之下,右侧停靠栏盖住自己那一行(开着的底部停靠栏仍显示在它下方),底部停靠栏长到工具栏之下;退出用同一枚按钮(原位变**退出全屏**)或把边界拖回。进出随主题的布局动效(`[data-layout-motion]` 因此也涵盖 `top`/`left`),减弱动效时即时;面板从第一帧起按终点尺寸排版,页面不重新排版、面板不重新挂载,退出后滚动位置 / 文件预览 / 编辑器草稿 / 终端画面原样还在。全屏**不记住**:切换对话、隐藏停靠栏、关掉最后一个标签、被它盖住的停靠栏要显示内容时都会结束;底部停靠栏原先仅触屏可用的「放大到整屏」按钮由它取代。**面板改成注册表**:每种面板是 `features/dock/panel-registry.ts` 里的一条 `DockPanelDefinition`(id、名称、图标、排序、是否提供 + 它的变更订阅、主体组件),`PANEL_KINDS` 与各处 per-kind 分支消失,标签条 / **添加面板** / 空停靠栏的选单 / 快捷方式悬浮球都读它,主体经新的 `useDockPanel()` 取本停靠栏的能力;上一轮那两处内联视图(工作区文件、记忆)因此搬进新的 `builtin-dock-panels.tsx`(`chat-page.tsx` 里两个调用点与两条 import 一起删掉),另有新的 `chat-dock-context.tsx` 与 `panel-context.tsx`;ui 新增 `DOCK_FULLSCREEN_Z` 与 `data-fullscreen` 相位。**为什么是这一条**:它是 5.4 里 `9b170c61`(#975)与 `234183f5`(#978)的前置 —— 后两条要改的 `builtin-dock-panels.tsx` / `chat-dock-context.tsx` 由它引入,本树此前没有(第十九轮记过);选它之前 `git apply -3 --check` 实测**一处错误都没有**。**本地化**:三处冲突(`browser-layer.tsx` / `panel-meta.tsx` / `chat-page.tsx`)都在 import 区 —— 包 scope 与本仓两处本地新增,逐条解;新文件里 4 处 `@prismshadow/` → `@lmliheng/`;changelog 按本仓惯例改名到本轮日期、去掉上游 PR 链接、写明移植出处 | 六包 `typecheck` 全过(`ifaces.json unchanged`,187 接口 / 535 类型)· `pnpm lint` **0 警告 0 错误**(2078 文件,+5)· `pnpm format:check` 干净 · 五包 test 逐包 `EXIT=0` 全绿:core **1359**/5 跳过(65 文件)· ui **1007**(127)· cli **506**(34)· web **2976**/2 跳过(**242** 文件,+13 条 = 新的 `panel-registry.test.ts` 与扩写的 `dock-state.test.ts`)· server **185 文件 / 2690 通过 / 4 跳过**,**0 失败**;另跑 `@lmliheng/penguin-docs` **62 通过**(8 文件,本轮改到它的内容)· **界面真跑**(重建 ui + web 后,一次性数据根 `/root/adelie-fork-data/r27-dock`、7494、真浏览器):登录 + 建会话 → 点**右侧栏** → 停靠栏打开并列出注册表里的七个面板(智能体面板 / 终端 / 文件浏览 / 记忆 / 轨迹观测 / 远程控制 / 定时任务)→ 打开**文件浏览** → 点**全屏**:`[data-fullscreen]` 变 `full`、按钮变**退出全屏**、对话列被盖住而工具栏与左侧栏保留 → 点**退出全屏**:回到 `null`、布局复原 → 再开**下侧栏**同样列出选单;**console 0 error / 0 pageerror / 页面无一条 4xx**(仅三条 `net::ERR_ABORTED`,是关浏览器时中断的长连接),截图 6 张在 scratchpad · 本轮没动端口,3003 / 3004 / 4000 / 7364 / 7369 全程没碰 | `e7a0a5a7` |
| 2026-10-09 | 5.4(主块) | **权限菜单给出具名沙箱预设**(上游 `9b170c61` `#975` 移植,照改动落、不是合分支;67 文件 / +6107 −919):权限按钮不再列三段十档,而是列具名预设(完全访问 / 每次询问 / 仅工作区可写 / 只读,管理员另有「更多…」);沙盒卡片有**启用**开关与一张**预设表**(名称 / 文件 / 网络 / 询问模式 / 操作,行内可拖动排序、图钉决定是否进菜单、「…」菜单可设为默认 / 删除,「添加预设」新增行)。服务端:`PluginConfigField` 多 `table` 类型(固定行 + 类型化列、只存与默认不同的单元格、锁定单元格忽略、可声明 `rowChoice` / `pin` / `columnGroup` / `extensible`),字段多 `advanced` / `hint`,分组可声明布尔 `switch`;沙盒分组改成 `enabled` + `presets` + `defaultPreset`(六个内置预设),自己的 `mode` / `network` 去掉;新 `sandbox/settings-policy.ts`(新会话起点 + 旧文档向后兼容)与 `sandbox/settings-status.ts`(后端状态与「本系统默认该装哪个包」);会话视图多 `presets` / `advanced` / `switchOn`。Web 的设置页插件配置面整片重写成表,UI 的 `Dropdown` / `Select` / `ConfirmModal` 跟上。**本树缺的三处前置**(typecheck 逼出来的)已补:`ICONS.star`、`S.settings.pluginAction{Title,Run,Confirm}` 中英各三条、以及上游那笔自带的「执行插件操作前先问一句」(补丁父提交里已有、补丁要改到那几行,故一并落下)。**本地化**:`@prismshadow/penguin-*` → `@lmliheng/penguin-*`;沙盒后端推荐包名 `@penguinharness/sandbox-*` → `@lmliheng/penguin-plugin-sandbox-*`(必须改,否则卡片会去装一个不存在的包);四份上游 changelog 改名到本轮日期、去 PR 行、写明移植出处 | 六包 `typecheck` 全过(`ifaces.json` 187 接口 / 547 类型)· `pnpm lint` **0 警告 0 错误**(2101 文件)· `pnpm format:check` 干净(首跑一条,`prettier --write` 后复检通过)· 五包 test 逐包 `EXIT=0` 全绿:core **1359**/5 跳过(64 文件)· ui **1008**(127)· cli **506**(34)· web **3019**/2 跳过(**247** 文件,+43 = 这笔带来的六个新用例文件与扩写)· server **187 文件 / 2755 通过 / 4 跳过**(+65)—— **0 失败**;另跑 `@lmliheng/penguin-docs` **62 通过**(8 文件,本轮改到它的内容)· **界面真跑**(重建 core/server/web 产物 —— server 的 tsup 默认堆会 OOM,`NODE_OPTIONS=--max-old-space-size=4096` 单跑即过;一次性数据根 `/root/adelie-fork-data/r28-presets`、7496、真浏览器):全新安装开关默认关,权限菜单只有四档审批方式 + 「更多…」→ 「更多…」按设计打开设置对话框的沙盒卡片(只有标题、一条「没有可用后端」提示与开关)→ 点开关弹出**安装后端**对话框,点名的包是 `@lmliheng/penguin-plugin-sandbox-bwrap`(本地化在界面上可见)→ 「暂不」后卡片展开预设表与「添加预设」「高级选项」→ **保存**后刷新重开菜单:变成 **完全访问 / 每次询问 / 仅工作区可写 / 只读**,后两者标「未安装」置灰(本机没有沙盒后端,是设计的诚实标注)→ **console 0 error / 0 pageerror / 无一条 4xx**(脚本打印 `[]`),截图 6 张在 scratchpad · 没用到的端口一律没碰,3003 / 3004 / 4000 / 7364 / 7369 全程没碰 · **CI 两跑**:`37922789257` 红在两个 macOS 作业的**服务端声明构建**(OOM,不是测试)—— 与上游同一提交的红点相同,已按仓库既有的 `run-with-env.mjs` 写法给 tsup 一个 4096MB 的默认堆(`a8347184`),详见本轮「CI」一节 | `2e9d53b6` `a8347184` |
+| 2026-10-09 | 5.4(最后一块) | **Linux 沙盒在默认的 Ubuntu 上也能工作 —— 走 Landlock**(上游 `234183f5` `#978` 移植,照改动落、不是合分支;65 文件 / +1523 −258):路由改成「**实现维度最多的后端负责**」(`SandboxService.pick()`,注册顺序只用于打破平局),bubblewrap 加载得到的地方每条策略仍由它负责、DSH 适配器只在它是仅剩的那一个时服务;新增 **`closed-temp`** 维度(bubblewrap / Seatbelt / WSL 声明,DSH 适配器不声明 —— 它每一级都会在仅工作区可写下放开一个临时目录),关闭「临时目录可写」的策略绝不路由给没有它的后端;core 插件契约多出(都可选)`SandboxProvider.mechanism`(谁在实施,如 `bubblewrap` / `Landlock`)、`SandboxProvider.limits`(本机留下的缺口,中英)与 `ConfinedSpawn.runnerLines`(后端自报的提示行从命令与钩子脚本 stderr 的开头去掉,如老 ABI 上的 `landlock-run: partial enforcement`);DSH 适配器**在加载时选定并用 `mechanism` 报出它那一级**,两级都不通的主机因此带着 DSH 的原因加载失败,而不是挂上一个拒绝每条命令的后端;沙盒卡片的后端字段 `backend.recommended` 由**单个字符串改成列表**(Linux 两个包),打开开关时按顺序装整张列表,「Backends:」一行改成 `Enforced here: … / Not enforced here: …` 加一个折叠的 **More info**(列出在用后端的缺口、每个已安装但未启用的后端及其原因),没有能隔离网络的后端时「无网络」与「仅本机」一样置灰;四个沙盒插件包升 **0.2.3**(不升的话已装有 0.2.2 的机器会继续跑旧内容、拿不到 `closed-temp` 声明);Web 那边为「旧服务端只报一个字符串」留了一条向后兼容(`recommendedOf`,带 `TODO(recommended-string-compat)`)。**本地化**:`@penguinharness/sandbox-*` → `@lmliheng/penguin-plugin-sandbox-*`(必须改,否则卡片会去装一个不存在的包)、`@prismshadow/penguin-*` → `@lmliheng/penguin-*`、`~/.penguin` → `~/.adelie`、`PENGUIN_HOME` → `ADELIE_HOME`(保留「旧名仍读」的说明);四份上游 changelog 改名到本轮日期、去掉 PR 行、写明移植出处 | 六包 `typecheck` 全过(`ifaces.json` 187 接口 / 549 类型;core 要**先重建** server 才看得到新契约)· `pnpm lint` **0 警告 0 错误**(2108 文件)· `pnpm format:check` 干净 · 五包 test 逐包 `EXIT=0`:core **1368**/5 跳过(65 文件)· ui **1008**(127)· cli **506**(34)· web **3032**/2 跳过(**248** 文件)· server **189 文件 / 2766 通过 / 4 跳过** —— **0 失败**;另跑 `@lmliheng/penguin-docs` **62**、四个沙箱插件包(bwrap 29 · dsh 21+1 跳过 · seatbelt 17+5 跳过 · wsl 25)全绿 · **界面真跑**(重建 core/server/web 产物 + 一次性数据根 `/root/adelie-fork-data/r29-landlock`、7497、真浏览器):全新安装点开沙盒卡片的开关后弹出的**安装提示点名两个包、顺序与列表一致**(`@lmliheng/penguin-plugin-sandbox-bwrap 和 @lmliheng/penguin-plugin-sandbox-dsh`,文案写明「两者都可用时,使用封禁范围更大的那个」),卡片与预设表排版正常,**console 0 error / 0 pageerror / 无一条 4xx**(脚本打印 `[]`)· **真跑一次 DSH 适配器的加载与约束**:本机(内核 6.1)加载成功、`mechanism` = `Landlock (partial)`,受限命令**在工作区内写成功、在工作区外(`$HOME`)被拒**(`Permission denied`,文件不存在)· 3003 / 3004 / 4000 / 7364 / 7369 与 `/root/penguin-harness` / `/root/Adelie` / `legacy/main` 全程没碰 | 见本行提交 |
> **2026-10-06 与另一条线的交汇(第六轮)**:本轮开工时 `git status --short` 是干净的;做完检查那一
> 步时工作区里多出**另一条线**的改动 —— 47 个 `package.json` 的 `version` 0.3.0 → 0.3.1、
@@ -4340,3 +4344,97 @@ settings-status.ts`、`packages/web/src/features/chat/builtin-dock-panels.tsx`
### 收尾:提交、推送与汇报
- **代码提交 `2e9d53b6`**(67 个文件 / +6107 −919,见「已完成的轮次」那一行);台账这一笔另起一笔。
+
+## 第二十九轮:Linux 沙盒在默认的 Ubuntu 上走 Landlock(2026-10-09,条目 5.4 的最后一块)
+
+一次无人值守的自主推进。**没有切版本号、没发 npm、没发安装包、没发发布汇总**;`legacy/main`、
+`/root/Adelie` 工作区、`/root/penguin-harness`、`/root/AgentCode`、3003 / 3004 / 4000 / 7364 / 7369
+全程没碰;按本轮纪律**没有碰 `packages/desktop` 与 electron**。
+
+### 为什么是这一条
+
+开工自检:`git status --short` 干净、`main` = `origin/main` = `dae8936a`,
+`git fetch origin && git merge --ff-only origin/main` 报 `Already up to date`。
+
+表上最靠前的未勾选条目照旧是 **2.2c**,其「还差什么」四条仍全在纪律禁止或明说留到发布期的一侧
+(写侧只剩 `packages/desktop`、既有部署单元 `adelie-app.service`、桌面壳自己的开关、画廊 mock 与
+`packages/docs` 的环境表);**3.5** 要用户拍板且本轮不许碰 desktop、**3.6** 要模型 key、**4.1–4.3**
+明令不动。所以做 **5.4 剩下的那一块**:上游 `234183f5`(#978)—— 第二十六到二十八轮把 #977 / #961 /
+#975 依次落下之后,它是这条链上唯一还剩的一块,也是「得单独一轮」的那一轮。
+
+### 改了什么(65 个文件 / +1523 −258,含四份 changelog)
+
+`git show 234183f5 | git apply -3 -`,**16 处冲突**逐条解掉:
+
+| 冲突 | 两侧是什么 | 取哪一支 |
+| --- | --- | --- |
+| 四个插件 `package.json` | 本仓的 `@lmliheng/penguin-plugin-sandbox-*` + `private` | 上游的 `@penguinharness/sandbox-*` 与 `version 0.2.3` | 名字与 `private` 取本仓,**版本取上游的 0.2.3** |
+| `builtin-index.json`(4 处) | 同上(名字 / 版本 / description) | 同上:本仓的名字与 description + 上游的版本 |
+| `settings-status.ts`(2 处) | 本仓的 scope | 上游新增的 import 与 `DEFAULT_BACKEND` → `DEFAULT_BACKENDS` | 上游的新导入与新结构 + 本仓 scope 与本仓的包名 |
+| `sandbox-dsh/src/index.ts` 的 import 区 | 本仓 scope | 上游新增 `node:os` / `node:path` | **只取上游那一支**(上游的重写里已含 `Bind, Component` 那行) |
+| 其余 8 处(四份文档、bwrap 的 README 与其源码注释、两个用例、`plugin-config-heading.tsx`) | 上游的重写 | 本仓的 scope、`~/.adelie` 与旧名说明 | 上游的正文 + 本地化 |
+
+**一条不在冲突区里的漏网**:`plugins/sandbox-bwrap/src/index.ts` 的拒绝文案整行由上游那一笔带来
+(它落在 conflict 之外,`git apply -3` 直接写进文件),里面的包名还是 `@penguinharness/sandbox-dsh`
+—— 逐行扫 diff 时抓出来改掉(`@lmliheng/penguin-plugin-sandbox-dsh`)。
+
+**本地化**:`@penguinharness/sandbox-*` → `@lmliheng/penguin-plugin-sandbox-*`(**必须改**:本仓那四个
+后端包就叫这个名字,照上游写卡片会去装一个不存在的包)、`@prismshadow/penguin-*` → `@lmliheng/penguin-*`、
+`~/.penguin` → `~/.adelie`、`PENGUIN_HOME` → `ADELIE_HOME`(**并保留本仓「旧名仍读」的那句说明** ——
+上游那一版没有它,是本仓 2.2a 的事实,改文档时不能丢)。`changelog/` 里那四份(上游的
+`2026-10-03-sandbox-landlock-floor` 与 `2026-10-03-backward-compatibility-sandbox-recommended` 各中英一份)
+按本仓惯例改名到本轮日期(`2026-10-09-sandbox-landlock-floor` / `2026-10-09-sandbox-recommended-backward-compatibility`)、
+去掉上游 PR 行、正文写明「移植自上游 PenguinHarness(#978,提交 `234183f5`)」、互链跟着改。
+
+### 验证(都不是推测)
+
+- **静态**:六包 `typecheck` 全过(`gen:ifaces` 报 **187 接口 / 549 类型**)—— 注意**core 要先重建**,
+ `packages/server` 是从 core 的 `dist` 读契约的,不重建会报 `SandboxLimit` 未导出、`closed-temp`
+ 不是 `SandboxDimension` 那一串;`pnpm lint` **0 警告 0 错误**(2108 文件);`pnpm format:check` 干净。
+- **测试**(逐包 `EXIT=0`,**0 失败**):core **1368 通过 / 5 跳过**(65 文件,比上一轮 +9 —— 正是
+ `runner-lines` 这笔)· ui **1008**(127)· cli **506**(34)· web **3032 / 2 跳过**(**248** 文件)
+ · server **189 文件 / 2766 通过 / 4 跳过**;另跑 `@lmliheng/penguin-docs` **62** 与四个沙箱插件包
+ (bwrap **29** · dsh **21 + 1 跳过** · seatbelt **17 + 5 跳过** · wsl **25**)全绿。
+- **界面真跑了一遍**(这一条改的是界面):按当前源码重建 `packages/{core,server,web}` 的 dist(server 的
+ tsup 现在自带 4096MB 默认堆,第二十八轮那一笔),一次性数据根 `/root/adelie-fork-data/r29-landlock`
+ (`ADELIE_SEED_ADMIN_PASSWORD` 起,不走认领链接)在 **7497** 起服务,Playwright(本机 chromium,
+ 1440×900,zh-CN):
+ - 权限菜单照旧四档审批方式 + 「更多…」,点「更多…」按设计打开设置对话框的沙盒卡片;
+ - 全新数据根 = 全新安装,卡片只有标题、一条「没有可用后端」提示与**启用**开关;**点开关后弹出的安装
+ 提示点名两个包、顺序与列表一致** —— `@lmliheng/penguin-plugin-sandbox-bwrap` 与
+ `@lmliheng/penguin-plugin-sandbox-dsh`,并按上游文案写明「两者都可用时,使用封禁范围更大的那个」
+ (这正是 `recommended` 由字符串改成列表在界面上的样子,也是本轮唯一能在这台机器上看到的界面变化);
+ - 「暂不」后卡片展开预设表与「添加预设」「高级选项」,排版正常;
+ - **console 0 error / 0 pageerror / 一条 4xx 都没有**(脚本从进测试页起记账,最后打印 `[]`);
+ - 截图 5 张(`01-draft` / `02-permission-menu` / `03-sandbox-card-off` / `04-sandbox-card-on`
+ (安装提示开着)/ `05-card-after-prompt`)与脚本 `landlock-smoke.cjs`、`smoke.log` 都在会话 scratchpad,
+ 未提交进仓库。服务用完已停(7497 已释放),数据根留着当现场。
+- **真跑一次 DSH 适配器的加载与约束**(这一条的核心主张,本机就能跑):把 `plugins/sandbox-dsh` 构建出
+ dist,用一段一次性脚本直接 `loadDshAdaptor()` ——
+ 本机(内核 6.1,Landlock ABI 2)**加载成功**,`mechanism` = **`Landlock (partial)`**,`limits` 三条
+ 与 `rungLimits` 一致(scratchpad 不可写 / 临时目录是宿主共享的 `/tmp` / 老 ABI 的 ioctl 与截断缺口);
+ 受限命令**在工作区内写成功**(文件在)、**在工作区外(`$HOME`)被拒** —— 退出码 1、
+ `/bin/sh: line 1: /root/r29-outside-*.txt: Permission denied`、文件确实不存在。
+ 也就是说「bubblewrap 拒绝时由 Landlock 只约束文件写入」这条在本机是**跑出来的**,不是推的。
+ 脚本与日志是 scratchpad 里的 `dsh-probe.mjs` / `dsh-probe.log`。
+- **有意没验的**:Ubuntu 23.10+ 上「bubblewrap 被 userns 限制拒绝 → 适配器接手」那一整条要在那种主机上
+ 才成立(本机是 Debian,userns 不受限,bubblewrap 会赢);服务端那一侧由本笔带来的
+ `test/sandbox-floor.test.ts`(285 行:路由偏好与平局、bwrap 被拒时适配器服务文件而断网请求 fail-closed
+ 并带全量原因、卡片标题与 More info 与置灰选项、关临时目录的策略绝不到达适配器)与
+ `session-sandbox-masks.test.ts` 钉住。
+- 本轮**没有碰 `packages/desktop` 与 electron**(依赖没装)。
+
+### 没做 / 还差什么
+
+- **5.4 已勾掉**:代码面到此清零。只剩 `1ba104c9`(沙盒后端拆成 npm 包并发布),属 4.x 的发布链路。
+- **2.2c / 3.5 / 3.6** 照旧停在原地,原因同前。
+- **一件本笔自带、本机看不到的**:上游这一笔假定 DSH「自带依赖」(那撮提交在系列顶端,不在本树),
+ 本机的 dsh 包靠 workspace 的 `node_modules` 解析 `@deepseek-ai/*` —— 真到发布一份不带依赖的安装上,
+ 这条链还得按上游系列顶端那一撮收(不在本台账的待办里,记在这里备查)。
+- `refs/adelie-tmp/*` 七个本地临时引用仍在(第 23 轮拉的),没推、没改 remote 配置;本轮没有新增。
+- 中间物:会话 scratchpad 里有 `landlock-smoke.cjs` / 5 张截图 / `smoke.log` / `dsh-probe.{mjs,log}` /
+ `PLAN.md`;`/root/adelie-fork-data/r29-landlock` 是本轮的取证数据根(留着当现场)。
+
+### 收尾:提交、推送与汇报
+
+- **代码提交**见「已完成的轮次」那一行;台账这一笔另起一笔。
diff --git a/packages/core/src/environment/tools/command/runner-lines.ts b/packages/core/src/environment/tools/command/runner-lines.ts
new file mode 100644
index 00000000..b0576401
--- /dev/null
+++ b/packages/core/src/environment/tools/command/runner-lines.ts
@@ -0,0 +1,58 @@
+/**
+ * Drops the lines a sandbox runner prints on stderr before it execs the confined command
+ * (see `ConfinedSpawn.runnerLines`) — the Landlock launcher's "partial enforcement"
+ * report on an older kernel, printed on every run. Only the HEAD of the stream is examined:
+ * the runner writes before the exec, so once a line that is not one of them (or any byte that
+ * cannot begin one) has passed, everything after is the command's own and flows untouched. A
+ * command whose own FIRST stderr line is word for word one of them loses that line — the price
+ * of not parsing the command's output.
+ */
+export interface RunnerLineFilter {
+ /** Feeds one stderr chunk; returns what to pass on now (possibly empty). */
+ push(chunk: string): string;
+ /** The stream ended: returns what was held back waiting for a line's end. */
+ flush(): string;
+}
+
+/**
+ * A filter for one stream; null when the runner names no lines, so callers keep their plain
+ * listener.
+ */
+export function runnerLineFilter(lines: readonly string[] | undefined): RunnerLineFilter | null {
+ if (lines === undefined || lines.length === 0) return null;
+ // Matched by exact line, case-insensitively, as the runner contract states it.
+ const known = lines.map((l) => l.toLowerCase());
+ let head = true;
+ let held = "";
+ // A held tail may already carry the CR of a CRLF line end.
+ const startsOne = (partial: string) => {
+ const p = partial.replace(/\r$/, "").toLowerCase();
+ return known.some((l) => l.startsWith(p));
+ };
+ return {
+ push(chunk) {
+ if (!head) return chunk;
+ held += chunk;
+ for (;;) {
+ const nl = held.indexOf("\n");
+ if (nl === -1) {
+ if (startsOne(held)) return "";
+ break;
+ }
+ const line = held.slice(0, nl).replace(/\r$/, "");
+ if (!known.includes(line.toLowerCase())) break;
+ held = held.slice(nl + 1);
+ }
+ head = false;
+ const out = held;
+ held = "";
+ return out;
+ },
+ flush() {
+ head = false;
+ const out = held;
+ held = "";
+ return out;
+ },
+ };
+}
diff --git a/packages/core/src/environment/tools/command/session.ts b/packages/core/src/environment/tools/command/session.ts
index da135ba3..6cdead8c 100644
--- a/packages/core/src/environment/tools/command/session.ts
+++ b/packages/core/src/environment/tools/command/session.ts
@@ -28,6 +28,7 @@
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
import type { ToolResult } from "../types.js";
import type { ConfinedSpawn } from "../../../interfaces/index.js";
+import { runnerLineFilter } from "./runner-lines.js";
import { CappedTextBuffer, WakeSignal } from "../background/index.js";
import { sessionShell } from "./shell.js";
import { pathPrependPrefix } from "./path-prepend.js";
@@ -145,7 +146,20 @@ export class ManagedSession {
// as an unhandled error.
this.child.stdin?.on("error", () => {});
this.child.stdout?.on("data", (c: string) => this.handleData(c));
- this.child.stderr?.on("data", (c: string) => this.handleData(c));
+ // The runner's own report lines (ConfinedSpawn.runnerLines) are not the command's output.
+ const runner = runnerLineFilter(confined.runnerLines);
+ if (runner === null) {
+ this.child.stderr?.on("data", (c: string) => this.handleData(c));
+ } else {
+ this.child.stderr?.on("data", (c: string) => {
+ const out = runner.push(c);
+ if (out !== "") this.handleData(out);
+ });
+ this.child.stderr?.on("end", () => {
+ const out = runner.flush();
+ if (out !== "") this.handleData(out);
+ });
+ }
// exit follows waitpid semantics: it fires as soon as bash exits, without waiting for
// stdout/stderr pipe EOF — background child processes that inherit and hold the pipe open
// won't hold up termination.
diff --git a/packages/core/src/hooks/script-hook.ts b/packages/core/src/hooks/script-hook.ts
index b96bad63..c5b09390 100644
--- a/packages/core/src/hooks/script-hook.ts
+++ b/packages/core/src/hooks/script-hook.ts
@@ -30,6 +30,7 @@
import { spawn } from "node:child_process";
import path from "node:path";
import { prependPathEnv } from "../environment/tools/command/path-prepend.js";
+import { runnerLineFilter } from "../environment/tools/command/runner-lines.js";
import type { ConfinedSpawn, SpawnConfiner } from "../interfaces/index.js";
import type { UserPromptTrigger } from "../plugins/index.js";
import type { StopHook, StopHookInput, StopHookResult } from "./stop-hook.js";
@@ -120,7 +121,16 @@ export async function runHookScript(
};
opts.signal?.addEventListener("abort", onAbort, { once: true });
child.stdout.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk));
- child.stderr.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk));
+ // The runner's own report lines (ConfinedSpawn.runnerLines) are no reason for a failure.
+ const runner = runnerLineFilter(confined.runnerLines);
+ if (runner === null) {
+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk));
+ } else {
+ child.stderr
+ .setEncoding("utf8")
+ .on("data", (chunk: string) => (stderr += runner.push(chunk)));
+ child.stderr.on("end", () => (stderr += runner.flush()));
+ }
child.on("error", (err) => fail(err.message));
child.on("close", (code) => {
if (code !== 0) {
diff --git a/packages/core/src/interfaces/environment.ts b/packages/core/src/interfaces/environment.ts
index df298cb8..5c5c31ef 100644
--- a/packages/core/src/interfaces/environment.ts
+++ b/packages/core/src/interfaces/environment.ts
@@ -388,6 +388,13 @@ export type SpawnConfiner = (
export interface ConfinedSpawn {
argv: readonly string[];
env?: Readonly<Record<string, string>>;
+ /**
+ * Whole lines the runner itself prints at the head of stderr before it execs the command
+ * (a report, not an error — the Landlock launcher's "partial enforcement" on an older
+ * kernel). The spawn drops them from the head of the command's stderr, matched by exact
+ * line, case-insensitively; the command's own output is never examined past its first line.
+ */
+ runnerLines?: readonly string[];
}
/**
diff --git a/packages/core/src/plugin/sandbox.ts b/packages/core/src/plugin/sandbox.ts
index e2ec2ca1..176c9b17 100644
--- a/packages/core/src/plugin/sandbox.ts
+++ b/packages/core/src/plugin/sandbox.ts
@@ -33,9 +33,13 @@ export type ConfinedSandboxMode = Exclude<SandboxMode, "danger-full-access">;
* and `mask-paths` are optional implementations (see {@link SandboxProvider.dimensions}).
* `network-local` is the local network level: only the host's localhost is reachable. It is
* its own dimension because a backend that can cut the network cannot necessarily keep the
- * host's loopback while cutting the rest.
+ * host's loopback while cutting the rest. `closed-temp` is withholding the temporary directory
+ * when a policy does not grant it ({@link SandboxPolicy.writableTemp}): a backend whose temp
+ * area is always writable (the DSH adaptor, which grants the host's /tmp under
+ * `workspace-write`) does not declare it, and a policy closing temp is never routed to it.
*/
-export type SandboxDimension = "fs-write" | "network" | "network-local" | "mask-paths";
+export type SandboxDimension =
+ "fs-write" | "network" | "network-local" | "mask-paths" | "closed-temp";
/**
* The network levels, narrowest first: `none` = no network at all, `local` = only the host's
@@ -83,7 +87,8 @@ export interface SandboxPolicy {
maskPaths?: readonly string[];
/**
* The system temporary directory is writable, in either confining mode: shells and most
- * tools need somewhere to write before they run anything. Absent = not granted.
+ * tools need somewhere to write before they run anything. Absent = not granted — which the
+ * service hands only to a backend declaring `closed-temp`.
*/
writableTemp?: boolean;
}
@@ -144,9 +149,27 @@ export interface SandboxProvider {
* unimplemented dimension can never be silently ignored.
*/
readonly dimensions?: readonly SandboxDimension[];
+ /**
+ * What enforces the confinement on this host, as an administrator would name it
+ * ("bubblewrap", "Landlock"). The settings card says what this machine enforces and by
+ * what; absent, it names the backend instead.
+ */
+ readonly mechanism?: string;
+ /**
+ * What this backend leaves open on this host beyond the dimensions it does not declare —
+ * a policy field it cannot honour in full, a kernel that enforces only part of it — in an
+ * administrator's words. The settings card discloses them under what this machine enforces.
+ */
+ readonly limits?: readonly SandboxLimit[];
confine(argv: readonly string[], policy: SandboxPolicy): ConfinedArgv;
}
+/** One limit of a backend on this host (see {@link SandboxProvider.limits}). */
+export interface SandboxLimit {
+ text: string;
+ textZh?: string;
+}
+
/** A provider, or a promise of one: backends load asynchronously (dynamic imports, probes). */
export type SandboxProviderLoad = SandboxProvider | PromiseLike<SandboxProvider | null> | null;
diff --git a/packages/core/test/runner-lines.test.ts b/packages/core/test/runner-lines.test.ts
new file mode 100644
index 00000000..9eba9578
--- /dev/null
+++ b/packages/core/test/runner-lines.test.ts
@@ -0,0 +1,87 @@
+/**
+ * A sandbox runner's own report lines (ConfinedSpawn.runnerLines) leave the head of the confined
+ * command's stderr — in the filter, a command's output and a hook's failure reason — and only those.
+ */
+import { mkdtemp, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { runnerLineFilter } from "../src/environment/tools/command/runner-lines.js";
+import { ManagedSession } from "../src/environment/index.js";
+import { runHookScript } from "../src/index.js";
+import { rmEventually } from "./rm-eventually.js";
+
+const LINE = "landlock-run: partial enforcement (older Landlock ABI)";
+
+describe("the runner-line filter on a stderr stream", () => {
+ const run = (lines: readonly string[], chunks: readonly string[]) => {
+ const filter = runnerLineFilter(lines)!;
+ return chunks.map((c) => filter.push(c)).join("") + filter.flush();
+ };
+
+ it.each([
+ [[`${LINE}\nboom\n`], "boom\n"],
+ [["landlock-run: par", "tial enforcement (older Landlock ABI)\r", "\nx"], "x"],
+ [[`${LINE.toUpperCase()}\n`], ""],
+ // The command's own stderr: the same words after its first line, another runner-prefixed line.
+ [[`own\n${LINE}\n`], `own\n${LINE}\n`],
+ [["landlock-run: other\n"], "landlock-run: other\n"],
+ // Held while it could still be the runner's line; released when the stream ends.
+ [["landlock-run"], "landlock-run"],
+ ])("%j leaves %j", (chunks, out) => {
+ expect(run([LINE], chunks)).toBe(out);
+ });
+
+ it("is null when the runner names no lines, so the plain listener stays", () => {
+ expect(runnerLineFilter(undefined)).toBeNull();
+ expect(runnerLineFilter([])).toBeNull();
+ });
+});
+
+// The command case runs a POSIX shell line.
+describe.skipIf(process.platform === "win32")("the spawn paths drop the runner's lines", () => {
+ let dir: string;
+ let wrap: string;
+ beforeEach(async () => {
+ dir = await mkdtemp(path.join(tmpdir(), "penguin-runner-lines-"));
+ // A stand-in runner: prints its report line on stderr, then runs the rest of its argv.
+ wrap = path.join(dir, "runner.mjs");
+ await writeFile(
+ wrap,
+ 'import { spawnSync } from "node:child_process";\n' +
+ `process.stderr.write(${JSON.stringify(LINE + "\n")});\n` +
+ 'process.exit(spawnSync(process.argv[2], process.argv.slice(3), { stdio: "inherit" }).status ?? 1);\n',
+ );
+ });
+ afterEach(() => rmEventually(dir));
+
+ it("a command's output", async () => {
+ const session = new ManagedSession({
+ cmd: "echo out; echo own-error >&2",
+ cwd: dir,
+ env: process.env,
+ confine: (argv) => ({ argv: [process.execPath, wrap, ...argv], runnerLines: [LINE] }),
+ });
+ try {
+ let output = "";
+ for await (const chunk of session.collect(5000)) output += chunk;
+ expect(output).toContain("out");
+ expect(output).toContain("own-error");
+ expect(output).not.toContain("partial enforcement");
+ } finally {
+ session.kill();
+ }
+ });
+
+ it("a hook script's failure reason", async () => {
+ const script = path.join(dir, "fail.mjs");
+ await writeFile(script, 'process.stderr.write("hook broke\\n"); process.exit(3);\n');
+ const confine = {
+ confine: (argv: readonly string[]) => ({
+ argv: [argv[0]!, wrap, ...argv],
+ runnerLines: [LINE],
+ }),
+ };
+ await expect(runHookScript(script, {}, confine)).rejects.toThrow(/^exit 3: hook broke$/);
+ });
+});
diff --git a/packages/docs/content/interfaces.en.md b/packages/docs/content/interfaces.en.md
index c149c7a6..a41765ba 100644
--- a/packages/docs/content/interfaces.en.md
+++ b/packages/docs/content/interfaces.en.md
@@ -279,6 +279,7 @@ type SpawnConfiner = (
interface ConfinedSpawn {
argv: readonly string[]; // spawned instead of the original argv
env?: Readonly<Record<string, string>>; // entries the sandbox runner itself needs, laid over the command's env
+ runnerLines?: readonly string[]; // lines the runner prints before the command; dropped from the head of its stderr
}
// The policy itself (@lmliheng/penguin-core/plugin). "danger-full-access" with no network cut
diff --git a/packages/docs/content/interfaces.zh.md b/packages/docs/content/interfaces.zh.md
index 19dff3fd..3459d041 100644
--- a/packages/docs/content/interfaces.zh.md
+++ b/packages/docs/content/interfaces.zh.md
@@ -279,6 +279,7 @@ type SpawnConfiner = (
interface ConfinedSpawn {
argv: readonly string[]; // spawned instead of the original argv
env?: Readonly<Record<string, string>>; // entries the sandbox runner itself needs, laid over the command's env
+ runnerLines?: readonly string[]; // lines the runner prints before the command; dropped from the head of its stderr
}
// The policy itself (@lmliheng/penguin-core/plugin). "danger-full-access" with no network cut
diff --git a/packages/docs/content/quickstart-cli.en.md b/packages/docs/content/quickstart-cli.en.md
index 016a57c3..58174c8b 100644
--- a/packages/docs/content/quickstart-cli.en.md
+++ b/packages/docs/content/quickstart-cli.en.md
@@ -198,9 +198,11 @@ The data root is `~/.penguin/data` by default (`%USERPROFILE%\.penguin\data` on
### Sandbox on Ubuntu
-The Linux sandbox backend, `@lmliheng/penguin-plugin-sandbox-bwrap`, confines commands with bubblewrap, which needs unprivileged user namespaces. Ubuntu 23.10 and later, including a default Ubuntu 24.04, grant them only to programs that have an AppArmor profile allowing it (`kernel.apparmor_restrict_unprivileged_userns` is `1`), and the install script, the npm install, the release archive and a Docker container all run as an ordinary user, so none of them can install a profile. On those installs the backend's startup check fails, and the [Sandbox](/settings#sandbox) card shows `@lmliheng/penguin-plugin-sandbox-bwrap` as enabled but not in use, with `setting up uid map: Permission denied` in the reason.
+On Linux, turning the sandbox on installs two backends. `@lmliheng/penguin-plugin-sandbox-bwrap` confines commands with bubblewrap: file writes, the network and masked paths. `@lmliheng/penguin-plugin-sandbox-dsh` confines file writes only, through Landlock where bubblewrap cannot run. Where both work, bubblewrap serves every command.
-To fix this, install a profile for the bubblewrap the backend ships. This takes root once:
+Ubuntu 23.10 and later, including a default Ubuntu 24.04, grant unprivileged user namespaces only to programs that have an AppArmor profile allowing it (`kernel.apparmor_restrict_unprivileged_userns` is `1`), and bubblewrap needs them. The desktop `.deb` installs such a profile for the app. The install script, the npm install and the release archive run without root and cannot, so on those installs bubblewrap is refused and the sandbox works through Landlock with no step from you. The [Sandbox](/settings#sandbox) card says so: `Enforced here: file writes, by Landlock (dsh-local). Not enforced here: network isolation, localhost-only network and masked paths.` Every built-in preset leaves the network open, so all of them are enforced. A preset with No network is greyed out on the card, and masked paths are refused rather than run with less confinement. **More info** under that line shows why bubblewrap is not in use (`setting up uid map: Permission denied`) and the bwrap path it tried.
+
+To add network isolation and masked paths, let bubblewrap run with an AppArmor profile for the copy the backend ships. This step is optional and takes root once:
```bash
sudo tee /etc/apparmor.d/adelie-sandbox-bwrap >/dev/null <<'EOF'
@@ -214,7 +216,7 @@ EOF
sudo apparmor_parser -r /etc/apparmor.d/adelie-sandbox-bwrap
```
-Then select **Save** on the Sandbox card. The backend is checked again without a restart. The profile loads again at every boot. Its pattern matches every place the backend's bubblewrap is unpacked under `~/.adelie`: the installation's bundled plugins (`~/.adelie/lib/plugins/`), a download into the data root (`~/.adelie/data/plugins/`) and the plugins a hot push carries (under `~/.adelie/data/hmr/`). An upgrade replaces the package at the same path, so later versions stay covered. If `ADELIE_HOME` (its pre-rename name is `PENGUIN_HOME`) or `PENGUIN_INSTALL_DIR` points outside `~/.adelie`, load a copy of the profile under another name with `@{HOME}/.adelie` replaced by that directory.
+Then select **Save** on the Sandbox card: the backends are checked again without a restart, and the card names bubblewrap. The profile loads again at every boot. Its pattern matches every place the backend's bubblewrap is unpacked under `~/.adelie`: a download into the data root (`~/.adelie/data/plugins/`), the installation's bundled plugins (`~/.adelie/lib/plugins/`) and the plugins a hot push carries (under `~/.adelie/data/hmr/`). An upgrade replaces the package at the same path, so later versions stay covered. If `ADELIE_HOME` (its pre-rename name is `PENGUIN_HOME`) or `PENGUIN_INSTALL_DIR` points outside `~/.adelie`, load a copy of the profile under another name with `@{HOME}/.adelie` replaced by that directory.
The profile applies to whatever program is at that path, and you can write to that path. On a machine shared with users you do not trust, set the bwrap program on the Sandbox card to a root-owned copy, such as `/usr/bin/bwrap` from `apt install bubblewrap`, and name that path in the profile instead. The other option is to lift the restriction for every program with `sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0`. To keep that setting after a reboot, add the same line without `sudo sysctl -w` to a file in `/etc/sysctl.d/`.
diff --git a/packages/docs/content/quickstart-cli.zh.md b/packages/docs/content/quickstart-cli.zh.md
index 171d8fd1..cf4dce5d 100644
--- a/packages/docs/content/quickstart-cli.zh.md
+++ b/packages/docs/content/quickstart-cli.zh.md
@@ -198,9 +198,11 @@ Windows 上还有以下不同:
### Ubuntu 上的沙盒
-Linux 沙盒后端 `@lmliheng/penguin-plugin-sandbox-bwrap` 用 bubblewrap 约束命令,需要非特权 user namespace。Ubuntu 23.10 及以后的版本(包括默认的 Ubuntu 24.04)只把它交给带有相应 AppArmor profile 的程序(`kernel.apparmor_restrict_unprivileged_userns` 为 `1`),而安装脚本、npm 安装、Release 压缩包与 Docker 容器都以普通用户运行,装不了 profile。这几种安装上,后端的启动检查会失败,[沙盒](/settings#沙盒)卡片显示 `@lmliheng/penguin-plugin-sandbox-bwrap` 已启用但未在用,原因里带有 `setting up uid map: Permission denied`。
+在 Linux 上打开沙盒会装上两个后端。`@lmliheng/penguin-plugin-sandbox-bwrap` 用 bubblewrap 约束命令,覆盖文件写入、网络与屏蔽路径;`@lmliheng/penguin-plugin-sandbox-dsh` 只约束文件写入,在 bubblewrap 无法运行的地方通过 Landlock 实施。两者都能用时,每条命令都由 bubblewrap 约束。
-解决办法是为后端自带的 bubblewrap 装一份 profile。这一步需要 root,只做一次:
+Ubuntu 23.10 及以后的版本(包括默认的 Ubuntu 24.04)只把非特权 user namespace 交给带有相应 AppArmor profile 的程序(`kernel.apparmor_restrict_unprivileged_userns` 为 `1`),而 bubblewrap 需要它。桌面 `.deb` 会为应用装上这样一份 profile。安装脚本、npm 安装和 Release 压缩包都不以 root 运行,装不了 profile,所以在这些安装上 bubblewrap 被拒绝,沙盒改由 Landlock 实施,你无需做任何操作。[沙盒](/settings#沙盒)卡片会写明这一点:`本机实施:文件写入,由 Landlock (dsh-local) 实施。本机不实施:网络隔离、仅本机网络、屏蔽路径。`内置预设都不限制网络,因此全部可以实施。卡片会把设为「无网络」的预设显示为灰色;屏蔽路径会被拒绝,而不是以更弱的约束运行。这一行下方的**更多信息**会给出 bubblewrap 未启用的原因(`setting up uid map: Permission denied`)以及它尝试的 bwrap 路径。
+
+如果还需要网络隔离与屏蔽路径,可以为后端自带的 bubblewrap 装一份 AppArmor profile,让它能够运行。这一步是可选的,需要 root,只做一次:
```bash
sudo tee /etc/apparmor.d/adelie-sandbox-bwrap >/dev/null <<'EOF'
@@ -214,7 +216,7 @@ EOF
sudo apparmor_parser -r /etc/apparmor.d/adelie-sandbox-bwrap
```
-然后在沙盒卡片上点**保存**,后端会重新检查,无需重启。profile 在每次开机时重新加载。它的路径模式匹配 `~/.adelie` 下后端自带的 bubblewrap 可能被解压到的每个位置:安装目录随包带的插件(`~/.adelie/lib/plugins/`)、下载到数据根目录的插件(`~/.adelie/data/plugins/`),以及热推送携带的插件(位于 `~/.adelie/data/hmr/` 下)。升级会在同一路径上替换这个包,所以后端升级后依然有效。如果 `ADELIE_HOME`(旧名 `PENGUIN_HOME`)或 `PENGUIN_INSTALL_DIR` 指向 `~/.adelie` 之外,再以另一个名字加载一份 profile,把其中的 `@{HOME}/.adelie` 换成那个目录。
+然后在沙盒卡片上点**保存**,后端会重新检查,无需重启,卡片随即改为由 bubblewrap 实施。profile 在每次开机时重新加载。它的路径模式匹配 `~/.adelie` 下后端自带的 bubblewrap 可能解压到的每个位置:下载到数据根目录的(`~/.adelie/data/plugins/`)、安装目录随包带的插件(`~/.adelie/lib/plugins/`),以及热推送携带的插件(位于 `~/.adelie/data/hmr/` 下)。升级会在同一路径上替换这个包,所以后端升级后依然有效。如果 `ADELIE_HOME`(旧名 `PENGUIN_HOME`)或 `PENGUIN_INSTALL_DIR` 指向 `~/.adelie` 之外,再以另一个名字加载一份 profile,把其中的 `@{HOME}/.adelie` 换成那个目录。
这份 profile 作用于该路径上的任何程序,而这个路径你自己就能写入。在与不受信任的用户共用的机器上,改为在沙盒卡片上把 bwrap 程序设为一份属于 root 的副本(例如 `apt install bubblewrap` 装的 `/usr/bin/bwrap`),并在 profile 里写那个路径。另一种做法是用 `sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0` 对所有程序解除这项限制。要在重启后保留这项设置,把同一行(去掉 `sudo sysctl -w`)写进 `/etc/sysctl.d/` 下的一个文件。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index cbfedfa5..8595ee99 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -169,7 +169,7 @@ A settings group is a contribution to `PluginConfigProvider.groups`; the sandbox
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. A field marked `advanced: true` is drawn in the card's Advanced fold, collapsed by default; it is stored and validated like any other. A field's `description` is what it means, drawn behind a "?" beside its title; its `hint` is the shape a value must take, shown under it. A `table` field has fixed `rows` and `columns` (`string`, `boolean` or `enum`, each with an optional `description` for its header's "?"), and may declare a `rowChoice` (a single choice of a row, stored in an `enum` field of the group, drawn as its title in brackets after the chosen row's name and picked from the row's "…" menu), a `pin` (a boolean column drawn as a pin toggle, with an `on` and `off` tooltip), a `columnGroup` (a header over adjacent columns) and `extensible` (rows may be added and reordered: stored under `"$added"` and `"$order"` beside the changed cells; only added rows may be deleted, and a row choice naming no row is refused). A row may carry a `description` and an `enum` option a `description`, both for the "?" after the row's name. A configuration may name a boolean field as its `switch`: while it is off, the card draws that field alone.
-The sandbox's entry also carries `backend`: `installed` says whether a sandbox backend for this machine's OS is installed, and `recommended` names the package this OS defaults to (`@lmliheng/penguin-plugin-sandbox-bwrap` on Linux, `@lmliheng/penguin-plugin-sandbox-seatbelt` on macOS, `@lmliheng/penguin-plugin-sandbox-wsl` on Windows). Its `enabled` switch decides whether new Sessions start confined, and `defaultPreset` (the presets table's `rowChoice`, drawn as "(Default)" after the row's name) names the row whose mode, network and approval mode they start from. A document saved before the switch existed reads it as on when its old policy confined anything (a mode other than Off, a network that is not open, or masked paths); one saved before the default preset (with its own `mode` or `network`, or masked paths, and no `defaultPreset`) keeps starting new Sessions by its own `mode` and `network` until an administrator picks a default. For such a document `values.defaultPreset` is the first row whose start is exactly that one, and a save pins it; when no row gives it (a network of `none` or `local`, or Off with masked paths), `defaultPreset` is absent, a notice says what is in effect, and a save of other fields writes no `defaultPreset`. Neither is rewritten on read. A table's `rowChoice` may name no row: a save is not refused for that, only for leaving it on a row the table no longer has. The chat defaults' `sandbox.defaultApprovalMode` is the default preset's approval mode while the switch is on.
+The sandbox's entry also carries `backend`: `installed` says whether a sandbox backend for this machine's OS is installed, and `recommended` lists the packages this OS defaults to, installed together (`@lmliheng/penguin-plugin-sandbox-bwrap` and `@lmliheng/penguin-plugin-sandbox-dsh` on Linux, `@lmliheng/penguin-plugin-sandbox-seatbelt` on macOS, `@lmliheng/penguin-plugin-sandbox-wsl` on Windows). Its first notice says what this machine enforces and by what; a notice may carry `details` (and `detailsZh`), shown collapsed under it — here, each installed backend that is not in use, with its reason. Its `enabled` switch decides whether new Sessions start confined, and `defaultPreset` (the presets table's `rowChoice`, drawn as "(Default)" after the row's name) names the row whose mode, network and approval mode they start from. A document saved before the switch existed reads it as on when its old policy confined anything (a mode other than Off, a network that is not open, or masked paths); one saved before the default preset (with its own `mode` or `network`, or masked paths, and no `defaultPreset`) keeps starting new Sessions by its own `mode` and `network` until an administrator picks a default. For such a document `values.defaultPreset` is the first row whose start is exactly that one, and a save pins it; when no row gives it (a network of `none` or `local`, or Off with masked paths), `defaultPreset` is absent, a notice says what is in effect, and a save of other fields writes no `defaultPreset`. Neither is rewritten on read. A table's `rowChoice` may name no row: a save is not refused for that, only for leaving it on a row the table no longer has. The chat defaults' `sandbox.defaultApprovalMode` is the default preset's approval mode while the switch is on.
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.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 480f058b..fdcf314d 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -169,7 +169,7 @@ PUT 按如下规则校验:
字段类型有 `string`、`secret`、`boolean`、`number`、`enum`(带 `options`)和 `list`(每行一个值,可选 `maxItems`)。`number` 可声明 `minimum` 与 `maximum`;`string` 与 `list` 可声明每个值或每一行都须匹配的 `pattern`(配 `patternErrorMessage`)。标记 `advanced: true` 的字段画在卡片默认折叠的「高级选项」里,存储与校验与其他字段相同。字段的 `description` 说明其含义,收在标题旁的「?」里;`hint` 是取值须符合的格式,显示在字段下方。`table` 字段有固定的 `rows` 与 `columns`(`string`、`boolean` 或 `enum`,各可带 `description`,用于列标题的「?」),并可声明 `rowChoice`(单选一行,存入该组的一个 `enum` 字段,画作被选行名称后带括号的标题,在该行的「…」菜单里选定)、`pin`(把一个布尔列画成图钉按钮,带 `on` 与 `off` 两种提示)、`columnGroup`(相邻几列上方的分组标题)与 `extensible`(可新增行并调整顺序,在改动的单元格旁存于 `"$added"` 与 `"$order"`;只有新增的行可删除,单选列不指向任何行的保存会被拒绝)。行可带 `description`,`enum` 的选项也可带 `description`,都用于行名称后的「?」。配置可把一个布尔字段声明为 `switch`:它关闭时,卡片只画这一个字段。
-沙盒条目另带 `backend`:`installed` 表示是否装有适用于本机操作系统的沙盒后端,`recommended` 是本系统的默认后端包(Linux 为 `@lmliheng/penguin-plugin-sandbox-bwrap`,macOS 为 `@lmliheng/penguin-plugin-sandbox-seatbelt`,Windows 为 `@lmliheng/penguin-plugin-sandbox-wsl`)。其 `enabled` 开关决定新建 Session 是否进入沙盒,`defaultPreset`(预设表的 `rowChoice`,画作行名称后的「(默认)」)指定新 Session 取哪一行的封禁模式、网络与审批方式。开关出现之前保存的设置,旧策略有任何封禁(封禁模式不是「关闭」、网络不是完全开放,或设置了屏蔽路径)即视为打开;默认预设出现之前保存的设置(带自身的 `mode` 或 `network`、或设置了屏蔽路径,且没有 `defaultPreset`),新 Session 仍按其自身的 `mode` 与 `network` 开始,直到管理员选定默认行。对这类文档,`values.defaultPreset` 是起点与之完全相同的第一行,保存时写入它;没有这样的行时(网络为 `none` 或 `local`,或模式为关闭而设了屏蔽路径),`defaultPreset` 缺省,一条提示写明实际生效的值,保存别的字段也不写入 `defaultPreset`。读取时都不改写文档。表的 `rowChoice` 可以不指向任何一行:保存不因此被拒,只有让它指向表里已不存在的行时才被拒。chat defaults 的 `sandbox.defaultApprovalMode` 是开关打开时默认预设的审批方式。
+沙盒条目另带 `backend`:`installed` 表示是否装有适用于本机操作系统的沙盒后端,`recommended` 列出本系统默认一并安装的后端包(Linux 为 `@lmliheng/penguin-plugin-sandbox-bwrap` 与 `@lmliheng/penguin-plugin-sandbox-dsh`,macOS 为 `@lmliheng/penguin-plugin-sandbox-seatbelt`,Windows 为 `@lmliheng/penguin-plugin-sandbox-wsl`)。它的第一条提示写明本机实施什么、由什么实施;提示可以带 `details`(及 `detailsZh`),折叠显示在其下方——这里是每个已安装但未启用的后端及原因。其 `enabled` 开关决定新建 Session 是否进入沙盒,`defaultPreset`(预设表的 `rowChoice`,画作行名称后的「(默认)」)指定新 Session 取哪一行的封禁模式、网络与审批方式。开关出现之前保存的设置,旧策略有任何封禁(封禁模式不是「关闭」、网络不是完全开放,或设置了屏蔽路径)即视为打开;默认预设出现之前保存的设置(带自身的 `mode` 或 `network`、或设置了屏蔽路径,且没有 `defaultPreset`),新 Session 仍按其自身的 `mode` 与 `network` 开始,直到管理员选定默认行。对这类文档,`values.defaultPreset` 是起点与之完全相同的第一行,保存时写入它;没有这样的行时(网络为 `none` 或 `local`,或模式为关闭而设了屏蔽路径),`defaultPreset` 缺省,一条提示写明实际生效的值,保存别的字段也不写入 `defaultPreset`。读取时都不改写文档。表的 `rowChoice` 可以不指向任何一行:保存不因此被拒,只有让它指向表里已不存在的行时才被拒。chat defaults 的 `sandbox.defaultApprovalMode` 是开关打开时默认预设的审批方式。
PUT 时,请求省略的字段保持原值,`null` 或 `""` 清除该字段,密钥按掩码原样送回即保持存储值。被拒的字段返回 `400` `plugin_config_invalid` 并点名该字段;没有分组叫这个名字时返回 `404` `plugin_config_unknown`。声明它的模块自己经 watch 或下次读取拿到改动,无需重启。
diff --git a/packages/docs/content/settings.en.md b/packages/docs/content/settings.en.md
index 29eaebdd..112b2ce0 100644
--- a/packages/docs/content/settings.en.md
+++ b/packages/docs/content/settings.en.md
@@ -272,12 +272,12 @@ The sandbox is the first card on the page. It sets the policy a new Session is c
- **Enable**: the switch at the top. Off (a fresh install), a new Session has full file and network access and is held only by its approval mode, and the composer's permission menu lists the approval modes alone. While it is off, the card shows the switch alone: the presets, the Advanced fold, the backends' own settings and the card's notices come back when it is turned on, as they were.
- **Presets**: the table of what the permission menu offers, one row per preset: its name, file mode (off, workspace, read-only), network (full, localhost, none) and approval mode, and an **Action** group: a pin for whether the menu lists it, a drag handle, and a "…" menu with **Set as default** and, on presets you added, **Delete**. The default row reads "(Default)" after its name, and each name's "?" says what the row is for — for a preset you added, or a built-in one whose values you changed, what each of its values does. Each header's "?" says what the column (or each icon) means. Drag a row's handle (or press the arrow keys on it) to reorder; the order is the menu's. **Add preset** adds a row; only added rows can be deleted, and not while they are the default. Workspace allows writes to the Session's Workspace, its scratchpad (the plan file, a goal's state file, attachments) and the temporary directory; read-only allows the temporary directory only. The network level applies to the image URLs `read_file` fetches too, and localhost needs a backend that can enforce it. The default row is the one a new Session starts from while the switch is on — its file mode, network and approval mode; Workspace Write until changed. Settings saved before the presets table keep their own file mode and network until you set a default: the card marks as default the row that starts Sessions exactly where they do, and saving pins it. When no row does (a cut or localhost-only network, or masked paths with the file mode off), no row is marked, a notice at the top of the card says what is in effect, and saving other settings keeps it; set a row as default, or add a preset with those values and set it.
- Under **Advanced**, folded by default:
- - **Temporary directory**: whether it stays writable. On by default, in either confining mode, because shells and most tools cannot start without one.
+ - **Temporary directory**: whether it stays writable. On by default, in either confining mode, because shells and most tools cannot start without one. Turning it off needs a backend that can close it: with only DSH in use the switch is held on and says why (on Landlock the temporary directory is the host's shared `/tmp`).
- **Masked paths**: paths hidden from the agent's commands, hook scripts, `stdio` MCP Servers and file tools, reads included; one absolute path per line, at most 64.
Neither confining mode lets the agent write its Agent State: `AGENTS.md`, `system_config.yaml`, Skills, hook packages, memory, the vault and scheduled tasks. To let an agent write memory, write its own Skills or hook packages, or change its configuration, switch that conversation to full access with its **Permissions** button. An MCP Server started over `stdio` is confined the same way when it starts — at a context open or a reconnect — so a Server that must write outside those directories, or reach a network the level cuts, fails to connect in a confining Session; MCP Servers reached over `http` or `sse` are not processes of this machine and are not confined.
-A sandbox backend installed as a plugin (bwrap, Seatbelt, WSL, DSH) enforces the policy on all of them: the file tools work through a helper process the same backend wraps (see [File tools](/tools#file-tools)). 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 and file operation, fails every hook and connects no `stdio` MCP Server. Two backends need a word: DSH does not make the scratchpad writable; WSL runs hook scripts and the file tools' helper on the `nodejs` the distro's initialization now installs — a distro initialized before that has to be initialized again, and until then hooks and file operations fail under it rather than running unconfined — and a `stdio` MCP Server runs there only if its command exists inside the distro.
+A sandbox backend installed as a plugin (bwrap, Seatbelt, WSL, DSH) enforces the policy on all of them: the file tools work through a helper process the same backend wraps (see [File tools](/tools#file-tools)). The card's first line says what this machine enforces and by what — on a default Ubuntu, `Enforced here: file writes, by Landlock (dsh-local)` — and what it does not, with **More info** under it naming each installed backend that is not in use and why ([Sandbox on Ubuntu](/quickstart-cli#sandbox-on-ubuntu)); it says so when there is no backend. A network level or masked paths no backend here enforces are greyed out or refused rather than enforced in part. Without a backend, every mode but off refuses every agent command and file operation, fails every hook and connects no `stdio` MCP Server. Two backends need a word: DSH does not make the scratchpad writable and cannot close the temporary directory — **More info** lists what its rung leaves open, and what `(partial)` means on an older Landlock; WSL runs hook scripts and the file tools' helper on the `nodejs` the distro's initialization now installs — a distro initialized before that has to be initialized again, and until then hooks and file operations fail under it rather than running unconfined — and a `stdio` MCP Server runs there only if its command exists inside the distro.
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.
diff --git a/packages/docs/content/settings.zh.md b/packages/docs/content/settings.zh.md
index da667079..ef8e70f4 100644
--- a/packages/docs/content/settings.zh.md
+++ b/packages/docs/content/settings.zh.md
@@ -272,12 +272,12 @@ Trace 会成为该 Agent 的一段新对话。如果该 Agent 下已有相同 id
- **启用**:卡片顶部的开关。关闭时(全新安装即如此),新 Session 拥有完全的文件与网络访问,只受审批模式约束,输入框的权限菜单只列出审批模式。关闭期间卡片只显示这个开关:预设表、高级选项、后端自身的设置与卡片的提示都在打开后原样恢复。
- **预设**:权限菜单提供的选项表,每个预设一行:名称、文件模式(关闭、仅工作区、只读)、网络(完全、仅本机、无)、审批方式,以及**操作**一组图标:图钉表示是否进菜单,拖动手柄,以及「…」菜单,内有**设为默认**和(仅新增预设上的)**删除**。默认行在名称后标有「(默认)」;每个名称旁的「?」说明这一行的用途——新增的预设,或改过取值的内置预设,则逐项说明各取值的作用。每个标题旁的「?」说明该列(或每个图标)的含义。拖动手柄(或在手柄上按上下方向键)调整顺序,菜单按此顺序列出。**添加预设**新增一行;只有新增的行可以删除,且不能是默认行。仅工作区时,可写的是 Session 的 Workspace、它的 scratchpad(计划文件、goal 的状态文件与附件都在这里)和临时目录;只读时只有临时目录可写。网络档位同样约束 `read_file` 读取的图片 URL,仅本机需要能实施它的后端。默认行是开关打开时新 Session 的起点——取该行的文件模式、网络与审批方式;未改动时为 Workspace Write。预设表出现之前保存的设置,在你设定默认行之前沿用自身的文件模式与网络:卡片把起点与之完全相同的那一行标为默认,保存时写入它。没有这样的行时(网络为无网络或仅本机,或文件模式为关闭而设了屏蔽路径),不标任何一行,卡片顶部的提示写明实际生效的值,保存其他设置也保留它;把一行设为默认,或先添加一条同值的预设再设为默认即可。
- 收在默认折叠的**高级选项**里:
- - **临时目录**:是否保持可写。默认开启,两种封禁模式下都生效,因为 Shell 与大多数工具没有它就无法启动。
+ - **临时目录**:是否保持可写。默认开启,两种封禁模式下都生效,因为 Shell 与大多数工具没有它就无法启动。关闭它需要能关闭临时目录的后端:只有 DSH 在用时开关保持开启并说明原因(在 Landlock 下,临时目录就是宿主共享的 `/tmp`)。
- **屏蔽路径**:对 Agent 的命令、钩子脚本、`stdio` MCP Server 和文件工具隐藏的路径,读取也不例外;每行一个绝对路径,最多 64 条。
两种封禁模式都不允许 Agent 写自己的 Agent State:`AGENTS.md`、`system_config.yaml`、Skill、钩子包、记忆、vault 与定时任务。要让 Agent 写记忆、自行编写 Skill 或钩子包、修改自己的配置,用该对话的**权限**按钮把它切到完全访问。以 `stdio` 方式启动的 MCP Server 在启动时(上下文开启或重连)受同样的封禁:必须写这些目录之外、或访问网络档位所切断的网络的 Server,在封禁的 Session 里会连接失败;经 `http` / `sse` 访问的 MCP Server 不是本机进程,不在封禁之列。
-真正实施封禁的是以插件形式安装的沙盒后端(bwrap、Seatbelt、WSL、DSH),它们约束全部四类:文件工具经一个由同一后端包裹的助手进程工作(见[文件工具](/tools#文件工具))。卡片列出已挂载的后端及各自实现的隔离维度,一个都没有时会明确说明。没有后端时,除关闭外的任何模式都会拒绝 Agent 的每条命令与每次文件操作,每个钩子都会失败,`stdio` MCP Server 也一个都连不上。有两个后端需要说明:DSH 不让 scratchpad 可写;WSL 用发行版初始化时装入的 `nodejs` 运行钩子脚本与文件工具的助手——在此之前初始化的发行版需要重新初始化,在那之前钩子与文件操作在其下会失败,而不会脱离封禁运行;`stdio` MCP Server 只有命令在发行版里存在时才能运行。
+真正实施封禁的是以插件形式安装的沙盒后端(bwrap、Seatbelt、WSL、DSH),它们约束全部四类:文件工具经一个由同一后端包裹的助手进程工作(见[文件工具](/tools#文件工具))。卡片第一行写明本机实施什么、由什么实施——默认的 Ubuntu 上是 `本机实施:文件写入,由 Landlock (dsh-local) 实施`——以及不实施什么,其下的**更多信息**列出每个已安装但未启用的后端及原因([Ubuntu 上的沙盒](/quickstart-cli#ubuntu-上的沙盒));一个后端都没有时会明确说明。本机没有后端能实施的网络级别或屏蔽路径会显示为灰色或被拒绝,而不会只实施一部分。没有后端时,除关闭外的任何模式都会拒绝 Agent 的每条命令与每次文件操作,每个钩子都会失败,`stdio` MCP Server 也一个都连不上。有两个后端需要说明:DSH 不让 scratchpad 可写,也无法关闭临时目录——**更多信息**列出它所用的那一级留下的缺口,以及较旧的 Landlock 上 `(partial)` 的含义;WSL 用发行版初始化时装入的 `nodejs` 运行钩子脚本与文件工具的助手——在此之前初始化的发行版需要重新初始化,在那之前钩子与文件操作在其下会失败,而不会脱离封禁运行;`stdio` MCP Server 只有命令在发行版里存在时才能运行。
后端自己的选项(例如 bwrap 的程序路径与 1–30 秒的探测超时,Seatbelt 的程序路径)画在同一张卡片里,卡片的一个**保存**一并存下。未通过自检的后端(例如程序路径写错)会在这次保存后重新加载,无需重启。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index d24c3a0a..c1aaf0c8 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1529,6 +1529,19 @@ export interface SessionSandbox {
* (400 `sandbox_unsupported`).
*/
localNetworkSupported?: boolean;
+ /** Response only, ignored in requests: whether a backend here can enforce `masksPaths`. */
+ maskPathsSupported?: boolean;
+ /**
+ * Response only, ignored in requests: true when this policy hides paths (the Sandbox card's
+ * masked paths, kept by every pick). Where `maskPathsSupported` is false, every level then
+ * refuses every command, and the composer says so.
+ */
+ masksPaths?: boolean;
+ /**
+ * Response only, ignored in requests: the names of the sandbox backends in use here, which the
+ * composer names when a level is beyond what they enforce. Absent with none in use.
+ */
+ backendsInUse?: string[];
/**
* Response only, ignored in requests: the sandbox backends that are enabled here but failed
* to load or failed their check (a WSL distro not set up, a wrong program path), each with
@@ -5611,6 +5624,9 @@ export interface PluginConfigNotice {
tone: "attention" | "muted" | "progress";
text: string;
textZh?: string;
+ /** More about the notice, disclosed under it on request; lines separated by `\n`. */
+ details?: string;
+ detailsZh?: string;
}
/** One settings group (GET /api/admin/plugin-config): its schema and its values, secrets masked. */
@@ -5630,26 +5646,31 @@ export interface PluginConfigEntry {
unavailable?: PluginConfigUnavailableDecl[];
/**
* For a group whose settings a backend plugin enforces (the sandbox): whether one that
- * applies to this machine's OS is installed, and which package this OS defaults to. The card
+ * applies to this machine's OS is installed, and which packages this OS defaults to. The card
* offers to install `recommended` when the group's switch is turned on and none is installed.
* Asked per read, like the notices; the client never guesses the OS.
*/
backend?: PluginConfigBackend;
}
-/** Whether a backend that applies to this machine is installed, and this OS's default one. */
+/** Whether a backend that applies to this machine is installed, and this OS's default ones. */
export interface PluginConfigBackend {
/** A backend for this OS is installed: loaded, or installed and failing its check. */
installed: boolean;
- /** The npm package this OS defaults to; absent on an OS with no default backend. */
- recommended?: string;
+ /**
+ * The npm packages this OS defaults to, installed together; absent on an OS with no default
+ * backend. Linux names two: bubblewrap, and sandbox-dsh, which confines files through
+ * Landlock where bubblewrap is refused.
+ */
+ recommended?: string[];
}
-/** One enum option a settings group cannot honour on this machine, and why. */
+/** One enum option (or boolean position) a settings group cannot honour on this machine, and why. */
export interface PluginConfigUnavailableDecl {
field: string;
/** A `table` field's column: the option is unavailable in every cell of that column. */
column?: string;
+ /** An enum option, or a boolean field's position: "true" or "false". */
value: string;
reason: string;
reasonZh?: string;
diff --git a/packages/server/src/plugin/builtin-index.json b/packages/server/src/plugin/builtin-index.json
index 5d9bd63a..84989299 100644
--- a/packages/server/src/plugin/builtin-index.json
+++ b/packages/server/src/plugin/builtin-index.json
@@ -1,7 +1,7 @@
[
{
"name": "@lmliheng/penguin-plugin-sandbox-bwrap",
- "version": "0.2.2",
+ "version": "0.2.3",
"description": "Bubblewrap sandbox backend for Adelie: filesystem confinement plus network isolation and path masking.",
"authors": ["Prism Shadow"],
"license": "Apache-2.0",
@@ -11,7 +11,7 @@
},
{
"name": "@lmliheng/penguin-plugin-sandbox-seatbelt",
- "version": "0.2.2",
+ "version": "0.2.3",
"description": "macOS Seatbelt sandbox backend for Adelie: filesystem confinement plus network isolation and path masking.",
"authors": ["Prism Shadow"],
"license": "Apache-2.0",
@@ -21,7 +21,7 @@
},
{
"name": "@lmliheng/penguin-plugin-sandbox-wsl",
- "version": "0.2.2",
+ "version": "0.2.3",
"description": "WSL sandbox backend for Adelie on Windows: commands run in a dedicated WSL2 distro under bubblewrap, with Windows interop switched off.",
"authors": ["Prism Shadow"],
"license": "Apache-2.0",
@@ -31,7 +31,7 @@
},
{
"name": "@lmliheng/penguin-plugin-sandbox-dsh",
- "version": "0.2.2",
+ "version": "0.2.3",
"description": "DeepSeek Harness sandbox adaptor for Adelie: the DSH local backend chain behind the harness's own sandbox interface.",
"authors": ["Prism Shadow"],
"license": "Apache-2.0",
diff --git a/packages/server/src/plugin/config-page.ts b/packages/server/src/plugin/config-page.ts
index ee51926e..4f1710ff 100644
--- a/packages/server/src/plugin/config-page.ts
+++ b/packages/server/src/plugin/config-page.ts
@@ -89,6 +89,7 @@ export interface PluginConfigUnavailable {
field: string;
/** A `table` field's column: the option is unavailable in every cell of that column. */
column?: string;
+ /** An enum option, or a boolean field's position: "true" or "false". */
value: string;
reason: string;
reasonZh?: string;
@@ -211,7 +212,9 @@ export class PluginConfigPage {
}
continue;
}
- if (update[u.field] === u.value) {
+ // A boolean field's position is named "true" / "false".
+ const sent = update[u.field];
+ if ((typeof sent === "boolean" ? String(sent) : sent) === u.value) {
throw new PluginConfigError(
u.field,
`"${u.field}" cannot be "${u.value}" here: ${u.reason}`,
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index c471c556..ae67f15d 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -2712,6 +2712,7 @@ export class SessionsModule {
sandboxDefaults: () => sandbox.currentSettings(),
sandboxDimensions: () => [...new Set(sandbox.backends().flatMap((b) => b.dimensions))],
sandboxUnavailable: () => sandbox.failures(),
+ sandboxBackends: () => sandbox.backends().map((b) => b.name),
// The Sandbox card's presets, read per view: a rename there reaches the next read.
sandboxPresets: () =>
sandboxPresetsOf(pluginConfig.schema(SANDBOX_GROUP), pluginConfig.get(SANDBOX_GROUP)),
diff --git a/packages/server/src/sandbox/dimensions.ts b/packages/server/src/sandbox/dimensions.ts
index 78a73928..f7ffc3c9 100644
--- a/packages/server/src/sandbox/dimensions.ts
+++ b/packages/server/src/sandbox/dimensions.ts
@@ -20,6 +20,7 @@ export const SANDBOX_DIMENSIONS: readonly SandboxDimension[] = [
"network",
"network-local",
"mask-paths",
+ "closed-temp",
];
/** The dimensions a provider implements (absent declaration = filesystem only). */
@@ -33,5 +34,9 @@ export function requestedDimensions(settings: SandboxSettings): SandboxDimension
if (settings.network === "none") dims.push("network");
if (settings.network === "local") dims.push("network-local");
if (settings.maskPaths !== undefined && settings.maskPaths.length > 0) dims.push("mask-paths");
+ // Temp closed matters only while confining: full access writes everywhere anyway.
+ if (settings.writableTemp === false && settings.mode !== "danger-full-access") {
+ dims.push("closed-temp");
+ }
return dims;
}
diff --git a/packages/server/src/sandbox/index.ts b/packages/server/src/sandbox/index.ts
index 9c167c22..c73a45c7 100644
--- a/packages/server/src/sandbox/index.ts
+++ b/packages/server/src/sandbox/index.ts
@@ -26,7 +26,10 @@
*
* The DSH adaptor is the portable floor covering file effects only (its own chain picks
* bwrap/Landlock, Seatbelt or the Windows ACL runner per host); the three native
- * backends add the other two dimensions, one per platform. Windows is served by bubblewrap
+ * backends add the other two dimensions, one per platform, and serve every policy they cover
+ * when the adaptor is mounted beside them. On Linux the adaptor is the floor where bubblewrap
+ * is refused (Ubuntu 23.10 and later restrict unprivileged user namespaces to AppArmor-profiled
+ * programs): it confines files through Landlock, which needs neither. Windows is served by bubblewrap
* inside a dedicated WSL2 distro, so commands there run in Linux (see sandbox-wsl's README).
* Where none implements a requested dimension, service.ts fails closed naming what each
* covers rather than quietly confining less than was asked.
diff --git a/packages/server/src/sandbox/service.ts b/packages/server/src/sandbox/service.ts
index 4a667296..6d20848d 100644
--- a/packages/server/src/sandbox/service.ts
+++ b/packages/server/src/sandbox/service.ts
@@ -3,18 +3,19 @@
* backend that implements the dimensions it requires, and produces the SpawnConfiner
* closure the runtime transports into core's command-session seam.
*
- * Routing is by CAPABILITY, not by registration order alone: a policy requiring only
- * `fs-write` goes to the first backend that covers it (the DSH adaptor, which works on
- * Linux/macOS/Windows alike), while a policy also requiring `network` or `mask-paths`
- * goes to the first backend implementing those (penguin-bwrap). Registration order
- * only breaks ties between backends that both cover the request. A request nothing
- * covers fails closed — never a silent unconfined run, and never a silently dropped
- * dimension.
+ * Routing is by CAPABILITY, not by registration order: of the mounted backends covering
+ * every dimension a policy requires, the one implementing the most dimensions wins, so a
+ * native backend (penguin-bwrap) serves every policy it covers even when the portable DSH
+ * adaptor is mounted beside it, and the adaptor serves only where it is the one left — a
+ * Linux host refusing bubblewrap's user namespaces, where it confines files through
+ * Landlock. Registration order only breaks ties. A request nothing covers fails closed —
+ * never a silent unconfined run, and never a silently dropped dimension.
*/
import fs from "node:fs";
import type { SpawnConfiner } from "@lmliheng/penguin-core";
import type {
SandboxDimension,
+ SandboxLimit,
SandboxPolicy,
SandboxProvider,
SandboxProviderSource,
@@ -187,11 +188,23 @@ export class SandboxService {
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 }) => ({
+ /**
+ * The mounted backends and what each implements, in routing preference: the one a policy
+ * goes to first (diagnostics / the config surface).
+ */
+ backends(): Array<{
+ name: string;
+ dimensions: readonly SandboxDimension[];
+ mechanism?: string;
+ limits?: readonly SandboxLimit[];
+ }> {
+ return byPreference(this.mounted).map(({ name, provider }) => ({
name,
dimensions: providerDimensions(provider),
+ ...(provider.mechanism !== undefined ? { mechanism: provider.mechanism } : {}),
+ ...(provider.limits !== undefined && provider.limits.length > 0
+ ? { limits: provider.limits }
+ : {}),
}));
}
@@ -243,17 +256,25 @@ export class SandboxService {
...(settings.writableTemp !== false ? { writableTemp: true } : {}),
};
// ConfinedArgv also carries enforcement / denialSignatures / runnerFailureRules;
- // the classification consumer (denial vs runner failure) lands with escalation.
+ // the classification consumer (denial vs runner failure) lands with escalation. The
+ // rules' informational lines are what the runner reports on every run (the Landlock
+ // launcher on an older kernel): the spawn drops them from the command's stderr.
const confined = provider.confine(argv, policy);
- return confined.env === undefined
- ? { argv: confined.argv }
- : { argv: confined.argv, env: confined.env };
+ const runnerLines = confined.runnerFailureRules.flatMap((r) => r.informationalLines ?? []);
+ return {
+ argv: confined.argv,
+ ...(confined.env !== undefined ? { env: confined.env } : {}),
+ ...(runnerLines.length > 0 ? { runnerLines } : {}),
+ };
};
}
- /** The first mounted backend implementing every required dimension, or a fail-closed throw. */
+ /**
+ * The preferred mounted backend implementing every required dimension (byPreference), or a
+ * fail-closed throw.
+ */
private pick(required: readonly SandboxDimension[], mode: string): SandboxProvider {
- const match = this.mounted.find(({ provider }) => {
+ const match = byPreference(this.mounted).find(({ provider }) => {
const implemented = providerDimensions(provider);
return required.every((dimension) => implemented.includes(dimension));
});
@@ -278,6 +299,17 @@ export class SandboxService {
}
}
+/**
+ * Backends in routing preference: more implemented dimensions first, registration order among
+ * equals (the sort is stable). Bubblewrap and the DSH adaptor both cover a files-only policy;
+ * the one that could also have cut the network or masked a path is the one that serves it, on
+ * whatever order the Projects' plugin lists name them in.
+ */
+function byPreference(mounted: readonly MountedProvider[]): MountedProvider[] {
+ const size = (m: MountedProvider) => providerDimensions(m.provider).length;
+ return [...mounted].sort((a, b) => size(b) - size(a));
+}
+
/**
* Creates the Session's scratchpad if it is missing (a no-op when it exists). A failure
* throws, fail-closed: dropping the root and confining without it would start the command
diff --git a/packages/server/src/sandbox/settings-status.ts b/packages/server/src/sandbox/settings-status.ts
index a3a766cf..4ec0eaf5 100644
--- a/packages/server/src/sandbox/settings-status.ts
+++ b/packages/server/src/sandbox/settings-status.ts
@@ -1,15 +1,16 @@
/**
- * The Sandbox card's live status (`PluginConfigPage.status`): 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 —
- * plus the enum options no backend here can honour and the backend package this OS defaults
- * to. A code contribution, so it must not require plugin configuration itself.
+ * The Sandbox card's live status (`PluginConfigPage.status`): what this machine enforces and by
+ * what, why each installed backend that is not in use is not, a warning when the saved policy
+ * needs isolation no usable backend implements, the enum options no backend here can honour,
+ * and which backend packages this OS defaults to. A code contribution, so it must not require
+ * plugin configuration itself.
*/
import { Bind, Component, Use } from "@lmliheng/penguin-core/kernel";
+import type { SandboxDimension } from "@lmliheng/penguin-core/plugin";
import type { PluginConfigNotice } from "../api/types.js";
-import type { SettingsGroupStatus } from "../plugin/config-page.js";
+import type { PluginConfigUnavailable, SettingsGroupStatus } from "../plugin/config-page.js";
import { Sandbox, SandboxModule } from "./service.js";
-import { requestedDimensions } from "./dimensions.js";
+import { SANDBOX_DIMENSIONS, requestedDimensions } from "./dimensions.js";
import {
DEFAULT_PRESET,
prePresetNotice,
@@ -18,21 +19,153 @@ import {
} from "./settings-policy.js";
/**
- * The backend package each OS defaults to: what the card offers to install when the switch is
- * turned on and no backend for this OS is installed. sandbox-dsh serves every OS but is never
- * the default, because it confines the file system only.
+ * The backend packages each OS defaults to: what the card offers to install when the switch is
+ * turned on and no backend for this OS is installed. Linux takes two. Bubblewrap enforces files,
+ * network and masked paths, but needs unprivileged user namespaces, which Ubuntu 23.10 and later
+ * grant only to AppArmor-profiled programs; sandbox-dsh confines files through Landlock, which
+ * needs neither a namespace nor root, so a default Ubuntu is still confined with no step of its
+ * own. Where both load, bubblewrap serves every policy (service.ts prefers the backend
+ * implementing more).
*/
-const DEFAULT_BACKEND: Partial<Record<NodeJS.Platform, string>> = {
- linux: "@lmliheng/penguin-plugin-sandbox-bwrap",
- darwin: "@lmliheng/penguin-plugin-sandbox-seatbelt",
- win32: "@lmliheng/penguin-plugin-sandbox-wsl",
+const DEFAULT_BACKENDS: Partial<Record<NodeJS.Platform, readonly string[]>> = {
+ linux: ["@lmliheng/penguin-plugin-sandbox-bwrap", "@lmliheng/penguin-plugin-sandbox-dsh"],
+ darwin: ["@lmliheng/penguin-plugin-sandbox-seatbelt"],
+ win32: ["@lmliheng/penguin-plugin-sandbox-wsl"],
};
+/** Each dimension as the card names it, in English and Chinese. */
+const DIMENSION_WORDS: Record<SandboxDimension, readonly [string, string]> = {
+ "fs-write": ["file writes", "文件写入"],
+ network: ["network isolation", "网络隔离"],
+ "network-local": ["localhost-only network", "仅本机网络"],
+ "mask-paths": ["masked paths", "屏蔽路径"],
+ "closed-temp": ["closing the temporary directory", "关闭临时目录"],
+};
+
+/** "a", "a and b", "a, b and c". */
+function andList(items: readonly string[]): string {
+ return items.length <= 1
+ ? items.join("")
+ : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
+}
+
+type MountedBackend = ReturnType<Sandbox["backends"]>[number];
+
+/**
+ * The card's headline while a backend serves: what this machine enforces, by the backends a
+ * policy can go to, and what it does not. A backend is named when it covers a dimension none
+ * preferred over it does — the backend serving every policy alone where it covers all the
+ * others do. Under it are disclosed the named backends' own limits on this host, then each
+ * installed backend that is not in use with its reason — the refusal names its own remedy
+ * (bubblewrap's names the optional root step on Ubuntu) — and that a save of the card checks
+ * them again.
+ */
+export function enforcementNotice(
+ backends: readonly MountedBackend[],
+ failures: ReadonlyArray<{ name: string; reason: string }>,
+): PluginConfigNotice {
+ const serving: MountedBackend[] = [];
+ const covered: SandboxDimension[] = [];
+ for (const backend of backends) {
+ const adds = backend.dimensions.filter((d) => !covered.includes(d));
+ if (adds.length === 0) continue;
+ serving.push(backend);
+ covered.push(...adds);
+ }
+ const nameOf = (b: MountedBackend) =>
+ b.mechanism !== undefined ? `${b.mechanism} (${b.name})` : b.name;
+ const enforced = SANDBOX_DIMENSIONS.filter((d) => covered.includes(d));
+ const missing = SANDBOX_DIMENSIONS.filter((d) => !covered.includes(d));
+ const en = (ds: readonly SandboxDimension[]) => andList(ds.map((d) => DIMENSION_WORDS[d][0]));
+ const zh = (ds: readonly SandboxDimension[]) => ds.map((d) => DIMENSION_WORDS[d][1]).join("、");
+ const notice: PluginConfigNotice = {
+ tone: "muted",
+ text:
+ `Enforced here: ${en(enforced)}, by ${andList(serving.map(nameOf))}.` +
+ (missing.length > 0 ? ` Not enforced here: ${en(missing)}.` : ""),
+ textZh:
+ `本机实施:${zh(enforced)},由 ${serving.map(nameOf).join("、")} 实施。` +
+ (missing.length > 0 ? `本机不实施:${zh(missing)}。` : ""),
+ };
+ const limits = serving.flatMap((b) => b.limits ?? []);
+ const lines = [
+ ...limits.map((l) => l.text),
+ ...failures.map(({ name, reason }) => `${name} is installed but not in use: ${reason}`),
+ ];
+ const linesZh = [
+ ...limits.map((l) => l.textZh ?? l.text),
+ ...failures.map(({ name, reason }) => `${name} 已安装但未启用:${reason}`),
+ ];
+ if (failures.length > 0) {
+ lines.push("Saving this card checks these backends again.");
+ linesZh.push("保存此卡片会重新检查这些后端。");
+ }
+ return lines.length === 0
+ ? notice
+ : { ...notice, details: lines.join("\n"), detailsZh: linesZh.join("\n") };
+}
+
+/**
+ * The temp choice where no mounted backend can close the temporary directory (the DSH adaptor
+ * alone, whose temp stays writable): its off position is greyed out and a save turning it off
+ * refused. With none mounted every confining choice is refused alike, which the card's warning
+ * says.
+ */
+export function unavailableClosedTemp(
+ backends: readonly MountedBackend[],
+): PluginConfigUnavailable[] {
+ if (backends.length === 0 || backends.some((b) => b.dimensions.includes("closed-temp"))) {
+ return [];
+ }
+ const names = backends.map((b) => b.name).join(", ");
+ return [
+ {
+ field: "writableTemp",
+ value: "false",
+ reason: `the sandbox backend in use here (${names}) cannot close the temporary directory: it stays writable`,
+ reasonZh: `本机在用的沙盒后端(${names})无法关闭临时目录:它始终可写`,
+ },
+ ];
+}
+
+/**
+ * The network levels no mounted backend can enforce, for the presets table's network column.
+ * Localhost only needs a backend declaring it, and is greyed out wherever none does. No network
+ * is greyed out where a backend serves but none isolates the network — the DSH adaptor alone;
+ * with none mounted every confining choice is refused alike, which the card's warning says.
+ */
+export function unavailableNetworks(
+ backends: readonly MountedBackend[],
+): PluginConfigUnavailable[] {
+ const covers = (d: SandboxDimension) => backends.some((b) => b.dimensions.includes(d));
+ const unavailable: PluginConfigUnavailable[] = [];
+ if (!covers("network-local")) {
+ unavailable.push({
+ field: "presets",
+ column: "network",
+ value: "local",
+ reason: "no sandbox backend on this host supports it",
+ reasonZh: "本机的沙盒后端不支持",
+ });
+ }
+ if (backends.length > 0 && !covers("network")) {
+ const names = backends.map((b) => b.name).join(", ");
+ unavailable.push({
+ field: "presets",
+ column: "network",
+ value: "none",
+ reason: `the sandbox backend in use here (${names}) confines files only and does not isolate the network`,
+ reasonZh: `本机在用的沙盒后端(${names})只封禁文件,不隔离网络`,
+ });
+ }
+ return unavailable;
+}
+
/**
- * 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
+ * The sandbox card's live notices: a warning when the saved policy needs isolation no usable
+ * backend implements (every command would be refused), what the machine enforces, 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({
@@ -68,36 +201,31 @@ export class SandboxSettingsStatus {
? update
: { ...update, defaultPreset: current.defaultPreset },
// A backend for this OS is installed when it is in use or failed (to load, or its check):
- // one that declined is for another OS. Installing the default would not fix a failure.
+ // one that declined is for another OS. Installing the defaults would not fix a failure.
backend: () => {
- const recommended = DEFAULT_BACKEND[process.platform];
+ const recommended = DEFAULT_BACKENDS[process.platform];
return {
installed: sandbox.backends().length > 0 || sandbox.failures().length > 0,
- ...(recommended !== undefined ? { recommended } : {}),
+ ...(recommended !== undefined ? { recommended: [...recommended] } : {}),
};
},
// 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: () => {
- if (sandbox.backends().some((b) => b.dimensions.includes("network-local"))) return [];
- const why = {
- value: "local",
- reason: "no sandbox backend on this host supports it",
- reasonZh: "本机的沙盒后端不支持",
- };
- return [{ field: "presets", column: "network", ...why }];
- },
+ // Greyed out with the reason; a save choosing one is refused.
+ unavailable: () => [
+ ...unavailableNetworks(sandbox.backends()),
+ ...unavailableClosedTemp(sandbox.backends()),
+ ],
notices: (stored, configuration): PluginConfigNotice[] => {
const notices: PluginConfigNotice[] = [];
const prePreset = prePresetNotice(stored, configuration);
if (prePreset !== undefined) notices.push(prePreset);
const backends = sandbox.backends();
const settings = sandbox.currentSettings();
- if (settings.mode !== "danger-full-access") {
- const required = requestedDimensions(settings);
+ const required = requestedDimensions(settings);
+ // Full access needs a backend too once it cuts the network or masks a path.
+ if (settings.mode !== "danger-full-access" || required.length > 1) {
const served = backends.some((b) => required.every((d) => b.dimensions.includes(d)));
if (!served) {
const needs = required.join(" + ");
@@ -108,29 +236,27 @@ export class SandboxSettingsStatus {
});
}
}
- 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 and hook script.${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}` });
+ if (backends.length > 0) {
+ // Confinement works: a backend that is not in use is disclosed under the headline.
+ notices.push(enforcementNotice(backends, sandbox.failures()));
+ return notices;
}
- // 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";
+ 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 and hook script.${elsewhere}`,
+ textZh: `当前部署没有可用的沙盒后端:在插件页安装适用于本平台的后端之前,除「关闭」外的任何模式都会拒绝 Agent 的每条命令与钩子脚本。${elsewhereZh}`,
+ });
+ // With nothing serving, why each installed backend is not in use is the headline.
for (const { name, reason } of sandbox.failures()) {
notices.push({
- tone,
+ tone: "attention",
text: `${name} is not in use: ${reason}`,
textZh: `${name} 未启用:${reason}`,
});
diff --git a/packages/server/src/sandbox/settings-store.ts b/packages/server/src/sandbox/settings-store.ts
index b70592f2..0bb1c633 100644
--- a/packages/server/src/sandbox/settings-store.ts
+++ b/packages/server/src/sandbox/settings-store.ts
@@ -9,8 +9,8 @@
* 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.
- * The card's live status (whether the saved policy can be enforced, which backends are in use
- * and why each other one is not) is `SandboxSettingsStatus`, in settings-status.ts.
+ * The card's live status (what this machine enforces, which backends are not in use and why)
+ * is `SandboxSettingsStatus`, in settings-status.ts.
*/
import { Bind, Component, Use } from "@lmliheng/penguin-core/kernel";
import type { SandboxMode, SandboxSettings as Policy } from "@lmliheng/penguin-core/plugin";
@@ -144,9 +144,9 @@ export const SANDBOX_GROUP = "sandbox";
title: "Network",
titleZh: "网络",
description:
- "What a confined command, hook script or read_file URL may reach. Localhost allows only this machine, and needs a backend that can enforce it.",
+ "What a confined command, hook script or read_file URL may reach. Localhost allows only this machine. Each limit needs a backend that can enforce it — sandbox-dsh confines files only — and is greyed out where the backends in use cannot.",
descriptionZh:
- "被封禁的命令、钩子脚本与 read_file 的 URL 能访问的网络。仅本机只允许访问本机,需要能实施它的后端。",
+ "被封禁的命令、钩子脚本与 read_file 的 URL 能访问的网络。仅本机只允许访问本机。每种限制都需要能实施它的后端(sandbox-dsh 只封禁文件),在用的后端不能实施时显示为灰色。",
options: [
{
value: "open",
@@ -339,9 +339,9 @@ export const SANDBOX_GROUP = "sandbox";
title: "Temporary directory writable",
titleZh: "临时目录可写",
description:
- "Confined commands, hook scripts and file tools may write the system temp directory, in either mode. Shells and most tools need one to start; off keeps it read-only too.",
+ "Confined commands, hook scripts and file tools may write the system temp directory, in either mode. Shells and most tools need one to start; off keeps it read-only too. Off needs a backend that can close it — sandbox-dsh cannot — and is greyed out where the backends in use cannot.",
descriptionZh:
- "被封禁的命令、钩子脚本与文件工具在两种模式下都可以写系统临时目录。Shell 与大多数工具需要它才能启动;关闭后临时目录同样只读。",
+ "被封禁的命令、钩子脚本与文件工具在两种模式下都可以写系统临时目录。Shell 与大多数工具需要它才能启动;关闭后临时目录同样只读。关闭需要能关闭它的后端(sandbox-dsh 不能),在用的后端不能关闭时显示为灰色。",
default: true,
},
maskPaths: {
@@ -350,8 +350,9 @@ export const SANDBOX_GROUP = "sandbox";
title: "Masked paths",
titleZh: "屏蔽路径",
description:
- "Paths hidden from confined commands, hook scripts and file tools, reads included.",
- descriptionZh: "对被封禁的命令、钩子脚本与文件工具隐藏的路径,读取也不例外。",
+ "Paths hidden from confined commands, hook scripts and file tools, reads included. Needs a backend that masks paths — sandbox-dsh does not: without one, every command is refused while any is listed.",
+ descriptionZh:
+ "对被封禁的命令、钩子脚本与文件工具隐藏的路径,读取也不例外。需要能屏蔽路径的后端(sandbox-dsh 不能):没有这样的后端时,只要列了路径,每条命令都会被拒绝。",
hint: "One absolute path per line, at most 64.",
hintZh: "每行一个绝对路径,最多 64 条。",
maxItems: 64,
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index 79bd6f97..0b160784 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -70,7 +70,8 @@ export function sessionSandboxOf(
switchOn?: boolean,
ceiling?: SandboxSettings,
): SessionSandbox {
- const advanced = (policy.maskPaths ?? []).length > 0 || policy.writableTemp === false;
+ const masksPaths = (policy.maskPaths ?? []).length > 0;
+ const advanced = masksPaths || policy.writableTemp === false;
const above = (p: SessionSandboxPreset) =>
ceiling !== undefined &&
aboveSandboxCeiling(p, { mode: ceiling.mode, network: networkOf(ceiling) }) !== null;
@@ -80,6 +81,8 @@ export function sessionSandboxOf(
confinementSupported: dimensions.includes("fs-write"),
noNetworkSupported: dimensions.includes("network"),
localNetworkSupported: dimensions.includes("network-local"),
+ maskPathsSupported: dimensions.includes("mask-paths"),
+ ...(masksPaths ? { masksPaths: true } : {}),
unavailableBackends: unavailable.map(({ name, reason }) => ({ name, reason })),
...(presets !== undefined
? { presets: presets.map((p) => ({ ...p, ...(above(p) ? { aboveCeiling: true } : {}) })) }
@@ -215,6 +218,8 @@ export interface SessionServiceDeps {
sandboxDimensions?: () => readonly SandboxDimension[];
/** The enabled sandbox backends that failed to load or failed their check, with why. */
sandboxUnavailable?: () => readonly UnavailableSandboxBackend[];
+ /** The names of the sandbox backends in use, in routing preference (none when absent). */
+ sandboxBackends?: () => readonly string[];
/** The Sandbox card's presets table, in table order (absent: the view carries none). */
sandboxPresets?: () => readonly SessionSandboxPreset[];
/** The Sandbox card's switch: whether new Sessions start confined (absent: not reported). */
@@ -242,14 +247,18 @@ export class SessionService {
/** A policy as the composer sees it, with which of its levels this server can enforce. */
sandboxView(policy: SandboxSettings): SessionSandbox {
- return sessionSandboxOf(
- policy,
- this.sandboxDimensions(),
- this.deps.sandboxUnavailable?.() ?? [],
- this.deps.sandboxPresets?.(),
- this.deps.sandboxSwitchOn?.(),
- this.defaultSandbox(),
- );
+ const backends = this.deps.sandboxBackends?.() ?? [];
+ return {
+ ...sessionSandboxOf(
+ policy,
+ this.sandboxDimensions(),
+ this.deps.sandboxUnavailable?.() ?? [],
+ this.deps.sandboxPresets?.(),
+ this.deps.sandboxSwitchOn?.(),
+ this.defaultSandbox(),
+ ),
+ ...(backends.length > 0 ? { backendsInUse: [...backends] } : {}),
+ };
}
/**
diff --git a/packages/server/test/project-chat-defaults.test.ts b/packages/server/test/project-chat-defaults.test.ts
index 1c5e7c3b..f2b6790e 100644
--- a/packages/server/test/project-chat-defaults.test.ts
+++ b/packages/server/test/project-chat-defaults.test.ts
@@ -37,6 +37,7 @@ const SERVED = {
confinementSupported: false,
noNetworkSupported: false,
localNetworkSupported: false,
+ maskPathsSupported: false,
unavailableBackends: [],
// The Sandbox card's presets table rides beside it (session-sandbox.test.ts pins its rows).
presets: expect.any(Array),
diff --git a/packages/server/test/sandbox-floor.test.ts b/packages/server/test/sandbox-floor.test.ts
new file mode 100644
index 00000000..2ecff366
--- /dev/null
+++ b/packages/server/test/sandbox-floor.test.ts
@@ -0,0 +1,285 @@
+/**
+ * The Linux floor: where bubblewrap is refused (a default Ubuntu 23.10+), the DSH adaptor confines
+ * files through Landlock, the service routes only what it implements, and the card says so.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { parseManifest } from "@lmliheng/penguin-core/kernel";
+import type { ModuleDef } from "@lmliheng/penguin-core/kernel";
+import type {
+ SandboxDimension,
+ SandboxProvider,
+ SandboxProviderSource,
+} from "@lmliheng/penguin-core/plugin";
+import type { PluginConfigEntry, PluginConfigResponse } from "../src/api/types.js";
+import { PluginHost } from "../src/plugin/host.js";
+import { SandboxService } from "../src/sandbox/index.js";
+import { enforcementNotice } from "../src/sandbox/settings-status.js";
+import { apiClient, createTestApp, loginAdmin } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const ARGV = ["bash", "-lc", "echo hi"];
+const OPTS = { cwd: "/work/project", workspaceDir: "/work/project" };
+const BWRAP_DIMENSIONS: SandboxDimension[] = ["fs-write", "network", "mask-paths", "closed-temp"];
+const REFUSED =
+ "'bwrap' is missing or refuses the base profile (setting up uid map: Permission denied)";
+
+/** A backend that prefixes its label; `dimensions` absent = filesystem only. */
+function fake(label: string, dimensions?: SandboxDimension[], mechanism?: string) {
+ const calls: string[][] = [];
+ const provider: SandboxProvider = {
+ ...(dimensions !== undefined ? { dimensions } : {}),
+ ...(mechanism !== undefined ? { mechanism } : {}),
+ confine(argv) {
+ calls.push([...argv]);
+ return {
+ argv: [label, ...argv],
+ enforcement: "full",
+ denialSignatures: [],
+ runnerFailureRules: [],
+ };
+ },
+ };
+ return { provider, calls };
+}
+
+async function service(...entries: Array<[string, SandboxProviderSource]>) {
+ const svc = new SandboxService(entries);
+ await svc.whenReady();
+ return svc;
+}
+
+describe("routing between bubblewrap and the DSH adaptor", () => {
+ it("between backends implementing as much, registration order decides", async () => {
+ const first = fake("first", ["fs-write", "network"]);
+ const second = fake("second", ["fs-write", "mask-paths"]);
+ const svc = await service(["first", first.provider], ["second", second.provider]);
+ svc.configure({ mode: "read-only" });
+ expect(svc.confiner()(ARGV, OPTS).argv).toEqual(["first", ...ARGV]);
+ // A requirement only the second covers still reaches it.
+ svc.configure({ mode: "read-only", maskPaths: ["/k"] });
+ expect(svc.confiner()(ARGV, OPTS).argv).toEqual(["second", ...ARGV]);
+ });
+
+ it("where bubblewrap is refused, the adaptor serves files and a network cut fails closed", async () => {
+ const dsh = fake("dsh", undefined, "Landlock");
+ const svc = await service(
+ ["penguin-bwrap", () => Promise.reject(new Error(REFUSED))],
+ ["dsh-local", dsh.provider],
+ );
+ svc.configure({ mode: "workspace-write" });
+ expect(svc.confiner()(ARGV, OPTS).argv).toEqual(["dsh", ...ARGV]);
+ expect(svc.backends()).toEqual([
+ { name: "dsh-local", dimensions: ["fs-write"], mechanism: "Landlock" },
+ ]);
+ svc.configure({ mode: "workspace-write", network: "none" });
+ expect(() => svc.confiner()(ARGV, OPTS)).toThrow(
+ `requires fs-write + network, but no mounted sandbox backend implements all of it (dsh-local: fs-write); backends not in use: penguin-bwrap (${REFUSED})`,
+ );
+ expect(dsh.calls).toHaveLength(1);
+ });
+});
+
+/** A plugin contributing bubblewrap (refused or serving) and the adaptor, as Linux installs them. */
+function linuxBackends(bwrap: "refused" | "serving"): PluginHost {
+ const module: ModuleDef = {
+ manifest: parseManifest({
+ name: "LinuxBackends",
+ requires: {},
+ provides: {},
+ contributes: {
+ "SandboxModule.providers": [
+ { id: "bwrap.provider", name: "penguin-bwrap", dimensions: BWRAP_DIMENSIONS },
+ { id: "dsh.provider", name: "dsh-local", dimensions: ["fs-write"] },
+ ],
+ },
+ children: [],
+ }),
+ create: () => ({
+ api: {},
+ bind: {
+ "bwrap.provider":
+ bwrap === "serving"
+ ? fake("bwrap", BWRAP_DIMENSIONS, "bubblewrap").provider
+ : () => Promise.reject(new Error(REFUSED)),
+ "dsh.provider": fake("dsh", ["fs-write"], "Landlock").provider,
+ },
+ }),
+ };
+ const host = new PluginHost();
+ host.use({ specifier: "linux-backends", modules: [module], replaces: [] });
+ return host;
+}
+
+describe("the sandbox card on the Linux floor", () => {
+ const apps: TestApp[] = [];
+ afterEach(async () => {
+ for (const t of apps.splice(0)) await t.cleanup();
+ });
+
+ async function boot(bwrap: "refused" | "serving") {
+ const t = await createTestApp({ plugins: linuxBackends(bwrap) });
+ apps.push(t);
+ const admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ await t.deps.tree.api<SandboxService>("SandboxModule", "sandbox").whenReady();
+ const card = async (): Promise<PluginConfigEntry> =>
+ (
+ (await (await admin.get("/api/admin/plugin-config")).json()) as PluginConfigResponse
+ ).plugins.find((e) => e.name === "sandbox")!;
+ const save = (values: Record<string, unknown>) =>
+ admin.put("/api/admin/plugin-config", { name: "sandbox", values });
+ const refusal = async (values: Record<string, unknown>) => {
+ const res = await save(values);
+ expect(res.status).toBe(400);
+ return ((await res.json()) as { error: { message: string } }).error.message;
+ };
+ return { admin, card, save, refusal };
+ }
+
+ it("says files only, by Landlock, discloses why bubblewrap is not in use, and tells the composer", async () => {
+ const { admin, card } = await boot("refused");
+ const entry = await card();
+ expect(entry.notices).toEqual([
+ expect.objectContaining({
+ tone: "muted",
+ text: "Enforced here: file writes, by Landlock (dsh-local). Not enforced here: network isolation, localhost-only network, masked paths and closing the temporary directory.",
+ details: `penguin-bwrap is installed but not in use: ${REFUSED}\nSaving this card checks these backends again.`,
+ detailsZh: `penguin-bwrap 已安装但未启用:${REFUSED}\n保存此卡片会重新检查这些后端。`,
+ }),
+ ]);
+ // A backend for this OS is installed: nothing is offered.
+ expect(entry.backend?.installed).toBe(true);
+ const defaults = (await (
+ await admin.get("/api/projects/default_project/chat-defaults")
+ ).json()) as { sandbox: { backendsInUse?: string[] } };
+ expect(defaults.sandbox.backendsInUse).toEqual(["dsh-local"]);
+ });
+
+ it("greys out what the adaptor cannot enforce and refuses saving it", async () => {
+ const { card, save, refusal } = await boot("refused");
+ expect((await card()).unavailable).toEqual([
+ expect.objectContaining({ column: "network", value: "local" }),
+ expect.objectContaining({
+ column: "network",
+ value: "none",
+ reason:
+ "the sandbox backend in use here (dsh-local) confines files only and does not isolate the network",
+ }),
+ expect.objectContaining({
+ field: "writableTemp",
+ value: "false",
+ reason:
+ "the sandbox backend in use here (dsh-local) cannot close the temporary directory: it stays writable",
+ }),
+ ]);
+ expect(await refusal({ presets: { "workspace-write": { network: "none" } } })).toContain(
+ '"presets.workspace-write.network" cannot be "none" here',
+ );
+ expect(await refusal({ writableTemp: false })).toContain(
+ '"writableTemp" cannot be "false" here',
+ );
+ // The default table keeps the network open, and turning temp on is never refused.
+ expect((await save({ enabled: true, writableTemp: true })).status).toBe(200);
+ });
+
+ it("warns that saved masked paths refuse every command", async () => {
+ const { card, save } = await boot("refused");
+ expect((await save({ enabled: true, maskPaths: ["/k"] })).status).toBe(200);
+ expect((await card()).notices?.[0]).toMatchObject({
+ tone: "attention",
+ text: expect.stringContaining("every agent command and hook script is refused"),
+ });
+ });
+
+ it("names bubblewrap where it serves, greys out only Localhost only, and lets temp be closed", async () => {
+ const { card, save } = await boot("serving");
+ const entry = await card();
+ expect(entry.notices?.map((n) => [n.text, n.details])).toEqual([
+ [
+ "Enforced here: file writes, network isolation, masked paths and closing the temporary directory, by bubblewrap (penguin-bwrap). Not enforced here: localhost-only network.",
+ undefined,
+ ],
+ ]);
+ expect(entry.unavailable?.map((u) => u.value)).toEqual(["local"]);
+ expect((await save({ writableTemp: false })).status).toBe(200);
+ });
+});
+
+describe("closing the temporary directory", () => {
+ it("is routed only to a backend declaring closed-temp, and refused where none does", async () => {
+ const dsh = fake("dsh", undefined, "Landlock");
+ const svc = await service(["dsh-local", dsh.provider]);
+ // The adaptor grants temp whatever the policy says: never handed one closing it.
+ for (const mode of ["workspace-write", "read-only"] as const) {
+ svc.configure({ mode, writableTemp: false });
+ expect(() => svc.confiner()(ARGV, OPTS)).toThrow(
+ "sandbox policy requires fs-write + closed-temp, but no mounted sandbox backend implements all of it (dsh-local: fs-write)",
+ );
+ }
+ // Full access writes everywhere anyway: nothing to close, no backend asked.
+ svc.configure({ mode: "danger-full-access", writableTemp: false });
+ expect(svc.confiner()(ARGV, OPTS).argv).toEqual(ARGV);
+ expect(dsh.calls).toHaveLength(0);
+
+ const bwrap = fake("bwrap", BWRAP_DIMENSIONS, "bubblewrap");
+ const both = await service(["dsh-local", dsh.provider], ["penguin-bwrap", bwrap.provider]);
+ both.configure({ mode: "workspace-write", writableTemp: false });
+ expect(both.confiner()(ARGV, OPTS).argv).toEqual(["bwrap", ...ARGV]);
+ });
+});
+
+describe("the runner's informational lines", () => {
+ it("reach the spawn as runnerLines, so it drops them from the command's stderr", async () => {
+ const LINE = "landlock-run: partial enforcement (older Landlock ABI)";
+ const landlock: SandboxProvider = {
+ confine: (argv) => ({
+ argv: ["landlock-run", "--", ...argv],
+ enforcement: "partial",
+ denialSignatures: [],
+ runnerFailureRules: [{ fatalSignatures: ["landlock-run: "], informationalLines: [LINE] }],
+ }),
+ };
+ const svc = await service(["dsh-local", landlock]);
+ svc.configure({ mode: "workspace-write" });
+ expect(svc.confiner()(ARGV, OPTS)).toEqual({
+ argv: ["landlock-run", "--", ...ARGV],
+ runnerLines: [LINE],
+ });
+ // A runner that reports nothing adds no field.
+ const plain = await service(["dsh-local", fake("dsh").provider]);
+ plain.configure({ mode: "workspace-write" });
+ expect(plain.confiner()(ARGV, OPTS)).toEqual({ argv: ["dsh", ...ARGV] });
+ });
+});
+
+describe("the enforcement headline", () => {
+ const dsh = { name: "dsh-local", dimensions: ["fs-write"] as SandboxDimension[] };
+
+ it("names every backend that adds a dimension, and only those", () => {
+ const notice = enforcementNotice(
+ [
+ { name: "penguin-bwrap", dimensions: BWRAP_DIMENSIONS, mechanism: "bubblewrap" },
+ { ...dsh, mechanism: "Landlock" },
+ { name: "local-net", dimensions: ["fs-write", "network-local"] },
+ ],
+ [],
+ );
+ expect(notice.text).toBe(
+ "Enforced here: file writes, network isolation, localhost-only network, masked paths and closing the temporary directory, by bubblewrap (penguin-bwrap) and local-net.",
+ );
+ expect(notice.textZh).toContain("由 bubblewrap (penguin-bwrap)、local-net 实施");
+ });
+
+ it("discloses the serving backend's limits, before why others are not in use", () => {
+ const limited = {
+ ...dsh,
+ limits: [{ text: "scratchpad not writable", textZh: "scratchpad 不可写" }],
+ };
+ const notice = enforcementNotice([limited], [{ name: "penguin-bwrap", reason: "refused" }]);
+ expect(notice.details).toBe(
+ "scratchpad not writable\npenguin-bwrap is installed but not in use: refused\nSaving this card checks these backends again.",
+ );
+ expect(notice.detailsZh?.split("\n")[0]).toBe("scratchpad 不可写");
+ // With no backend failing, the limits stand alone, and nothing is checked again.
+ expect(enforcementNotice([limited], []).details).toBe("scratchpad not writable");
+ });
+});
diff --git a/packages/server/test/sandbox-settings.test.ts b/packages/server/test/sandbox-settings.test.ts
index 22526186..2adae0a3 100644
--- a/packages/server/test/sandbox-settings.test.ts
+++ b/packages/server/test/sandbox-settings.test.ts
@@ -38,7 +38,7 @@ function backend(seen: Seen[]): ModuleDef {
{
id: "test.provider",
name: "test-backend",
- dimensions: ["fs-write", "network", "mask-paths"],
+ dimensions: ["fs-write", "network", "mask-paths", "closed-temp"],
},
// Installed for another platform: it declines here, and says nothing on the card.
{ id: "elsewhere.provider", name: "other-platform", dimensions: ["fs-write"] },
@@ -61,7 +61,7 @@ function backend(seen: Seen[]): ModuleDef {
bind: {
"elsewhere.provider": Promise.resolve(null),
"test.provider": {
- dimensions: ["fs-write", "network", "mask-paths"],
+ dimensions: ["fs-write", "network", "mask-paths", "closed-temp"],
confine(argv: readonly string[], policy: SandboxPolicy) {
seen.push({ policy, runner: config.get("sandbox-test").runner });
return {
@@ -112,7 +112,8 @@ describe("sandbox settings group", () => {
expect(sandbox.notices).toEqual([
expect.objectContaining({
tone: "muted",
- text: "Backends: test-backend (fs-write, network, mask-paths)",
+ // What this machine enforces, by the backend that serves (no mechanism declared: its name).
+ text: "Enforced here: file writes, network isolation, masked paths and closing the temporary directory, by test-backend. Not enforced here: localhost-only network.",
}),
]);
const child = entries.find((e) => e.name === "sandbox-test")!;
@@ -356,7 +357,11 @@ describe("sandbox settings group", () => {
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(card.notices?.map((n) => n.text)).toEqual([
+ "Enforced here: file writes, by probed. Not enforced here: network isolation, localhost-only network, masked paths and closing the temporary directory.",
+ ]);
+ // Nothing failed any more: nothing to disclose under it.
+ expect(card.notices?.[0]?.details).toBeUndefined();
expect(sandbox.failures()).toEqual([]);
sandbox.configure({ mode: "read-only" });
expect(sandbox.confiner()(["true"], { workspaceDir: "/w" } as never).argv).toEqual([
diff --git a/packages/server/test/sandbox-switch.test.ts b/packages/server/test/sandbox-switch.test.ts
index 2f4ac085..d0e6f885 100644
--- a/packages/server/test/sandbox-switch.test.ts
+++ b/packages/server/test/sandbox-switch.test.ts
@@ -16,13 +16,13 @@ import type { SandboxService } from "../src/sandbox/service.js";
import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-/** What the server defaults to on the OS the suite runs on. */
+/** What the server defaults to on this OS; Linux offers sandbox-dsh (Landlock) beside bubblewrap. */
const recommended = (
{
- linux: "@lmliheng/penguin-plugin-sandbox-bwrap",
- darwin: "@lmliheng/penguin-plugin-sandbox-seatbelt",
- win32: "@lmliheng/penguin-plugin-sandbox-wsl",
- } as Partial<Record<NodeJS.Platform, string>>
+ linux: ["@lmliheng/penguin-plugin-sandbox-bwrap", "@lmliheng/penguin-plugin-sandbox-dsh"],
+ darwin: ["@lmliheng/penguin-plugin-sandbox-seatbelt"],
+ win32: ["@lmliheng/penguin-plugin-sandbox-wsl"],
+ } as Partial<Record<NodeJS.Platform, string[]>>
)[process.platform];
/** A backend plugin whose providers resolve as given: a provider, null (declined), or a failure. */
@@ -292,7 +292,7 @@ describe("the sandbox switch", () => {
expect(((await picked.json()) as Created).session).toMatchObject(pick);
});
- it("reports no backend for this OS, the OS's default package, and names its switch", async () => {
+ it("reports no backend for this OS, the OS's default packages, and names its switch", async () => {
const entry = await (await boot()).card();
expect(entry.backend).toEqual({ installed: false, ...(recommended ? { recommended } : {}) });
expect(
diff --git a/packages/server/test/sandbox.test.ts b/packages/server/test/sandbox.test.ts
index 9d93f54d..5e7cef71 100644
--- a/packages/server/test/sandbox.test.ts
+++ b/packages/server/test/sandbox.test.ts
@@ -262,15 +262,20 @@ describe("sandbox service — capability routing across backends", () => {
return { dsh, bwrap };
};
- it("a filesystem-only policy takes the first backend covering it (the portable one)", async () => {
- const { dsh, bwrap } = entries();
- const svc = await service([
- ["dsh-local", dsh.provider],
- ["penguin-bwrap", bwrap.provider],
- ]);
- svc.configure({ mode: "workspace-write" });
- expect(svc.confiner()([...ARGV], OPTS).argv).toEqual(["dsh", "--", ...ARGV]);
- expect(bwrap.calls).toHaveLength(0);
+ it("a filesystem-only policy goes to the backend implementing more, whatever the registration order", async () => {
+ for (const order of ["dsh first", "bwrap first"]) {
+ const { dsh, bwrap } = entries();
+ const both: Array<[string, SandboxProviderSource]> = [
+ ["dsh-local", dsh.provider],
+ ["penguin-bwrap", bwrap.provider],
+ ];
+ const svc = await service(order === "dsh first" ? both : both.reverse());
+ svc.configure({ mode: "workspace-write" });
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual(["bwrap", "--", ...ARGV]);
+ expect(dsh.calls).toHaveLength(0);
+ // The card reads them in the same preference.
+ expect(svc.backends().map((b) => b.name)).toEqual(["penguin-bwrap", "dsh-local"]);
+ }
});
it("a policy requiring network or mask-paths routes past it to the backend implementing them", async () => {
@@ -338,7 +343,8 @@ describe("sandbox service — capability routing across backends", () => {
["penguin-bwrap", bwrap.provider],
]);
svc.configure({ mode: "read-only", maskPaths: [] });
- expect(svc.confiner()([...ARGV], OPTS).argv).toEqual(["dsh", "--", ...ARGV]);
+ // Either backend serves it: the one implementing more does.
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual(["bwrap", "--", ...ARGV]);
});
it("a backend throw (unusable runner, etc.) propagates — fail-closed end to end", async () => {
diff --git a/packages/server/test/session-sandbox-masks.test.ts b/packages/server/test/session-sandbox-masks.test.ts
new file mode 100644
index 00000000..14aac6c6
--- /dev/null
+++ b/packages/server/test/session-sandbox-masks.test.ts
@@ -0,0 +1,15 @@
+// `masksPaths` marks a Session whose policy hides paths; `maskPathsSupported` says whether a
+// backend here can enforce it.
+import { describe, expect, it } from "vitest";
+import { sessionSandboxOf } from "../src/services/session-service.js";
+
+describe("a Session's view when its policy masks paths", () => {
+ it("is marked only by masked paths, never by a closed temp", () => {
+ expect(sessionSandboxOf({ mode: "workspace-write", writableTemp: false }).masksPaths).toBe(
+ undefined,
+ );
+ expect(
+ sessionSandboxOf({ mode: "workspace-write", maskPaths: ["/k"] }, ["fs-write"]),
+ ).toMatchObject({ masksPaths: true, maskPathsSupported: false, confinementSupported: true });
+ });
+});
diff --git a/packages/server/test/session-sandbox.test.ts b/packages/server/test/session-sandbox.test.ts
index 4c32eb8b..7422ba92 100644
--- a/packages/server/test/session-sandbox.test.ts
+++ b/packages/server/test/session-sandbox.test.ts
@@ -22,6 +22,7 @@ const NO_BACKEND = {
confinementSupported: false,
noNetworkSupported: false,
localNetworkSupported: false,
+ maskPathsSupported: false,
unavailableBackends: [],
};
@@ -85,6 +86,8 @@ describe("picking a Session's sandbox from the composer", () => {
network: "none",
...NO_BACKEND,
advanced: true,
+ // The masked paths need a backend that masks; none is mounted here.
+ masksPaths: true,
});
});
@@ -111,6 +114,7 @@ describe("picking a Session's sandbox from the composer", () => {
confinementSupported: true,
noNetworkSupported: false,
localNetworkSupported: false,
+ maskPathsSupported: false,
unavailableBackends: [],
});
});
diff --git a/packages/web/src/features/chat/permission-select.tsx b/packages/web/src/features/chat/permission-select.tsx
index 69d3ff4b..1d7bd778 100644
--- a/packages/web/src/features/chat/permission-select.tsx
+++ b/packages/web/src/features/chat/permission-select.tsx
@@ -132,6 +132,7 @@ export function PermissionSelect({
// mounted, every preset that confines: not installed, or enabled but failing its check, with
// the first such backend's reason.
const failed = firstUnavailableBackend(sandbox);
+ const inUse = sandbox.backendsInUse?.join(", ");
const blockText = (block: PresetBlock): { reason: string; note?: string } =>
block === "above-ceiling"
? { reason: P.aboveCeiling, note: P.adminOnly }
@@ -139,7 +140,14 @@ export function PermissionSelect({
? { reason: P.noBackend, note: P.notInstalled }
: block === "unavailable" && failed !== null
? { reason: P.backendUnavailable(failed.name, failed.reason), note: P.notAvailable }
- : { reason: block === "local-unsupported" ? P.localUnsupported : P.noNetworkUnsupported };
+ : {
+ reason:
+ block === "local-unsupported"
+ ? P.localUnsupported
+ : block === "mask-unsupported"
+ ? P.maskUnsupported(inUse)
+ : P.noNetworkUnsupported(inUse),
+ };
const hintOf = (p: SessionSandboxPreset, block: PresetBlock | null) => {
const { blocks, allows } = presetEffects(p);
const list = (effects: string[]) =>
diff --git a/packages/web/src/features/settings/plugin-config-field.tsx b/packages/web/src/features/settings/plugin-config-field.tsx
index 56db91c2..68cce366 100644
--- a/packages/web/src/features/settings/plugin-config-field.tsx
+++ b/packages/web/src/features/settings/plugin-config-field.tsx
@@ -1,9 +1,10 @@
/**
* One field of a settings group, drawn from its declared type: a text box, a password box with
- * the stored value's mask and a clear box, a switch, a number box, a select (its options this
- * machine cannot honour greyed out with the reason), a list of lines, or a table
- * (plugin-config-table.tsx). It shows the draft it is handed and reports each edit; the page
- * owns the drafts, the errors and what a change sets in motion.
+ * the stored value's mask and a clear box, a switch (held where one position is not supported
+ * here), a number box, a select (its options this machine cannot honour greyed out with the
+ * reason), a list of lines, or a table (plugin-config-table.tsx). It shows the draft it is
+ * handed and reports each edit; the page owns the drafts, the errors and what a change sets in
+ * motion.
*/
import type { PluginConfigEntry, PluginConfigField } from "@lmliheng/penguin-server/api";
import { Checkbox, Input, PasswordInput, Select, Textarea, ToggleRow } from "@lmliheng/penguin-ui";
@@ -120,19 +121,35 @@ export function ConfigField({
onChange={(e) => onChange(e.target.value)}
/>
);
- case "boolean":
+ case "boolean": {
+ // A position this machine cannot honour ("true" / "false") is named under the switch, and
+ // the switch is held at the other one — unless it already stands there (a backend went
+ // away since), where it stays movable so the setting can be put right.
+ const off = entry.unavailable?.find(
+ (u) => u.field === name && (u.value === "true" || u.value === "false"),
+ );
+ const position = off?.value === "true";
+ const locked =
+ off === undefined
+ ? undefined
+ : S.settings.pluginPositionUnavailable(
+ position ? S.settings.pluginPositionOn : S.settings.pluginPositionOff,
+ localized(off.reason, off.reasonZh) ?? off.reason,
+ );
+ const shownHint = [hint, locked].filter((h) => h !== undefined).join(" ");
return (
<ToggleRow
key={name}
variant="plain"
label={label}
- {...(hint !== undefined ? { hint } : {})}
+ {...(shownHint !== "" ? { hint: shownHint } : {})}
{...(info !== undefined ? { info } : {})}
checked={value === true}
onChange={onChange}
- disabled={disabled}
+ disabled={disabled || (off !== undefined && (value === true) !== position)}
/>
);
+ }
case "secret": {
const masked = typeof entry.values[name] === "string" ? (entry.values[name] as string) : "";
const typed = typeof value === "string" ? (value as string) : "";
diff --git a/packages/web/src/features/settings/plugin-config-heading.tsx b/packages/web/src/features/settings/plugin-config-heading.tsx
index 954c37f1..0b2a9562 100644
--- a/packages/web/src/features/settings/plugin-config-heading.tsx
+++ b/packages/web/src/features/settings/plugin-config-heading.tsx
@@ -3,11 +3,12 @@
* actions it offers
* (what the deployment must do once on the machine, as buttons beside what each will do) and
* its live notices — a spinner for work in progress, a strip for what needs attention, quiet
- * text for the rest. While the group's switch is off (as drafted), only the title is drawn:
- * the actions and notices concern the group in use.
+ * text for the rest; a notice's details fold under it, collapsed (the sandbox's headline
+ * discloses why an installed backend is not in use). While the group's switch is off (as
+ * drafted), only the title is drawn: the actions and notices concern the group in use.
*/
import type { PluginConfigEntry } from "@lmliheng/penguin-server/api";
-import { Button, InfoPopover, NoticeStrip, Spinner } from "@lmliheng/penguin-ui";
+import { Button, HelpFold, InfoPopover, NoticeStrip, Spinner } from "@lmliheng/penguin-ui";
import { S } from "../../lib/strings";
import { toneInk } from "../../lib/tone";
import type { Locale } from "../../state/locale";
@@ -71,22 +72,34 @@ export function ConfigHeading({
</div>
)}
{live &&
- (entry.notices ?? []).map((notice, i) =>
- notice.tone === "progress" ? (
- <p key={i} className={`flex items-center gap-2 text-xs ${toneInk.busy}`}>
- <Spinner size="sm" label={S.common.loading} />
- <span className="min-w-0 break-words">{localized(notice.text, notice.textZh)}</span>
- </p>
- ) : notice.tone === "attention" ? (
- <NoticeStrip tone="attention" as="p" key={i} className="rounded-md px-3 py-2 text-xs">
- {localized(notice.text, notice.textZh)}
- </NoticeStrip>
- ) : (
- <p key={i} className="text-xs text-fg-muted">
- {localized(notice.text, notice.textZh)}
- </p>
- ),
- )}
+ (entry.notices ?? []).map((notice, i) => {
+ const details = localized(notice.details, notice.detailsZh);
+ const line =
+ notice.tone === "progress" ? (
+ <p key={i} className={`flex items-center gap-2 text-xs ${toneInk.busy}`}>
+ <Spinner size="sm" label={S.common.loading} />
+ <span className="min-w-0 break-words">{localized(notice.text, notice.textZh)}</span>
+ </p>
+ ) : notice.tone === "attention" ? (
+ <NoticeStrip tone="attention" as="p" key={i} className="rounded-md px-3 py-2 text-xs">
+ {localized(notice.text, notice.textZh)}
+ </NoticeStrip>
+ ) : (
+ <p key={i} className="text-xs text-fg-muted">
+ {localized(notice.text, notice.textZh)}
+ </p>
+ );
+ if (details === undefined) return line;
+ // No title of its own to anchor a "?" to: the fold names itself.
+ return (
+ <div key={i} className="space-y-1">
+ {line}
+ <HelpFold label={title}>
+ <p className="whitespace-pre-line break-words">{details}</p>
+ </HelpFold>
+ </div>
+ );
+ })}
</div>
);
}
diff --git a/packages/web/src/features/settings/plugin-config-live.ts b/packages/web/src/features/settings/plugin-config-live.ts
new file mode 100644
index 00000000..dc08fece
--- /dev/null
+++ b/packages/web/src/features/settings/plugin-config-live.ts
@@ -0,0 +1,25 @@
+/**
+ * A settings page's live parts — what a group's status reports per read (notices, actions, the
+ * backend report, the options this machine cannot honour) — laid over the entries on screen
+ * after something changed the machine (an install from the Sandbox card's prompt), without
+ * touching their values, so drafts being edited are kept.
+ */
+import type { PluginConfigEntry } from "@lmliheng/penguin-server/api";
+
+export function withLiveParts(
+ entries: readonly PluginConfigEntry[],
+ fresh: readonly PluginConfigEntry[],
+): PluginConfigEntry[] {
+ return entries.map((e) => {
+ const next = fresh.find((p) => p.name === e.name);
+ if (next === undefined) return e;
+ const { notices: _n, actions: _a, backend: _b, unavailable: _u, ...rest } = e;
+ return {
+ ...rest,
+ ...(next.notices !== undefined ? { notices: next.notices } : {}),
+ ...(next.actions !== undefined ? { actions: next.actions } : {}),
+ ...(next.backend !== undefined ? { backend: next.backend } : {}),
+ ...(next.unavailable !== undefined ? { unavailable: next.unavailable } : {}),
+ };
+ });
+}
diff --git a/packages/web/src/features/settings/plugins-section.tsx b/packages/web/src/features/settings/plugins-section.tsx
index 9136829e..43079f00 100644
--- a/packages/web/src/features/settings/plugins-section.tsx
+++ b/packages/web/src/features/settings/plugins-section.tsx
@@ -37,6 +37,7 @@ import {
THIS_SERVER_KEY,
backendToOffer,
dismissBackendPrompt,
+ installInOrder,
} from "../../lib/sandbox-backend-prompt";
import { dispatchPluginConfigSaved } from "../../lib/plugin-config-event";
import { MachinePicker } from "../machines/machine-picker";
@@ -52,6 +53,7 @@ import {
import type { Draft } from "./plugin-config-draft";
import { ConfigField } from "./plugin-config-field";
import { ConfigHeading } from "./plugin-config-heading";
+import { withLiveParts } from "./plugin-config-live";
import { SandboxBackendPrompt } from "./sandbox-backend-prompt";
import {
Button,
@@ -111,7 +113,7 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {
const nameOf = (id: string) => machineLabels.get(id) ?? id;
const projectId = useProject().currentProject?.projectId ?? null;
/** The backend package the install prompt offers, while it is open. */
- const [offered, setOffered] = useState<string | null>(null);
+ const [offered, setOffered] = useState<string[] | null>(null);
const [installing, setInstalling] = useState(false);
const adopt = (list: PluginConfigEntry[]) => {
@@ -314,11 +316,11 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {
/**
* The switch was turned on: if the machine reports no sandbox backend for its OS, ask whether
- * to install its default one. The switch stays on in the draft whatever the answer.
+ * to install its default ones. The switch stays on in the draft whatever the answer.
*/
const offerBackend = (entry: PluginConfigEntry) => {
- const pkg = backendToOffer(entry, machine ?? THIS_SERVER_KEY);
- if (pkg !== null) setOffered(pkg);
+ const pkgs = backendToOffer(entry, machine ?? THIS_SERVER_KEY);
+ if (pkgs !== null) setOffered(pkgs);
};
const closePrompt = (dontAskAgain: boolean) => {
if (dontAskAgain) dismissBackendPrompt(machine ?? THIS_SERVER_KEY);
@@ -326,10 +328,11 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {
};
/**
- * Installs the offered backend the way the Plugins page does: into this Project's table for
- * the machine on screen only — this server's own machine id when the card shows this server,
- * so no other machine is asked to run it. Afterwards the card's live parts (notices, the
- * backend report) are read again; drafts being edited are kept.
+ * Installs the offered backends the way the Plugins page does, one after another: into this
+ * Project's table for the machine on screen only — this server's own machine id when the card
+ * shows this server, so no other machine is asked to run it. A request that fails stops the
+ * run and is reported; either way the prompt closes and the card's live parts (notices, the
+ * backend report) are read again, so what did install shows; drafts being edited are kept.
*/
const installOffered = async (dontAskAgain: boolean) => {
if (offered === null || installing) return;
@@ -337,30 +340,25 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {
toastError(S.settings.sandboxBackendPrompt.noProject);
return;
}
- const pkg = offered;
setInstalling(true);
+ let target = machine;
+ await installInOrder(
+ offered,
+ async (pkg) => {
+ const to = (target ??= (await api.getInstalledPlugins(projectId)).machineId);
+ const res = await api.installPlugin(projectId, pkg, to);
+ return res.plugins.find((p) => p.specifier === pkg)?.error;
+ },
+ {
+ installed: (pkg) => toastSuccess(S.plugins.deploymentInstalledToast(pkg)),
+ failed: (pkg, error) => toastError(S.plugins.deploymentFailedToast(pkg, error)),
+ threw: (e) => toastError(apiErrorText(e)),
+ },
+ );
+ closePrompt(dontAskAgain);
try {
- const target = machine ?? (await api.getInstalledPlugins(projectId)).machineId;
- const res = await api.installPlugin(projectId, pkg, target);
- const row = res.plugins.find((p) => p.specifier === pkg);
- if (row?.error !== undefined) toastError(S.plugins.deploymentFailedToast(pkg, row.error));
- else toastSuccess(S.plugins.deploymentInstalledToast(pkg));
- closePrompt(dontAskAgain);
const config = await api.adminGetPluginConfig(machine);
- 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, backend: _b, unavailable: _u, ...rest } = e;
- return {
- ...rest,
- ...(next.notices !== undefined ? { notices: next.notices } : {}),
- ...(next.actions !== undefined ? { actions: next.actions } : {}),
- ...(next.backend !== undefined ? { backend: next.backend } : {}),
- ...(next.unavailable !== undefined ? { unavailable: next.unavailable } : {}),
- };
- }),
- );
+ setEntries((prev) => withLiveParts(prev ?? [], config.plugins));
} catch (e) {
toastError(apiErrorText(e));
} finally {
@@ -536,7 +534,7 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {
</p>
</ConfirmModal>
<SandboxBackendPrompt
- pkg={offered}
+ pkgs={offered}
machineName={machine === null ? S.plugins.thisServer : nameOf(machine)}
busy={installing}
onInstall={(dontAskAgain) => void installOffered(dontAskAgain)}
diff --git a/packages/web/src/features/settings/sandbox-backend-prompt.tsx b/packages/web/src/features/settings/sandbox-backend-prompt.tsx
index a3fcd795..cab0bb8d 100644
--- a/packages/web/src/features/settings/sandbox-backend-prompt.tsx
+++ b/packages/web/src/features/settings/sandbox-backend-prompt.tsx
@@ -1,6 +1,6 @@
/**
* The question the Sandbox card asks when its switch is turned on and the machine has no
- * sandbox backend for its OS: install this OS's default one? Install / Not now, plus "Don't
+ * sandbox backend for its OS: install this OS's default ones? Install / Not now, plus "Don't
* ask again" for this machine (lib/sandbox-backend-prompt.ts keeps that in this browser).
*
* The answer never touches the switch: it stays on in the card either way, and the card's Save
@@ -12,14 +12,14 @@ import { Checkbox, ConfirmModal, ICONS } from "@lmliheng/penguin-ui";
import { S } from "../../lib/strings";
export function SandboxBackendPrompt({
- pkg,
+ pkgs,
machineName,
busy,
onInstall,
onLater,
}: {
- /** The package to offer; null keeps the dialog closed. */
- pkg: string | null;
+ /** The packages to offer, installed together; null keeps the dialog closed. */
+ pkgs: readonly string[] | null;
/** The machine the card is editing, as the picker names it. */
machineName: string;
busy: boolean;
@@ -30,7 +30,7 @@ export function SandboxBackendPrompt({
const P = S.settings.sandboxBackendPrompt;
return (
<ConfirmModal
- open={pkg !== null}
+ open={pkgs !== null}
title={P.title}
tone="primary"
glyph={ICONS.download}
@@ -41,7 +41,7 @@ export function SandboxBackendPrompt({
onClose={() => onLater(dontAsk)}
>
<div className="space-y-2 text-sm">
- <p>{P.body(machineName, pkg ?? "")}</p>
+ <p>{P.body(machineName, pkgs ?? [])}</p>
<p className="text-xs text-fg-muted">{P.cost}</p>
<Checkbox checked={dontAsk} disabled={busy} label={P.dontAsk} onChange={setDontAsk} />
</div>
diff --git a/packages/web/src/lib/permission-level.ts b/packages/web/src/lib/permission-level.ts
index 5ab6e1d1..2c6082fc 100644
--- a/packages/web/src/lib/permission-level.ts
+++ b/packages/web/src/lib/permission-level.ts
@@ -68,7 +68,8 @@ export const PERMISSION_LEVEL_GLYPH: Record<PermissionLevel, string> = {
* cannot enforce. Only an explicit false from the server counts — one that does not report a
* level is not second-guessed.
*/
-export type LevelBlock = "no-backend" | "unavailable" | "local-unsupported" | "none-unsupported";
+export type LevelBlock =
+ "no-backend" | "unavailable" | "local-unsupported" | "none-unsupported" | "mask-unsupported";
/** The first enabled backend that is not in use, whose reason the composer shows, or null. */
export function firstUnavailableBackend(
@@ -82,6 +83,17 @@ function unmounted(sandbox: SessionSandbox): LevelBlock {
return firstUnavailableBackend(sandbox) === null ? "no-backend" : "unavailable";
}
+/**
+ * The block every level shares when the Session's policy masks paths (kept by every pick) and no
+ * mounted backend masks: each command would be refused, full access included. Only an explicit
+ * false counts, like the other flags.
+ */
+export function maskBlock(sandbox: SessionSandbox): LevelBlock | null {
+ if (sandbox.masksPaths !== true) return null;
+ if (sandbox.confinementSupported === false) return unmounted(sandbox);
+ return sandbox.maskPathsSupported === false ? "mask-unsupported" : null;
+}
+
export function fsModeBlock(
sandbox: SessionSandbox,
mode: SessionSandbox["mode"],
@@ -285,8 +297,8 @@ export interface PresetPicker {
}
/**
- * Why a preset cannot be picked, or null when it can: its mode's enforcement block, else its
- * network's, else — given who is picking — the ceiling, which holds a non-admin only and never on
+ * Why a preset cannot be picked, or null when it can: the masked paths' enforcement block, else
+ * its mode's, else its network's, else — given who is picking — the ceiling, which holds a non-admin only and never on
* the preset the Session is already on (picking it changes nothing).
*/
export function presetBlock(
@@ -295,7 +307,10 @@ export function presetBlock(
Partial<Pick<SessionSandboxPreset, "id" | "aboveCeiling">>,
picker?: PresetPicker,
): PresetBlock | null {
- const enforce = fsModeBlock(sandbox, preset.mode) ?? networkBlock(sandbox, preset.network);
+ const enforce =
+ maskBlock(sandbox) ??
+ fsModeBlock(sandbox, preset.mode) ??
+ networkBlock(sandbox, preset.network);
if (enforce !== null) return enforce;
if (
picker !== undefined &&
diff --git a/packages/web/src/lib/sandbox-backend-prompt.ts b/packages/web/src/lib/sandbox-backend-prompt.ts
index a4e26d20..e1b5ff92 100644
--- a/packages/web/src/lib/sandbox-backend-prompt.ts
+++ b/packages/web/src/lib/sandbox-backend-prompt.ts
@@ -1,9 +1,9 @@
/**
- * When the Sandbox card offers to install a sandbox backend: the admin turned the switch on,
- * the machine reports no backend for its OS, it names a package to suggest, and nobody ticked
+ * When the Sandbox card offers to install sandbox backends: the admin turned the switch on,
+ * the machine reports no backend for its OS, it names packages to suggest, and nobody ticked
* "Don't ask again" for that machine in this browser.
*
- * The OS and the package come from the server (`PluginConfigEntry.backend`); this module never
+ * The OS and the packages come from the server (`PluginConfigEntry.backend`); this module never
* guesses either. "Don't ask again" is remembered per machine in this browser only — it is a
* question about this person's prompts, not a setting of the machine — so it is never sent to
* a server. Storage that is unavailable or throws (a private window, blocked site data) reads
@@ -64,16 +64,60 @@ export function dismissBackendPrompt(
}
/**
- * The package to offer when the switch is turned on for this entry on this machine, or null
- * when there is nothing to ask: a backend for the OS is installed, the OS has no default, the
- * server does not report it, or the prompt was dismissed for this machine.
+ * The packages to offer, installed together, when the switch is turned on for this entry on this
+ * machine — or null when there is nothing to ask: a backend for the OS is installed, the OS has
+ * no default, the server does not report it, or the prompt was dismissed for this machine.
*/
export function backendToOffer(
entry: Pick<PluginConfigEntry, "backend">,
machine: string,
storage: PromptStorage | null = defaultStorage(),
-): string | null {
+): string[] | null {
const report = entry.backend;
- if (report === undefined || report.installed || report.recommended === undefined) return null;
- return backendPromptDismissed(machine, storage) ? null : report.recommended;
+ const recommended = recommendedOf(report?.recommended);
+ if (report === undefined || report.installed || recommended.length === 0) return null;
+ return backendPromptDismissed(machine, storage) ? null : recommended;
+}
+
+/**
+ * The report's packages as a list. TODO(recommended-string-compat): a remote machine running a
+ * server from before the list form reports one package as a bare string, which spreading would
+ * split into characters; remove once every machine runs a server with the list form.
+ */
+function recommendedOf(recommended: readonly string[] | string | undefined): string[] {
+ if (recommended === undefined) return [];
+ return typeof recommended === "string" ? [recommended] : [...recommended];
+}
+
+/** How a run of installs is reported, package by package. */
+export interface InstallReport {
+ installed(pkg: string): void;
+ /** The server installed the package but it failed to load, with why. */
+ failed(pkg: string, error: string): void;
+ /** A request threw: the run stops there. */
+ threw(error: unknown): void;
+}
+
+/**
+ * Installs the offered packages one after another (`install` answers a package's load error, or
+ * undefined). A request that throws ends the run — the packages after it are not tried — and
+ * resolves rather than rejects, so the caller always gets to close the prompt and read the
+ * card again, showing what did install.
+ */
+export async function installInOrder(
+ pkgs: readonly string[],
+ install: (pkg: string) => Promise<string | undefined>,
+ report: InstallReport,
+): Promise<void> {
+ for (const pkg of pkgs) {
+ let error: string | undefined;
+ try {
+ error = await install(pkg);
+ } catch (e) {
+ report.threw(e);
+ return;
+ }
+ if (error !== undefined) report.failed(pkg, error);
+ else report.installed(pkg);
+ }
}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index f2902683..075d65f7 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -438,6 +438,11 @@ export const en: Strings = {
/** An enum option this machine cannot honour, listed greyed out. */
pluginOptionUnavailable: (title: string, reason: string) =>
`${title} (not supported: ${reason})`,
+ /** A switch one of whose positions this machine cannot honour, under the switch. */
+ pluginPositionUnavailable: (position: string, reason: string) =>
+ `${position} is not supported here: ${reason}`,
+ pluginPositionOn: "On",
+ pluginPositionOff: "Off",
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. */
@@ -494,8 +499,9 @@ export const en: Strings = {
/** Asked when the Sandbox switch is turned on and the machine has no sandbox backend. */
sandboxBackendPrompt: {
title: "Install a sandbox backend",
- body: (machine: string, pkg: string) =>
- `${machine} has no sandbox backend for its operating system, so new sessions cannot be confined yet. Install ${pkg}?`,
+ body: (machine: string, pkgs: readonly string[]) =>
+ `${machine} has no sandbox backend for its operating system, so new sessions cannot be confined yet. Install ${pkgs.join(" and ")}?` +
+ (pkgs.length > 1 ? " Where both work, the one that confines more is used." : ""),
cost: "Installing reloads the server's plugins, which stops agent runs in progress in every Project. The switch stays on either way.",
install: "Install",
installing: "Installing…",
@@ -2799,7 +2805,11 @@ export const en: Strings = {
notInstalled: "Not installed",
noBackend:
"No sandbox backend is installed on this server, so commands cannot be confined. An administrator can enable this platform's backend on the Plugins page (More…).",
- noNetworkUnsupported: "No sandbox backend on this machine can cut the network off",
+ /** `backends`: the backends in use, as the server names them (absent from an older server). */
+ noNetworkUnsupported: (backends?: string) =>
+ `The sandbox on this machine confines files only${backends !== undefined ? ` (${backends} does not isolate the network)` : ""}, so it cannot cut the network off`,
+ maskUnsupported: (backends?: string) =>
+ `This session hides masked paths from its commands, and no sandbox backend on this machine can${backends !== undefined ? ` (${backends} cannot mask paths)` : ""}, so every command would be refused. An administrator can clear the masked paths on the Sandbox card (More…).`,
/** The short note beside a level whose enabled backend failed its check. */
notAvailable: "Unavailable",
/** The short note beside a preset wider than the server's sandbox settings, for a non-admin. */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 39520fa6..f2fc2b7d 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -503,6 +503,11 @@ export const zh = {
pluginsTitle: "插件",
/** An enum option this machine cannot honour, listed greyed out. */
pluginOptionUnavailable: (title: string, reason: string) => `${title}(不支持:${reason})`,
+ /** A switch one of whose positions this machine cannot honour, under the switch. */
+ pluginPositionUnavailable: (position: string, reason: string) =>
+ `本机不支持${position}:${reason}`,
+ pluginPositionOn: "开启",
+ pluginPositionOff: "关闭",
pluginsInfo:
"各已装载插件在其包里声明的选项,表单按插件自己的 schema 生成。与插件本身一样是服务器全局的;保存后立即送达插件,无需重启。没有声明选项的插件不会出现在这里。",
/** A secret field with a stored value: submitting it empty keeps the stored one. */
@@ -557,8 +562,9 @@ export const zh = {
/** Asked when the Sandbox switch is turned on and the machine has no sandbox backend. */
sandboxBackendPrompt: {
title: "安装沙盒后端",
- body: (machine: string, pkg: string) =>
- `${machine} 没有适用于其操作系统的沙盒后端,新会话暂时无法进入沙盒。是否安装 ${pkg}?`,
+ body: (machine: string, pkgs: readonly string[]) =>
+ `${machine} 没有适用于其操作系统的沙盒后端,新会话暂时无法进入沙盒。是否安装 ${pkgs.join(" 和 ")}?` +
+ (pkgs.length > 1 ? "两者都可用时,使用封禁范围更大的那个。" : ""),
cost: "安装会重新装载服务器的插件,所有项目中正在进行的 Agent 运行都会停止。无论是否安装,开关都保持打开。",
install: "安装",
installing: "正在安装…",
@@ -2855,7 +2861,10 @@ export const zh = {
notInstalled: "未安装",
noBackend:
"本服务器没有安装沙盒后端,命令无法被封禁。管理员可在插件页启用适用于本平台的后端(更多…)。",
- noNetworkUnsupported: "本机的沙盒后端不支持断开网络",
+ noNetworkUnsupported: (backends?: string) =>
+ `本机的沙盒只封禁文件${backends !== undefined ? `(${backends} 不隔离网络)` : ""},无法断开网络`,
+ maskUnsupported: (backends?: string) =>
+ `本会话要对命令隐藏屏蔽路径,但本机没有能屏蔽路径的沙盒后端${backends !== undefined ? `(${backends} 不能屏蔽路径)` : ""},每条命令都会被拒绝。管理员可在「更多…」里的沙盒卡片清空屏蔽路径。`,
notAvailable: "不可用",
adminOnly: "仅管理员",
aboveCeiling: "超出了本服务器的沙盒上限:只有管理员可以给会话这么大的权限。",
diff --git a/packages/web/test/permission-level.test.ts b/packages/web/test/permission-level.test.ts
index 8c517bda..4c8bad51 100644
--- a/packages/web/test/permission-level.test.ts
+++ b/packages/web/test/permission-level.test.ts
@@ -191,6 +191,25 @@ describe("the composer's presets", () => {
expect(presetBlock(FULL, { mode: "read-only", network: "local" })).toBe("local-unsupported");
});
+ // The DSH adaptor alone confines files but masks no paths: every command would be refused.
+ const fsOnly: SessionSandbox = {
+ ...FULL,
+ confinementSupported: true,
+ noNetworkSupported: false,
+ localNetworkSupported: false,
+ maskPathsSupported: false,
+ masksPaths: true,
+ };
+ it.each<[string | null, SessionSandbox]>([
+ ["mask-unsupported", fsOnly],
+ ["no-backend", { ...fsOnly, confinementSupported: false, unavailableBackends: [] }],
+ [null, { ...fsOnly, maskPathsSupported: true }],
+ [null, { ...fsOnly, masksPaths: undefined }],
+ [null, { ...FULL, masksPaths: true }],
+ ])("a policy masking paths blocks every preset with %s (%j)", (block, sandbox) => {
+ expect(new Set(BUILTIN_PRESETS.map((p) => presetBlock(sandbox, p)))).toEqual(new Set([block]));
+ });
+
it("greys out a preset above the ceiling for a non-admin, never for an admin or the current one", () => {
const presets = BUILTIN_PRESETS.map((p) =>
p.mode === "danger-full-access" ? { ...p, aboveCeiling: true as const } : p,
diff --git a/packages/web/test/plugin-config-card.test.ts b/packages/web/test/plugin-config-card.test.ts
index cf200a0f..0cbd6dfc 100644
--- a/packages/web/test/plugin-config-card.test.ts
+++ b/packages/web/test/plugin-config-card.test.ts
@@ -1,6 +1,7 @@
/**
- * What the Sandbox card draws from its entry and draft: the switch alone while off, the table's
- * name boxes, "?"s, "(Default)" mark, row menus, pin toggles and locked cells.
+ * What the Sandbox card draws from its entry and draft: the switch alone while off, a notice's
+ * details folded under it, the table's name boxes, "?"s, "(Default)" mark, row menus, pin
+ * toggles and locked cells.
*/
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { ReactElement } from "react";
@@ -36,7 +37,7 @@ const ENTRY: PluginConfigEntry = {
actions: [{ id: "setup", title: "Set up" }],
};
-const heading = (draft: Record<string, unknown>, entry = ENTRY) =>
+const heading = (draft: Record<string, unknown>, entry = ENTRY, locale: "en" | "zh" = "en") =>
renderToStaticMarkup(
createElement(ConfigHeading, {
entry,
@@ -44,7 +45,7 @@ const heading = (draft: Record<string, unknown>, entry = ENTRY) =>
nested: false,
disabled: false,
onAction: () => {},
- locale: "en",
+ locale,
}),
);
@@ -64,6 +65,26 @@ describe("the settings card", () => {
expect(heading({ enabled: false })).toContain("Sandbox");
});
+ it("folds a notice's details under it, collapsed, in the page's language", () => {
+ const notice = { tone: "muted" as const, text: "Enforced here: file writes." };
+ const withDetails = (locale: "en" | "zh") =>
+ heading(
+ { enabled: true },
+ { ...ENTRY, notices: [{ ...notice, details: "bwrap refused", detailsZh: "bwrap 已拒绝" }] },
+ locale,
+ );
+ const html = withDetails("en");
+ // A collapsed button controlling the hidden panel that holds the details.
+ const control = /aria-expanded="false" aria-controls="([^"]+)"/.exec(html)?.[1];
+ expect(html.slice(html.indexOf(`id="${control}"`))).toMatch(
+ /^id="[^"]+" hidden=""[^]*bwrap refused/,
+ );
+ expect(withDetails("zh")).toContain("bwrap 已拒绝");
+ expect(heading({ enabled: true }, { ...ENTRY, notices: [notice] })).not.toContain(
+ "aria-expanded",
+ );
+ });
+
it("holds the effective name in the name box, the declared one when not renamed", () => {
const html = renderTable(PRESETS, { b: { name: "Look only", mode: "ro", enabled: false } });
// A wrapping box: a <textarea>, whose value renders as its content.
diff --git a/packages/web/test/plugin-config-switch.test.ts b/packages/web/test/plugin-config-switch.test.ts
new file mode 100644
index 00000000..2c928c09
--- /dev/null
+++ b/packages/web/test/plugin-config-switch.test.ts
@@ -0,0 +1,70 @@
+// A switch one of whose positions this machine cannot honour (the sandbox's "Temporary
+// directory writable" where the backends in use cannot close it).
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import type { PluginConfigEntry, PluginConfigField } from "@lmliheng/penguin-server/api";
+import { setActiveStrings, zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+import { ConfigField } from "../src/features/settings/plugin-config-field";
+
+const FIELD: PluginConfigField = { type: "boolean", title: "Temporary directory writable" };
+const REASON = "the sandbox backend in use here (dsh-local) cannot close the temporary directory";
+
+const entry = (unavailable: boolean): PluginConfigEntry => ({
+ name: "sandbox",
+ configuration: { title: "Sandbox", properties: { writableTemp: FIELD } },
+ values: { writableTemp: true },
+ ...(unavailable
+ ? {
+ unavailable: [
+ { field: "writableTemp", value: "false", reason: REASON, reasonZh: "无法关闭临时目录" },
+ ],
+ }
+ : {}),
+});
+
+const draw = (unavailable: boolean, value: boolean, locale: "en" | "zh" = "en") =>
+ renderToStaticMarkup(
+ createElement(ConfigField, {
+ entry: entry(unavailable),
+ name: "writableTemp",
+ field: FIELD,
+ value,
+ error: undefined,
+ tableErrors: [],
+ clearing: false,
+ onChange: () => {},
+ onClearingChange: () => {},
+ disabled: false,
+ locale,
+ }),
+ );
+
+const switchTag = (html: string) => /<button[^>]*role="switch"[^>]*>/.exec(html)?.[0] ?? "";
+
+describe("a switch with a position this machine cannot honour", () => {
+ beforeAll(() => setActiveStrings(en));
+ afterAll(() => setActiveStrings(zh));
+
+ // Held on while it stands on; left movable when already off (a backend went away since).
+ it.each([
+ [true, true, true],
+ [true, false, false],
+ [false, true, false],
+ ])("unavailable %s, on %s: held %s", (unavailable, on, held) => {
+ const html = draw(unavailable, on);
+ expect(switchTag(html)).toContain(`aria-checked="${on}"`);
+ expect(switchTag(html).includes('disabled=""')).toBe(held);
+ expect(html.includes(`Off is not supported here: ${REASON}`)).toBe(unavailable);
+ });
+
+ it("names the reason in the page's language", () => {
+ setActiveStrings(zh);
+ try {
+ expect(draw(true, true, "zh")).toContain("本机不支持关闭:无法关闭临时目录");
+ } finally {
+ setActiveStrings(en);
+ }
+ });
+});
diff --git a/packages/web/test/sandbox-backend-prompt.test.ts b/packages/web/test/sandbox-backend-prompt.test.ts
index 3a8cb0ed..8603a7a3 100644
--- a/packages/web/test/sandbox-backend-prompt.test.ts
+++ b/packages/web/test/sandbox-backend-prompt.test.ts
@@ -1,6 +1,7 @@
/**
- * When the Sandbox card offers to install a backend: only where none for the OS is installed and
- * a default is named; "Don't ask again" holds per machine; broken storage never hides the prompt.
+ * When the Sandbox card offers to install backends: every default together, only where none for
+ * the OS is installed; "Don't ask again" holds per machine; broken storage never hides the prompt;
+ * a failing install stops the run and resolves.
*/
import { describe, expect, it } from "vitest";
import {
@@ -8,6 +9,7 @@ import {
backendPromptDismissed,
backendToOffer,
dismissBackendPrompt,
+ installInOrder,
} from "../src/lib/sandbox-backend-prompt";
import type { PromptStorage } from "../src/lib/sandbox-backend-prompt";
@@ -16,17 +18,20 @@ function memoryStorage(): PromptStorage & { data: Map<string, string> } {
return { data, getItem: (k) => data.get(k) ?? null, setItem: (k, v) => void data.set(k, v) };
}
-const BWRAP = "@lmliheng/penguin-plugin-sandbox-bwrap";
-const MISSING = { backend: { installed: false, recommended: BWRAP } };
+const LINUX = ["@lmliheng/penguin-plugin-sandbox-bwrap", "@lmliheng/penguin-plugin-sandbox-dsh"];
+const MISSING = { backend: { installed: false, recommended: LINUX } };
describe("the default-backend prompt", () => {
it.each([
- [MISSING, BWRAP],
- [{ backend: { installed: true, recommended: BWRAP } }, null],
+ [MISSING, LINUX],
+ [{ backend: { installed: true, recommended: LINUX } }, null],
[{ backend: { installed: false } }, null],
+ [{ backend: { installed: false, recommended: [] } }, null],
[{}, null],
- ])("offers %j: %s", (report, offer) => {
- expect(backendToOffer(report, "m1", memoryStorage())).toBe(offer);
+ // An older server names its one default as a bare string: that package, not its characters.
+ [{ backend: { installed: false, recommended: "@x/bwrap" } } as never, ["@x/bwrap"]],
+ ])("offers %j: %j", (report, offer) => {
+ expect(backendToOffer(report, "m1", memoryStorage())).toEqual(offer);
});
it("remembers don't-ask-again per machine, in this browser's storage only", () => {
@@ -34,7 +39,7 @@ describe("the default-backend prompt", () => {
dismissBackendPrompt("m1", storage);
dismissBackendPrompt("m1", storage);
expect(backendToOffer(MISSING, "m1", storage)).toBeNull();
- expect(backendToOffer(MISSING, "m2", storage)).toBe(BWRAP);
+ expect(backendToOffer(MISSING, "m2", storage)).toEqual(LINUX);
expect(JSON.parse(storage.data.get(BACKEND_PROMPT_DISMISSED_KEY)!)).toEqual(["m1"]);
});
@@ -44,8 +49,8 @@ describe("the default-backend prompt", () => {
};
const throwing: PromptStorage = { getItem: blocked, setItem: blocked };
expect(() => dismissBackendPrompt("m1", throwing)).not.toThrow();
- expect(backendToOffer(MISSING, "m1", throwing)).toBe(BWRAP);
- expect(backendToOffer(MISSING, "m1", null)).toBe(BWRAP);
+ expect(backendToOffer(MISSING, "m1", throwing)).toEqual(LINUX);
+ expect(backendToOffer(MISSING, "m1", null)).toEqual(LINUX);
const garbage = memoryStorage();
garbage.setItem(BACKEND_PROMPT_DISMISSED_KEY, "{not json");
expect(backendPromptDismissed("m1", garbage)).toBe(false);
@@ -53,3 +58,28 @@ describe("the default-backend prompt", () => {
expect(backendPromptDismissed("m1", garbage)).toBe(true);
});
});
+
+describe("installing the offered backends", () => {
+ it("reports each, and stops at a request that throws without rejecting", async () => {
+ const events: string[] = [];
+ const tried: string[] = [];
+ await expect(
+ installInOrder(
+ ["a", "b", "c", "d"],
+ async (pkg) => {
+ tried.push(pkg);
+ if (pkg === "b") return "load failed";
+ if (pkg === "c") throw new Error("network down");
+ return undefined;
+ },
+ {
+ installed: (pkg) => events.push(`ok ${pkg}`),
+ failed: (pkg, error) => events.push(`failed ${pkg}: ${error}`),
+ threw: (e) => events.push(`threw ${(e as Error).message}`),
+ },
+ ),
+ ).resolves.toBeUndefined();
+ expect(events).toEqual(["ok a", "failed b: load failed", "threw network down"]);
+ expect(tried).toEqual(["a", "b", "c"]);
+ });
+});
diff --git a/plugins/sandbox-bwrap/README.md b/plugins/sandbox-bwrap/README.md
index 802591ee..78257ef2 100644
--- a/plugins/sandbox-bwrap/README.md
+++ b/plugins/sandbox-bwrap/README.md
@@ -1,19 +1,22 @@
# Bubblewrap sandbox backend
Confines command subprocesses with [bubblewrap](https://github.com/containers/bubblewrap),
-talking to `bwrap` directly. Implements **all three** dimensions of the harness sandbox
-interface — filesystem writes, network isolation and path masking.
+talking to `bwrap` directly. Implements filesystem writes, network isolation, path masking
+and closing the temporary directory (a policy that does not grant temp leaves `/tmp` read-only).
## Requirements
- Linux. On any other platform the backend declines to mount, so a policy is routed to a backend
that host has.
-- Unprivileged user namespaces enabled. The backend probes functionally at load and
- declines when the kernel will not grant them, rather than confining less than asked.
- Ubuntu 23.10 and later (24.04 by default) grant them only to AppArmor-profiled programs
- (`kernel.apparmor_restrict_unprivileged_userns=1`): the CLI package, the one-line installer, npm
- and Docker all run as an ordinary user, and installing a profile takes root. The one-time host
- step is in the CLI quickstart's "Sandbox on Ubuntu" section.
+- Unprivileged user namespaces enabled. The backend probes functionally at load and fails the
+ load when the kernel will not grant them, with what bwrap said, rather than confining less than
+ asked. Ubuntu 23.10 and later (24.04 by default) grant them only to AppArmor-profiled programs
+ (`kernel.apparmor_restrict_unprivileged_userns=1`): the desktop `.deb` installs such a profile;
+ the CLI package, the one-line installer, npm and Docker cannot, because the profile needs root.
+ There `@lmliheng/penguin-plugin-sandbox-dsh`, which the Sandbox card installs beside this backend,
+ confines file writes through Landlock with no host step. The optional one-time root step that
+ lets this backend run, adding network isolation and masked paths, is in the CLI quickstart's
+ "Sandbox on Ubuntu" section.
**It brings its own bubblewrap.** The package ships a binary per architecture
(`vendor/linux-x64`, `vendor/linux-arm64`), pinned by URL and sha256 from conda-forge and
diff --git a/plugins/sandbox-bwrap/package.json b/plugins/sandbox-bwrap/package.json
index 9830a81e..abe56dfb 100644
--- a/plugins/sandbox-bwrap/package.json
+++ b/plugins/sandbox-bwrap/package.json
@@ -1,6 +1,6 @@
{
"name": "@lmliheng/penguin-plugin-sandbox-bwrap",
- "version": "0.2.2",
+ "version": "0.2.3",
"private": true,
"type": "module",
"description": "Bubblewrap sandbox backend for Adelie: filesystem confinement plus network isolation and path masking.",
diff --git a/plugins/sandbox-bwrap/src/index.ts b/plugins/sandbox-bwrap/src/index.ts
index 4349f8d7..8c7afa66 100644
--- a/plugins/sandbox-bwrap/src/index.ts
+++ b/plugins/sandbox-bwrap/src/index.ts
@@ -192,10 +192,17 @@ function defaultProbe(timeoutMs: number, runner: string): boolean {
return probe.status === 0;
}
-/** The base-profile probe, without blocking the process: what the load-time check runs. */
-function probeAsync(timeoutMs: number, runner: string): Promise<boolean> {
+/**
+ * The base-profile probe, without blocking the process: what the load-time check runs. Null when
+ * bwrap accepted the profile, else what it said (`setting up uid map: Permission denied` where
+ * user namespaces are refused), or the spawn error when it did not start.
+ */
+function probeAsync(timeoutMs: number, runner: string): Promise<string | null> {
return new Promise((resolve) => {
- execFile(runner, BASE_PROFILE_PROBE, { timeout: timeoutMs }, (err) => resolve(err === null));
+ execFile(runner, BASE_PROFILE_PROBE, { timeout: timeoutMs }, (err, _stdout, stderr) => {
+ if (err === null) resolve(null);
+ else resolve(String(stderr).trim().split("\n")[0] || err.message);
+ });
});
}
@@ -218,17 +225,17 @@ export async function loadPenguinBwrapProvider(
runner: internals.runner ?? (vendoredRunner() || "bwrap"),
probeTimeoutMs: PROBE_TIMEOUT_MS,
};
- const usable = internals.probe
+ const refusal = internals.probe
? internals.probe(probeTimeoutMs, runner)
+ ? null
+ : "the probe failed"
: await probeAsync(probeTimeoutMs, runner);
- if (!usable) {
+ if (refusal !== null) {
// Two distributions, two switches: Debian gates unprivileged user namespaces with a sysctl,
// Ubuntu 23.10 and later lets only AppArmor-profiled programs create them (24.04's default).
- // Both are named because the reason is all an operator sees on the Sandbox card, and Ubuntu's
- // is not a sysctl they can just flip where a profile is what the kernel wants: the reason
- // points at the one-time step the docs spell out.
+ // Neither is needed for the sandbox to work: sandbox-dsh confines files through Landlock.
throw new Error(
- `'${runner}' is missing or refuses the base profile (are unprivileged user namespaces allowed on this host? Debian: \`sysctl kernel.unprivileged_userns_clone\`; Ubuntu 23.10 and later: \`sysctl kernel.apparmor_restrict_unprivileged_userns\`, see "Sandbox on Ubuntu" in the CLI quickstart)`,
+ `'${runner}' is missing or refuses the base profile (${refusal}). Are unprivileged user namespaces allowed on this host? Debian: \`sysctl kernel.unprivileged_userns_clone\`; Ubuntu 23.10 and later: \`sysctl kernel.apparmor_restrict_unprivileged_userns\`. @lmliheng/penguin-plugin-sandbox-dsh confines file writes without them, through Landlock. Optional: a one-time root step lets bubblewrap run here, adding network isolation and masked paths — see "Sandbox on Ubuntu" in the CLI quickstart`,
);
}
return createPenguinBwrapProvider(internals);
@@ -250,7 +257,8 @@ export function createPenguinBwrapProvider(internals: PenguinBwrapInternals = {}
}));
const usable = new Map<string, boolean>();
return {
- dimensions: ["fs-write", "network", "mask-paths"],
+ dimensions: ["fs-write", "network", "mask-paths", "closed-temp"],
+ mechanism: "bubblewrap",
confine(argv, policy): ConfinedArgv {
const { runner, probeTimeoutMs } = settings();
if (!usable.has(runner)) usable.set(runner, probe(probeTimeoutMs, runner));
@@ -287,7 +295,7 @@ export function createPenguinBwrapProvider(internals: PenguinBwrapInternals = {}
{
id: "sandbox-bwrap.provider",
name: "penguin-bwrap",
- dimensions: ["fs-write", "network", "mask-paths"],
+ dimensions: ["fs-write", "network", "mask-paths", "closed-temp"],
},
],
"PluginConfigProvider.groups": [
diff --git a/plugins/sandbox-bwrap/test/profile.test.ts b/plugins/sandbox-bwrap/test/profile.test.ts
index e400081f..cd69a531 100644
--- a/plugins/sandbox-bwrap/test/profile.test.ts
+++ b/plugins/sandbox-bwrap/test/profile.test.ts
@@ -162,6 +162,7 @@ describe("penguin-bwrap provider", () => {
"fs-write",
"network",
"mask-paths",
+ "closed-temp",
]);
});
@@ -237,6 +238,22 @@ describe("bwrap on another platform", () => {
const rejection = loadPenguinBwrapProvider({ platform: "linux", probe: () => false });
await expect(rejection).rejects.toThrow(/kernel\.unprivileged_userns_clone/);
await expect(rejection).rejects.toThrow(/kernel\.apparmor_restrict_unprivileged_userns/);
+ // The root step is optional: sandbox-dsh confines files without it.
+ await expect(rejection).rejects.toThrow(/sandbox-dsh confines file writes without them/);
+ await expect(rejection).rejects.toThrow(/Optional: a one-time root step lets bubblewrap run/);
+ });
+
+ it("carries what the runner said, and that it did not start at all", async () => {
+ await expect(
+ loadPenguinBwrapProvider({
+ platform: "linux",
+ settings: () => ({ runner: "/nonexistent/bwrap", probeTimeoutMs: 5000 }),
+ }),
+ ).rejects.toThrow(/'\/nonexistent\/bwrap' is missing or refuses the base profile \(.*ENOENT/);
+ });
+
+ it("names itself bubblewrap on the settings card", () => {
+ expect(createPenguinBwrapProvider({ probe: () => true }).mechanism).toBe("bubblewrap");
});
it("points at the documented step, which is the actionable half on Ubuntu", async () => {
diff --git a/plugins/sandbox-dsh/README.md b/plugins/sandbox-dsh/README.md
index c7caa91a..86e100ff 100644
--- a/plugins/sandbox-dsh/README.md
+++ b/plugins/sandbox-dsh/README.md
@@ -19,6 +19,32 @@ DSH's policy vocabulary governs **file-write effects only**, so this adaptor dec
exactly `fs-write`. The sandbox service therefore never routes a `network` or
`mask-paths` policy here, and the adaptor never has to silently drop a dimension it
cannot honor — for those, use the bubblewrap, Seatbelt or WSL backend for your platform.
+Mounted beside one of those, it is used only where that backend is refused: the service
+routes every policy to the backend implementing the most dimensions.
+
+The chain picks its rung when the adaptor loads, and the settings card names the rung that
+serves (`Landlock`, with `(partial)` on an older Landlock ABI). On Linux that runs the chain's
+probes, so a host where neither rung works fails the load with DSH's reason rather than
+mounting a backend that refuses every command; macOS and Windows have one rung each, which DSH
+selects without probing.
+
+What every rung leaves open, disclosed on the card under what the machine enforces:
+
+- **The Session scratchpad is not writable** under Workspace Write. DSH's policy takes the
+ Workspace alone, so commands cannot write the plan, goal or attachment files kept there.
+- **The temporary directory cannot be closed.** Every rung grants one under Workspace Write;
+ Landlock grants the host's shared `/tmp`. The adaptor does not declare `closed-temp`, so the
+ card greys out turning **Temporary directory writable** off, and a policy turning it off is
+ never routed here.
+- **Landlock (partial)**: on a kernel older than Landlock ABI 5 (Linux 6.10; Ubuntu 24.04's
+ 6.8 has ABI 4), ioctl on device files outside the Workspace is not restricted, and below ABI 3
+ (Linux 6.2) neither is truncating a file. The launcher reports this on every run; the harness
+ drops that line from the command's stderr.
+
+On Linux this is the floor the Sandbox card installs beside bubblewrap. Ubuntu 23.10 and later
+restrict unprivileged user namespaces to AppArmor-profiled programs, which refuses bubblewrap
+on an install that could not add a profile; Landlock needs neither a namespace nor root, so file
+writes stay confined there with no host step.
## Windows: run command sessions under PowerShell
diff --git a/plugins/sandbox-dsh/package.json b/plugins/sandbox-dsh/package.json
index 13d86b0d..2a1c3261 100644
--- a/plugins/sandbox-dsh/package.json
+++ b/plugins/sandbox-dsh/package.json
@@ -1,6 +1,6 @@
{
"name": "@lmliheng/penguin-plugin-sandbox-dsh",
- "version": "0.2.2",
+ "version": "0.2.3",
"private": true,
"type": "module",
"description": "DeepSeek Harness sandbox adaptor for Adelie: the DSH local backend chain behind the harness's own sandbox interface.",
diff --git a/plugins/sandbox-dsh/src/index.ts b/plugins/sandbox-dsh/src/index.ts
index 2089512e..6589bed4 100644
--- a/plugins/sandbox-dsh/src/index.ts
+++ b/plugins/sandbox-dsh/src/index.ts
@@ -21,10 +21,13 @@
* them fails THIS load — reported fail-closed by the service — instead of failing the
* whole platform bundle's import.
*/
+import { tmpdir } from "node:os";
+import path from "node:path";
import { Bind, Component } from "@lmliheng/penguin-core/plugin";
import type {
ConfinedArgv,
Plugin,
+ SandboxLimit,
SandboxProvider,
SandboxProviderSource,
} from "@lmliheng/penguin-core/plugin";
@@ -148,6 +151,46 @@ export interface DshLoadHost {
sessionShell?: SessionShell | null;
}
+/**
+ * The rung DSH's chain selected, by the program its wrap starts: on Linux bubblewrap when it
+ * passed the chain's probe, else the Landlock launcher; one rung each on macOS and Windows.
+ */
+export function rungName(platform: NodeJS.Platform, runner: string | undefined): string {
+ if (platform === "darwin") return "Seatbelt";
+ if (platform === "win32") return "the Windows ACL runner";
+ return runner === "bwrap" ? "bubblewrap" : "Landlock";
+}
+
+/**
+ * What the rung leaves open, for the settings card. DSH's policy takes the mode and the
+ * Workspace and nothing more, so no rung grants the Session's scratchpad (SandboxPolicy
+ * .writableRoots). Landlock grants the host's own /tmp; on a kernel older than Landlock ABI 5
+ * the launcher governs only part of the file accesses, and says so on every run (dropped from
+ * the command's stderr, see the core's ConfinedSpawn.runnerLines).
+ */
+export function rungLimits(rung: string, enforcement: "full" | "partial"): SandboxLimit[] {
+ const limits: SandboxLimit[] = [
+ {
+ text: `${rung}: under Workspace Write the Session scratchpad is not writable — DSH's policy takes the Workspace alone — so commands cannot write the plan, goal or attachment files kept there.`,
+ textZh: `${rung}:仅工作区可写下 Session scratchpad 不可写(DSH 的策略只接受工作区),命令无法写入其中的计划、目标与附件文件。`,
+ },
+ ];
+ if (rung !== "Landlock") return limits;
+ limits.push({
+ text: "Landlock: under Workspace Write the temporary directory is the host's shared /tmp, writable by every confined command; it cannot be closed or made private here.",
+ textZh:
+ "Landlock:仅工作区可写下,临时目录就是宿主共享的 /tmp,每条受限命令都可写;本机无法关闭它,也无法让它私有。",
+ });
+ if (enforcement === "partial") {
+ limits.push({
+ text: "Landlock (partial): this kernel's Landlock ABI is older than 5 (Linux 6.10), so ioctl on device files outside the Workspace is not restricted; below ABI 3 (Linux 6.2) truncating a file outside the Workspace is not restricted either.",
+ textZh:
+ "Landlock(partial):本机内核的 Landlock ABI 低于 5(Linux 6.10),工作区外设备文件上的 ioctl 不受限制;低于 ABI 3(Linux 6.2)时,截断工作区外的文件也不受限制。",
+ });
+ }
+ return limits;
+}
+
/**
* Mount the stock DSH chain on a bare cordis Context — exactly how DSH's own tests mount it —
* after checking, on Windows, that its ACL runner can start the session shell at all.
@@ -167,9 +210,19 @@ export async function loadDshAdaptor(host: DshLoadHost = {}): Promise<SandboxPro
// `ctx.plugin` is cordis's own API name, not this repo's vocabulary.
await ctx.plugin(LocalSandboxProvider, {});
const dsh = ctx.sandbox;
+ // The chain picks its rung on the first confine; do that here, so the settings card can name
+ // the rung that serves. On Linux, whose chain has two rungs, that is the chain's functional
+ // probes (DSH keeps the verdict for the provider's lifetime), and a host where neither works
+ // fails this load with DSH's reason instead of mounting a backend that refuses every command.
+ // macOS and Windows have a single rung, which DSH selects unprobed: this proves nothing there.
+ const probe = dsh.confine([process.execPath], { mode: "read-only", workspaceRoot: tmpdir() });
+ const rung = rungName(platform, probe.argv[0]);
return {
- // DSH's own words: "Network and process visibility are outside this vocabulary."
+ // DSH's own words: "Network and process visibility are outside this vocabulary." Nor can it
+ // close the temporary directory (`closed-temp`): every rung grants one under workspace-write.
dimensions: ["fs-write"],
+ mechanism: rung + (probe.enforcement === "partial" ? " (partial)" : ""),
+ limits: rungLimits(rung, probe.enforcement),
confine(argv, policy): ConfinedArgv {
if (policy.mode === "danger-full-access") {
// Unreachable: this backend implements only fs-write, so the service never hands it a
diff --git a/plugins/sandbox-dsh/test/live.test.ts b/plugins/sandbox-dsh/test/live.test.ts
index 5dd67090..52277924 100644
--- a/plugins/sandbox-dsh/test/live.test.ts
+++ b/plugins/sandbox-dsh/test/live.test.ts
@@ -121,6 +121,14 @@ describe.skipIf(!usable)("DSH adaptor live enforcement (host-gated)", () => {
expect(r.out).toContain("READ_OK");
});
+ it("names the rung that serves for the settings card", () => {
+ expect(provider!.mechanism).toMatch(
+ /^(bubblewrap|Landlock|Seatbelt|the Windows ACL runner)( \(partial\))?$/,
+ );
+ // Read by a host check that wants to see which rung a CI runner reached.
+ console.log(`sandbox-dsh confines through ${provider!.mechanism}`);
+ });
+
it("workspace-write: a write outside the workspace is denied by the kernel", async () => {
mode = "workspace-write";
const r = await run(probes.writeOutside);
diff --git a/plugins/sandbox-dsh/test/rung.test.ts b/plugins/sandbox-dsh/test/rung.test.ts
new file mode 100644
index 00000000..a83049a0
--- /dev/null
+++ b/plugins/sandbox-dsh/test/rung.test.ts
@@ -0,0 +1,26 @@
+/** The rung the settings card names for the DSH adaptor, read off the program a wrap starts, and its limits. */
+import { describe, expect, it } from "vitest";
+import { rungLimits, rungName } from "../src/index.js";
+
+describe("the DSH rung", () => {
+ it.each([
+ ["linux", "bwrap", "bubblewrap"],
+ ["linux", "/opt/penguin/node_modules/.bin/landlock-run", "Landlock"],
+ ["darwin", "sandbox-exec", "Seatbelt"],
+ ["win32", "C:\\node.exe", "the Windows ACL runner"],
+ ] as const)("on %s, %s is %s", (platform, program, name) => {
+ expect(rungName(platform, program)).toBe(name);
+ });
+
+ it("names the scratchpad on every rung, Landlock's shared /tmp, and a partial Landlock's ABI gaps", () => {
+ expect(rungLimits("bubblewrap", "full").map((l) => l.text)).toEqual([
+ expect.stringContaining("Session scratchpad is not writable"),
+ ]);
+ const [, tmp, ...rest] = rungLimits("Landlock", "full");
+ const partial = rungLimits("Landlock", "partial")[2];
+ expect(rest).toEqual([]);
+ expect(tmp!.text).toContain("the host's shared /tmp");
+ expect(tmp!.textZh).toContain("宿主共享的 /tmp");
+ expect(partial!.text).toMatch(/older than 5 .*ioctl.*below ABI 3 .*truncating/);
+ });
+});
diff --git a/plugins/sandbox-seatbelt/README.md b/plugins/sandbox-seatbelt/README.md
index 5ba786b4..f68d0e3a 100644
--- a/plugins/sandbox-seatbelt/README.md
+++ b/plugins/sandbox-seatbelt/README.md
@@ -1,8 +1,9 @@
# macOS Seatbelt sandbox backend
The macOS counterpart to the bubblewrap backend, built on `sandbox-exec` (Seatbelt).
-Implements **all three** dimensions of the harness sandbox interface — filesystem writes,
-network isolation and path masking — as policy rules rather than mounts.
+Implements every dimension of the harness sandbox interface — filesystem writes, network
+isolation (none, or localhost only), path masking and closing the temporary directory — as
+policy rules rather than mounts.
## The program it runs
diff --git a/plugins/sandbox-seatbelt/package.json b/plugins/sandbox-seatbelt/package.json
index 700e1334..426cf67f 100644
--- a/plugins/sandbox-seatbelt/package.json
+++ b/plugins/sandbox-seatbelt/package.json
@@ -1,6 +1,6 @@
{
"name": "@lmliheng/penguin-plugin-sandbox-seatbelt",
- "version": "0.2.2",
+ "version": "0.2.3",
"private": true,
"type": "module",
"description": "macOS Seatbelt sandbox backend for Adelie: filesystem confinement plus network isolation and path masking.",
diff --git a/plugins/sandbox-seatbelt/src/index.ts b/plugins/sandbox-seatbelt/src/index.ts
index 977706e0..50aa8a8d 100644
--- a/plugins/sandbox-seatbelt/src/index.ts
+++ b/plugins/sandbox-seatbelt/src/index.ts
@@ -232,7 +232,7 @@ export function createSeatbeltProvider(internals: SeatbeltInternals = {}): Sandb
const settings = internals.settings ?? (() => ({ runner: internals.runner ?? defaultRunner() }));
const usable = new Map<string, boolean>();
return {
- dimensions: ["fs-write", "network", "network-local", "mask-paths"],
+ dimensions: ["fs-write", "network", "network-local", "mask-paths", "closed-temp"],
confine(argv, policy): ConfinedArgv {
const { runner } = settings();
if (!usable.has(runner)) usable.set(runner, probe(PROBE_TIMEOUT_MS, runner));
@@ -266,7 +266,7 @@ export function createSeatbeltProvider(internals: SeatbeltInternals = {}): Sandb
{
id: "sandbox-seatbelt.provider",
name: "penguin-seatbelt",
- dimensions: ["fs-write", "network", "network-local", "mask-paths"],
+ dimensions: ["fs-write", "network", "network-local", "mask-paths", "closed-temp"],
},
],
"PluginConfigProvider.groups": [
diff --git a/plugins/sandbox-seatbelt/test/profile.test.ts b/plugins/sandbox-seatbelt/test/profile.test.ts
index 58fded2d..2c4cff09 100644
--- a/plugins/sandbox-seatbelt/test/profile.test.ts
+++ b/plugins/sandbox-seatbelt/test/profile.test.ts
@@ -160,6 +160,7 @@ describe("seatbelt provider", () => {
"network",
"network-local",
"mask-paths",
+ "closed-temp",
]);
});
diff --git a/plugins/sandbox-wsl/README.md b/plugins/sandbox-wsl/README.md
index a6408c3c..1da8fa6d 100644
--- a/plugins/sandbox-wsl/README.md
+++ b/plugins/sandbox-wsl/README.md
@@ -7,6 +7,7 @@ A Windows sandbox backend for Adelie. Each agent command runs in a dedicated WSL
| fs-write | The distro is read-only; the Workspace is bound read-write (or read-only) at its /mnt path, and under `workspace-write` so are the policy's `writableRoots` (the Session's scratchpad) |
| 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 |
+| closed-temp | `/tmp` gets a private tmpfs only when the policy grants temp; otherwise it stays read-only |
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.
diff --git a/plugins/sandbox-wsl/package.json b/plugins/sandbox-wsl/package.json
index 9454a694..c1266e91 100644
--- a/plugins/sandbox-wsl/package.json
+++ b/plugins/sandbox-wsl/package.json
@@ -1,6 +1,6 @@
{
"name": "@lmliheng/penguin-plugin-sandbox-wsl",
- "version": "0.2.2",
+ "version": "0.2.3",
"private": true,
"type": "module",
"description": "WSL sandbox backend for Adelie on Windows: commands run in a dedicated WSL2 distro under bubblewrap, with Windows interop switched off.",
diff --git a/plugins/sandbox-wsl/src/index.ts b/plugins/sandbox-wsl/src/index.ts
index 09f89823..f03cb9de 100644
--- a/plugins/sandbox-wsl/src/index.ts
+++ b/plugins/sandbox-wsl/src/index.ts
@@ -119,7 +119,7 @@ export function createWslProvider(
const node = internals.node ?? process.execPath;
const launcher = internals.launcher ?? launcherPath();
return {
- dimensions: ["fs-write", "network", "mask-paths"],
+ dimensions: ["fs-write", "network", "mask-paths", "closed-temp"],
confine(argv, policy: SandboxPolicy): ConfinedArgv {
const state = readState();
if (state === null) {
@@ -397,7 +397,7 @@ export class SandboxWslStatus {
{
id: "sandbox-wsl.provider",
name: "penguin-wsl",
- dimensions: ["fs-write", "network", "mask-paths"],
+ dimensions: ["fs-write", "network", "mask-paths", "closed-temp"],
},
],
"PluginConfigProvider.groups": [