A local-first multi-agent app development platform, built on PenguinHarness
feat(sandbox): the sandbox confines hook scripts, stdio MCP Servers and the file tools, with the scratchpad writable (#893)
Yaowei Zheng1a77dd096dc7
diff --git a/changelog/unreleased/2026-09-29-sandbox-hooks-and-file-tools.md b/changelog/unreleased/2026-09-29-sandbox-hooks-and-file-tools.mdnew file mode 100644index 00000000..7756bb32--- /dev/null+++ b/changelog/unreleased/2026-09-29-sandbox-hooks-and-file-tools.md@@ -0,0 +1,33 @@+# The sandbox confines hook scripts, stdio MCP Servers and the file tools, with the scratchpad writable++- **Date:** 2026-09-29+- **Type:** feature+- **Scope:** `core`, `server`, `plugins`, `docs`+- **PR:** [#893](https://github.com/Prism-Shadow/penguin-harness/pull/893)+- **Breaking:** yes — in a confining sandbox mode the file tools and hook scripts are confined like commands and cannot write memory or Agent State; `scriptStopHook` / `scriptPreToolUseHook` / `scriptUserPromptHook` take an options object++[中文版](2026-09-29-sandbox-hooks-and-file-tools.zh.md)++The Session's sandbox policy, which had confined only the commands an agent runs, was extended to the hook scripts its Session runs, to the MCP Servers it starts over `stdio`, and to the file tools `read_file`, `edit_file` and `write_file`. Under `workspace-write`, the Session's scratchpad (`<agent>/scratchpad/<session_id>`, where the plan file, a goal's state file and the attachments live) became writable beside the Workspace and the temporary directory, for all three.++## Details++- **One policy, one seam.** The policy stayed the `SandboxSettings` snapshot on the Session's row (mode, network, masked paths, writable temp), shared by its subagents, and reached core through `confineSpawn` alone, which now wraps everything core spawns for the Session: command subprocesses, hook scripts, `stdio` MCP Servers and the file tools' helper. The confiner's answer for the helper's argv also decides whether a Session is confined at all: an answer that leaves the argv alone (the contract's word for "unconfined") keeps the file tools in-process.+- **Hook scripts.** `runHookScript` took `confine?: (argv) => ConfinedSpawn` and spawned the argv it returned, with the runner's environment entries laid over the script's. `scriptStopHook`, `scriptPreToolUseHook` and `scriptUserPromptHook` took an options object, `ScriptHookOptions`: `timeoutS`, `pathPrepend`, a `confineSpawn` getter re-read at every run, and `scope: { workspaceDir, scratchpadDir }`, plus `trigger` for the user-prompt adapter. `Agent.sessionHooks` bound the Session's confiner and scope into every installed command, so a script was confined as `node <script>` with its package directory as cwd. A confiner that threw failed the hook with a `sandbox: …` error, recorded as `hook failed: sandbox: …` like any hook failure; the script did not run.+- **stdio MCP Servers.** `McpToolProviderOptions` gained `confineSpawn` and `scratchpadDir`, which the Environment passes from its own; a `stdio` Server's `[command, ...args]` went through the confiner before the transport was built, with the Server's working directory as `cwd` and the Session's Workspace and scratchpad as scope, and the runner's environment entries lay over the Server's. A confiner that threw was that Server's connect failure (`sandbox: …` in its `error_message`), reported like any other, and the Server did not start. Servers over `http` / `sse` are not processes of this machine and were untouched.+- **File tools.** `read_file`, `edit_file` and `write_file` now do every file-system effect — stat, reads (the windowed text scan included), atomic writes, directory listings, `realpath`, `readlink`, `mkdir`, and `read_file`'s download of an image URL — through a port (`environment/tools/fs-port.ts`, `FsPort`), handed to the tool as `ToolExecutionContext.fs`, resolved on first use so a call that touches no file never consults the confiner; `fs.sandboxed` says which port it is. An unconfined Session's port is this process (`localFsPort`). A confined Session's is a helper process (`environment/tools/fs-worker.ts`): a Node process started as `node -e <program>` — the program travels inline, builtin modules only, so nothing ships beside a bundle — whose argv the confiner rewrote with the Session's Workspace and scratchpad as scope, serving the primitives as JSON lines over stdin and stdout, binary as base64. One helper serves a Session (`SandboxedFsHost`): started at the first confined file operation, reused afterwards, started over when the confiner's answer changes or after a crash, killed by an abort (the sandbox may be stalling the operation), stopped on `Environment.dispose`. Errors keep their `code` across the boundary, so the tools' diagnoses are unchanged; a permission error (`EROFS` / `EACCES` / `EPERM`) under a confining Session is reported as refused by the sandbox. Inside a Linux distro serving a Windows host (WSL), drive paths are mapped to `/mnt/<drive>` on the way in and back on the way out.+- **The scratchpad reached the backends.** `SpawnConfiner`'s options gained `scratchpadDir`, and the server's `confinerFor` put it into a new optional field of the plugin contract, `SandboxPolicy.writableRoots`. Under `workspace-write`, bwrap and Seatbelt added it to their writable roots, and WSL bound it into the distro at its translated path when the distro could reach it. A backend that ignores the field confines more narrowly, not more widely, so no dimension guards it.+- **Docs and skill.** The Settings (Sandbox), Tools & Approval (File tools), The Agent Loop (Hooks), Skills & Plugins (Hook packages), Core Interfaces and Server Boot and Subsystems pages described the three executors, the writable directories and the new seams. The `agent-initialization` skill said that a hook runs under the Session's sandbox, and its hooks reference listed the `sandbox:` failure.++## Not covered++- Memory and Agent State (`AGENTS.md`, `system_config.yaml`, the vault, Skills, hook packages, scheduled tasks) stayed outside the writable directories of both confining modes. A confined agent could not write memory, write its own Skills or hook packages, or change its configuration, and so could not add an MCP Server either; those took full access.+- A change the injected `penguin` CLI makes through the server API (a scheduled task, a plugin install) travels over the network, not the file system, so only the network level bounds it: under `none` that route is closed.+- The DSH adaptor passed DSH only the mode and the Workspace, so under DSH commands and hook scripts could not write the scratchpad.+- The WSL distro's default package list gained `nodejs`, which runs hook scripts and the file tools' helper; the confinement check reports whether it is there. A distro initialized before has to be initialized again — until then hooks and file operations fail under it instead of running unconfined.++## Compatibility++- A Session whose policy confines has its file tools and hook scripts confined from their next call, open conversations included, and its `stdio` MCP Servers from their next start (a context open or a reconnect); a Server that writes outside the writable directories or needs a network the level cuts no longer connects there. Writes to memory, Skills, hook packages and the agent's configuration are refused; switch a conversation that needs them to full access with its **Permissions** button. Nothing changes for a Session whose sandbox is off.+- Under DSH, hooks that write the scratchpad fail, goal mode's among them; under WSL, a distro initialized without `nodejs` fails every hook and file operation until it is initialized again, and a `stdio` Server runs only if its command exists in the distro. A conversation that needs them there runs with full access.+- SDK: `EnvironmentConfig.sandboxPolicy` and `CreateAgentOptions.sandboxPolicy` do not exist; `confineSpawn` is the one seam. Pass the former `timeoutS` and `pathPrepend` arguments of `scriptStopHook`, `scriptPreToolUseHook` and `scriptUserPromptHook` as the fourth argument, `{ timeoutS, pathPrepend }`.diff --git a/changelog/unreleased/2026-09-29-sandbox-hooks-and-file-tools.zh.md b/changelog/unreleased/2026-09-29-sandbox-hooks-and-file-tools.zh.mdnew file mode 100644index 00000000..00af352d--- /dev/null+++ b/changelog/unreleased/2026-09-29-sandbox-hooks-and-file-tools.zh.md@@ -0,0 +1,33 @@+# 沙盒约束钩子脚本、stdio MCP Server 与文件工具,scratchpad 可写++- **Date:** 2026-09-29+- **Type:** feature+- **Scope:** `core`, `server`, `plugins`, `docs`+- **PR:** [#893](https://github.com/Prism-Shadow/penguin-harness/pull/893)+- **Breaking:** yes — 封禁模式下,文件工具与钩子脚本和命令一样受约束,不能写记忆与 Agent State;`scriptStopHook` / `scriptPreToolUseHook` / `scriptUserPromptHook` 改为接受选项对象++[English](2026-09-29-sandbox-hooks-and-file-tools.md)++Session 的沙盒策略原先只约束 Agent 执行的命令,此次扩展到 Session 运行的钩子脚本、它以 `stdio` 方式启动的 MCP Server,以及文件工具 `read_file`、`edit_file` 与 `write_file`。`workspace-write` 下,Session 的 scratchpad(`<agent>/scratchpad/<session_id>`,计划文件、goal 的状态文件与附件都在这里)与 Workspace、临时目录一同可写,对三者同口径。++## 细节++- **一份策略,一条缝。** 策略仍是 Session 索引行上的 `SandboxSettings` 快照(模式、网络、屏蔽路径、临时目录可写),子会话沿用;它只经 `confineSpawn` 抵达 core,这条缝现在包裹 core 为 Session 拉起的一切:命令子进程、钩子脚本、`stdio` MCP Server 与文件工具的助手。confiner 对助手 argv 的回答同时决定该 Session 是否处于封禁:原样返回 argv(契约中「不封禁」的表达)即让文件工具留在进程内。+- **钩子脚本。** `runHookScript` 新增 `confine?: (argv) => ConfinedSpawn`,拉起它返回的 argv,并把运行器所需的环境项叠加在脚本的环境上。`scriptStopHook`、`scriptPreToolUseHook` 与 `scriptUserPromptHook` 改为接受选项对象 `ScriptHookOptions`:`timeoutS`、`pathPrepend`、每次运行都重读的 `confineSpawn` getter,以及 `scope: { workspaceDir, scratchpadDir }`,user-prompt 适配器另有 `trigger`。`Agent.sessionHooks` 把 Session 的 `confineSpawn` 与范围绑定到每条已安装的命令上,因此脚本以 `node <script>`、包目录为 cwd 的形式受封禁。`confineSpawn` 抛错时该次钩子失败,错误为 `sandbox: …`,与其他钩子失败一样记为 `hook failed: sandbox: …`;脚本不会运行。+- **stdio MCP Server。** `McpToolProviderOptions` 新增 `confineSpawn` 与 `scratchpadDir`,由 Environment 从自己的配置传入;`stdio` Server 的 `[command, ...args]` 在构建 transport 之前先经 confiner 改写,`cwd` 为该 Server 的工作目录、范围为 Session 的 Workspace 与 scratchpad,运行器要求的环境项叠加在 Server 自己的环境之上。confiner 抛错即该 Server 连接失败(`error_message` 带 `sandbox: …`),与其它连接失败同样上报,Server 不会启动。经 `http` / `sse` 访问的 Server 不是本机进程,不受影响。+- **文件工具。** `read_file`、`edit_file` 与 `write_file` 的每一次文件系统效果——stat、读取(含分块的文本窗口扫描)、原子写入、列目录、`realpath`、`readlink`、`mkdir`,以及 `read_file` 下载图片 URL——都改经一个端口执行(`environment/tools/fs-port.ts` 的 `FsPort`),以 `ToolExecutionContext.fs` 交给工具,首次使用时才解析,不碰文件的调用不会向 confiner 询问;`fs.sandboxed` 说明它是哪一个端口。未封禁的 Session 用本进程(`localFsPort`);封禁的 Session 用一个助手进程(`environment/tools/fs-worker.ts`):以 `node -e <程序>` 启动的 Node 进程——程序内联传入、只用内置模块,无需随 bundle 分发任何文件——其 argv 经 confiner 改写、范围为 Session 的 Workspace 与 scratchpad,以 stdin / stdout 上的 JSON 行提供各原语,二进制走 base64。每个 Session 一个助手(`SandboxedFsHost`):在第一次受封禁的文件操作时启动、此后复用,confiner 的回答变化或崩溃后重新启动,调用被中止时被杀掉(沙箱可能正卡住该操作),随 `Environment.dispose` 结束。错误的 `code` 原样跨越边界,工具的诊断不变;封禁 Session 下的权限错误(`EROFS` / `EACCES` / `EPERM`)报告为被沙箱拒绝。在为 Windows 宿主服务的 Linux 发行版内(WSL),盘符路径进入时映射为 `/mnt/<盘符>`,返回时还原。+- **scratchpad 交给后端。** `SpawnConfiner` 的选项新增 `scratchpadDir`,服务端的 `confinerFor` 把它放进插件契约新增的可选字段 `SandboxPolicy.writableRoots`。`workspace-write` 下,bwrap 与 Seatbelt 把它加入可写根,WSL 在发行版能访问它时按转换后的路径把它绑定进发行版。不实现该字段的后端只会约束得更窄,不会更宽,因此没有为它设隔离维度。+- **文档与 Skill。** 设置(沙盒)、工具与审批(文件工具)、Agent 运行循环(钩子)、技能与插件(钩子包)、核心接口以及 Server 启动与子系统各页描述了三类执行者、可写目录与新的接缝。`agent-initialization` Skill 写明钩子在 Session 的沙盒下运行,它的钩子参考列出了 `sandbox:` 失败。++## 未覆盖++- 记忆与 Agent State(`AGENTS.md`、`system_config.yaml`、vault、Skill、钩子包、定时任务)仍在两种封禁模式的可写目录之外。封禁中的 Agent 写不了记忆,不能自行编写 Skill 或钩子包,也改不了自己的配置,因此同样加不进 MCP Server;这些都需要完全访问。+- 注入的 `penguin` CLI 经服务端 API 所做的改动(定时任务、插件安装)走网络而非文件系统,只受网络档位约束:无网络档位下该路径随之关闭。+- DSH 适配器只把模式与 Workspace 交给 DSH,因此在 DSH 下,命令与钩子脚本写不了 scratchpad。+- WSL 发行版的默认软件包列表新增 `nodejs`,用来运行钩子脚本与文件工具的助手;隔离检查会报告它是否存在。此前初始化的发行版需要重新初始化——在那之前,钩子与文件操作在其下会失败,而不会脱离封禁运行。++## 兼容性++- 策略为封禁模式的 Session,其文件工具与钩子脚本从下一次调用起受约束,已打开的对话也不例外;其 `stdio` MCP Server 从下一次启动(上下文开启或重连)起受约束,必须写可写目录之外、或需要网络档位所切断的网络的 Server 在那里不再能连接。写记忆、Skill、钩子包与 Agent 配置会被拒绝;需要这些的对话,用它的**权限**按钮切到完全访问。沙盒关闭的 Session 不受影响。+- DSH 下,写 scratchpad 的钩子(包括目标模式的钩子)会失败;WSL 下,没有 `nodejs` 就初始化的发行版会让每个钩子与文件操作失败,直到重新初始化;`stdio` Server 只有命令在发行版里存在时才能运行。需要在这些后端上使用它们的对话,改用完全访问运行。+- SDK:不存在 `EnvironmentConfig.sandboxPolicy` 与 `CreateAgentOptions.sandboxPolicy`,`confineSpawn` 是唯一的缝。`scriptStopHook`、`scriptPreToolUseHook` 与 `scriptUserPromptHook` 原先的 `timeoutS` 与 `pathPrepend` 参数,改为以第四个参数 `{ timeoutS, pathPrepend }` 传入。diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.tsindex 162e331e..ee813473 100644--- a/packages/core/src/agent.ts+++ b/packages/core/src/agent.ts@@ -59,6 +59,7 @@ import {} from "./trace/index.js";import { Session } from "./session.js";import { scriptPreToolUseHook, scriptStopHook, scriptUserPromptHook } from "./hooks/script-hook.js";+import type { ScriptHookOptions } from "./hooks/script-hook.js";import type { HookSubagentRequest, SessionHooks } from "./hooks/stop-hook.js";import { predatesEveryPromptHooks, userPromptTrigger } from "./plugins/index.js";import type { SessionConfig, SessionOpenedContext } from "./session.js";@@ -906,7 +907,7 @@ export class Agent {trace,openNextContext: rt.openNextContext,// The first context's hooks; each context `openNextContext` opens brings its own.- hooks: this.sessionHooks(rt.subagentRunner, context.hookPackages),+ hooks: this.sessionHooks(rt.subagentRunner, context.hookPackages, spec),createBareLLM: rt.createBareLLM,compaction: context.compaction,@@ -1316,7 +1317,7 @@ export class Agent {sessionMeta: sessionMeta(next.meta),maxTurns: next.maxTurns ?? -1,compaction: next.compaction,- hooks: this.sessionHooks(subagentRunner, next.hookPackages),+ hooks: this.sessionHooks(subagentRunner, next.hookPackages, spec),};};@@ -1384,33 +1385,47 @@ export class Agent {* the context opens, which is how uninstalling the last package reaches a conversation* that is running. This is the one place a Session's hooks are assembled.*/- private sessionHooks(runner: SubagentRunner, installed: readonly InstalledHook[]): SessionHooks {- // Hook scripts get the same PATH front as commands do (see- // CreateAgentOptions.pathPrepend). Only the environment half applies: a hook is run as- // `node <script>` directly, with no shell and so no login profile to re-prepend- // anything after it.- const pathPrepend = this.pathPrepend;+ private sessionHooks(+ runner: SubagentRunner,+ installed: readonly InstalledHook[],+ spec: SessionSpec,+ ): SessionHooks {+ const { root, projectId, agentId } = this.state;+ const ctx: ControlEnvContext = { projectId, agentId, sessionId: spec.sessionId };+ // A hook script is spawned the way a command is: the same PATH front (see+ // CreateAgentOptions.pathPrepend — only the environment half applies, a hook is run+ // as `node <script>` with no shell to re-order PATH afterwards), and the same sandbox+ // (CreateAgentOptions.confineSpawn, bound to this Session's coordinates and re-read+ // at every run), with the Session's Workspace and scratchpad as its scope.+ const options: ScriptHookOptions = {+ ...(this.pathPrepend ? { pathPrepend: this.pathPrepend } : {}),+ ...(this.confineSpawn ? { confineSpawn: () => this.confineSpawn!(ctx) } : {}),+ scope: {+ workspaceDir: spec.workspaceDir,+ scratchpadDir: sessionScratchpadDir(root, projectId, agentId, spec.sessionId),+ },+ };+ const withTimeout = (timeoutS: number | undefined): ScriptHookOptions => ({+ ...options,+ ...(timeoutS !== undefined ? { timeoutS } : {}),+ });const stop = installed.flatMap((hook) =>hook.stop.map((cmd) =>- scriptStopHook(hook.name, hook.dir, cmd.command, cmd.timeout, pathPrepend),+ scriptStopHook(hook.name, hook.dir, cmd.command, withTimeout(cmd.timeout)),),);const preToolUse = installed.flatMap((hook) =>hook.pre_tool_use.map((cmd) =>- scriptPreToolUseHook(hook.name, hook.dir, cmd.command, cmd.timeout, pathPrepend),+ scriptPreToolUseHook(hook.name, hook.dir, cmd.command, withTimeout(cmd.timeout)),),);const userPrompt = installed.flatMap((hook) => {remindToUpdate(hook);return hook.user_prompt.map((cmd) =>- scriptUserPromptHook(- hook.name,- hook.dir,- cmd.command,- cmd.timeout,- pathPrepend,- userPromptTrigger(hook.version, cmd),- ),+ scriptUserPromptHook(hook.name, hook.dir, cmd.command, {+ ...withTimeout(cmd.timeout),+ trigger: userPromptTrigger(hook.version, cmd),+ }),);});return {diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.tsindex 74431a0f..3656a3fe 100644--- a/packages/core/src/environment/environment.ts+++ b/packages/core/src/environment/environment.ts@@ -42,6 +42,7 @@ import type {SubagentMessageOutcome,SubagentRunner,ThinkingLevelName,+ SpawnConfiner,ToolConfig,ToolDefinition,ToolDetachResult,@@ -50,6 +51,9 @@ import type {} from "../interfaces/index.js";import type { BuiltinTool, ToolResult } from "./tools/types.js";import { BUILTIN_TOOL_FACTORIES } from "./tools/registry.js";+import { SandboxedFsHost, fsWorkerArgv } from "./tools/fs-worker.js";+import { lazyToolFs, localFsPort } from "./tools/fs-port.js";+import type { ToolFs } from "./tools/fs-port.js";import { McpToolProvider } from "./mcp/provider.js";import { CommandSessionManager } from "./tools/command/index.js";import { ManagedSubagentSession, SubagentSessionManager } from "./tools/subagent/index.js";@@ -159,6 +163,12 @@ export class Environment implements EnvironmentInterface {private readonly subagentRunner: SubagentRunner | null;/** The runtime services every tool factory receives — Session-lifetime registries and sinks, so each context's toolset is assembled onto the same ones. */private readonly services: EnvironmentServices;+ /** The Session's scratchpad, writable beside the Workspace under a workspace-write policy. */+ private readonly sessionScratchpadDir: string | null;+ /** The Session's confiner getter (see EnvironmentConfig.confineSpawn), for the stdio MCP servers and the file helper this Environment starts; commands take it through their session manager. */+ private readonly confineSpawn: (() => SpawnConfiner | null) | undefined;+ /** The file tools' sandboxed helper (see tools/fs-worker.ts): started at the first confined file operation, kept for the Session, restarted when the confiner's answer changes. */+ private readonly fsHost = new SandboxedFsHost();constructor(config: EnvironmentConfig) {this.workspaceDir = config.workspaceDir;@@ -178,7 +188,12 @@ export class Environment implements EnvironmentInterface {...(config.pathPrepend !== undefined ? { pathPrepend: config.pathPrepend } : {}),...(config.confineSpawn !== undefined ? { confineSpawn: config.confineSpawn } : {}),workspaceDir: config.workspaceDir,+ ...(config.sessionScratchpadDir !== undefined+ ? { scratchpadDir: config.sessionScratchpadDir }+ : {}),});+ this.sessionScratchpadDir = config.sessionScratchpadDir ?? null;+ this.confineSpawn = config.confineSpawn;this.subagentSessions = new SubagentSessionManager();// Background-task liveness fans in from both registries and from the subagent run-state// pings: the host's background-state listener hears every change of "what is still@@ -228,10 +243,42 @@ export class Environment implements EnvironmentInterface {*/private newMcpProvider(servers: ToolConfig["mcpServers"]): McpToolProvider | null {return servers.length > 0- ? new McpToolProvider(servers, { workspaceDir: this.workspaceDir })+ ? new McpToolProvider(servers, {+ workspaceDir: this.workspaceDir,+ // A stdio server is started under the Session's sandbox like a command, with the+ // same confiner and scope (see McpToolProviderOptions.confineSpawn).+ ...(this.confineSpawn !== undefined ? { confineSpawn: this.confineSpawn } : {}),+ ...(this.sessionScratchpadDir !== null+ ? { scratchpadDir: this.sessionScratchpadDir }+ : {}),+ }): null;}+ /**+ * The port the file tools work through: the sandboxed helper's when the Session is+ * confined, this process's when it is not. The confiner is asked for the helper's argv at+ * every call that touches a file, like for a command at every spawn: an answer that+ * leaves the argv alone is the confiner's word for "unconfined" (see SpawnConfiner), and+ * the tools then work in this process; any other answer names the sandboxed helper to+ * work through, started from that very answer (see fs-worker.ts).+ */+ private fileSystem(): ToolFs {+ const confiner = this.confineSpawn?.() ?? null;+ if (confiner === null) return localFsPort;+ const argv = fsWorkerArgv();+ const confined = confiner(argv, {+ cwd: this.workspaceDir,+ workspaceDir: this.workspaceDir,+ ...(this.sessionScratchpadDir !== null ? { scratchpadDir: this.sessionScratchpadDir } : {}),+ });+ const unchanged =+ confined.env === undefined &&+ confined.argv.length === argv.length &&+ confined.argv.every((arg, i) => arg === argv[i]);+ return unchanged ? localFsPort : this.fsHost.portFor(confined);+ }+/*** Re-equips the Environment for a new model context (the composition layer calls it when a* compaction opens one): the toolset — builtin entries and MCP Servers — and the vault are@@ -262,7 +309,7 @@ export class Environment implements EnvironmentInterface {return this.mcp?.pendingServerNames() ?? [];}- /** Releases runtime resources held by Environment: finalizes all managed background sessions (command and subagent) and closes MCP clients (stdio server processes included). Idempotent. */+ /** Releases runtime resources held by Environment: finalizes all managed background sessions (command and subagent), closes MCP clients (stdio server processes included) and stops the file tools' sandboxed helper. Idempotent. */dispose(): void {// Suppress completion reports first: dispose kills the remaining background sessions, and// their exits must not masquerade as task completions after the Session has ended.@@ -272,6 +319,7 @@ export class Environment implements EnvironmentInterface {this.commandSessions.dispose();this.subagentSessions.dispose();this.mcp?.closeQuietly();+ this.fsHost.dispose();}// Background completion reports: a single listener (the owning Session), with events fired@@ -640,6 +688,9 @@ export class Environment implements EnvironmentInterface {toolCallId,signal: ac.signal,detachSignal: detachCtrl.signal,+ // The file system a file tool works through, decided from the Session's confiner+ // when the tool first touches a file (see fileSystem below).+ fs: lazyToolFs(() => this.fileSystem()),// Pass through the parent's approve callback (run_subagent uses it so the child Session// inherits the parent's approval mode; other tools ignore it)....(request.approve ? { approve: request.approve } : {}),diff --git a/packages/core/src/environment/index.ts b/packages/core/src/environment/index.tsindex f0f72f79..f4534c2f 100644--- a/packages/core/src/environment/index.ts+++ b/packages/core/src/environment/index.ts@@ -3,6 +3,8 @@*/export { Environment } from "./environment.js";export type { BuiltinTool, ToolExecutionContext } from "./tools/types.js";+export { localFsPort } from "./tools/fs-port.js";+export type { FsDirent, FsFetchResult, FsPort, FsStat } from "./tools/fs-port.js";export { BUILTIN_TOOL_FACTORIES } from "./tools/registry.js";export type { BuiltinToolFactory } from "./tools/registry.js";export { createReadFileTool, READ_FILE_NAME } from "./tools/read-file.js";diff --git a/packages/core/src/environment/mcp/provider.ts b/packages/core/src/environment/mcp/provider.tsindex 0d445298..185fc59b 100644--- a/packages/core/src/environment/mcp/provider.ts+++ b/packages/core/src/environment/mcp/provider.ts@@ -39,7 +39,13 @@ import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocimport { partialToolCallOutput } from "../../omnimessage/index.js";import type { McpServerConnectResult, OmniMessage } from "../../omnimessage/index.js";import { VERSION } from "../../index.js";-import type { MCPServerConfig, ToolDefinition, ToolPermission } from "../../interfaces/index.js";+import type {+ ConfinedSpawn,+ MCPServerConfig,+ SpawnConfiner,+ ToolDefinition,+ ToolPermission,+} from "../../interfaces/index.js";import type { BuiltinTool, ToolResult } from "../tools/types.js";import { resolveMCPServers, type ResolvedMCPServer } from "./config.js";@@ -83,6 +89,16 @@ function clientInfo(): { name: string; version: string } {export interface McpToolProviderOptions {/** Session Workspace: the default working directory for stdio server processes. */workspaceDir?: string;+ /**+ * The Session's sandbox (see {@link EnvironmentConfig.confineSpawn}): a stdio server is a+ * process the harness starts for the Session, so its argv goes through the same confiner+ * a command's does, re-read at every start. A confiner that cannot enforce the policy+ * fails that server's connect — reported like any other connect failure — and the server+ * never starts unconfined. Absent, or a getter returning null = servers start unconfined.+ */+ confineSpawn?: () => SpawnConfiner | null;+ /** The Session's scratchpad, the confiner's scope beside the Workspace. */+ scratchpadDir?: string;/** Warning sink; defaults to a `[penguin]`-prefixed stderr line. */warn?: (message: string) => void;}@@ -163,6 +179,8 @@ export class McpToolProvider {private servers: ResolvedMCPServer[];private configWarnings: string[];private readonly workspaceDir: string | undefined;+ private readonly confineSpawn: (() => SpawnConfiner | null) | undefined;+ private readonly scratchpadDir: string | undefined;private readonly warn: (message: string) => void;/** Single-flight connect+discovery of the servers still pending; resolved results live in the fields below. */private ensurePromise: Promise<void> | null = null;@@ -184,6 +202,8 @@ export class McpToolProvider {this.servers = resolved.servers;this.configWarnings = resolved.warnings;this.workspaceDir = options?.workspaceDir;+ this.confineSpawn = options?.confineSpawn;+ this.scratchpadDir = options?.scratchpadDir;this.warn = options?.warn ?? ((message) => process.stderr.write(`[penguin] ${message}\n`));}@@ -389,9 +409,16 @@ export class McpToolProvider {let transport: Transport;const t = server.transport;if (t.kind === "stdio") {+ const cwd = t.cwd ?? this.workspaceDir;+ // The server's argv under the Session's sandbox, exactly as a command's: confined+ // before anything starts, so a policy nothing can enforce is this server's connect+ // failure and not a server running outside the sandbox.+ const confined = this.confine([t.command, ...t.args], cwd);+ const [command, ...args] = confined.argv;+ if (command === undefined) throw new Error("sandbox: the confiner returned an empty argv");const stdio = new StdioClientTransport({- command: t.command,- args: t.args,+ command,+ args,// Safe inherited defaults plus the entry's own env — and nothing else: the Agent// vault is deliberately NOT injected into MCP server processes (unlike command// subprocesses); a variable a server needs must be listed in the entry's env.@@ -399,11 +426,10 @@ export class McpToolProvider {// harness's own configuration — every PENGUIN_* variable, PORT/HOST and the rest —// never reaches a server: the same outcome the command-session strip enforces,// by the opposite mechanism. Widening this base (e.g. to process.env) would undo- // that; the "harness variables never reach a stdio server" test pins it.- env: { ...getDefaultEnvironment(), ...t.env },- ...(t.cwd !== undefined || this.workspaceDir !== undefined- ? { cwd: t.cwd ?? this.workspaceDir }- : {}),+ // that; the "harness variables never reach a stdio server" test pins it. A+ // sandbox runner's own entries lie over the result.+ env: { ...getDefaultEnvironment(), ...t.env, ...confined.env },+ ...(cwd !== undefined ? { cwd } : {}),stderr: "pipe",});// The tail makes spawn/startup failures diagnosable ("command not found", stack@@ -454,6 +480,26 @@ export class McpToolProvider {}}+ /**+ * The argv a stdio server is started with under the Session's sandbox: the confiner's+ * answer, with the server's working directory as `cwd` and the Session's Workspace and+ * scratchpad as scope; the argv itself when the Session has no confiner. A throw is the+ * server's connect failure.+ */+ private confine(argv: readonly string[], cwd: string | undefined): ConfinedSpawn {+ const confiner = this.confineSpawn?.() ?? null;+ if (confiner === null) return { argv };+ try {+ return confiner(argv, {+ cwd: cwd ?? process.cwd(),+ workspaceDir: this.workspaceDir ?? cwd ?? process.cwd(),+ ...(this.scratchpadDir !== undefined ? { scratchpadDir: this.scratchpadDir } : {}),+ });+ } catch (err) {+ throw new Error(`sandbox: ${describeError(err)}`);+ }+ }+/** Builds the executable wrapper of one discovered tool; null when it cannot join the toolset (skips are warned, never thrown). `seen` holds the names already taken on this server. */private wrap(server: ResolvedMCPServer,diff --git a/packages/core/src/environment/tools/command/session-manager.ts b/packages/core/src/environment/tools/command/session-manager.tsindex e2bd9db3..de99069d 100644--- a/packages/core/src/environment/tools/command/session-manager.ts+++ b/packages/core/src/environment/tools/command/session-manager.ts@@ -236,6 +236,8 @@ export class CommandSessionManager {* those fall back to the spawn cwd.*/private readonly workspaceDir: string | undefined;+ /** The Session's scratchpad, bound into every confiner call as `opts.scratchpadDir`: writable beside the Workspace under a workspace-write policy. */+ private readonly scratchpadDir: string | undefined;constructor(opts?: {vault?: Record<string, string>;@@ -244,6 +246,7 @@ export class CommandSessionManager {pathPrepend?: () => string[];confineSpawn?: () => SpawnConfiner | null;workspaceDir?: string;+ scratchpadDir?: string;}) {this.vault = opts?.vault ?? {};this.proxyEnv = opts?.proxyEnv;@@ -251,6 +254,7 @@ export class CommandSessionManager {this.pathPrepend = opts?.pathPrepend;this.confineSpawn = opts?.confineSpawn;this.workspaceDir = opts?.workspaceDir;+ this.scratchpadDir = opts?.scratchpadDir;this.registry.onChange(() => this.changeListener?.());}@@ -295,7 +299,11 @@ export class CommandSessionManager {...(confiner !== null? {confine: (argv: readonly string[], o: { cwd: string }) =>- confiner(argv, { cwd: o.cwd, workspaceDir: this.workspaceDir ?? o.cwd }),+ confiner(argv, {+ cwd: o.cwd,+ workspaceDir: this.workspaceDir ?? o.cwd,+ ...(this.scratchpadDir !== undefined ? { scratchpadDir: this.scratchpadDir } : {}),+ }),}: {}),// Spread order is priority: vault overrides host variables of the same name; thediff --git a/packages/core/src/environment/tools/edit-file.ts b/packages/core/src/environment/tools/edit-file.tsindex e193aaeb..7fbea1d8 100644--- a/packages/core/src/environment/tools/edit-file.ts+++ b/packages/core/src/environment/tools/edit-file.ts@@ -24,13 +24,13 @@* Docs: /docs/tools § "File tools".*/import path from "node:path";-import { readFile, stat } from "node:fs/promises";import { partialToolCallOutput } from "../../omnimessage/index.js";import type { OmniMessage } from "../../omnimessage/index.js";import type { ToolDefinitionConfig } from "../../interfaces/index.js";import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";-import { atomicWriteFile } from "../../internal/atomic-write.js";import { fileLockKey, withFileLock } from "../../internal/file-lock.js";+import { describeFsError, errorCode, localFsPort } from "./fs-port.js";+import type { FsPort } from "./fs-port.js";import { buildReplacementHunks, renderHunk } from "./diff.js";import { missingPathHint } from "./path-hint.js";import { describeArgumentError } from "./tool-arguments.js";@@ -76,32 +76,37 @@ async function applyEdit(params: {oldString: string;newString: string;replaceAll: boolean;+ /** The file system to work through (see fs-port.ts), and whether it is the sandboxed helper. */+ fs: FsPort;+ sandboxed: boolean;signal?: AbortSignal;}): Promise<EditOutcome> {- const { resolved, filePath, oldString, newString, replaceAll, signal } = params;+ const { resolved, filePath, oldString, newString, replaceAll, fs, sandboxed, signal } = params;let content: string;let fileMode: number | undefined;try {- const st = await stat(resolved);- if (st.isDirectory()) {+ const st = await fs.stat(resolved);+ if (st.isDirectory) {return { kind: "fatal", text: `Cannot edit "${filePath}": it is a directory.` };}fileMode = st.mode & 0o777;- content = await readFile(resolved, { encoding: "utf8", ...(signal ? { signal } : {}) });+ content = (await fs.readFile(resolved)).toString("utf8");} catch (err) {if (signal?.aborted) return { kind: "aborted" };- const code = (err as NodeJS.ErrnoException).code;+ const code = errorCode(err);// ENOTDIR is the same mistake seen one segment later (a file used as a directory),// so it gets the same diagnosis instead of a raw errno message.if (code === "ENOENT" || code === "ENOTDIR") {- const hint = await missingPathHint(resolved);+ const hint = await missingPathHint(resolved, fs);return {kind: "fatal",text: `File not found: "${filePath}". edit_file only edits existing files — check the path (absolute paths are supported), or use write_file to create it.${hint}`,};}- const message = err instanceof Error ? err.message : String(err);- return { kind: "fatal", text: `Failed to read "${filePath}": ${message}` };+ return {+ kind: "fatal",+ text: `Failed to read "${filePath}": ${describeFsError(err, sandboxed)}`,+ };}if (signal?.aborted) return { kind: "aborted" };@@ -129,15 +134,16 @@ async function applyEdit(params: {? content.split(oldString).join(newString): content.slice(0, replaceStart) + newString + content.slice(replaceStart + oldString.length);try {- await atomicWriteFile(resolved, newContent, {+ await fs.writeFileAtomic(resolved, Buffer.from(newContent, "utf8"), {...(fileMode !== undefined ? { mode: fileMode } : {}),- ...(signal ? { signal } : {}),followSymlinks: true,});} catch (err) {if (signal?.aborted) return { kind: "aborted" };- const message = err instanceof Error ? err.message : String(err);- return { kind: "fatal", text: `Failed to write "${filePath}": ${message}` };+ return {+ kind: "fatal",+ text: `Failed to write "${filePath}": ${describeFsError(err, sandboxed)}`,+ };}return { kind: "ok", content, replaced: replaceAll ? occurrences : 1 };@@ -204,13 +210,27 @@ export function createEditFileTool(definition: ToolDefinitionConfig): BuiltinTooconst replaceAll = args["replace_all"] === true;const resolved = path.resolve(ctx.workspaceDir, filePath);+ // Every file-system effect goes through the Session's port: its sandboxed helper+ // when the Session is confined, this process otherwise (see fs-port.ts).+ const fs = ctx.fs ?? localFsPort;+ const { sandboxed } = fs;// One file, one writer at a time: the read and the write that follows it are a single// critical section, so a concurrent edit lands entirely before or entirely after this// one instead of being overwritten by it.const key = await fileLockKey(resolved);const outcome = await withFileLock(key,- () => applyEdit({ resolved, filePath, oldString, newString, replaceAll, signal }),+ () =>+ applyEdit({+ resolved,+ filePath,+ oldString,+ newString,+ replaceAll,+ fs,+ sandboxed,+ signal,+ }),signal,).catch((err: unknown): EditOutcome => {// Interrupted while queued behind another writer on the same file — the samediff --git a/packages/core/src/environment/tools/fs-port.ts b/packages/core/src/environment/tools/fs-port.tsnew file mode 100644index 00000000..99dda7ea--- /dev/null+++ b/packages/core/src/environment/tools/fs-port.ts@@ -0,0 +1,175 @@+/**+ * The file-system port of the file tools. read_file, edit_file and write_file do their+ * file-system work through this interface rather than through `node:fs` directly, so that+ * the same tool code runs against two implementations: the harness process itself+ * (`localFsPort`), and a helper process the Session's sandbox confines exactly as it+ * confines a command (see fs-worker.ts). Which one a call gets is the Environment's+ * decision, made from the Session's confiner at every call: an unconfined Session works+ * in-process, a confined one through the helper.+ *+ * The surface is the handful of primitives the three tools need, spelled so both sides+ * can carry them over a JSON line: plain stat facts instead of a `Stats` object, bytes+ * instead of file handles, a fetch that answers with the body already read. Errors keep+ * their `code` (ENOENT, EISDIR, EROFS…) on both sides, since the tools diagnose from it.+ */+import path from "node:path";+import { mkdir, open, readdir, readFile, readlink, realpath, stat } from "node:fs/promises";+import { atomicWriteFile } from "../../internal/atomic-write.js";++export interface FsStat {+ isFile: boolean;+ isDirectory: boolean;+ size: number;+ /** The permission bits, for an overwrite that keeps them. */+ mode: number;+}++export interface FsDirent {+ name: string;+ isFile: boolean;+ isDirectory: boolean;+}++/** What a URL read comes back with: the response's status and type, and its whole body. */+export interface FsFetchResult {+ ok: boolean;+ status: number;+ contentType: string | null;+ bytes: Buffer;+}++export interface FsPort {+ stat(target: string): Promise<FsStat>;+ /** The whole file; the caller has checked the size. */+ readFile(target: string): Promise<Buffer>;+ /** Up to `length` bytes from `position`; fewer at the end of the file, none past it. */+ readRange(target: string, position: number, length: number): Promise<Buffer>;+ readdir(target: string): Promise<FsDirent[]>;+ realpath(target: string): Promise<string>;+ readlink(target: string): Promise<string>;+ /** Creates the directory and its missing parents. */+ mkdir(target: string): Promise<void>;+ /** Writes atomically (temp file + rename); `followSymlinks` lands the content where a link points (see atomic-write.ts). */+ writeFileAtomic(+ target: string,+ content: Buffer,+ opts: { mode?: number; followSymlinks?: boolean },+ ): Promise<void>;+ /** Downloads `url` whole; `maxBytes` caps the body, a declared or actual size beyond it rejects with code `ETOOBIG`. */+ fetch(url: string, opts: { maxBytes: number; signal?: AbortSignal }): Promise<FsFetchResult>;+}++/** The port a file tool works through: the primitives, and whether they run in the sandboxed helper — which decides how a refused effect is worded. */+export interface ToolFs extends FsPort {+ readonly sandboxed: boolean;+}++/** The port over this process's own file system: what an unconfined Session works through. */+export const localFsPort: ToolFs = {+ sandboxed: false,+ async stat(target) {+ const st = await stat(target);+ return { isFile: st.isFile(), isDirectory: st.isDirectory(), size: st.size, mode: st.mode };+ },+ readFile: (target) => readFile(target),+ async readRange(target, position, length) {+ const fd = await open(target, "r");+ try {+ const buf = Buffer.alloc(length);+ const { bytesRead } = await fd.read(buf, 0, length, position);+ return buf.subarray(0, bytesRead);+ } finally {+ await fd.close();+ }+ },+ async readdir(target) {+ const entries = await readdir(target, { withFileTypes: true });+ return entries.map((e) => ({ name: e.name, isFile: e.isFile(), isDirectory: e.isDirectory() }));+ },+ realpath: (target) => realpath(target),+ readlink: (target) => readlink(target),+ async mkdir(target) {+ await mkdir(target, { recursive: true });+ },+ writeFileAtomic: (target, content, opts) => atomicWriteFile(target, content, opts),+ async fetch(url, opts) {+ const res = await fetch(url, opts.signal ? { signal: opts.signal } : {});+ const declared = Number(res.headers.get("content-length") ?? "");+ if (Number.isFinite(declared) && declared > opts.maxBytes) throw tooBig(declared);+ const bytes = Buffer.from(await res.arrayBuffer());+ if (bytes.length > opts.maxBytes) throw tooBig(bytes.length);+ return { ok: res.ok, status: res.status, contentType: res.headers.get("content-type"), bytes };+ },+};++/**+ * A port that decides which port it is on first use: the Environment hands every tool call+ * one of these, and only a tool that touches a file — the first `sandboxed` read or+ * primitive — makes it ask the Session's confiner, so a command or an MCP call never+ * consults the confiner on the file tools' behalf. What `resolve` throws (a policy no+ * backend can enforce) surfaces from that first use, as the tool's failure.+ */+export function lazyToolFs(resolve: () => ToolFs): ToolFs {+ let resolved: ToolFs | null = null;+ const get = (): ToolFs => (resolved ??= resolve());+ return {+ get sandboxed() {+ return get().sandboxed;+ },+ stat: (target) => get().stat(target),+ readFile: (target) => get().readFile(target),+ readRange: (target, position, length) => get().readRange(target, position, length),+ readdir: (target) => get().readdir(target),+ realpath: (target) => get().realpath(target),+ readlink: (target) => get().readlink(target),+ mkdir: (target) => get().mkdir(target),+ writeFileAtomic: (target, content, opts) => get().writeFileAtomic(target, content, opts),+ fetch: (url, opts) => get().fetch(url, opts),+ };+}++/** The error a fetch past `maxBytes` rejects with: `size` is what was declared or read. */+export function tooBig(size: number): Error & { code: string; size: number } {+ return Object.assign(new Error(`response body of ${size} bytes exceeds the limit`), {+ code: "ETOOBIG",+ size,+ });+}++/** The `code` of a file-system error, or undefined. */+export function errorCode(err: unknown): string | undefined {+ const code = (err as { code?: unknown } | null)?.code;+ return typeof code === "string" ? code : undefined;+}++/**+ * An error as a tool reports it. Under a confining sandbox the kernel answers a refused+ * effect with a permission error the model would otherwise read as the file's own — so+ * when the port is the sandboxed one, those codes name the sandbox.+ */+export function describeFsError(err: unknown, sandboxed: boolean): string {+ const message = err instanceof Error ? err.message : String(err);+ const code = errorCode(err);+ if (sandboxed && (code === "EROFS" || code === "EACCES" || code === "EPERM")) {+ return `${message} — refused by this session's sandbox, which does not allow that here.`;+ }+ return message;+}++/** The path the write aimed at `target` lands on: the end of its symlink chain, through the port. */+export async function resolveWriteTargetThrough(fs: FsPort, target: string): Promise<string> {+ let current = target;+ for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop += 1) {+ let link: string;+ try {+ link = await fs.readlink(current);+ } catch {+ return current;+ }+ current = path.resolve(path.dirname(current), link);+ }+ return current;+}++/** Symlink hops followed before a chain is called a loop (mirrors atomic-write.ts). */+const MAX_SYMLINK_HOPS = 40;diff --git a/packages/core/src/environment/tools/fs-worker.ts b/packages/core/src/environment/tools/fs-worker.tsnew file mode 100644index 00000000..2368c17e--- /dev/null+++ b/packages/core/src/environment/tools/fs-worker.ts@@ -0,0 +1,350 @@+/**+ * The file tools' sandboxed helper: a Node process the Session's sandbox confines exactly+ * as it confines a command, serving the {@link FsPort} primitives over one JSON line per+ * request on stdin and one per answer on stdout (binary as base64). Every file-system+ * effect of read_file, edit_file and write_file happens inside it when a Session is+ * confined, so the backend that bounds the Session's commands bounds its file tools too —+ * one policy, one enforcer, and nothing for the harness to re-implement.+ *+ * The helper's program travels as a `-e` argument, so no file has to be shipped beside any+ * bundle that inlines core; it uses only builtin modules and syntax an older Node in a+ * sandbox distro understands. One helper serves a Session, started at its first confined+ * file operation and kept for the next ones; it is started over when the confiner's answer+ * changes (the policy was edited), after a crash, and after an abort, which kills it so an+ * operation the sandbox is stalling cannot outlive the call.+ *+ * Paths cross as the host spells them. Inside a Linux distro serving a Windows host (the+ * WSL backend), a drive path is mapped to its `/mnt/<drive>` spelling on the way in and+ * back on the way out, so the tools never see the distro's view.+ */+import { spawn } from "node:child_process";+import type { ChildProcess } from "node:child_process";+import readline from "node:readline";+import type { ConfinedSpawn } from "../../interfaces/index.js";+import type { FsDirent, FsFetchResult, FsStat, ToolFs } from "./fs-port.js";++/**+ * The helper's program (CommonJS, builtin modules only — the same shape a hook script+ * has). Ops answer with JSON-serializable results; buffers travel base64. Windows drive+ * paths are mapped for a Linux distro and unmapped in answers that carry paths.+ */+export const FS_WORKER_SOURCE = String.raw`+const fs = require("node:fs/promises");+const path = require("node:path");+const readline = require("node:readline");+const linux = process.platform !== "win32";+const DRIVE = /^([A-Za-z]):[\\/](.*)$/;+function toLocal(p) {+ const m = linux ? DRIVE.exec(p) : null;+ if (!m) return p;+ const rest = m[2].split(/[\\/]+/).filter(Boolean);+ return ["/mnt/" + m[1].toLowerCase()].concat(rest).join("/");+}+function fromLocal(p, like) {+ if (!linux || !DRIVE.test(like)) return p;+ const m = /^\/mnt\/([a-z])(?:\/(.*))?$/.exec(p);+ if (!m) return p;+ return m[1].toUpperCase() + ":\\" + (m[2] || "").split("/").join("\\");+}+async function writeAtomic(target, content, mode, followSymlinks) {+ let dest = target;+ if (followSymlinks) {+ for (let hop = 0; hop < 40; hop += 1) {+ let link;+ try {+ link = await fs.readlink(dest);+ } catch {+ break;+ }+ dest = path.resolve(path.dirname(dest), link);+ }+ }+ const tmp = path.join(+ path.dirname(dest),+ "." + path.basename(dest) + ".tmp-" + process.pid + "-" + Math.random().toString(36).slice(2, 8),+ );+ try {+ await fs.writeFile(tmp, content, mode === undefined ? { flush: true } : { mode, flush: true });+ if (mode !== undefined) await fs.chmod(tmp, mode);+ await fs.rename(tmp, dest);+ } catch (err) {+ await fs.rm(tmp, { force: true }).catch(() => undefined);+ throw err;+ }+}+const ops = {+ async stat({ p }) {+ const s = await fs.stat(toLocal(p));+ return { isFile: s.isFile(), isDirectory: s.isDirectory(), size: s.size, mode: s.mode };+ },+ async readFile({ p }) {+ return (await fs.readFile(toLocal(p))).toString("base64");+ },+ async readRange({ p, position, length }) {+ const fh = await fs.open(toLocal(p), "r");+ try {+ const buf = Buffer.alloc(length);+ const { bytesRead } = await fh.read(buf, 0, length, position);+ return buf.subarray(0, bytesRead).toString("base64");+ } finally {+ await fh.close();+ }+ },+ async readdir({ p }) {+ const entries = await fs.readdir(toLocal(p), { withFileTypes: true });+ return entries.map((e) => ({ name: e.name, isFile: e.isFile(), isDirectory: e.isDirectory() }));+ },+ async realpath({ p }) {+ return fromLocal(await fs.realpath(toLocal(p)), p);+ },+ async readlink({ p }) {+ return fromLocal(await fs.readlink(toLocal(p)), p);+ },+ async mkdir({ p }) {+ await fs.mkdir(toLocal(p), { recursive: true });+ },+ async writeFileAtomic({ p, content, mode, followSymlinks }) {+ await writeAtomic(toLocal(p), Buffer.from(content, "base64"), mode, followSymlinks === true);+ },+ async fetch({ url, maxBytes }) {+ const res = await fetch(url);+ const declared = Number(res.headers.get("content-length") || "");+ if (Number.isFinite(declared) && declared > maxBytes) {+ throw Object.assign(new Error("response body of " + declared + " bytes exceeds the limit"), { code: "ETOOBIG", size: declared });+ }+ const bytes = Buffer.from(await res.arrayBuffer());+ if (bytes.length > maxBytes) {+ throw Object.assign(new Error("response body of " + bytes.length + " bytes exceeds the limit"), { code: "ETOOBIG", size: bytes.length });+ }+ return { ok: res.ok, status: res.status, contentType: res.headers.get("content-type"), bytes: bytes.toString("base64") };+ },+};+const out = (msg) => process.stdout.write(JSON.stringify(msg) + "\n");+readline.createInterface({ input: process.stdin, terminal: false }).on("line", (line) => {+ let req;+ try {+ req = JSON.parse(line);+ } catch {+ return;+ }+ const op = ops[req.op];+ if (!op) {+ out({ id: req.id, ok: false, error: { code: "ENOSYS", message: "unknown op " + req.op } });+ return;+ }+ op(req.args || {}).then(+ (result) => out({ id: req.id, ok: true, result: result === undefined ? null : result }),+ (err) => out({ id: req.id, ok: false, error: { code: err && err.code, message: err && err.message ? err.message : String(err), size: err && err.size } }),+ );+});+process.stdin.on("end", () => process.exit(0));+`;++/** The argv the helper is spawned as, before the confiner rewrites it. */+export function fsWorkerArgv(): string[] {+ return [process.execPath, "-e", FS_WORKER_SOURCE];+}++interface Pending {+ resolve: (value: unknown) => void;+ reject: (err: Error) => void;+}++/** One running helper: the confiner's answer it was started from, its process and the requests in flight. */+interface Worker {+ key: string;+ child: ChildProcess;+ pending: Map<number, Pending>;+ exited: boolean;+}++/**+ * The Session's helper, started on demand and kept until `dispose`. `portFor` answers a+ * port over the helper the confiner's answer describes, starting one when none runs or the+ * running one was started from a different answer.+ */+export class SandboxedFsHost {+ private worker: Worker | null = null;+ private nextId = 1;+ private disposed = false;++ constructor(private readonly spawnWorker: (spawn: ConfinedSpawn) => ChildProcess = start) {}++ /** A port over a helper started from `confined` (the confiner's answer for the helper argv). */+ portFor(confined: ConfinedSpawn): ToolFs {+ const key = JSON.stringify([confined.argv, confined.env ?? null]);+ const request = (op: string, args: Record<string, unknown>, signal?: AbortSignal) =>+ this.request(key, confined, op, args, signal);+ const buffer = async (op: string, args: Record<string, unknown>): Promise<Buffer> =>+ Buffer.from((await request(op, args)) as string, "base64");+ return {+ sandboxed: true,+ stat: (p) => request("stat", { p }) as Promise<FsStat>,+ readFile: (p) => buffer("readFile", { p }),+ readRange: (p, position, length) => buffer("readRange", { p, position, length }),+ readdir: (p) => request("readdir", { p }) as Promise<FsDirent[]>,+ realpath: (p) => request("realpath", { p }) as Promise<string>,+ readlink: (p) => request("readlink", { p }) as Promise<string>,+ mkdir: async (p) => {+ await request("mkdir", { p });+ },+ writeFileAtomic: async (p, content, opts) => {+ await request("writeFileAtomic", {+ p,+ content: content.toString("base64"),+ ...(opts.mode !== undefined ? { mode: opts.mode } : {}),+ ...(opts.followSymlinks !== undefined ? { followSymlinks: opts.followSymlinks } : {}),+ });+ },+ fetch: async (url, opts) => {+ const answer = (await request("fetch", { url, maxBytes: opts.maxBytes }, opts.signal)) as {+ ok: boolean;+ status: number;+ contentType: string | null;+ bytes: string;+ };+ return { ...answer, bytes: Buffer.from(answer.bytes, "base64") } satisfies FsFetchResult;+ },+ };+ }++ /** Whether a helper is running right now (for tests and diagnostics). */+ get running(): boolean {+ return this.worker !== null && !this.worker.exited;+ }++ /** Stops the helper; the next port request starts a fresh one. */+ dispose(): void {+ this.disposed = true;+ this.stop(new Error("the file helper was disposed"));+ }++ private request(+ key: string,+ confined: ConfinedSpawn,+ op: string,+ args: Record<string, unknown>,+ signal?: AbortSignal,+ ): Promise<unknown> {+ if (this.disposed) return Promise.reject(new Error("the file helper was disposed"));+ if (signal?.aborted) return Promise.reject(abortError());+ const worker = this.ensure(key, confined);+ const id = this.nextId++;+ return new Promise<unknown>((resolve, reject) => {+ const onAbort = (): void => {+ // The sandbox may be stalling the operation; the helper goes with the call.+ this.stop(abortError());+ };+ signal?.addEventListener("abort", onAbort, { once: true });+ worker.pending.set(id, {+ resolve: (value) => {+ signal?.removeEventListener("abort", onAbort);+ resolve(value);+ },+ reject: (err) => {+ signal?.removeEventListener("abort", onAbort);+ reject(err);+ },+ });+ worker.child.stdin!.write(`${JSON.stringify({ id, op, args })}\n`, (err) => {+ if (err) this.settle(worker, id, { ok: false, error: { message: err.message } });+ });+ });+ }++ /** The running helper for `key`, or a fresh one — the previous one, started from another answer or exited, is stopped. */+ private ensure(key: string, confined: ConfinedSpawn): Worker {+ if (this.worker !== null && (this.worker.key !== key || this.worker.exited)) {+ this.stop(new Error("the file helper was restarted"));+ }+ if (this.worker !== null) return this.worker;+ const child = this.spawnWorker(confined);+ const worker: Worker = { key, child, pending: new Map(), exited: false };+ let stderr = "";+ child.stderr?.setEncoding("utf8").on("data", (chunk: string) => {+ stderr = (stderr + chunk).slice(-2048);+ });+ readline.createInterface({ input: child.stdout!, terminal: false }).on("line", (line) => {+ let msg: { id?: number; ok?: boolean; result?: unknown; error?: WireError };+ try {+ msg = JSON.parse(line) as typeof msg;+ } catch {+ return;+ }+ if (typeof msg.id === "number") this.settle(worker, msg.id, msg);+ });+ const onGone = (reason: string): void => {+ if (worker.exited) return;+ worker.exited = true;+ const tail = stderr.trim();+ const err = new Error(tail ? `${reason}: ${tail}` : reason);+ for (const p of worker.pending.values()) p.reject(err);+ worker.pending.clear();+ if (this.worker === worker) this.worker = null;+ };+ child.on("error", (err) => onGone(`sandbox: the file helper could not start (${err.message})`));+ child.on("close", (code, signal) =>+ onGone(`sandbox: the file helper exited (${signal ?? `code ${code}`})`),+ );+ child.stdin?.on("error", () => {+ // A helper that died mid-write closes the pipe; `close` above reports it.+ });+ this.worker = worker;+ return worker;+ }++ /** Answers one request from the helper's reply. */+ private settle(+ worker: Worker,+ id: number,+ msg: { ok?: boolean; result?: unknown; error?: WireError },+ ): void {+ const pending = worker.pending.get(id);+ if (!pending) return;+ worker.pending.delete(id);+ if (msg.ok) {+ pending.resolve(msg.result);+ return;+ }+ const error = msg.error ?? {};+ pending.reject(+ Object.assign(new Error(error.message ?? "the file helper failed"), {+ ...(error.code !== undefined && error.code !== null ? { code: error.code } : {}),+ ...(error.size !== undefined && error.size !== null ? { size: error.size } : {}),+ }),+ );+ }++ /** Kills the helper and fails what it still owed. */+ private stop(reason: Error): void {+ const worker = this.worker;+ if (worker === null) return;+ this.worker = null;+ if (!worker.exited) {+ worker.exited = true;+ worker.child.kill("SIGKILL");+ }+ for (const p of worker.pending.values()) p.reject(reason);+ worker.pending.clear();+ }+}++interface WireError {+ code?: string | null;+ message?: string;+ size?: number | null;+}++function abortError(): Error {+ return Object.assign(new Error("aborted"), { name: "AbortError" });+}++/** Spawns the helper from the confiner's answer: the runner's entries over an environment that runs the desktop app's binary as Node. */+function start(confined: ConfinedSpawn): ChildProcess {+ const [program, ...args] = confined.argv;+ if (program === undefined) throw new Error("sandbox: the confiner returned an empty argv");+ return spawn(program, args, {+ stdio: ["pipe", "pipe", "pipe"],+ env: { ...process.env, ELECTRON_RUN_AS_NODE: "1", ...confined.env },+ });+}diff --git a/packages/core/src/environment/tools/image-source.ts b/packages/core/src/environment/tools/image-source.tsindex bd4d6f69..fe91b602 100644--- a/packages/core/src/environment/tools/image-source.ts+++ b/packages/core/src/environment/tools/image-source.ts@@ -8,7 +8,8 @@* bytes is still handed over as an image rather than dumped as text.*/import path from "node:path";-import { open, readFile, stat } from "node:fs/promises";+import { describeFsError, errorCode, localFsPort } from "./fs-port.js";+import type { FsPort } from "./fs-port.js";/*** Image size upper bound (bytes): errors out above this. Taken as the common denominator of@@ -69,24 +70,17 @@ export function isHttpUrl(source: string): boolean {* file that cannot be opened is judged by extension alone — the caller's own read reports* the error afterwards.*/-export async function looksLikeImageFile(filePath: string): Promise<boolean> {- let fd;+export async function looksLikeImageFile(+ filePath: string,+ fs: FsPort = localFsPort,+): Promise<boolean> {+ let head: Buffer;try {- fd = await open(filePath, "r");+ head = await fs.readRange(filePath, 0, SNIFF_BYTES);} catch {return imageMimeFromExt(filePath) !== null;}- try {- const head = Buffer.alloc(SNIFF_BYTES);- const { bytesRead } = await fd.read(head, 0, SNIFF_BYTES, 0);- return (- sniffImageMime(head.subarray(0, bytesRead)) !== null || imageMimeFromExt(filePath) !== null- );- } catch {- return imageMimeFromExt(filePath) !== null;- } finally {- await fd.close();- }+ return sniffImageMime(head) !== null || imageMimeFromExt(filePath) !== null;}/** Byte count -> human-readable size (B / kB / MB, one decimal place). */@@ -118,25 +112,35 @@ export async function loadImage(source: string,workspaceDir: string,signal?: AbortSignal,+ /** The file system (and network) to work through — the Session's sandboxed helper when confined (see fs-port.ts). */+ fs: FsPort = localFsPort,+ sandboxed = false,): Promise<LoadImageResult> {if (signal?.aborted) return { ok: false, reason: "aborted" };let bytes: Buffer;let mime: string | null;if (isHttpUrl(source)) {- // URL branch: downloads via the global fetch (abort signal passed through to the request);- // mime is preferentially taken from the response header, falling back to magic number / URL- // extension.- let res: Response;+ // URL branch: downloaded through the port (the abort signal passed through), capped at+ // the image limit — a declared or actual size beyond it is refused before the bytes are+ // kept; mime is preferentially taken from the response header, falling back to magic+ // number / URL extension.+ let res;try {- res = await fetch(source, signal ? { signal } : {});+ res = await fs.fetch(source, { maxBytes: MAX_IMAGE_BYTES, ...(signal ? { signal } : {}) });} catch (err) {if (signal?.aborted) return { ok: false, reason: "aborted" };- const message = err instanceof Error ? err.message : String(err);+ if (errorCode(err) === "ETOOBIG") {+ return {+ ok: false,+ reason: "failed",+ message: OVERSIZE_MESSAGE((err as { size: number }).size),+ };+ }return {ok: false,reason: "failed",- message: `Failed to download image "${source}": ${message}`,+ message: `Failed to download image "${source}": ${describeFsError(err, sandboxed)}`,};}if (!res.ok) {@@ -146,24 +150,8 @@ export async function loadImage(message: `Failed to download image "${source}": HTTP ${res.status}`,};}- // When content-length is trustworthy, reject an oversized response early to avoid reading it- // into memory for nothing.- const declared = Number(res.headers.get("content-length") ?? "");- if (Number.isFinite(declared) && declared > MAX_IMAGE_BYTES) {- return { ok: false, reason: "failed", message: OVERSIZE_MESSAGE(declared) };- }- try {- bytes = Buffer.from(await res.arrayBuffer());- } catch (err) {- if (signal?.aborted) return { ok: false, reason: "aborted" };- const message = err instanceof Error ? err.message : String(err);- return {- ok: false,- reason: "failed",- message: `Failed to download image "${source}": ${message}`,- };- }- const headerMime = (res.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase();+ bytes = res.bytes;+ const headerMime = (res.contentType ?? "").split(";")[0]!.trim().toLowerCase();let urlExtMime: string | null = null;try {urlExtMime = imageMimeFromExt(new URL(source).pathname);@@ -177,10 +165,10 @@ export async function loadImage(// size before reading, to avoid reading an oversized file into memory in one go.const filePath = path.resolve(workspaceDir, source);try {- const st = await stat(filePath);+ const st = await fs.stat(filePath);// Explicitly reject non-file paths such as directories: readFile's EISDIR error isn't// model-friendly.- if (!st.isFile()) {+ if (!st.isFile) {return {ok: false,reason: "failed",@@ -190,14 +178,13 @@ export async function loadImage(if (st.size > MAX_IMAGE_BYTES) {return { ok: false, reason: "failed", message: OVERSIZE_MESSAGE(st.size) };}- bytes = await readFile(filePath);+ bytes = await fs.readFile(filePath);} catch (err) {if (signal?.aborted) return { ok: false, reason: "aborted" };- const message = err instanceof Error ? err.message : String(err);return {ok: false,reason: "failed",- message: `Failed to read image "${source}": ${message}`,+ message: `Failed to read image "${source}": ${describeFsError(err, sandboxed)}`,};}mime = sniffImageMime(bytes) ?? imageMimeFromExt(filePath);diff --git a/packages/core/src/environment/tools/path-hint.ts b/packages/core/src/environment/tools/path-hint.tsindex 394b78cb..36fb2996 100644--- a/packages/core/src/environment/tools/path-hint.ts+++ b/packages/core/src/environment/tools/path-hint.ts@@ -9,9 +9,8 @@* can be the right one. Failure-path only — the extra stats/readdir never run on success.*/import path from "node:path";-import { readdir, stat } from "node:fs/promises";-import type { Dirent } from "node:fs";import { modelVisiblePath } from "../../internal/model-visible-path.js";+import type { FsDirent, FsPort } from "./fs-port.js";/** Max directory entries named in the hint; the rest collapse into a "+N more" count. */const MAX_LISTED_ENTRIES = 8;@@ -21,7 +20,7 @@ const MAX_LISTED_ENTRIES = 8;* (near-misses like `agent_state/` vs `AGENTS.md` surface first), ties alphabetical.* Directories get a trailing "/" so the model can tell what one more segment would hit.*/-function rankEntries(entries: Dirent[], missing: string): string[] {+function rankEntries(entries: FsDirent[], missing: string): string[] {const target = missing.toLowerCase();const scored = entries.map((entry) => {const name = entry.name.toLowerCase();@@ -31,7 +30,7 @@ function rankEntries(entries: Dirent[], missing: string): string[] {return { entry, prefix };});scored.sort((a, b) => b.prefix - a.prefix || a.entry.name.localeCompare(b.entry.name));- return scored.map(({ entry }) => (entry.isDirectory() ? `${entry.name}/` : entry.name));+ return scored.map(({ entry }) => (entry.isDirectory ? `${entry.name}/` : entry.name));}/**@@ -40,13 +39,13 @@ function rankEntries(entries: Dirent[], missing: string): string[] {* Reports the deepest existing ancestor, the first missing segment, and the ancestor's* nearest-named entries — or that the "ancestor" is a file (the ENOTDIR case).*/-export async function missingPathHint(resolved: string): Promise<string> {+export async function missingPathHint(resolved: string, fs: FsPort): Promise<string> {let ancestor = path.dirname(resolved);let missing = path.basename(resolved);for (;;) {try {- const st = await stat(ancestor);- if (!st.isDirectory()) {+ const st = await fs.stat(ancestor);+ if (!st.isDirectory) {return ` Note: "${modelVisiblePath(ancestor)}" exists but is a file, not a directory.`;}break;@@ -60,9 +59,9 @@ export async function missingPathHint(resolved: string): Promise<string> {}}const head = ` The directory "${modelVisiblePath(ancestor)}" exists but has no entry "${missing}".`;- let entries: Dirent[];+ let entries: FsDirent[];try {- entries = await readdir(ancestor, { withFileTypes: true });+ entries = await fs.readdir(ancestor);} catch {return head;}diff --git a/packages/core/src/environment/tools/read-file.ts b/packages/core/src/environment/tools/read-file.tsindex 78709255..abf82120 100644--- a/packages/core/src/environment/tools/read-file.ts+++ b/packages/core/src/environment/tools/read-file.ts@@ -47,7 +47,9 @@*/import { modelVisiblePath } from "../../internal/model-visible-path.js";import path from "node:path";-import { open, realpath, stat } from "node:fs/promises";+import { realpath } from "node:fs/promises";+import { describeFsError, errorCode, localFsPort } from "./fs-port.js";+import type { FsPort } from "./fs-port.js";import { imageUrlMessage, partialToolCallOutput, userText } from "../../omnimessage/index.js";import type { OmniMessage } from "../../omnimessage/index.js";import type {@@ -181,6 +183,7 @@ async function scanWindow(filePath: string,offset: number,limit: number,+ fs: FsPort,signal?: AbortSignal,): Promise<ScanOutcome> {const end = offset + limit - 1;@@ -220,57 +223,54 @@ async function scanWindow(currentHasBytes = false;};- const fd = await open(filePath, "r");- try {- const chunk = Buffer.alloc(CHUNK_BYTES);- let prevByte = -1; // For CRLF detection across chunk boundaries- for (;;) {- if (signal?.aborted) {- out.aborted = true;- return out;- }- const toRead = Math.min(CHUNK_BYTES, READ_FILE_SCAN_CAP_BYTES - scanned);- if (toRead <= 0) {- // Scan cap: with no window line produced the request cannot be served (fails with- // guidance); with a partial window, return it plus a lower-bound total.- out.capBeforeWindow = out.lines.length === 0;- out.total = completedLines + (currentHasBytes ? 1 : 0);- return out;- }- const { bytesRead } = await fd.read(chunk, 0, toRead, scanned);- if (bytesRead === 0) {- // EOF: a final line without a trailing newline still counts.- if (currentHasBytes) finishLine();- out.total = completedLines;- out.totalKnown = true;+ let prevByte = -1; // For CRLF detection across chunk boundaries+ for (;;) {+ if (signal?.aborted) {+ out.aborted = true;+ return out;+ }+ const toRead = Math.min(CHUNK_BYTES, READ_FILE_SCAN_CAP_BYTES - scanned);+ if (toRead <= 0) {+ // Scan cap: with no window line produced the request cannot be served (fails with+ // guidance); with a partial window, return it plus a lower-bound total.+ out.capBeforeWindow = out.lines.length === 0;+ out.total = completedLines + (currentHasBytes ? 1 : 0);+ return out;+ }+ // One chunk per round trip through the port: a confined Session reads through its+ // sandboxed helper, so the loop asks for a range rather than holding a descriptor.+ const chunk = await fs.readRange(filePath, scanned, toRead);+ const bytesRead = chunk.length;+ if (bytesRead === 0) {+ // EOF: a final line without a trailing newline still counts.+ if (currentHasBytes) finishLine();+ out.total = completedLines;+ out.totalKnown = true;+ return out;+ }+ scanned += bytesRead;+ let from = 0;+ for (let i = 0; i < bytesRead; i += 1) {+ const b = chunk[i]!;+ if (b === 0) {+ out.binary = true;return out;}- scanned += bytesRead;- let from = 0;- for (let i = 0; i < bytesRead; i += 1) {- const b = chunk[i]!;- if (b === 0) {- out.binary = true;- return out;- }- if (b === 0x0a) {- if (prevByte === 0x0d) out.sawCRLF = true;- if (i > from) {- currentHasBytes = true;- if (inWindow()) appendRun(chunk, from, i);- }- finishLine();- from = i + 1;+ if (b === 0x0a) {+ if (prevByte === 0x0d) out.sawCRLF = true;+ if (i > from) {+ currentHasBytes = true;+ if (inWindow()) appendRun(chunk, from, i);}- prevByte = b;- }- if (from < bytesRead) {- currentHasBytes = true;- if (inWindow()) appendRun(chunk, from, bytesRead);+ finishLine();+ from = i + 1;}+ prevByte = b;+ }+ if (from < bytesRead) {+ currentHasBytes = true;+ if (inWindow()) appendRun(chunk, from, bytesRead);}- } finally {- await fd.close();}}@@ -310,7 +310,8 @@ async function* readImageSource(}}- const res = await loadImage(source, ctx.workspaceDir, signal);+ const fs = ctx.fs ?? localFsPort;+ const res = await loadImage(source, ctx.workspaceDir, signal, fs, fs.sandboxed);if (!res.ok) {if (res.reason === "aborted") return { stopReason: "aborted" };yield delta(res.message);@@ -426,12 +427,17 @@ export function createReadFileTool(}const limit = limitArg.value;- // A URL is only ever an image source: no path resolution, no text window.+ // A URL is only ever an image source: no path resolution, no text window. It is+ // fetched through the Session's port, so a confined Session's network level holds.if (isHttpUrl(filePath)) {return yield* readImageSource(filePath, args, ctx, describer, delta);}const resolved = path.resolve(ctx.workspaceDir, filePath);+ // Every file-system effect goes through the Session's port: its sandboxed helper+ // when the Session is confined, this process otherwise (see fs-port.ts).+ const fs = ctx.fs ?? localFsPort;+ const { sandboxed } = fs;// Secret stores are refused by name: read_file is auto-approved under read-only// approval, so it needs its own guard (aligned with the system prompt's ban).// secretStoreHit resolves symlinks and compares case-insensitively — the lexical@@ -447,8 +453,8 @@ export function createReadFileTool(let size: number;try {- const st = await stat(resolved);- if (st.isDirectory()) {+ const st = await fs.stat(resolved);+ if (st.isDirectory) {yield delta(`Cannot read "${filePath}": it is a directory. Pass the path of a file inside it.`,);@@ -457,17 +463,16 @@ export function createReadFileTool(size = st.size;} catch (err) {if (signal?.aborted) return { stopReason: "aborted" };- const code = (err as NodeJS.ErrnoException).code;+ const code = errorCode(err);// ENOTDIR is the same mistake seen one segment later (a file used as a directory),// so it gets the same diagnosis instead of a raw errno message.if (code === "ENOENT" || code === "ENOTDIR") {- const hint = await missingPathHint(resolved);+ const hint = await missingPathHint(resolved, fs);yield delta(`File not found: "${filePath}". Absolute paths are supported; relative paths resolve against the workspace (${modelVisiblePath(ctx.workspaceDir)}).${hint}`,);} else {- const message = err instanceof Error ? err.message : String(err);- yield delta(`Failed to read "${filePath}": ${message}`);+ yield delta(`Failed to read "${filePath}": ${describeFsError(err, sandboxed)}`);}return { stopReason: "fatal" };}@@ -478,17 +483,16 @@ export function createReadFileTool(}// Images take the image branch whatever offset/limit say; everything else is text.- if (await looksLikeImageFile(resolved)) {+ if (await looksLikeImageFile(resolved, fs)) {return yield* readImageSource(filePath, args, ctx, describer, delta);}let scan: ScanOutcome;try {- scan = await scanWindow(resolved, offset, limit, signal);+ scan = await scanWindow(resolved, offset, limit, fs, signal);} catch (err) {if (signal?.aborted) return { stopReason: "aborted" };- const message = err instanceof Error ? err.message : String(err);- yield delta(`Failed to read "${filePath}": ${message}`);+ yield delta(`Failed to read "${filePath}": ${describeFsError(err, sandboxed)}`);return { stopReason: "fatal" };}if (scan.aborted || signal?.aborted) return { stopReason: "aborted" };diff --git a/packages/core/src/environment/tools/types.ts b/packages/core/src/environment/tools/types.tsindex 900e6235..bd3bb9b2 100644--- a/packages/core/src/environment/tools/types.ts+++ b/packages/core/src/environment/tools/types.ts@@ -9,6 +9,7 @@*/import type { OmniMessage, StopReason } from "../../omnimessage/index.js";import type { ApproveFn, ToolDefinitionConfig } from "../../interfaces/index.js";+import type { ToolFs } from "./fs-port.js";/*** Tool execution context: runtime information needed to execute one tool call.@@ -32,6 +33,12 @@ export interface ToolExecutionContext {detachSignal?: AbortSignal;/** The parent Agent's approval callback; run_subagent passes it through to the child Session so it inherits the parent's approval mode (unused by most tools). */approve?: ApproveFn;+ /**+ * The file system the file tools work through (see fs-port.ts): the Session's sandboxed+ * helper for a confined Session, this process for an unconfined one, decided on first+ * use. Absent = this process.+ */+ fs?: ToolFs;}/**diff --git a/packages/core/src/environment/tools/write-file.ts b/packages/core/src/environment/tools/write-file.tsindex b970b0b4..c97111e0 100644--- a/packages/core/src/environment/tools/write-file.ts+++ b/packages/core/src/environment/tools/write-file.ts@@ -11,8 +11,9 @@* overwritten file's permission bits), so a crash mid-write cannot leave the target* half-written; a symlinked path is followed to the file it names, so the link survives* and the content lands where it points. Relative paths resolve against the Workspace;- * absolute paths are allowed (tools run with the user's full permissions, same as the- * shell tool). The write is serialized against edit_file and other write_file calls on the+ * absolute paths are allowed. Every file-system effect goes through the Session's port+ * (see fs-port.ts): a confined Session's sandboxed helper, so the sandbox bounds this tool+ * as it bounds the shell tool; unconfined, this process, with the user's full permissions. The write is serialized against edit_file and other write_file calls on the* same file in this process (see internal/file-lock.ts), so a concurrent edit of that file* applies either to the content this call replaced or to the content it wrote — never* computed from the one and written over the other.@@ -27,9 +28,9 @@* Docs: /docs/tools § "File tools".*/import path from "node:path";-import { mkdir, readFile, stat } from "node:fs/promises";-import { atomicWriteFile, resolveWriteTarget } from "../../internal/atomic-write.js";import { fileLockKey, withFileLock } from "../../internal/file-lock.js";+import { describeFsError, localFsPort, resolveWriteTargetThrough } from "./fs-port.js";+import type { FsPort } from "./fs-port.js";import { buildLineDiffHunks, renderHunk } from "./diff.js";import { partialToolCallOutput } from "../../omnimessage/index.js";import type { OmniMessage } from "../../omnimessage/index.js";@@ -75,17 +76,20 @@ async function applyWrite(params: {resolved: string;filePath: string;content: string;+ /** The file system to work through (see fs-port.ts), and whether it is the sandboxed helper. */+ fs: FsPort;+ sandboxed: boolean;signal?: AbortSignal;}): Promise<WriteOutcome> {- const { resolved, filePath, content, signal } = params;+ const { resolved, filePath, content, fs, sandboxed, signal } = params;// Determine created-vs-overwrote before writing; also reject directories up front// (writeFile's raw EISDIR is not model-friendly).let existed = false;let fileMode: number | undefined;let previous: string | null = null; // Previous content, for the overwrite difftry {- const st = await stat(resolved);- if (st.isDirectory()) {+ const st = await fs.stat(resolved);+ if (st.isDirectory) {return { kind: "fatal", text: `Cannot write "${filePath}": it is a directory.` };}existed = true;@@ -93,7 +97,7 @@ async function applyWrite(params: {// Read the old content back for the diff — bounded: a huge or unreadable/binary// previous file simply gets no diff (never a failure).if (st.size <= DIFF_SOURCE_CAP_BYTES) {- const bytes = await readFile(resolved);+ const bytes = await fs.readFile(resolved);if (!bytes.includes(0)) previous = bytes.toString("utf8");}} catch {@@ -105,16 +109,17 @@ async function applyWrite(params: {// The parent to create is the one holding the file that will actually be written:// through a symlink that is the target's directory, not the link's (a link pointing// into a directory that does not exist yet is created the way `>` would).- await mkdir(path.dirname(await resolveWriteTarget(resolved)), { recursive: true });- await atomicWriteFile(resolved, content, {+ await fs.mkdir(path.dirname(await resolveWriteTargetThrough(fs, resolved)));+ await fs.writeFileAtomic(resolved, Buffer.from(content, "utf8"), {...(fileMode !== undefined ? { mode: fileMode } : {}),- ...(signal ? { signal } : {}),followSymlinks: true,});} catch (err) {if (signal?.aborted) return { kind: "aborted" };- const message = err instanceof Error ? err.message : String(err);- return { kind: "fatal", text: `Failed to write "${filePath}": ${message}` };+ return {+ kind: "fatal",+ text: `Failed to write "${filePath}": ${describeFsError(err, sandboxed)}`,+ };}return { kind: "ok", existed, previous };@@ -156,13 +161,17 @@ export function createWriteFileTool(definition: ToolDefinitionConfig): BuiltinTo}const resolved = path.resolve(ctx.workspaceDir, filePath);+ // Every file-system effect goes through the Session's port: its sandboxed helper+ // when the Session is confined, this process otherwise (see fs-port.ts).+ const fs = ctx.fs ?? localFsPort;+ const { sandboxed } = fs;// One file, one writer at a time: the previous content this call reads back and the// content it writes are a single critical section, so a concurrent edit of the same// file is applied either before this write or on top of it.const key = await fileLockKey(resolved);const outcome = await withFileLock(key,- () => applyWrite({ resolved, filePath, content, signal }),+ () => applyWrite({ resolved, filePath, content, fs, sandboxed, signal }),signal,).catch((err: unknown): WriteOutcome => {// Interrupted while queued behind another writer on the same file — the samediff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 0ea6905b..b365a56c 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -31,4 +31,4 @@ export {scriptStopHook,scriptUserPromptHook,} from "./script-hook.js";-export type { RunHookScriptOptions } from "./script-hook.js";+export type { RunHookScriptOptions, ScriptHookOptions } from "./script-hook.js";diff --git a/packages/core/src/hooks/script-hook.ts b/packages/core/src/hooks/script-hook.tsindex 6beed1b5..b96bad63 100644--- a/packages/core/src/hooks/script-hook.ts+++ b/packages/core/src/hooks/script-hook.ts@@ -22,14 +22,19 @@* `runHookScript` is the generic runner behind the adapters (`scriptStopHook` /* `scriptPreToolUseHook` / `scriptUserPromptHook`), each turning one installed command into* the point's in-process interface.+ *+ * A script is spawned under the Session's sandbox exactly as a command is: the argv goes+ * through the same confiner (see `RunHookScriptOptions.confine`), and a confiner that+ * cannot enforce its policy fails the hook rather than running it unconfined.*/import { spawn } from "node:child_process";import path from "node:path";import { prependPathEnv } from "../environment/tools/command/path-prepend.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";import type { PreToolUseHook, PreToolUseHookInput, PreToolUseHookResult } from "./tool-hook.js";import type { UserPromptHook, UserPromptHookInput, UserPromptHookResult } from "./prompt-hook.js";-import type { UserPromptTrigger } from "../plugins/index.js";/** Seconds a script may run before it is killed, when its manifest names none. */export const DEFAULT_HOOK_TIMEOUT_S = 60;@@ -49,6 +54,13 @@ export interface RunHookScriptOptions {* `node <script>`, with no shell to re-order PATH afterwards.*/pathPrepend?: readonly string[];+ /**+ * The Session's sandbox: rewrites the argv about to be spawned (`[node, script]`) into+ * the one to spawn instead, the way a command's is rewritten (see+ * {@link SpawnConfiner}). A throw is the hook's failure — the script never runs+ * unconfined. Absent = unconfined (SDK/CLI standalone use).+ */+ confine?: (argv: readonly string[]) => ConfinedSpawn;}/**@@ -62,14 +74,30 @@ export async function runHookScript(opts: RunHookScriptOptions = {},): Promise<unknown> {const timeoutMs = (opts.timeoutS ?? DEFAULT_HOOK_TIMEOUT_S) * 1000;+ // Confined before anything is spawned, so a policy nothing can enforce is the hook's+ // failure and not a script running outside the sandbox.+ const argv = [process.execPath, script];+ let confined: ConfinedSpawn;+ try {+ confined = opts.confine ? opts.confine(argv) : { argv };+ } catch (err) {+ throw new Error(`sandbox: ${err instanceof Error ? err.message : String(err)}`);+ }+ const [program, ...args] = confined.argv;+ if (program === undefined) throw new Error("sandbox: the confiner returned an empty argv");return new Promise<unknown>((resolve, reject) => {- const child = spawn(process.execPath, [script], {+ // In the desktop app process.execPath is the Electron binary: without this flag the+ // spawn boots a whole Electron app (GPU process and all) instead of running the+ // script, and dies on machines where that fails. A plain Node execPath ignores it.+ // A runner's own entries (ConfinedSpawn.env) lie over that environment.+ const env = prependPathEnv(+ { ...process.env, ELECTRON_RUN_AS_NODE: "1" },+ opts.pathPrepend ?? [],+ );+ const child = spawn(program, args, {cwd: opts.cwd ?? path.dirname(script),stdio: ["pipe", "pipe", "pipe"],- // In the desktop app process.execPath is the Electron binary: without this flag the- // spawn boots a whole Electron app (GPU process and all) instead of running the- // script, and dies on machines where that fails. A plain Node execPath ignores it.- env: prependPathEnv({ ...process.env, ELECTRON_RUN_AS_NODE: "1" }, opts.pathPrepend ?? []),+ env: confined.env === undefined ? env : { ...env, ...confined.env },});let stdout = "";let stderr = "";@@ -181,6 +209,21 @@ export function parseUserPromptResult(value: unknown): UserPromptHookResult | unreturn typeof v.context === "string" ? { context: v.context } : {};}+/** How one installed command is run: the manifest's timeout, and the Session's host policies, each re-read per call. */+export interface ScriptHookOptions {+ timeoutS?: number;+ /** See {@link RunHookScriptOptions.pathPrepend}; a getter, re-read per call. */+ pathPrepend?: () => string[];+ /**+ * The Session's confiner (see {@link SpawnConfiner}), re-read per call like+ * `pathPrepend`; null = unconfined. Called with the package directory as `cwd` and the+ * `scope` below.+ */+ confineSpawn?: () => SpawnConfiner | null;+ /** The Session's Workspace and scratchpad, the confiner's scope; absent = the package directory stands in for the Workspace. */+ scope?: { workspaceDir: string; scratchpadDir?: string };+}+/*** One installed command as a runner: `command` relative to `dir` (the hook package's* directory, which is also the script's cwd), the manifest's timeout, and per call the@@ -190,19 +233,32 @@ export function parseUserPromptResult(value: unknown): UserPromptHookResult | unfunction scriptRunner(dir: string,command: string,- timeoutS: number | undefined,- pathPrepend: (() => string[]) | undefined,+ opts: ScriptHookOptions,): (input: Record<string, unknown>, signal: AbortSignal | undefined) => Promise<unknown> {const script = path.resolve(dir, command);- return (input, signal) =>- runHookScript(script, input, {+ return (input, signal) => {+ // Re-read per call, like the command-spawn side: the host may point PATH somewhere+ // else, or change the Session's policy, without the Session being rebuilt.+ const confiner = opts.confineSpawn?.() ?? null;+ return runHookScript(script, input, {cwd: dir,- ...(timeoutS !== undefined ? { timeoutS } : {}),+ ...(opts.timeoutS !== undefined ? { timeoutS: opts.timeoutS } : {}),...(signal ? { signal } : {}),- // Re-read per call, like the command-spawn side: the host may point it somewhere else- // without the Session being rebuilt.- ...(pathPrepend ? { pathPrepend: pathPrepend() } : {}),+ ...(opts.pathPrepend ? { pathPrepend: opts.pathPrepend() } : {}),+ ...(confiner !== null+ ? {+ confine: (argv: readonly string[]) =>+ confiner(argv, {+ cwd: dir,+ workspaceDir: opts.scope?.workspaceDir ?? dir,+ ...(opts.scope?.scratchpadDir !== undefined+ ? { scratchpadDir: opts.scope.scratchpadDir }+ : {}),+ }),+ }+ : {}),});+ };}/** One installed user-prompt command as a UserPromptHook; `trigger` is the command's resolved one (see plugins' userPromptTrigger). */@@ -210,11 +266,10 @@ export function scriptUserPromptHook(name: string,dir: string,command: string,- timeoutS?: number,- pathPrepend?: () => string[],- trigger?: UserPromptTrigger,+ opts: ScriptHookOptions & { trigger?: UserPromptTrigger } = {},): UserPromptHook {- const run = scriptRunner(dir, command, timeoutS, pathPrepend);+ const run = scriptRunner(dir, command, opts);+ const { trigger } = opts;return {name,...(trigger !== undefined ? { trigger } : {}),@@ -241,10 +296,9 @@ export function scriptPreToolUseHook(name: string,dir: string,command: string,- timeoutS?: number,- pathPrepend?: () => string[],+ opts: ScriptHookOptions = {},): PreToolUseHook {- const run = scriptRunner(dir, command, timeoutS, pathPrepend);+ const run = scriptRunner(dir, command, opts);return {name,async run(input: PreToolUseHookInput): Promise<PreToolUseHookResult | undefined> {@@ -270,10 +324,9 @@ export function scriptStopHook(name: string,dir: string,command: string,- timeoutS?: number,- pathPrepend?: () => string[],+ opts: ScriptHookOptions = {},): StopHook {- const run = scriptRunner(dir, command, timeoutS, pathPrepend);+ const run = scriptRunner(dir, command, opts);return {name,async run(input: StopHookInput): Promise<StopHookResult | undefined> {diff --git a/packages/core/src/interfaces/environment.ts b/packages/core/src/interfaces/environment.tsindex 5f500f1c..3734582e 100644--- a/packages/core/src/interfaces/environment.ts+++ b/packages/core/src/interfaces/environment.ts@@ -325,12 +325,14 @@ export interface EnvironmentConfig {*/pathPrepend?: () => string[];/**- * Sandbox-confinement seam for exec_command / input_command subprocesses (see- * {@link SpawnConfiner}). Like {@link EnvironmentConfig.proxyEnv} it is a getter- * re-read at every spawn, so the hosting server can change the active confiner at- * runtime (e.g. via a platform hot push) and reach Sessions that are already- * running. Absent, or a getter returning null = commands spawn unconfined (the- * default for SDK/CLI standalone use).+ * Sandbox-confinement seam for everything the Environment spawns for the Session: the+ * exec_command / input_command subprocesses, the stdio MCP Servers, and the helper the+ * file tools work through when the Session is confined (see {@link SpawnConfiner} and+ * tools/fs-worker.ts). Like {@link EnvironmentConfig.proxyEnv} it is a getter re-read+ * at every spawn, so the hosting server can change the active confiner at runtime+ * (e.g. via a platform hot push) and reach Sessions that are already running. Absent,+ * or a getter returning null = everything spawns unconfined (the default for SDK/CLI+ * standalone use).*/confineSpawn?: () => SpawnConfiner | null;}@@ -366,13 +368,15 @@ export type ProxyEnvPolicy = { mode: "strip" } | { mode: "inject"; url: string;* @param opts - spawn context: `cwd` is the working directory of THIS command (per-call,* may differ from the workspace); `workspaceDir` is the Session's Workspace root — the* directory a workspace-scoped confinement policy should treat as writable, never- * inferred from `cwd` (a command may run in a workdir outside the Workspace).+ * inferred from `cwd` (a command may run in a workdir outside the Workspace);+ * `scratchpadDir` is the Session's scratchpad, writable beside the workspace under+ * that policy (absent for a Session without one).* @returns what to spawn instead: the argv, and any environment entries the runner* itself needs (see {@link ConfinedSpawn}).*/export type SpawnConfiner = (argv: readonly string[],- opts: { cwd: string; workspaceDir: string },+ opts: { cwd: string; workspaceDir: string; scratchpadDir?: string },) => ConfinedSpawn;/**diff --git a/packages/core/src/plugin/sandbox.ts b/packages/core/src/plugin/sandbox.tsindex 81ff802c..618d8b93 100644--- a/packages/core/src/plugin/sandbox.ts+++ b/packages/core/src/plugin/sandbox.ts@@ -60,6 +60,14 @@ export interface SandboxPolicy {mode: SandboxMode;/** Absolute root directory `workspace-write` may write under. */workspaceRoot: string;+ /**+ * Further absolute directories `workspace-write` may write under, beside the workspace:+ * the Session's scratchpad, where the plan file, a goal's state file and the+ * attachments live. Meaningless under `read-only`. A backend that does not implement+ * the field confines more narrowly than asked, never more widely, so no dimension+ * guards it.+ */+ writableRoots?: readonly string[];/*** `network`: "none" = the confined process gets no network at all (dimension `network`);* "local" = it reaches the host's localhost and nothing else (dimension `network-local`).diff --git a/packages/core/test/exec-session.test.ts b/packages/core/test/exec-session.test.tsindex 149493c1..778db75c 100644--- a/packages/core/test/exec-session.test.ts+++ b/packages/core/test/exec-session.test.ts@@ -536,6 +536,32 @@ describe("confineSpawn seam rewrites the exact argv a command spawns", () => {expect(seen!.workspaceDir).toBe(tmp);});+ it("the Session's scratchpad rides beside the Workspace in the confiner's opts; without one there is no such key", async () => {+ const scratchpadDir = path.join(tmp, "scratchpad", "session-1");+ const seen: Array<{ cwd: string; workspaceDir: string; scratchpadDir?: string }> = [];+ confiner = (_argv, opts) => {+ seen.push({ ...opts });+ return { argv: [process.execPath, "-e", "console.log('CONFINED')"] };+ };+ const withScratchpad = new Environment({+ workspaceDir: tmp,+ toolConfig: sessionConfig(),+ sessionScratchpadDir: scratchpadDir,+ confineSpawn: () => confiner,+ });+ try {+ const res = await runTool(withScratchpad, "exec_command", { cmd: "echo original" });+ expect(res.output).toContain("CONFINED");+ } finally {+ withScratchpad.dispose();+ }+ await runTool(confinedEnv, "exec_command", { cmd: "echo original" });+ expect(seen).toStrictEqual([+ { cwd: tmp, workspaceDir: tmp, scratchpadDir },+ { cwd: tmp, workspaceDir: tmp },+ ]);+ });+it("a throwing confiner fails the spawn closed: reported as spawn error, nothing runs", async () => {confiner = () => {throw new Error('sandbox mode "workspace-write" requested but no backend is usable');diff --git a/packages/core/test/fixtures/mcp-runner.mjs b/packages/core/test/fixtures/mcp-runner.mjsnew file mode 100644index 00000000..8c3cc20d--- /dev/null+++ b/packages/core/test/fixtures/mcp-runner.mjs@@ -0,0 +1,7 @@+// A stand-in sandbox runner for the stdio MCP tests: sets a marker in the environment and+// runs the server script it was handed, in this process, so what the server reports shows+// it started through the runner.+import { pathToFileURL } from "node:url";++process.env.FIXTURE_SECRET = `via-runner:${process.env.FIXTURE_SECRET ?? ""}`;+await import(pathToFileURL(process.argv[2]).href);diff --git a/packages/core/test/hooks.test.ts b/packages/core/test/hooks.test.tsindex e44f88c8..26182433 100644--- a/packages/core/test/hooks.test.ts+++ b/packages/core/test/hooks.test.ts@@ -215,7 +215,7 @@ describe("script hooks", () => {'{ decision: "stop", reason: `${input.hook} ${input.session_id} ${input.trace_path}` }',),);- const hook = scriptStopHook("demo", dir, "stop.mjs", 5);+ const hook = scriptStopHook("demo", dir, "stop.mjs", { timeoutS: 5 });expect(hook.name).toBe("demo");expect(await hook.run({ sessionId: "s1", tracePath: "/t/s1_001.jsonl" })).toEqual({decision: "stop",@@ -224,6 +224,93 @@ describe("script hooks", () => {});});+describe("script hooks under the sandbox", () => {+ let dir: string;+ beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-hooks-sandbox-"));+ });+ afterEach(async () => {+ await rmEventually(dir);+ });++ it("spawns the confiner's argv with the runner's environment laid over the script's", async () => {+ // A stand-in runner: runs the script it is handed, and shows that it ran through it.+ const runner = path.join(dir, "runner.mjs");+ await fs.writeFile(+ runner,+ [+ 'import { pathToFileURL } from "node:url";',+ 'process.env.HOOK_RAN_THROUGH = "runner";',+ "await import(pathToFileURL(process.argv[2]).href);",+ ].join("\n"),+ );+ const script = path.join(dir, "report.mjs");+ await fs.writeFile(+ script,+ "process.stdout.write(JSON.stringify({ through: process.env.HOOK_RAN_THROUGH, marker: process.env.HOOK_RUNNER_MARK }));\n",+ );+ const seen: string[][] = [];+ const out = (await runHookScript(+ script,+ {},+ {+ confine: (argv) => {+ seen.push([...argv]);+ return { argv: [argv[0]!, runner, ...argv.slice(1)], env: { HOOK_RUNNER_MARK: "set" } };+ },+ },+ )) as { through: string; marker: string };+ expect(seen).toEqual([[process.execPath, script]]);+ expect(out).toEqual({ through: "runner", marker: "set" });+ });++ it("fails the hook when the confiner cannot enforce its policy, and never runs the script", async () => {+ const script = path.join(dir, "touch.mjs");+ const witness = path.join(dir, "ran");+ await fs.writeFile(+ script,+ `import fs from "node:fs"; fs.writeFileSync(${JSON.stringify(witness)}, "");\n`,+ );+ await expect(+ runHookScript(+ script,+ {},+ {+ confine: () => {+ throw new Error("no sandbox backend is mounted");+ },+ },+ ),+ ).rejects.toThrow(/sandbox: no sandbox backend is mounted/);+ await expect(fs.access(witness)).rejects.toThrow();+ });++ it("an installed command reads the Session's confiner at every run, with the package directory as cwd and the Session's scope", async () => {+ const script = path.join(dir, "stop.mjs");+ await fs.writeFile(script, 'process.stdout.write(JSON.stringify({ decision: "stop" }));\n');+ const scopes: unknown[] = [];+ let confiner: ((argv: readonly string[], opts: unknown) => { argv: readonly string[] }) | null =+ null;+ const hook = scriptStopHook("demo", dir, "stop.mjs", {+ confineSpawn: () => confiner,+ scope: { workspaceDir: "/ws", scratchpadDir: "/scratch/s1" },+ });+ // Unconfined while the getter answers null…+ expect(await hook.run(stopInput())).toEqual({ decision: "stop" });+ // …confined under whatever it answers next, with the scope a command would get.+ confiner = (argv, opts) => {+ scopes.push(opts);+ return { argv };+ };+ expect(await hook.run(stopInput())).toEqual({ decision: "stop" });+ expect(scopes).toEqual([{ cwd: dir, workspaceDir: "/ws", scratchpadDir: "/scratch/s1" }]);+ confiner = () => {+ throw new Error("refused");+ };+ await expect(hook.run(stopInput())).rejects.toThrow(/sandbox: refused/);+ });+});+describe("script pre-tool-use hooks", () => {let dir: string;beforeEach(async () => {@@ -315,7 +402,7 @@ describe("Session user-prompt hook", () => {imagesDir: scratchpad,modelHasVision: true,hooks: {- userPrompt: [scriptUserPromptHook("goal", dir, "expand.mjs", undefined, undefined, "host")],+ userPrompt: [scriptUserPromptHook("goal", dir, "expand.mjs", { trigger: "host" })],},});const result = await session.runUserPromptHook("goal", "ship it", { budget: 500 });diff --git a/packages/core/test/mcp-tools.test.ts b/packages/core/test/mcp-tools.test.tsindex c5ee0732..33a1e998 100644--- a/packages/core/test/mcp-tools.test.ts+++ b/packages/core/test/mcp-tools.test.ts@@ -261,6 +261,86 @@ describe("MCP over stdio through Environment", () => {});});+describe("MCP over stdio — under the Session's sandbox", () => {+ const RUNNER = fileURLToPath(new URL("./fixtures/mcp-runner.mjs", import.meta.url));+ let tmp: string;+ beforeAll(async () => {+ tmp = await realpath(await mkdtemp(path.join(tmpdir(), "penguin-mcp-sandbox-")));+ });+ afterAll(async () => {+ await rmEventually(tmp);+ });++ it("starts a server through the Session's confiner, with the runner's environment laid over the server's", async () => {+ const scopes: unknown[] = [];+ const env = new Environment({+ workspaceDir: tmp,+ sessionScratchpadDir: path.join(tmp, "scratchpad", "s1"),+ toolConfig: {+ customTools: [],+ mcpServers: [fixtureEntry({ env: { FIXTURE_SECRET: "from-entry" } })],+ },+ confineSpawn: () => (argv, opts) => {+ scopes.push(opts);+ return {+ argv: [argv[0]!, RUNNER, ...argv.slice(1)],+ env: { FIXTURE_SECRET: "from-runner" },+ };+ },+ });+ try {+ const final = finalPayload(await runTool(env, "mcp__fx__probe", {}));+ // The runner's entry lies over the entry's own, and the runner saw it first.+ expect(final.output).toMatch(/^via-runner:from-runner\|/);+ // The first spawn the confiner saw is the server's (the file tools' helper is asked+ // about at every tool call, after the server connected).+ expect(scopes[0]).toEqual({+ cwd: tmp,+ workspaceDir: tmp,+ scratchpadDir: path.join(tmp, "scratchpad", "s1"),+ });+ } finally {+ env.dispose();+ }+ });++ it("fails that server's connect when the confiner cannot enforce the policy, and starts nothing", async () => {+ const provider = new McpToolProvider([fixtureEntry()], {+ workspaceDir: tmp,+ confineSpawn: () => () => {+ throw new Error("no sandbox backend is mounted");+ },+ warn: () => {},+ });+ try {+ expect(await provider.listTools()).toEqual([]);+ const [result] = provider.connectResults();+ expect(result).toMatchObject({+ server: "fx",+ transport: "stdio",+ status: "fatal",+ error_code: "connect_failed",+ });+ expect(result!.error_message).toContain("sandbox: no sandbox backend is mounted");+ } finally {+ await provider.close();+ }+ });++ it("starts a server unconfined while the confiner getter answers null", async () => {+ const provider = new McpToolProvider([fixtureEntry()], {+ workspaceDir: tmp,+ confineSpawn: () => null,+ warn: () => {},+ });+ try {+ expect((await provider.listTools()).length).toBeGreaterThan(0);+ } finally {+ await provider.close();+ }+ });+});+describe("MCP over stdio — per-server budgets and interruption", () => {let tmp: string;diff --git a/packages/core/test/sandbox-fs-helper.test.ts b/packages/core/test/sandbox-fs-helper.test.tsnew file mode 100644index 00000000..01ed4034--- /dev/null+++ b/packages/core/test/sandbox-fs-helper.test.ts@@ -0,0 +1,371 @@+/**+ * The file tools under the sandbox (tools/fs-port.ts, tools/fs-worker.ts): a confined+ * Session's read_file, edit_file and write_file do their file-system work in a helper+ * process the Session's confiner wraps, so the backend that bounds its commands bounds+ * them too. The helper serves the port's primitives over JSON lines; the same tool code+ * runs against it and against this process.+ *+ * - The helper's port agrees with the in-process one, errors and their codes included.+ * - The Environment works through the helper when the confiner rewrites the helper's argv,+ * and in-process when the confiner leaves it alone.+ * - One helper serves a Session: reused across calls, started over when the confiner's+ * answer changes, killed by an abort and on dispose.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { spawn } from "node:child_process";+import { createServer } from "node:http";+import type { AddressInfo } from "node:net";+import {+ chmod,+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rm,+ symlink,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { Environment } from "../src/environment/index.js";+import { SandboxedFsHost, fsWorkerArgv } from "../src/environment/tools/fs-worker.js";+import { describeFsError, errorCode, localFsPort } from "../src/environment/tools/fs-port.js";+import type { FsPort } from "../src/environment/tools/fs-port.js";+import { EDIT_FILE_NAME } from "../src/environment/tools/edit-file.js";+import { READ_FILE_NAME } from "../src/environment/tools/read-file.js";+import { WRITE_FILE_NAME } from "../src/environment/tools/write-file.js";+import { toolCall } from "../src/omnimessage/index.js";+import type { ConfinedSpawn, SpawnConfiner, ToolConfig } from "../src/interfaces/index.js";++let tmp: string;++beforeEach(async () => {+ tmp = await realpath(await mkdtemp(path.join(tmpdir(), "penguin-fs-helper-")));+});++afterEach(async () => {+ await rm(tmp, { recursive: true, force: true });+});++/** A confiner's answer that names the helper as it is, with a runner entry so it reads as confined. */+const marked = (): ConfinedSpawn => ({ argv: fsWorkerArgv(), env: { PENGUIN_TEST_HELPER: "1" } });++describe("the helper's port", () => {+ let host: SandboxedFsHost;+ let port: FsPort;+ beforeEach(() => {+ host = new SandboxedFsHost();+ port = host.portFor(marked());+ });+ afterEach(() => {+ host.dispose();+ });++ it("answers every primitive like the in-process port", async () => {+ const file = path.join(tmp, "a.txt");+ await writeFile(file, "alpha\nbeta\n", { mode: 0o640 });+ await mkdir(path.join(tmp, "sub"));+ await symlink(file, path.join(tmp, "link.txt"));+ for (const fs of [localFsPort, port]) {+ const st = await fs.stat(file);+ expect(st).toMatchObject({ isFile: true, isDirectory: false, size: 11 });+ // Permission bits are a POSIX fact; Windows answers a fixed 0o666.+ if (process.platform !== "win32") expect(st.mode & 0o777).toBe(0o640);+ expect((await fs.readFile(file)).toString()).toBe("alpha\nbeta\n");+ expect((await fs.readRange(file, 6, 100)).toString()).toBe("beta\n");+ expect((await fs.readRange(file, 100, 10)).length).toBe(0);+ expect(await fs.readdir(tmp)).toEqual(+ expect.arrayContaining([+ { name: "a.txt", isFile: true, isDirectory: false },+ { name: "sub", isFile: false, isDirectory: true },+ ]),+ );+ expect(await fs.realpath(path.join(tmp, "link.txt"))).toBe(file);+ expect(await fs.readlink(path.join(tmp, "link.txt"))).toBe(file);+ }+ await port.mkdir(path.join(tmp, "deep", "er"));+ expect((await localFsPort.stat(path.join(tmp, "deep", "er"))).isDirectory).toBe(true);+ // A write through the link lands on the file it names, with the mode asked for.+ await port.writeFileAtomic(path.join(tmp, "link.txt"), Buffer.from("gamma\n"), {+ mode: 0o600,+ followSymlinks: true,+ });+ expect(await readFile(file, "utf8")).toBe("gamma\n");+ if (process.platform !== "win32")+ expect((await localFsPort.stat(file)).mode & 0o777).toBe(0o600);+ expect(await readFile(path.join(tmp, "link.txt"), "utf8")).toBe("gamma\n");+ });++ it("carries an error's code across, so the tools diagnose as they do in-process", async () => {+ for (const fs of [localFsPort, port]) {+ await expect(fs.stat(path.join(tmp, "missing"))).rejects.toMatchObject({ code: "ENOENT" });+ await expect(fs.readFile(tmp)).rejects.toMatchObject({ code: "EISDIR" });+ await expect(fs.readlink(path.join(tmp, "a.txt"))).rejects.toMatchObject({+ code: "ENOENT",+ });+ }+ });++ it("downloads through the helper, and refuses a body past the cap with ETOOBIG", async () => {+ const server = createServer((req, res) => {+ if (req.url === "/big") {+ res.writeHead(200, { "content-type": "image/png", "content-length": "99999999" });+ res.end();+ return;+ }+ res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });+ res.end("hello");+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ try {+ for (const fs of [localFsPort, port]) {+ const res = await fs.fetch(`${base}/ok`, { maxBytes: 1000 });+ expect(res).toMatchObject({+ ok: true,+ status: 200,+ contentType: "text/plain; charset=utf-8",+ });+ expect(res.bytes.toString()).toBe("hello");+ await expect(fs.fetch(`${base}/big`, { maxBytes: 1000 })).rejects.toMatchObject({+ code: "ETOOBIG",+ size: 99999999,+ });+ }+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });++ it("names the sandbox when a refused effect comes back as a permission error", async () => {+ const err = Object.assign(new Error("EROFS: read-only file system"), { code: "EROFS" });+ expect(describeFsError(err, true)).toContain("refused by this session's sandbox");+ expect(describeFsError(err, false)).toBe("EROFS: read-only file system");+ expect(errorCode(err)).toBe("EROFS");+ });+});++describe("one helper per Session", () => {+ it("is reused across calls, started over when the confiner's answer changes, and stopped on dispose", async () => {+ const starts: ConfinedSpawn[] = [];+ const host = new SandboxedFsHost((confined) => {+ starts.push(confined);+ const [program, ...args] = confined.argv;+ return spawn(program!, args, {+ stdio: ["pipe", "pipe", "pipe"],+ env: { ...process.env, ELECTRON_RUN_AS_NODE: "1", ...confined.env },+ });+ });+ try {+ const a = host.portFor(marked());+ await a.stat(tmp);+ await a.readdir(tmp);+ expect(starts).toHaveLength(1);+ expect(host.running).toBe(true);+ // The same answer again: the same helper. Another answer: a fresh one.+ await host.portFor(marked()).stat(tmp);+ expect(starts).toHaveLength(1);+ const b = host.portFor({ argv: fsWorkerArgv(), env: { PENGUIN_TEST_HELPER: "2" } });+ await b.stat(tmp);+ expect(starts).toHaveLength(2);+ expect(starts[1]!.env).toEqual({ PENGUIN_TEST_HELPER: "2" });+ } finally {+ host.dispose();+ }+ expect(host.running).toBe(false);+ await expect(host.portFor(marked()).stat(tmp)).rejects.toThrow(/disposed/);+ });++ it("an abort kills the helper mid-operation, and the next call starts a fresh one", async () => {+ // A download that never finishes: the helper is stuck inside it until the abort.+ const server = createServer((_req, res) => {+ res.writeHead(200, { "content-type": "image/png" });+ res.write("partial");+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ let started = 0;+ const host = new SandboxedFsHost((confined) => {+ started += 1;+ const [program, ...args] = confined.argv;+ return spawn(program!, args, { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env } });+ });+ try {+ const port = host.portFor(marked());+ const ac = new AbortController();+ const pending = port.fetch(`${base}/stall`, { maxBytes: 1000, signal: ac.signal });+ setTimeout(() => ac.abort(), 100);+ await expect(pending).rejects.toMatchObject({ name: "AbortError" });+ expect(host.running).toBe(false);+ expect((await port.stat(tmp)).isDirectory).toBe(true);+ expect(started).toBe(2);+ } finally {+ host.dispose();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });++ it("a helper that cannot start fails the operation with the spawn error", async () => {+ const host = new SandboxedFsHost();+ try {+ const port = host.portFor({ argv: ["definitely-not-a-real-runner-xyz", "--", "x"] });+ await expect(port.stat(tmp)).rejects.toThrow(/sandbox: the file helper could not start/);+ } finally {+ host.dispose();+ }+ });+});++describe("the file tools through the helper", () => {+ const toolConfig = (): ToolConfig => ({+ customTools: [+ { name: WRITE_FILE_NAME, description: "t", permission: "rw" },+ { name: EDIT_FILE_NAME, description: "t", permission: "rw" },+ { name: READ_FILE_NAME, description: "t", permission: "r" },+ ],+ mcpServers: [],+ });+ /** A confiner that names the helper as it is, plus a runner entry — enough for the Environment to route through it. */+ const confining: SpawnConfiner = (argv) => ({+ argv: [...argv],+ env: { PENGUIN_TEST_HELPER: "1" },+ });++ async function execute(env: Environment, name: string, args: Record<string, unknown>) {+ const call = toolCall({ name, arguments: JSON.stringify(args), toolCallId: "t1" });+ let output = "";+ let stopReason: string | undefined;+ for await (const msg of env.executeTool({ toolCall: call })) {+ const p = msg.payload as { type?: string; output?: string; stop_reason?: string };+ if (p.type === "tool_call_output") {+ output = p.output ?? "";+ stopReason = p.stop_reason;+ }+ }+ return { output, stopReason };+ }++ it("writes, edits and reads through the helper, with the same output as in-process", async () => {+ const seen: unknown[] = [];+ const env = new Environment({+ workspaceDir: tmp,+ toolConfig: toolConfig(),+ sessionScratchpadDir: path.join(tmp, "scratchpad", "s1"),+ confineSpawn: () => (argv, opts) => {+ seen.push(opts);+ return confining(argv, opts);+ },+ });+ try {+ await env.listTools();+ const file = path.join(tmp, "note.txt");+ const written = await execute(env, WRITE_FILE_NAME, {+ file_path: file,+ content: "one\ntwo\n",+ });+ expect(written.stopReason).toBe("completed");+ expect(written.output).toContain("Created");+ expect(await readFile(file, "utf8")).toBe("one\ntwo\n");+ const edited = await execute(env, EDIT_FILE_NAME, {+ file_path: file,+ old_string: "two",+ new_string: "three",+ });+ expect(edited.stopReason).toBe("completed");+ expect(edited.output).toContain("-two");+ expect(edited.output).toContain("+three");+ const read = await execute(env, READ_FILE_NAME, { file_path: "note.txt" });+ expect(read.output.split("\n")).toEqual([" 1\tone", " 2\tthree"]);+ // A missing path is diagnosed through the helper too, with the directory's entries.+ const missing = await execute(env, READ_FILE_NAME, { file_path: "nope.txt" });+ expect(missing.stopReason).toBe("fatal");+ expect(missing.output).toContain("has no entry");+ expect(missing.output).toContain("note.txt");+ // The helper is confined with the Session's scope, like a command.+ expect(seen[0]).toEqual({+ cwd: tmp,+ workspaceDir: tmp,+ scratchpadDir: path.join(tmp, "scratchpad", "s1"),+ });+ } finally {+ env.dispose();+ }+ });++ it("reads an image through the helper", async () => {+ const png = Buffer.from(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",+ "base64",+ );+ await writeFile(path.join(tmp, "dot.png"), png);+ const env = new Environment({+ workspaceDir: tmp,+ toolConfig: toolConfig(),+ confineSpawn: () => confining,+ });+ try {+ await env.listTools();+ const call = toolCall({+ name: READ_FILE_NAME,+ arguments: JSON.stringify({ file_path: "dot.png" }),+ toolCallId: "t2",+ });+ let images: string[] | undefined;+ for await (const msg of env.executeTool({ toolCall: call })) {+ const p = msg.payload as { type?: string; images?: string[] };+ if (p.type === "tool_call_output") images = p.images;+ }+ expect(images).toEqual([`data:image/png;base64,${png.toString("base64")}`]);+ } finally {+ env.dispose();+ }+ });++ it("reports a refused write as the sandbox's doing", async () => {+ if (process.platform === "win32" || process.getuid?.() === 0) return;+ const locked = path.join(tmp, "locked");+ await mkdir(locked);+ await writeFile(path.join(locked, "f.txt"), "x");+ await chmod(locked, 0o555);+ const env = new Environment({+ workspaceDir: tmp,+ toolConfig: toolConfig(),+ confineSpawn: () => confining,+ });+ try {+ await env.listTools();+ const written = await execute(env, WRITE_FILE_NAME, {+ file_path: path.join(locked, "f.txt"),+ content: "y",+ });+ expect(written.stopReason).toBe("fatal");+ expect(written.output).toContain("refused by this session's sandbox");+ } finally {+ env.dispose();+ await chmod(locked, 0o755);+ }+ });++ it("works in this process when the confiner leaves the helper's argv alone", async () => {+ let asked = 0;+ const env = new Environment({+ workspaceDir: tmp,+ toolConfig: toolConfig(),+ confineSpawn: () => (argv) => {+ asked += 1;+ return { argv };+ },+ });+ try {+ await env.listTools();+ const file = path.join(tmp, "plain.txt");+ const written = await execute(env, WRITE_FILE_NAME, { file_path: file, content: "z" });+ expect(written.stopReason).toBe("completed");+ expect(await readFile(file, "utf8")).toBe("z");+ expect(asked).toBe(1);+ } finally {+ env.dispose();+ }+ });+});diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.mdindex ee21e3b9..a14398f2 100644--- a/packages/docs/content/agent-loop.en.md+++ b/packages/docs/content/agent-loop.en.md@@ -133,7 +133,7 @@ A **hook** is a function the Session runs at a fixed point of the loop. Three poThe hooks a Session consults are the hook packages installed in the agent's `agent_state/hooks/` directory, whether a [plugin](/skills#hook-packages) shipped them or someone wrote them there by hand, the agent included. Like Skills, they are read from disk, together with the `hooks.enabled` switch, each time a model context opens: when the Session is created, after each compaction, and on resume. The new context's hooks replace the old ones whole, so a package written during a conversation is consulted from the next context on. SDK embedders can also register in-process functions through `SessionConfig.hooks.stop` / `.preToolUse` / `.userPrompt`.-An installed hook is a plain Node script, run as a subprocess the way Claude Code runs its command hooks. The script is told only where to look; it derives everything else from the Trace: Token usage, turn counts, how the Task ended, and its own state file. A non-zero exit is a failure, and the tail of stderr becomes the reason. A timeout kills the script; the timeout comes from the manifest's `timeout` field and defaults to 60 s.+An installed hook is a plain Node script, run as a subprocess the way Claude Code runs its command hooks. The subprocess runs under the Session's [sandbox](/settings#sandbox) exactly as a command does: same policy, same backend. A sandbox that cannot confine it fails the hook, with a reason that starts `hook failed: sandbox:`, and the script never runs unconfined. The script is told only where to look; it derives everything else from the Trace: Token usage, turn counts, how the Task ended, and its own state file. A non-zero exit is a failure, and the tail of stderr becomes the reason. A timeout kills the script; the timeout comes from the manifest's `timeout` field and defaults to 60 s.### Stop hooksdiff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.mdindex b0d0ee45..81ce2da5 100644--- a/packages/docs/content/agent-loop.zh.md+++ b/packages/docs/content/agent-loop.zh.md@@ -133,7 +133,7 @@ Task 由若干连续的 Request(轮)组成。每一轮:Session 咨询的钩子,就是安装在 Agent 的 `agent_state/hooks/` 目录里的钩子包,无论是[插件](/skills#钩子包)携带的,还是有人(包括 Agent 自己)手写进去的。它们像 Skill 一样,连同 `hooks.enabled` 开关,在每个模型上下文开启时从磁盘读取:创建 Session 时、每次压缩之后,以及恢复时。新上下文的钩子整体替换旧的,因此对话中写入的钩子包从下一个上下文起生效。SDK 嵌入方也可以经 `SessionConfig.hooks.stop` / `.preToolUse` / `.userPrompt` 注册进程内函数。-已安装的钩子是纯 Node 脚本,像 Claude Code 运行 command hook 那样以子进程运行。它只被告知去哪里看,其余一切都由它从 Trace 推导:Token 用量、轮数、Task 的结束方式,以及它自己的状态文件。退出码非零即为失败,stderr 的末尾成为 reason;超时的脚本会被终止,超时时长取清单里的 `timeout`,缺省 60 秒。+已安装的钩子是纯 Node 脚本,像 Claude Code 运行 command hook 那样以子进程运行。这个子进程与命令完全一样,在 Session 的[沙盒](/settings#沙盒)下运行:同一份策略,同一个后端。沙盒无法封禁它时,该次钩子失败,reason 以 `hook failed: sandbox:` 开头,脚本绝不会脱离封禁运行。它只被告知去哪里看,其余一切都由它从 Trace 推导:Token 用量、轮数、Task 的结束方式,以及它自己的状态文件。退出码非零即为失败,stderr 的末尾成为 reason;超时的脚本会被终止,超时时长取清单里的 `timeout`,缺省 60 秒。### Stop hookdiff --git a/packages/docs/content/interfaces.en.md b/packages/docs/content/interfaces.en.mdindex c518d303..2cf22722 100644--- a/packages/docs/content/interfaces.en.md+++ b/packages/docs/content/interfaces.en.md@@ -248,15 +248,17 @@ interface ToolExecutionRequest {interface EnvironmentConfig {workspaceDir: string;toolConfig: ToolConfig; // { customTools: ToolDefinitionConfig[]; mcpServers: MCPServerConfig[] }- sessionScratchpadDir?: string; // this Session's scratchpad (scratchpad/<sessionId>); enables truncated-output recovery+ sessionScratchpadDir?: string; // this Session's scratchpad (scratchpad/<sessionId>); enables truncated-output recovery,+ // and is writable beside the Workspace under a workspace-write sandboxservices?: EnvironmentServices; // runtime services injected into individual toolsvault?: Record<string, string>; // Vault env vars, injected into exec_command / input_command subprocessesproxyEnv?: () => ProxyEnvPolicy | null; // command-subprocess proxy policy; re-read per spawn, absent or null = pass throughcontrolEnv?: () => Record<string, string>; // host control variables (API address, token, Session coordinates); re-read per// spawn; override vault entries, never the hardened onespathPrepend?: () => string[]; // directories put at the front of PATH for command subprocesses; re-read per spawn- confineSpawn?: () => SpawnConfiner | null; // sandbox confinement for command subprocesses; re-read per spawn,- // absent or null = commands spawn unconfined+ confineSpawn?: () => SpawnConfiner | null; // sandbox confinement for everything spawned for the Session: command+ // subprocesses, stdio MCP Servers and the file tools' helper; re-read per+ // spawn, absent or null = everything spawns unconfined}// "strip" removes HTTP(S)_PROXY/ALL_PROXY (NO_PROXY kept); "inject" forces the explicit@@ -265,11 +267,28 @@ interface EnvironmentConfig {type ProxyEnvPolicy = { mode: "strip" } | { mode: "inject"; url: string; noProxy: string };// Rewrites the exact argv a command is about to spawn so it runs confined. Fail-closed: a-// confiner that cannot enforce its policy throws, and the command fails to spawn.+// confiner that cannot enforce its policy throws, and the command fails to spawn. What+// workspace-write may write is `workspaceDir` and `scratchpadDir` (the Session's scratchpad,+// absent without one), never `cwd`. Handed to createAgent, the same confiner also confines+// hook scripts: argv `[node, <script>]`, `cwd` the package directory.type SpawnConfiner = (argv: readonly string[],- opts: { cwd: string; workspaceDir: string },-) => readonly string[];+ opts: { cwd: string; workspaceDir: string; scratchpadDir?: string },+) => ConfinedSpawn;++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+}++// The policy itself (@prismshadow/penguin-core/plugin). "danger-full-access" with no network cut+// and no masked path is the sandbox off.+type SandboxSettings = {+ mode: "read-only" | "workspace-write" | "danger-full-access";+ network?: "none" | "local"; // absent = unrestricted; also bounds read_file's URL source+ maskPaths?: string[]; // hidden from commands, hook scripts and the file tools, reads included+ writableTemp?: boolean; // absent = the temporary directory is writable+};interface EnvironmentServices {subagentRunner?: SubagentRunner; // needed by run_subagent@@ -309,7 +328,9 @@ interface BuiltinTool {detachable?: boolean; // has a background form a running call can be moved toexecute(args: Record<string, unknown>,- ctx: ToolExecutionContext, // { workspaceDir, toolCallId, signal?, detachSignal?, approve? }+ ctx: ToolExecutionContext, // { workspaceDir, toolCallId, signal?, detachSignal?, approve?, fs? };+ // fs = the file-system port a file tool works through (the sandboxed helper+ // when the Session is confined, this process otherwise; fs.sandboxed says which)): AsyncGenerator<OmniMessage, ToolResult | void>;}@@ -382,7 +403,7 @@ interface VisionDescriberService {| --- | --- || Swap or customize model access | Implement `LLMInterface` (or just set `client_type` for OpenAI-compatible endpoints) || Swap the execution sandbox | Implement `EnvironmentInterface` |-| Confine the commands an agent runs | Supply `confineSpawn` with a `SpawnConfiner` |+| Confine what an agent runs and writes | Supply `confineSpawn` with a `SpawnConfiner`: it wraps commands, hook scripts, stdio MCP Servers and the file tools' helper alike || Add a tool | Implement `BuiltinTool`, register a factory, and list the tool under `tools.builtin` in `system_config.yaml` (entries without a registered factory are skipped); or connect an MCP server under `tools.mcpServers` || Customize approval policy | Inject an `ApproveFn` (the CLI and Web approval modes are wrappers over it) || Change an agent's behavior | Edit its Agent State (`system_config.yaml`, `AGENTS.md`, Skills); see the [Configuration Reference](/configuration) |diff --git a/packages/docs/content/interfaces.zh.md b/packages/docs/content/interfaces.zh.mdindex a6c95975..f06d3946 100644--- a/packages/docs/content/interfaces.zh.md+++ b/packages/docs/content/interfaces.zh.md@@ -248,15 +248,17 @@ interface ToolExecutionRequest {interface EnvironmentConfig {workspaceDir: string;toolConfig: ToolConfig; // { customTools: ToolDefinitionConfig[]; mcpServers: MCPServerConfig[] }- sessionScratchpadDir?: string; // this Session's scratchpad (scratchpad/<sessionId>); enables truncated-output recovery+ sessionScratchpadDir?: string; // this Session's scratchpad (scratchpad/<sessionId>); enables truncated-output recovery,+ // and is writable beside the Workspace under a workspace-write sandboxservices?: EnvironmentServices; // runtime services injected into individual toolsvault?: Record<string, string>; // Vault env vars, injected into exec_command / input_command subprocessesproxyEnv?: () => ProxyEnvPolicy | null; // command-subprocess proxy policy; re-read per spawn, absent or null = pass throughcontrolEnv?: () => Record<string, string>; // host control variables (API address, token, Session coordinates); re-read per// spawn; override vault entries, never the hardened onespathPrepend?: () => string[]; // directories put at the front of PATH for command subprocesses; re-read per spawn- confineSpawn?: () => SpawnConfiner | null; // sandbox confinement for command subprocesses; re-read per spawn,- // absent or null = commands spawn unconfined+ confineSpawn?: () => SpawnConfiner | null; // sandbox confinement for everything spawned for the Session: command+ // subprocesses, stdio MCP Servers and the file tools' helper; re-read per+ // spawn, absent or null = everything spawns unconfined}// "strip" removes HTTP(S)_PROXY/ALL_PROXY (NO_PROXY kept); "inject" forces the explicit@@ -265,11 +267,28 @@ interface EnvironmentConfig {type ProxyEnvPolicy = { mode: "strip" } | { mode: "inject"; url: string; noProxy: string };// Rewrites the exact argv a command is about to spawn so it runs confined. Fail-closed: a-// confiner that cannot enforce its policy throws, and the command fails to spawn.+// confiner that cannot enforce its policy throws, and the command fails to spawn. What+// workspace-write may write is `workspaceDir` and `scratchpadDir` (the Session's scratchpad,+// absent without one), never `cwd`. Handed to createAgent, the same confiner also confines+// hook scripts: argv `[node, <script>]`, `cwd` the package directory.type SpawnConfiner = (argv: readonly string[],- opts: { cwd: string; workspaceDir: string },-) => readonly string[];+ opts: { cwd: string; workspaceDir: string; scratchpadDir?: string },+) => ConfinedSpawn;++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+}++// The policy itself (@prismshadow/penguin-core/plugin). "danger-full-access" with no network cut+// and no masked path is the sandbox off.+type SandboxSettings = {+ mode: "read-only" | "workspace-write" | "danger-full-access";+ network?: "none" | "local"; // absent = unrestricted; also bounds read_file's URL source+ maskPaths?: string[]; // hidden from commands, hook scripts and the file tools, reads included+ writableTemp?: boolean; // absent = the temporary directory is writable+};interface EnvironmentServices {subagentRunner?: SubagentRunner; // needed by run_subagent@@ -309,7 +328,9 @@ interface BuiltinTool {detachable?: boolean; // has a background form a running call can be moved toexecute(args: Record<string, unknown>,- ctx: ToolExecutionContext, // { workspaceDir, toolCallId, signal?, detachSignal?, approve? }+ ctx: ToolExecutionContext, // { workspaceDir, toolCallId, signal?, detachSignal?, approve?, fs? };+ // fs = the file-system port a file tool works through (the sandboxed helper+ // when the Session is confined, this process otherwise; fs.sandboxed says which)): AsyncGenerator<OmniMessage, ToolResult | void>;}@@ -382,7 +403,7 @@ interface VisionDescriberService {| --- | --- || 更换或自定义模型访问 | 实现 `LLMInterface`(或者只为 OpenAI 兼容端点设置 `client_type`) || 更换执行沙箱 | 实现 `EnvironmentInterface` |-| 约束 Agent 执行的命令 | 给 `confineSpawn` 提供一个 `SpawnConfiner` |+| 约束 Agent 的执行与写入 | 给 `confineSpawn` 提供一个 `SpawnConfiner`:它同样包裹命令、钩子脚本、stdio MCP Server 与文件工具的助手 || 添加工具 | 实现 `BuiltinTool` 并注册工厂,然后在 `system_config.yaml` 的 `tools.builtin` 下列出这个工具(没有注册工厂的条目直接跳过);或者在 `tools.mcpServers` 下接入 MCP 服务器 || 自定义审批策略 | 注入一个 `ApproveFn`(CLI 和 Web 的审批模式都是对它的封装) || 修改 Agent 的行为 | 编辑它的 Agent State(`system_config.yaml`、`AGENTS.md`、Skill);见[配置参考](/configuration) |diff --git a/packages/docs/content/server-boot.en.md b/packages/docs/content/server-boot.en.mdindex f4f30aec..642c51ee 100644--- a/packages/docs/content/server-boot.en.md+++ b/packages/docs/content/server-boot.en.md@@ -206,7 +206,7 @@ Each subsystem's construction site and external surface. Step numbers ① to ⑫| HMR host / platform | `@prismshadow/penguin-hmr` (`HmrHost`, `hmrMain`) and `hmr/platform.ts` (the platform) | `PlatformApi` (`info` / `log` / `http` / `terminals` / `attachStream` / `business` / `shutdown` / `drained`, plus the kernel's `park`); `/api/hmr/*`, including `POST /api/hmr/upgrade`, is a route group the platform contributes — a pushed generation that does not serve it is refused before commit || Terminals | `terminal/` — **App-level** | `/api/terminals*` route group, WS `GET /api/terminals/:id/stream`; ptys are parked and survive swaps || Plugin host | built by each App's `create()` and registered at its commit for the next App to reuse; ⑤ `loadPlugins` publishes one in ⑥ for platforms that predate this | an npm package: its generated `ifaces.json` (the module payload), a default export `{ modules?: [<class>, …], replaces?: [<class>, …] }`; the configuration surface is the `[plugins]` table of each Project's `.project_config.toml`, written through `/api/projects/:projectId/plugins/installed` |-| Sandbox | `sandbox/service.ts` — **App-level** (a module; backends contribute to its `providers` slot) | a `SandboxModule.providers` contribution from a plugin module; enforcement reaches commands through core's spawn seam |+| Sandbox | `sandbox/service.ts` — **App-level** (a module; backends contribute to its `providers` slot) | a `SandboxModule.providers` contribution from a plugin module; enforcement reaches commands and hook scripts through core's spawn seam, and the Session's policy reaches the file tools through core's `sandboxPolicy` seam || Module tree | `src/platform.ts` — **App-level** (booted by create over the claimed capabilities) | `@Component()` on each service / repo class (a node is named by its class) with `@Use()` fields for its dependencies; `@Module({ children, exports })` groups (`IdentityModule`, `ProjectsModule`, …) whose exports are what their children offer the rest of the tree; `@Module({ … })` classes with `@Provide()` fields where one class builds several things; narrow consumer interfaces as abstract classes beside their consumer (`extends Interface<…>()`); no `modules/` directory — each node lives in the file of the thing it is; `src/ifaces.json` generated; `GET /api/contributions` lists what reached the web slots || Model catalog | No boot-time construction — static core data | `/api/projects/:projectId/models`; the catalog itself lives in `core/src/state/model-catalog.ts` |diff --git a/packages/docs/content/server-boot.zh.md b/packages/docs/content/server-boot.zh.mdindex c85ba2f8..cfa0ae7b 100644--- a/packages/docs/content/server-boot.zh.md+++ b/packages/docs/content/server-boot.zh.md@@ -206,7 +206,7 @@ createInner| HMR 宿主 / 平台 | `@prismshadow/penguin-hmr`(`HmrHost`、`hmrMain`)与 `hmr/platform.ts`(平台) | `PlatformApi`(`info` / `log` / `http` / `terminals` / `attachStream` / `business` / `shutdown` / `drained`,外加内核的 `park`);`/api/hmr/*`(含 `POST /api/hmr/upgrade`)是平台贡献的路由组,推送的新一代若不提供这组路由,会在提交前被拒 || 终端 | `terminal/`——**App 级** | `/api/terminals*` 路由组、WS `GET /api/terminals/:id/stream`;pty 寄存在注册表中,跨热替换存活 || 插件宿主 | 每个 App 的 `create()` 构建,在提交时登记进注册表供下一个 App 复用;⑤ `loadPlugins` 为早于这一改动的平台构建一份,在 ⑥ 发布 | 一个 npm 包:生成的 `ifaces.json`(模块载荷)、默认导出 `{ modules?: [<class>, …], replaces?: [<class>, …] }`;配置面是各 Project 的 `.project_config.toml` 中的 `[plugins]` 表,经 `/api/projects/:projectId/plugins/installed` 写入 |-| 沙箱 | `sandbox/service.ts`——**App 级**(一个模块;后端向它的 `providers` 槽位投递) | 插件模块向 `SandboxModule.providers` 投递的一条 contribution;约束经 core 的 spawn 接缝落到命令上 |+| 沙箱 | `sandbox/service.ts`——**App 级**(一个模块;后端向它的 `providers` 槽位投递) | 插件模块向 `SandboxModule.providers` 投递的一条 contribution;约束经 core 的 spawn 接缝落到命令与钩子脚本上,Session 的策略经 core 的 `sandboxPolicy` 接缝交给文件工具 || 模块树 | `src/platform.ts`——**App 级**(create 在认领的能力之上启动它) | 每个服务 / repo 类用 `@Component()` 标注(节点以类命名),依赖写成 `@Use()` 字段;`@Module({ children, exports })` 组(`IdentityModule`、`ProjectsModule` 等),exports 就是子节点向树里其余部分提供的东西;一个类要构建多个东西时,用带 `@Provide()` 字段的 `@Module({ … })` 类;消费方的窄接口是抽象类,声明在消费方旁边(`extends Interface<…>()`);没有 `modules/` 目录——每个节点就住在它对应事物所在的文件里;`src/ifaces.json` 为生成文件;`GET /api/contributions` 列出到达 web 槽位的内容 || 模型目录 | 无启动期构建——core 的静态数据 | `/api/projects/:projectId/models`;目录本体在 `core/src/state/model-catalog.ts` |diff --git a/packages/docs/content/settings.en.md b/packages/docs/content/settings.en.mdindex 030a8777..1f3b0817 100644--- a/packages/docs/content/settings.en.md+++ b/packages/docs/content/settings.en.md@@ -248,14 +248,16 @@ The **Plugins** page is admin-only and server-global. It shows the options each### Sandbox-The sandbox is the first card on the page. It sets the confinement every agent command is spawned under:+The sandbox is the first card on the page. It sets the policy a new Session is confined under. One policy governs the commands the agent runs, the hook scripts its Session runs, the MCP Servers it starts over `stdio`, and the file tools (`read_file`, `edit_file`, `write_file`):-- **Confinement mode**: off (full access), workspace write only, or read-only.-- **Network**: full access, local network (localhost only), or no network. The local level needs a backend that can enforce it.+- **Confinement mode**: off (full access), workspace write only, or read-only. Workspace write 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.+- **Network**: full access, local network (localhost only), or no network. It applies to the image URLs `read_file` fetches too. The local level needs a backend that can enforce it.- **Temporary directory**: whether it stays writable. On by default, in either confining mode, because shells and most tools cannot start without one.-- **Masked paths**: paths hidden from a confined command, one absolute path per line, at most 64.+- **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.-A sandbox backend installed as a plugin (bwrap, Seatbelt, DSH) enforces the mode. The card lists the mounted backends and the isolation each one implements, and says so when there is none. Without a backend, every mode but off refuses every agent command.+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 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.mdindex ff369df4..d36b9167 100644--- a/packages/docs/content/settings.zh.md+++ b/packages/docs/content/settings.zh.md@@ -248,14 +248,16 @@ Trace 会成为该 Agent 的一段新对话。如果该 Agent 下已有相同 id### 沙盒-沙盒是页面上的第一张卡片,设置 Agent 执行每条命令时所处的封禁:+沙盒是页面上的第一张卡片,设置新建 Session 所处的封禁策略。同一份策略约束 Agent 执行的命令、Session 运行的钩子脚本、它以 `stdio` 方式启动的 MCP Server,以及文件工具(`read_file`、`edit_file`、`write_file`):-- **封禁模式**:关闭(完全访问)、仅工作区可写或只读。-- **网络**:完全访问、本地网络(仅本机 localhost)或无网络。本地网络需要能实施它的后端。+- **封禁模式**:关闭(完全访问)、仅工作区可写或只读。仅工作区可写时,可写的是 Session 的 Workspace、它的 scratchpad(计划文件、goal 的状态文件与附件都在这里)和临时目录;只读时只有临时目录可写。+- **网络**:完全访问、本地网络(仅本机 localhost)或无网络。`read_file` 读取的图片 URL 同样受它约束。本地网络需要能实施它的后端。- **临时目录**:是否保持可写。默认开启,两种封禁模式下都生效,因为 Shell 与大多数工具没有它就无法启动。-- **屏蔽路径**:对被封禁命令隐藏的路径,每行一个绝对路径,最多 64 条。+- **屏蔽路径**:对 Agent 的命令、钩子脚本、`stdio` MCP Server 和文件工具隐藏的路径,读取也不例外;每行一个绝对路径,最多 64 条。-真正实施封禁的是以插件形式安装的沙盒后端(bwrap、Seatbelt、DSH)。卡片列出已挂载的后端及各自实现的隔离维度,一个都没有时会明确说明。没有后端时,除关闭外的任何模式都会拒绝 Agent 的每条命令。+两种封禁模式都不允许 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 的程序路径与 1–30 秒的探测超时,Seatbelt 的程序路径)画在同一张卡片里,卡片的一个**保存**一并存下。未通过自检的后端(例如程序路径写错)会在这次保存后重新加载,无需重启。diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.mdindex 3144e361..8ad01171 100644--- a/packages/docs/content/skills.en.md+++ b/packages/docs/content/skills.en.md@@ -141,7 +141,7 @@ To upload a zip file:3. If a package with the same name is already installed, confirm with **Overwrite**.> [!WARNING]-> An imported hook package takes effect at once. While the agent has hooks on, its scripts run on this machine at every hook point, so import only packages you trust.+> An imported hook package takes effect at once. While the agent has hooks on, its scripts run on this machine at every hook point, so import only packages you trust. They run under the conversation's [sandbox](/settings#sandbox), the same policy as the agent's commands; with the sandbox off, they have the harness's own permissions.## Server pluginsdiff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.mdindex c6242035..b9394e67 100644--- a/packages/docs/content/skills.zh.md+++ b/packages/docs/content/skills.zh.md@@ -141,7 +141,7 @@ zip 文件最大 14 MB,最多 200 个文件;解压后单个文件不超过 53. 如果已安装同名包,点击**覆盖安装**确认。> [!WARNING]-> 导入的钩子包立即生效。只要 Agent 开着钩子,这些脚本就会在本机的每个钩子点运行,请只导入你信任的包。+> 导入的钩子包立即生效。只要 Agent 开着钩子,这些脚本就会在本机的每个钩子点运行,请只导入你信任的包。它们在对话的[沙盒](/settings#沙盒)下运行,与 Agent 的命令遵守同一份策略;沙盒关闭时,它们拥有 harness 自身的权限。## 服务端插件diff --git a/packages/docs/content/tools.en.md b/packages/docs/content/tools.en.mdindex 8e59f5e9..96a14ff8 100644--- a/packages/docs/content/tools.en.md+++ b/packages/docs/content/tools.en.md@@ -188,9 +188,15 @@ The tools' arguments (explicit keys):### File tools-`read_file` / `edit_file` / `write_file` run with the user's full permissions, like the shell tool. Relative paths resolve against the Workspace, and absolute paths are allowed. A symlinked path is followed to the file it names: reads, edits and writes all land on that file, and the link stays a link. `read_file` refuses the secret stores `.vault.toml` and `.project_config.toml`, matched by file name in any directory and after following symlinks.+`read_file` / `edit_file` / `write_file` are harness code, but every file-system effect they have — a stat, a read, an atomic write, a directory listing, a symlink resolution, and `read_file`'s download of an image URL — goes through a file-system port. Relative paths resolve against the Workspace, and absolute paths are allowed. A symlinked path is followed to the file it names: reads, edits and writes all land on that file, and the link stays a link. `read_file` refuses the secret stores `.vault.toml` and `.project_config.toml`, matched by file name in any directory and after following symlinks.-The file tools return a single final output rather than a stream, with one exception: for a text-only model, `read_file` streams the vision model's description of an image. They never throw. Failures come back as explanatory text with `stop_reason: fatal`.+In a Session the [sandbox](/settings#sandbox) confines, the port is a helper process the same confiner wraps that wraps a command: the harness starts a Node process with the helper's program inline (`node -e …`, builtin modules only, so nothing has to ship beside a bundle) under the same policy and scope — the Workspace and the Session's scratchpad — and the tools' operations cross to it as JSON lines on its stdin and stdout. What the tools can do is then exactly what a command can: the backend that bounds the Session's commands bounds them, mask paths included, and a download follows the network level. One helper serves a Session: it starts at the first confined file operation, is reused for the rest, is started over when the Session's policy changes or after a crash, is killed when a call is aborted (the sandbox may be stalling that operation), and stops with the Session. A refused write comes back as the kernel's permission error, and the tool names the sandbox so the next attempt can take another route:++```text+Failed to write "/etc/hosts": EROFS: read-only file system, open '/etc/hosts' — refused by this session's sandbox, which does not allow that here.+```++Under the WSL backend the helper runs inside the distro, which the initialization installs `nodejs` into: Windows drive paths are mapped to their `/mnt/<drive>` spelling on the way in and back on the way out. A distro initialized before `nodejs` joined the package list needs initializing again. Without a sandbox, as when the SDK or the CLI runs standalone or the sandbox is off, the port is the harness process itself and the tools run with the user's full permissions, like the shell tool.`edit_file` and `write_file` serialize per file within the server process, keyed by the file's real path, so a symlink and its target count as one file. Parallel edits of one file are applied one after another, and an `old_string` that an earlier edit removed fails to match instead of overwriting it. Writes from other processes are outside this lock.@@ -390,7 +396,7 @@ tools:Each `tools.mcpServers` entry is `{ name, config }`. `name` becomes the tool-name prefix: it must start with a letter or digit and contain only letters, digits, `_` and `-`, and a duplicate name is skipped. `config` describes the transport. Three transports are supported:-- `stdio`: a local process (`command` / `args` / `env` / `cwd`). The process environment is the SDK's safe inherited defaults plus the entry's `env`, with `env` winning. Unlike command subprocesses, MCP Server processes do **not** receive the agent's Vault: list any variable a Server needs in the entry's `env`. `cwd` defaults to the Session's Workspace.+- `stdio`: a local process (`command` / `args` / `env` / `cwd`). The process environment is the SDK's safe inherited defaults plus the entry's `env`, with `env` winning. Unlike command subprocesses, MCP Server processes do **not** receive the agent's Vault: list any variable a Server needs in the entry's `env`. `cwd` defaults to the Session's Workspace. The process starts under the Session's [sandbox](/settings#sandbox) exactly as a command does: the same confiner rewrites its argv, and a policy no backend can enforce fails the Server's connect rather than starting it unconfined.- `http`: Streamable HTTP, the current spec's remote transport (`url` / `headers`).- `sse`: the legacy HTTP+SSE transport, kept for servers that have not migrated (`url` / `headers`).diff --git a/packages/docs/content/tools.zh.md b/packages/docs/content/tools.zh.mdindex 936d6260..e208f736 100644--- a/packages/docs/content/tools.zh.md+++ b/packages/docs/content/tools.zh.md@@ -188,9 +188,15 @@ exec_command(cmd)### 文件工具-`read_file` / `edit_file` / `write_file` 与 shell 工具一样,以用户的完整权限运行。相对路径以 Workspace 为基准解析,也允许绝对路径。符号链接会解析到它指向的文件:读取、编辑和写入都作用于目标文件,链接本身仍是链接。`read_file` 拒绝读取机密存储 `.vault.toml` 和 `.project_config.toml`:无论文件位于哪个目录、路径是否经过符号链接,都按文件名匹配。+`read_file` / `edit_file` / `write_file` 是 harness 自己的代码,但它们的每一次文件系统效果——stat、读取、原子写入、列目录、解析符号链接,以及 `read_file` 下载图片 URL——都经一个文件系统端口执行。相对路径以 Workspace 为基准解析,也允许绝对路径。符号链接会解析到它指向的文件:读取、编辑和写入都作用于目标文件,链接本身仍是链接。`read_file` 拒绝读取机密存储 `.vault.toml` 和 `.project_config.toml`:无论文件位于哪个目录、路径是否经过符号链接,都按文件名匹配。-文件工具返回单个最终输出,而不是流式输出;唯一的例外是:对纯文本模型,`read_file` 会流式返回视觉模型对图片的描述。这些工具从不抛出异常。失败时以解释性文字返回,并带有 `stop_reason: fatal`。+在被[沙盒](/settings#沙盒)封禁的 Session 里,这个端口是一个助手进程,由包裹命令的同一个 confiner 包裹:harness 以内联程序启动一个 Node 进程(`node -e …`,只用内置模块,因此无需随 bundle 分发任何文件),策略与范围(Workspace 与 Session 的 scratchpad)与命令相同,工具的各项操作以 JSON 行经它的 stdin / stdout 往返。文件工具能做的于是与命令完全一致:约束 Session 命令的后端同样约束它们,屏蔽路径也不例外,下载遵守网络档位。每个 Session 一个助手:在第一次受封禁的文件操作时启动、此后复用,Session 的策略改变或助手崩溃后重新启动,调用被中止时被杀掉(沙盒可能正卡住这次操作),随 Session 一起结束。被拒绝的写入以内核的权限错误返回,工具点明是沙盒所为,让模型换一条路再试:++```text+Failed to write "/etc/hosts": EROFS: read-only file system, open '/etc/hosts' — refused by this session's sandbox, which does not allow that here.+```++WSL 后端下,助手在发行版内运行,初始化时已把 `nodejs` 装进发行版:Windows 盘符路径在进入时映射为 `/mnt/<盘符>` 的写法,返回时还原。在 `nodejs` 加入软件包列表之前初始化的发行版需要重新初始化。没有沙盒时(SDK 或 CLI 独立运行,或沙盒关闭),端口就是 harness 进程本身,文件工具与 shell 工具一样以用户的完整权限运行。`edit_file` 和 `write_file` 在服务器进程内按文件串行执行,串行键取文件的真实路径,因此符号链接与其目标算作同一个文件。并行编辑同一文件时,会依次应用各次修改;如果前一次编辑已经移除了某个 `old_string`,后续编辑将匹配失败,而不是覆盖前面的修改。其他进程的写入不受这把锁约束。@@ -390,7 +396,7 @@ tools:`tools.mcpServers` 的每一项都是 `{ name, config }`。`name` 会成为工具名的前缀:必须以字母或数字开头,且只能包含字母、数字、`_` 和 `-`;名称重复的条目直接跳过。`config` 描述传输方式,支持三种:-- `stdio`:本地进程(`command` / `args` / `env` / `cwd`)。进程环境变量由 SDK 的安全继承默认值和条目的 `env` 合并而成,`env` 优先。与命令子进程不同,MCP Server 进程**不会**拿到 Agent 的 Vault:Server 需要的任何变量都要列在条目的 `env` 里。`cwd` 默认为当前 Session 的 Workspace。+- `stdio`:本地进程(`command` / `args` / `env` / `cwd`)。进程环境变量由 SDK 的安全继承默认值和条目的 `env` 合并而成,`env` 优先。与命令子进程不同,MCP Server 进程**不会**拿到 Agent 的 Vault:Server 需要的任何变量都要列在条目的 `env` 里。`cwd` 默认为当前 Session 的 Workspace。该进程与命令一样在 Session 的[沙盒](/settings#沙盒)下启动:同一个 confiner 改写它的 argv,没有后端能实施的策略会让该 Server 连接失败,而不是脱离封禁启动。- `http`:Streamable HTTP,当前规范的远程传输方式(`url` / `headers`)。- `sse`:旧式 HTTP+SSE 传输方式,为尚未迁移的 Server 保留(`url` / `headers`)。diff --git a/packages/server/src/sandbox/service.ts b/packages/server/src/sandbox/service.tsindex bf92f152..586de991 100644--- a/packages/server/src/sandbox/service.ts+++ b/packages/server/src/sandbox/service.ts@@ -222,6 +222,9 @@ export class SandboxService {const policy: SandboxPolicy = {mode: settings.mode,workspaceRoot: opts.workspaceDir,+ // The Session's scratchpad is writable beside the Workspace: the plan file, a goal's+ // state file and the attachments live there, and hooks and commands both write it.+ ...(opts.scratchpadDir !== undefined ? { writableRoots: [opts.scratchpadDir] } : {}),...(settings.network !== undefined ? { network: settings.network } : {}),...(settings.maskPaths !== undefined && settings.maskPaths.length > 0? { maskPaths: settings.maskPaths }diff --git a/packages/server/src/sandbox/settings-store.ts b/packages/server/src/sandbox/settings-store.tsindex 1208a6c7..19cba680 100644--- a/packages/server/src/sandbox/settings-store.ts+++ b/packages/server/src/sandbox/settings-store.ts@@ -76,9 +76,9 @@ export function sandboxPolicyOf(doc: Record<string, unknown>): Policy {title: "Network",titleZh: "网络",description:- "What a confined command may reach. Local network allows only this machine's localhost, and needs a backend that can enforce it.",+ "What a confined command, hook script or read_file URL may reach. Local network allows only this machine's localhost, and needs a backend that can enforce it.",descriptionZh:- "被封禁的命令能访问的网络。本地网络只允许访问本机 localhost,需要能实施它的后端。",+ "被封禁的命令、钩子脚本与 read_file 的 URL 能访问的网络。本地网络只允许访问本机 localhost,需要能实施它的后端。",default: "open",options: [{ value: "open", title: "Full access", titleZh: "完全访问" },@@ -95,9 +95,9 @@ export function sandboxPolicyOf(doc: Record<string, unknown>): Policy {title: "Temporary directory writable",titleZh: "临时目录可写",description:- "Confined commands may write the system temp directory, in either mode. Shells and most tools need one to start; off keeps it read-only too.",+ "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.",descriptionZh:- "被封禁的命令在两种模式下都可以写系统临时目录。Shell 与大多数工具需要它才能启动;关闭后临时目录同样只读。",+ "被封禁的命令、钩子脚本与文件工具在两种模式下都可以写系统临时目录。Shell 与大多数工具需要它才能启动;关闭后临时目录同样只读。",default: true,},maskPaths: {@@ -105,8 +105,8 @@ export function sandboxPolicyOf(doc: Record<string, unknown>): Policy {title: "Masked paths",titleZh: "屏蔽路径",description:- "One absolute path per line, hidden from confined commands (reads included).",- descriptionZh: "每行一个绝对路径,对被封禁的命令隐藏(包括读取)。",+ "One absolute path per line, hidden from confined commands, hook scripts and file tools (reads included).",+ descriptionZh: "每行一个绝对路径,对被封禁的命令、钩子脚本与文件工具隐藏(包括读取)。",maxItems: 64,// POSIX `/…`, Windows `C:\…` or `C:/…`, or a UNC `\\server\…`.pattern: "^(?:/|[A-Za-z]:[\\\\/]|\\\\\\\\)",@@ -176,8 +176,8 @@ export class SandboxSettingsStatus {const needs = required.join(" + ");notices.push({tone: "attention",- text: `The saved mode needs ${needs}, and no usable backend implements it: every agent command is refused until one does.`,- textZh: `当前保存的模式需要 ${needs},但没有可用的后端实现它:在有后端能实施之前,Agent 的每条命令都会被拒绝。`,+ text: `The saved mode needs ${needs}, and no usable backend implements it: every agent command and hook script is refused until one does.`,+ textZh: `当前保存的模式需要 ${needs},但没有可用的后端实现它:在有后端能实施之前,Agent 的每条命令与钩子脚本都会被拒绝。`,});}}@@ -191,8 +191,8 @@ export class SandboxSettingsStatus {declined.length === 0 ? "" : `已安装 ${declined.join("、")},但它们适用于其他平台。`;notices.push({tone: "attention",- text: `This deployment has no usable sandbox backend: until one for this platform is installed from the Plugins page, every mode but Off refuses every agent command.${elsewhere}`,- textZh: `当前部署没有可用的沙盒后端:在插件页安装适用于本平台的后端之前,除「关闭」外的任何模式都会拒绝 Agent 的每条命令。${elsewhereZh}`,+ 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(" · ");diff --git a/packages/server/test/sandbox-settings.test.ts b/packages/server/test/sandbox-settings.test.tsindex 9fc4c5e1..89c79ab0 100644--- a/packages/server/test/sandbox-settings.test.ts+++ b/packages/server/test/sandbox-settings.test.ts@@ -241,11 +241,11 @@ describe("sandbox settings group", () => {expect(notices).toEqual([["attention",- "The saved mode needs fs-write, and no usable backend implements it: every agent command is refused until one does.",+ "The saved mode needs fs-write, and no usable backend implements it: every agent command and hook script is refused until one does.",],["attention",- "This deployment has no usable sandbox backend: until one for this platform is installed from the Plugins page, every mode but Off refuses every agent command. other-platform is installed, but for another platform.",+ "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. other-platform is installed, but for another platform.",],["attention", "wrong-backend is not in use: 'bwrap' is missing"],]);diff --git a/packages/server/test/sandbox.test.ts b/packages/server/test/sandbox.test.tsindex a02f9c1f..5ffa6c2a 100644--- a/packages/server/test/sandbox.test.ts+++ b/packages/server/test/sandbox.test.ts@@ -158,6 +158,19 @@ describe("sandbox service — the built-in interface and its optional dimensionsexpect(svc.backends()).toEqual([{ name: "dsh-local", dimensions: ["fs-write"] }]);});+ it("the Session's scratchpad reaches the backend as a further writable root, and without one no such field does", async () => {+ const dsh = fake("dsh");+ const svc = await service([["dsh-local", dsh.provider]]);+ const confine = svc.confinerFor(() => ({ mode: "workspace-write" }));+ confine([...ARGV], { ...OPTS, scratchpadDir: "/data/agent/scratchpad/session-1" });+ confine([...ARGV], OPTS);+ expect(dsh.calls[0]).toMatchObject({+ workspaceRoot: "/work/project",+ writableRoots: ["/data/agent/scratchpad/session-1"],+ });+ expect(dsh.calls[1]).not.toHaveProperty("writableRoots");+ });+it("requiring a dimension nothing implements is refused, naming what each backend does", async () => {const dsh = fake("dsh");const svc = await service([["dsh-local", dsh.provider]]);diff --git a/plugins/agent-tuning/plugin.json b/plugins/agent-tuning/plugin.jsonindex bbfb5e38..e35905d4 100644--- a/plugins/agent-tuning/plugin.json+++ b/plugins/agent-tuning/plugin.json@@ -3,6 +3,6 @@"description_zh": "闭环的 Agent 调优:依据需求初始化 Agent、设计并校准能力 Benchmark、隔离执行与评分、再根据测得结果改进 Agent。","short_description": "Initialize, benchmark, evaluate and improve agents.","short_description_zh": "初始化、评测、评分与改进 Agent。",- "version": "2026.09.29.1",+ "version": "2026.09.30.1","category": "ai-app-development"}diff --git a/plugins/agent-tuning/skills/agent-initialization/SKILL.md b/plugins/agent-tuning/skills/agent-initialization/SKILL.mdindex 15d05163..6cd44aa3 100644--- a/plugins/agent-tuning/skills/agent-initialization/SKILL.md+++ b/plugins/agent-tuning/skills/agent-initialization/SKILL.md@@ -127,7 +127,7 @@ cd "$TARGET/agent_state/hooks/append-time"echo '{"hook":"user_prompt","session_id":"test","scratchpad_dir":"/tmp","prompt":"hello"}' | node time.mjs; echo "exit $?"```-A hook runs on the user's machine with the harness's own permissions, on every prompt, tool call or task. Tell the user what each hook you install does and at which point it fires. One switch turns all of an agent's hooks off without uninstalling them: `hooks.enabled: false` in `system_config.yaml`.+A hook runs on the user's machine, on every prompt, tool call or task, under the Session's sandbox: the same policy as the agent's commands, which with the sandbox off means the harness's own permissions. Tell the user what each hook you install does and at which point it fires. One switch turns all of an agent's hooks off without uninstalling them: `hooks.enabled: false` in `system_config.yaml`.## When a change takes effectdiff --git a/plugins/agent-tuning/skills/agent-initialization/reference/hooks.md b/plugins/agent-tuning/skills/agent-initialization/reference/hooks.mdindex e00a5ab3..552d6674 100644--- a/plugins/agent-tuning/skills/agent-initialization/reference/hooks.md+++ b/plugins/agent-tuning/skills/agent-initialization/reference/hooks.md@@ -92,7 +92,7 @@ The first `continue` wins. After a cutoff a `continue` is recorded but not run:## Failures-A non-zero exit, stdout that is not JSON, or a timeout is a failure. The harness records it as a `hook` event carrying the error (the tail of stderr for a non-zero exit) and carries on as if the hook had no opinion. To debug a hook that seems not to fire, look for `"type":"hook"` records in the Trace file, and run the script by hand:+A non-zero exit, stdout that is not JSON, or a timeout is a failure. So is a script the Session's sandbox could not confine: it never runs, and its error starts with `sandbox:`. The harness records a failure as a `hook` event carrying the error (the tail of stderr for a non-zero exit) and carries on as if the hook had no opinion. To debug a hook that seems not to fire, look for `"type":"hook"` records in the Trace file, and run the script by hand:```bashecho '{"hook":"stop","session_id":"test","trace_path":"/path/to/trace.jsonl"}' | node stop.mjs; echo "exit $?"diff --git a/plugins/sandbox-bwrap/README.md b/plugins/sandbox-bwrap/README.mdindex 6b7e453b..ef7be837 100644--- a/plugins/sandbox-bwrap/README.md+++ b/plugins/sandbox-bwrap/README.md@@ -31,7 +31,7 @@ profile is assembled in this sequence:| --- | --- || The read-only world | `--ro-bind / /`, `--dev /dev`, `--proc /proc`, `--die-with-parent` || writable temp (either mode) | `--tmpfs /tmp`, `--bind <tmpdir> <same>` when `$TMPDIR` is elsewhere |-| `workspace-write` | `--bind <workspaceRoot> <same>` |+| `workspace-write` | `--bind <workspaceRoot> <same>`, then `--bind <root> <same>` for each of the policy's `writableRoots` (the Session's scratchpad) || `network: none` | `--unshare-net` || `network: local` | not supported: an empty network namespace loses the host's loopback too || `mask-paths` | `--tmpfs <dir>` or `--ro-bind /dev/null <file>` |diff --git a/plugins/sandbox-bwrap/src/index.ts b/plugins/sandbox-bwrap/src/index.tsindex 825124f3..53d14936 100644--- a/plugins/sandbox-bwrap/src/index.ts+++ b/plugins/sandbox-bwrap/src/index.ts@@ -14,7 +14,7 @@** --ro-bind / / --dev /dev --proc /proc --die-with-parent the read-only world* [writable temp] --tmpfs /tmp --bind <tmpdir> <same> a private, writable /tmp- * [workspace-write] --bind <workspaceRoot> <same>+ * [workspace-write] --bind <workspaceRoot> <same> --bind <writableRoot> <same>…* [network: none] --unshare-net no network namespace* [mask-paths] --tmpfs <dir> | --ro-bind /dev/null <file> shadowing the above* -- <the caller's argv>@@ -124,12 +124,15 @@ export abstract class BwrapConfigReader {export const BWRAP_GROUP = "sandbox-bwrap";/**- * The writable roots a policy grants, canonical and deduplicated: the workspace under- * `workspace-write`, and the temp areas whenever the policy makes temp writable (either mode).+ * The writable roots a policy grants, canonical and deduplicated: the workspace and the+ * policy's further roots (the Session's scratchpad) under `workspace-write`, and the temp+ * areas whenever the policy makes temp writable (either mode).*/export function writableRoots(policy: SandboxPolicy): string[] {const roots = [- ...(policy.mode === "workspace-write" ? [policy.workspaceRoot] : []),+ ...(policy.mode === "workspace-write"+ ? [policy.workspaceRoot, ...(policy.writableRoots ?? [])]+ : []),...(policy.writableTemp === true ? ["/tmp", tmpdir()] : []),].map((root) => path.resolve(root));return [...new Set(roots)];diff --git a/plugins/sandbox-bwrap/test/profile.test.ts b/plugins/sandbox-bwrap/test/profile.test.tsindex 74a43388..cc03d974 100644--- a/plugins/sandbox-bwrap/test/profile.test.ts+++ b/plugins/sandbox-bwrap/test/profile.test.ts@@ -59,6 +59,28 @@ describe("penguin-bwrap profile", () => {},);+ // skipIf(win32): as above, host path resolution would rewrite the POSIX literals.+ it.skipIf(process.platform === "win32")(+ "workspace-write binds the policy's further roots (the Session's scratchpad) writable; read-only ignores them",+ () => {+ const scratchpad = "/data/agent/scratchpad/session-1";+ const args = bwrapProfileArgs({+ mode: "workspace-write",+ workspaceRoot: WS,+ writableRoots: [scratchpad],+ });+ expect(args.join(" ")).toContain(`--bind ${WS} ${WS}`);+ expect(args.join(" ")).toContain(`--bind ${scratchpad} ${scratchpad}`);++ const readOnly = bwrapProfileArgs({+ mode: "read-only",+ workspaceRoot: WS,+ writableRoots: [scratchpad],+ });+ expect(readOnly).toEqual(bwrapProfileArgs({ mode: "read-only", workspaceRoot: WS }));+ },+ );+it("read-only with writable temp: a tmpfs /tmp is the only writable place", () => {const args = bwrapProfileArgs({ mode: "read-only", workspaceRoot: WS, writableTemp: true });expect(args.join(" ")).toContain("--tmpfs /tmp");diff --git a/plugins/sandbox-seatbelt/README.md b/plugins/sandbox-seatbelt/README.mdindex 9a58af77..b9dcbe60 100644--- a/plugins/sandbox-seatbelt/README.md+++ b/plugins/sandbox-seatbelt/README.md@@ -24,7 +24,7 @@ still name another program, and a host where it does not work is caught by the l(allow default) ; start from the host's world(deny file-write*) ; nothing is writable…(allow file-write* (literal "/dev/null") …) ; …beyond the required sinks-;; workspace-write, and the temp areas when temp is writable+;; workspace-write (the Workspace and the policy's writableRoots, the Session's scratchpad), and the temp areas when temp is writable(allow file-write* (subpath "<workspaceRoot>") …);; network: none(deny network*)diff --git a/plugins/sandbox-seatbelt/src/index.ts b/plugins/sandbox-seatbelt/src/index.tsindex 74082c2d..67b3fbdd 100644--- a/plugins/sandbox-seatbelt/src/index.ts+++ b/plugins/sandbox-seatbelt/src/index.ts@@ -110,14 +110,17 @@ export function canonicalPath(target: string): string {}/**- * The writable roots a policy grants, canonical and deduplicated: the workspace under- * `workspace-write`, and the temp areas whenever the policy makes temp writable (either mode).+ * The writable roots a policy grants, canonical and deduplicated: the workspace and the+ * policy's further roots (the Session's scratchpad) under `workspace-write`, and the temp+ * areas whenever the policy makes temp writable (either mode).*/export function writableRoots(policy: SandboxPolicy): string[] {return [...new Set([- ...(policy.mode === "workspace-write" ? [policy.workspaceRoot] : []),+ ...(policy.mode === "workspace-write"+ ? [policy.workspaceRoot, ...(policy.writableRoots ?? [])]+ : []),...(policy.writableTemp === true ? ["/tmp", tmpdir()] : []),].map(canonicalPath),),diff --git a/plugins/sandbox-seatbelt/test/profile.test.ts b/plugins/sandbox-seatbelt/test/profile.test.tsindex c5007bf7..58fded2d 100644--- a/plugins/sandbox-seatbelt/test/profile.test.ts+++ b/plugins/sandbox-seatbelt/test/profile.test.ts@@ -47,6 +47,25 @@ describe.skipIf(process.platform === "win32")("seatbelt profile", () => {expect(withTemp).toContain(`(subpath "${canonicalPath(tmpdir())}")`);});+ it("workspace-write allows the policy's further roots (the Session's scratchpad) beside the workspace; read-only ignores them", () => {+ const scratchpad = "/data/agent/scratchpad/session-1";+ const profile = seatbeltProfile({+ mode: "workspace-write",+ workspaceRoot: WS,+ writableRoots: [scratchpad],+ });+ expect(profile).toContain(+ `(allow file-write* (subpath "${canonicalPath(WS)}") (subpath "${canonicalPath(scratchpad)}"))`,+ );++ const readOnly = seatbeltProfile({+ mode: "read-only",+ workspaceRoot: WS,+ writableRoots: [scratchpad],+ });+ expect(readOnly).toBe(seatbeltProfile({ mode: "read-only", workspaceRoot: WS }));+ });+it("read-only with writable temp: the temp areas are the only writable roots", () => {expect(writableRoots({ mode: "read-only", workspaceRoot: WS, writableTemp: true })).toEqual([...new Set(["/tmp", tmpdir()].map(canonicalPath)),diff --git a/plugins/sandbox-wsl/README.md b/plugins/sandbox-wsl/README.mdindex 8ce1487e..6dbb0339 100644--- a/plugins/sandbox-wsl/README.md+++ b/plugins/sandbox-wsl/README.md@@ -4,7 +4,7 @@ A Windows sandbox backend for PenguinHarness. Each agent command runs in a dedic| Dimension | How || ---------- | ------------------------------------------------------------------------------------------ |-| fs-write | The distro is read-only; the Workspace is bound read-write (or read-only) at its /mnt path |+| 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 |diff --git a/plugins/sandbox-wsl/src/index.ts b/plugins/sandbox-wsl/src/index.tsindex 123ed1d2..6ba8acdf 100644--- a/plugins/sandbox-wsl/src/index.ts+++ b/plugins/sandbox-wsl/src/index.ts@@ -446,7 +446,7 @@ export class SandboxWslStatus {"Packages Initialize installs besides bubblewrap, one per line (for example nodejs, npm, python3). They are apt packages on Ubuntu and apk packages on Alpine. Windows toolchains cannot run inside the sandbox.",descriptionZh:"初始化时除 bubblewrap 外安装的软件包,每行一个(例如 nodejs、npm、python3)。Ubuntu 上是 apt 包,Alpine 上是 apk 包。Windows 工具链无法在沙盒内运行。",- default: ["git", "curl"],+ default: ["git", "curl", "nodejs"],pattern: "^[a-z0-9][a-z0-9._+-]*$",patternErrorMessage: "must be package names",},diff --git a/plugins/sandbox-wsl/src/profile.ts b/plugins/sandbox-wsl/src/profile.tsindex 6c782e21..9a4adc0e 100644--- a/plugins/sandbox-wsl/src/profile.ts+++ b/plugins/sandbox-wsl/src/profile.ts@@ -14,6 +14,7 @@* [confining modes] --tmpfs /mnt every Windows drive hidden …* [exposeWindowsDrives] --ro-bind /mnt/<d> … … or shown read-only* [workspace] --bind | --ro-bind <ws> the Workspace, at its own /mnt path+ * [writable roots] --bind <root> <root>… the policy's further roots (the scratchpad)* --ro-bind-try /mnt/wsl/resolv.conf … the file /etc/resolv.conf points at* --remount-ro /mnt the covering tmpfs itself is read-only* [mask-paths] --tmpfs <dir> | --ro-bind /dev/null <file>@@ -126,8 +127,17 @@ export function bwrapArgs(policy: SandboxPolicy, host: ProfileHost): string[] {args.push("--ro-bind", `${MOUNT_ROOT}/${d}`, `${MOUNT_ROOT}/${d}`);}args.push(policy.mode === "workspace-write" ? "--bind" : "--ro-bind", workspace, workspace);- // Last over /mnt, and only now: the bind above needs a writable tmpfs to create its- // mountpoint in, and the remount is what stops a write outside the Workspace from+ // The policy's further writable roots (the Session's scratchpad), where the distro can+ // reach them: one that cannot be reached is left out, which confines more narrowly+ // rather than more widely.+ if (policy.mode === "workspace-write") {+ for (const root of policy.writableRoots ?? []) {+ const linux = toLinuxPath(root, host.distro);+ if (linux !== null && !within(linux, [workspace])) args.push("--bind", linux, linux);+ }+ }+ // Last over /mnt, and only now: the binds above need a writable tmpfs to create their+ // mountpoints in, and the remount is what stops a write outside the Workspace from// "succeeding" into a tmpfs nobody ever reads.args.push(...RESOLV_MNT, "--remount-ro", MOUNT_ROOT);}diff --git a/plugins/sandbox-wsl/src/tasks.ts b/plugins/sandbox-wsl/src/tasks.tsindex 025933a2..cf2b16d9 100644--- a/plugins/sandbox-wsl/src/tasks.ts+++ b/plugins/sandbox-wsl/src/tasks.ts@@ -53,7 +53,8 @@ export const UBUNTU_IMAGES = "https://cdimage.ubuntu.com/ubuntu-base/releases";export const UBUNTU_ARCHIVE = "http://archive.ubuntu.com/ubuntu";export const UBUNTU_SECURITY = "http://security.ubuntu.com/ubuntu";export const ALPINE_MIRROR = "https://dl-cdn.alpinelinux.org/alpine";-export const DEFAULT_PACKAGES = ["git", "curl"];+/** `nodejs` is what runs the harness's hook scripts and its file-tool helper inside the distro (see core's fs-worker.ts); the rest is what a shell session expects to find. */+export const DEFAULT_PACKAGES = ["git", "curl", "nodejs"];/** The account commands run as inside the distro: not root, so bwrap is the only way up. */export const SANDBOX_USER = "penguin";@@ -695,6 +696,17 @@ export async function check(alive.stdout || alive.stderr,);+ report({ en: "Node is in the distro", zh: "发行版里有 Node" });+ const node = await confined(base, "node --version");+ add(+ "Node runs hook scripts and the file tools' helper",+ "Node 能运行钩子脚本与文件工具的助手",+ node.code === 0,+ node.code === 0+ ? node.stdout.trim()+ : "nodejs is not installed: hook scripts and the file tools fail under this sandbox until the distro is initialized again with it.",+ );+report({ en: "writing the Workspace", zh: "写工作区" });await confined(base, "echo ok > probe.txt");const wrote = fs.existsSync(path.win32.join(ws, "probe.txt"));diff --git a/plugins/sandbox-wsl/test/profile.test.ts b/plugins/sandbox-wsl/test/profile.test.tsindex 499a14cd..33d59a87 100644--- a/plugins/sandbox-wsl/test/profile.test.ts+++ b/plugins/sandbox-wsl/test/profile.test.ts@@ -66,6 +66,24 @@ describe("bwrapArgs", () => {expect(bind).toBeGreaterThan(mnt);});+ it("workspace-write binds the policy's further roots (the Session's scratchpad) writable at their distro path; read-only ignores them", () => {+ const scratchpad = "C:\\Users\\k\\.penguin\\data\\p\\a\\scratchpad\\session-1";+ const linux = "/mnt/c/Users/k/.penguin/data/p/a/scratchpad/session-1";+ const args = bwrapArgs(+ { mode: "workspace-write", workspaceRoot: WS, writableRoots: [scratchpad] },+ HOST,+ );+ const bind = args.indexOf(linux);+ expect(args.slice(bind - 1, bind + 2)).toEqual(["--bind", linux, linux]);+ // Under the tmpfs over /mnt, and before it is sealed read-only.+ expect(bind).toBeGreaterThan(args.indexOf("/mnt"));+ expect(bind).toBeLessThan(args.indexOf("--remount-ro"));++ expect(+ bwrapArgs({ mode: "read-only", workspaceRoot: WS, writableRoots: [scratchpad] }, HOST),+ ).toEqual(bwrapArgs({ mode: "read-only", workspaceRoot: WS }, HOST));+ });+it("read-only binds the Workspace read-only; network none drops --share-net", () => {const args = bwrapArgs({ mode: "read-only", workspaceRoot: WS, network: "none" }, HOST);expect(args).not.toContain("--share-net");