Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

feat(agent): full access permission preset; recursive deletes still ask

Marlad5926448ef7b
diff --git a/dsh-runtime/plugins/amb-delete-gate.mjs b/dsh-runtime/plugins/amb-delete-gate.mjs
new file mode 100644
index 0000000..747f5f6
--- /dev/null
+++ b/dsh-runtime/plugins/amb-delete-gate.mjs
@@ -0,0 +1,259 @@
+// anymodel bot: recursive-delete gate for the Full Access preset (MIT, part of anymodel bot).
+//
+// A bot on 完全权限 runs DSH's danger-full-access sandbox mode: commands run unconfined and never
+// ask to escalate. Recursive deletes are the one exception: before a shell tool runs, its command
+// text goes through recursiveDelete(); a hit turns the call into a normal DSH approval request,
+// which amb-bridge routes to the chat. The host loads this plugin only for full-access bots.
+//
+// It guards against accidents, not against a hostile model: the text is matched, never run, so
+// commands built at runtime (eval "$(…)", curl … | sh) or hidden in build tools (make clean,
+// npm run clean) are not seen. Scripts named on the command line are read and checked too.
+// When unsure it asks: a needless prompt is cheap, a missed `rm -rf` is not.
+import fs from 'node:fs'
+import path from 'node:path'
+
+export const name = 'amb-delete-gate'
+
+/** POSIX rm 家族:-r / -R / --recursive(选项可以写在路径后面) */
+const RM = new Set(['rm', 'srm', 'grm', 'gnurm'])
+/** PowerShell 的 Remove-Item 及其别名(Windows 上 rm/del/rd/rmdir 都是它) */
+const PS_RM = new Set(['remove-item', 'ri', 'rm', 'del', 'erase', 'rd', 'rmdir'])
+/** find -exec / xargs 后面跟着就算批量删除的命令 */
+const ANY_RM = new Set([...RM, ...PS_RM, 'unlink', 'shred'])
+/** cmd 的 rd /s、rmdir /s、del /s、erase /s */
+const CMD_RM = new Set(['rd', 'rmdir', 'del', 'erase'])
+/** 本身就是递归删除的命令(出现在命令的位置上才算:npm install rimraf 不问) */
+const ALWAYS = new Set(['rimraf', 'del-cli', 'deltree'])
+/** 包在别的命令前面、把后面的词当命令运行的前缀 */
+const WRAP = new Set(['sudo', 'doas', 'env', 'nice', 'nohup', 'time', 'timeout', 'command', 'builtin', 'exec', 'npx', 'pnpx', 'bunx', 'dlx', 'yarn', 'pnpm', 'xargs', 'parallel', '%', 'foreach-object', 'foreach'])
+
+/** 解释器与脚本语言里的递归删除 API(在原文上匹配,不分大小写) */
+const API = [
+ [/\brmtree\b|\bremove_tree\b/i, 'rmtree'], // Python shutil / Perl File::Path
+ [/\brm_rf?\b|\bremove_dir\b|\bremove_entry(?:_secure)?\b/i, 'FileUtils.rm_r'], // Ruby
+ [/\b(?:rm|rmdir)(?:Sync)?\s*\([^)]*\brecursive\b/i, 'fs.rm(…, { recursive })'], // Node
+ [/\bemptyDir(?:Sync)?\s*\(/, 'emptyDir'], // fs-extra
+ [/\bRemoveAll\b|\bremove_dir_all\b/i, 'RemoveAll'], // Go / Rust
+ [/\bdeleteRecursively\b|\bdeleteDirectory\b|\bcleanDirectory\b|\bforceDelete\b/i, 'deleteDirectory'], // Kotlin / Java / VB
+ [/\bDirectory\s*\]?\s*(?:::|\.)\s*Delete\s*\(/i, 'Directory.Delete'], // .NET [IO.Directory]::Delete、Directory.Delete
+ [/\.Delete\s*\(\s*\$?true\s*\)/i, '.Delete($true)'], // DirectoryInfo.Delete($true)
+]
+
+const SCRIPT = /\.(?:sh|bash|zsh|ksh|ps1|psm1|bat|cmd|py|js|mjs|cjs|rb|pl)$/i
+/** 运行脚本文件的解释器与前缀 */
+const RUNS = new Set(['sh', 'bash', 'zsh', 'ksh', 'dash', 'ash', 'source', '.', 'python', 'python3', 'py', 'node', 'deno', 'bun', 'tsx', 'ruby', 'perl', 'pwsh', 'powershell', 'cmd', 'call', 'start', ...WRAP])
+const DASHES = '-\u2013\u2014\u2015' // PowerShell 也把 – — ― 当作参数前缀
+
+const base = (w) => w.toLowerCase().split(/[\\/]/).pop().replace(/\.exe$/, '')
+/** PowerShell:-Recurse 的任意前缀(-r、-rec、-Recurse:$true,大小写不限)、-rf 这类 POSIX 写法、@splat(可能带着 Recurse) */
+function psRecursive(w) {
+ if (/^@[a-z_]\w*$/i.test(w)) return true
+ if (!DASHES.includes(w[0])) return false
+ const n = w.slice(1).split(':')[0].toLowerCase()
+ return n.length > 0 && ('recurse'.startsWith(n) || /^[rfvdi]*r[rfvdi]*$/.test(n))
+}
+/** rm 的递归选项:POSIX 的 -r/-R/-rf/-fr…(getopt 也认 --r、--rec… 这样的长选项前缀),以及 PowerShell 的写法 */
+function rmRecursive(w, ps) {
+ if (psRecursive(w) || /^--r/i.test(w)) return true
+ return !ps && /^-(?!-)[a-z0-9]*r/i.test(w)
+}
+/** 列文件时递归(管道后面再删 = 递归删除):-r/-R/-Recurse、dir /s、find 的 -depth */
+const listsRecursively = (w) => psRecursive(w) || /^-(?!-)[a-z]*r/i.test(w) || /^--recursive$/i.test(w) || /^\/s$/i.test(w) || /^-depth$/i.test(w)
+
+/** 管道里这一段的命令是不是删除(跳过 % { …、xargs、sudo 这类前缀):返回那个词 */
+function deleter(words) {
+ for (const w of words) {
+ const b = base(w)
+ if (ANY_RM.has(b) || /\.delete$/i.test(w)) return w
+ if (!WRAP.has(b) && !DASHES.includes(w[0]) && !w.includes('=')) return undefined
+ }
+ return undefined
+}
+
+/** git 子命令:跳过 -C <dir>、-c <k=v> 这类全局选项 */
+function gitSub(rest) {
+ for (let i = 0; i < rest.length; i++) {
+ const w = rest[i].toLowerCase()
+ if (/^(-c|--git-dir|--work-tree|--namespace|--exec-path|--config-env)$/.test(w)) i++
+ else if (!w.startsWith('-')) return { sub: w, at: i, args: rest.slice(i + 1).map((x) => x.toLowerCase()) }
+ }
+ return { sub: '', at: -1, args: [] }
+}
+
+/** pwsh -EncodedCommand <base64(UTF-16LE)>:解出来再查;解不出来的当作可疑 */
+function encoded(words, i) {
+ for (let j = i + 1; j < words.length; j++) {
+ const w = words[j].toLowerCase()
+ if (!DASHES.includes(w[0])) continue
+ const n = w.slice(1)
+ if (n === 'e' || n === 'ec' || (n.length >= 2 && 'encodedcommand'.startsWith(n))) {
+ const b64 = words[j + 1]
+ if (!b64) return undefined
+ const text = Buffer.from(b64, 'base64').toString('utf16le')
+ // eslint-disable-next-line no-control-regex
+ if (!text || /[\u0000-\u0008\u000e-\u001f]/.test(text)) return '-EncodedCommand'
+ return recursiveDelete(text, { shell: 'ps' })
+ }
+ }
+ return undefined
+}
+
+/** 一段管道里的一条命令(已拆成词)。返回命中的说明或 undefined。 */
+function stageHit(words, ps) {
+ // git rm 是 git 的子命令,归下面的 git 规则管(--cached 只动索引);git submodule foreach 'rm -rf …' 照常查
+ const gitRm = new Set()
+ words.forEach((w, g) => {
+ const s = base(w) === 'git' ? gitSub(words.slice(g + 1)) : undefined
+ if (s?.sub === 'rm') gitRm.add(g + 1 + s.at)
+ })
+ for (let i = 0; i < words.length; i++) {
+ const raw = words[i].toLowerCase()
+ const b = base(raw)
+ const rest = words.slice(i + 1)
+ if (ALWAYS.has(b) && (i === 0 || WRAP.has(base(words[i - 1])))) return b
+ const viaGit = gitRm.has(i)
+ if (!viaGit && RM.has(b) && rest.some((w) => rmRecursive(w, ps))) return `${b} ${rest.find((w) => rmRecursive(w, ps))}`
+ if (!viaGit && PS_RM.has(b) && rest.some(psRecursive)) return `${words[i]} ${rest.find(psRecursive)}`
+ // cmd:rd /s /q、del /s、rd/s/q(命令名后面直接跟开关)
+ const glued = /^(rd|rmdir|del|erase)\//.exec(raw)
+ if (CMD_RM.has(b) || glued) {
+ const switches = [...(glued ? [raw.slice(glued[1].length)] : []), ...rest.map((w) => w.toLowerCase())]
+ if (switches.some((w) => w.startsWith('/') && w.split('/').includes('s'))) return `${glued ? glued[1] : b} /s`
+ }
+ if (b === 'find') {
+ if (rest.some((w) => w.toLowerCase() === '-delete')) return 'find -delete'
+ const x = rest.findIndex((w) => /^-(exec|execdir|ok|okdir)$/i.test(w))
+ if (x >= 0 && rest.slice(x + 1).some((w) => ANY_RM.has(base(w)))) return 'find -exec rm'
+ }
+ if ((b === 'xargs' || b === 'parallel') && rest.some((w) => ANY_RM.has(base(w)))) return `${b} rm`
+ if (b === 'git') {
+ const { sub, args } = gitSub(rest)
+ if (sub === 'clean' && !args.some((w) => w === '--dry-run' || /^-[a-z]*n/.test(w))) return 'git clean'
+ if (sub === 'rm' && args.some((w) => /^-[a-z]*r/.test(w)) && !args.includes('--cached')) return 'git rm -r'
+ }
+ if (b === 'rsync' && rest.some((w) => /^--del/i.test(w) || /^--remove-source-files$/i.test(w))) return 'rsync --delete'
+ if (b === 'robocopy' && rest.some((w) => /^\/(mir|purge)$/i.test(w))) return 'robocopy /MIR'
+ // 打包后删掉原文件
+ if (b === 'tar' && rest.some((w) => /^--remove-files$/i.test(w))) return 'tar --remove-files'
+ if (b === 'zip' && rest.some((w) => /^-(?!-)[a-z0-9]*m/i.test(w) || /^--move$/i.test(w))) return 'zip -m'
+ if (b === 'pwsh' || b === 'powershell' || b === 'pwsh-preview') {
+ const hit = encoded(words, i)
+ if (hit) return hit
+ }
+ }
+ return undefined
+}
+
+/**
+ * 去掉引号与转义,把子命令、括号、数组之类的标点变成空格:嵌套的 sh -c "…"、cmd /c "…"、
+ * python -c "subprocess.run(['rm', '-rf', p])" 都摊平成同一串词再查。只会多问,不会少问。
+ */
+function flatten(src, ps) {
+ let s = String(src).replace(/\\\r?\n/g, ' ')
+ s = ps ? s.replace(/`\r?\n/g, ' ').replace(/`(.)/g, '$1') : s.replace(/\\(.)/g, '$1')
+ return s
+ .replace(/['"\u2018\u2019\u201a\u201b\u201c\u201d\u201e^]/g, '')
+ .replace(/\$\(|@\(|[(){}[\],<>`]/g, ' ')
+}
+
+/** 未加引号的变量或命令替换当 rm 的参数(rm $opts dir):展开后可能就是 -r,问一下 */
+function hiddenArgs(src) {
+ for (const seg of String(src).split(/[;&|\r\n]+/)) {
+ const words = seg.trim().split(/\s+/)
+ const i = words.findIndex((w) => RM.has(base(w.replace(/^\\/, ''))))
+ if (i >= 0 && words.slice(i + 1).some((w) => /^(\$|`)/.test(w))) return `${words[i]} ${words.slice(i + 1).find((w) => /^(\$|`)/.test(w))}`
+ }
+ return undefined
+}
+
+/**
+ * 判断一条 shell 命令是否会递归删除。shell = 'posix'(bash 工具)或 'ps'(Windows 的 pwsh 工具);
+ * read(path) 可选,返回命令里点名的脚本文件内容(脚本里的递归删除也问)。
+ * 返回命中的简短说明(例如 "rm -rf"),没有命中返回 undefined。
+ */
+export function recursiveDelete(command, { shell = 'posix', read } = {}) {
+ const src = String(command ?? '')
+ if (!src.trim()) return undefined
+ const ps = shell === 'ps'
+ for (const [re, what] of API) if (re.test(src)) return what
+ if (!ps) {
+ const hidden = hiddenArgs(src)
+ if (hidden) return hidden
+ }
+ const flat = flatten(src, ps)
+ const scripts = []
+ for (const stmt of flat.split(/&&|\|\||[;&\r\n]/)) {
+ const stages = stmt.split('|').map((s) => s.trim().split(/\s+/).filter(Boolean)).filter((s) => s.length)
+ for (let k = 0; k < stages.length; k++) {
+ const hit = stageHit(stages[k], ps)
+ if (hit) return hit
+ // gci -Recurse | Remove-Item、gci -r | % { $_.Delete() }:前面递归列出,后面逐个删
+ const del = k > 0 ? deleter(stages[k]) : undefined
+ if (del && stages.slice(0, k).some((s) => s.some(listsRecursively))) return `${stages.slice(0, k).flat().find(listsRecursively)} | ${del}`
+ // 要运行的脚本:./x.sh、bash x.sh、python3 -u x.py、pwsh -File x.ps1(cat x.sh 这类只是读,不算)
+ stages[k].forEach((w, i) => {
+ if (SCRIPT.test(w) && (i === 0 || stages[k].slice(0, i).some((p) => RUNS.has(base(p))))) scripts.push(w)
+ })
+ }
+ }
+ if (read) {
+ for (const w of scripts) {
+ const text = read(w)
+ if (typeof text !== 'string') continue
+ const hit = recursiveDelete(text, { shell: /\.(ps1|psm1|bat|cmd)$/i.test(w) ? 'ps' : 'posix' })
+ if (hit) return `${w}: ${hit}`
+ }
+ }
+ return undefined
+}
+
+function argsOf(exec) {
+ const a = exec?.arguments
+ if (typeof a === 'string') {
+ try {
+ return JSON.parse(a)
+ } catch {
+ return {}
+ }
+ }
+ return a && typeof a === 'object' ? a : {}
+}
+
+/** 读命令里点名的脚本(相对 workdir 或进程当前目录,最多 256 KB)。 */
+function scriptReader(cwd) {
+ return (p) => {
+ try {
+ const f = path.resolve(cwd, p)
+ const st = fs.statSync(f)
+ return st.isFile() && st.size <= 256 * 1024 ? fs.readFileSync(f, 'utf8') : undefined
+ } catch {
+ return undefined
+ }
+ }
+}
+
+export function apply(ctx) {
+ if (process.env.DSH_PERMISSION_MODE !== 'danger-full-access') return
+ ctx.on('tools/pre-execute', async (exec, next) => {
+ const downstream = await next()
+ if (downstream?.kind !== 'allow') return downstream
+ const args = argsOf(exec)
+ if (typeof args.command !== 'string') return downstream
+ const tool = String(exec?.name ?? '')
+ const shell = /pwsh|powershell/i.test(tool) ? 'ps' : 'posix'
+ // 相对路径的脚本按这次命令的目录找:workdir 参数,否则会话当前目录(working_directory 工具可以改)
+ let root = process.cwd()
+ try {
+ const wd = ctx.get?.('workingDirectory')?.get?.(exec?.agent?.session)
+ if (typeof wd === 'string' && wd) root = wd
+ } catch {}
+ const cwd = typeof args.workdir === 'string' && args.workdir ? path.resolve(root, args.workdir) : root
+ const hit = recursiveDelete(args.command, { shell, read: scriptReader(cwd) })
+ if (!hit) return downstream
+ return {
+ kind: 'ask',
+ reason: `Recursive delete (${hit}) needs the user's approval, even with full access`,
+ displayReason: { en: `Recursive delete: ${hit}`, zh: `递归删除,需要你确认(${hit})` },
+ }
+ }, { prepend: true })
+}
diff --git a/src/agent/host.ts b/src/agent/host.ts
index 8a704fb..9863eef 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -483,6 +483,7 @@ export class AgentHost {
" - id: amb-present",
" name: '@deepseek-ai/dsh-tool-present'",
...this.computerUseLines(apps),
+ ...this.fullAccessLines(),
"",
].join("\n");
const f = path.join(this.home, "amb.patch.yml");
@@ -490,6 +491,28 @@ export class AgentHost {
return f;
}
+ /**
+ * 完全权限:DSH 的 danger-full-access(不进沙箱、不请求提权)。它自带的这个预设把审批策略设成 never(一律自动拒绝),
+ * 这里改成 ask,递归删除闸门(amb-delete-gate)才能经审批中心问用户;其他两个预设原样保留。
+ * 必须跟在插件 insert 列表的最后:后面两条是顶层的行补丁。
+ */
+ private fullAccessLines(): string[] {
+ if (this.settings().permission !== "full") return [];
+ return [
+ " - id: amb-delete-gate",
+ ` name: ${yamlStr(path.join(this.o.runtimeDir, "plugins", "amb-delete-gate.mjs"))}`,
+ "- id: approval",
+ " config:",
+ " policy: ask",
+ "- id: permission",
+ " config:",
+ " presets:",
+ " read-only: { sandbox: read-only, approval: ask }",
+ " workspace-write: { sandbox: workspace-write, approval: ask }",
+ " danger-full-access: { sandbox: danger-full-access, approval: ask }",
+ ];
+ }
+
/** media 技能:怎么挑模型、读文档、写请求体、交付结果。没有连接 Modelflare 时删掉。 */
private writeMediaSkill(): void {
const dir = path.join(this.home, "skills", "media");
diff --git a/src/agent/settings.ts b/src/agent/settings.ts
index 8b03022..c0ce781 100644
--- a/src/agent/settings.ts
+++ b/src/agent/settings.ts
@@ -1,5 +1,5 @@
/** 每个机器人的身份与行为设置(存在 bots.settings JSON 列,网页可编辑)。 */
-export type PermissionPreset = "readonly" | "workspace";
+export type PermissionPreset = "readonly" | "workspace" | "full";
export type CuBackend = "cua" | "codex";
export type CuApproval = "auto" | "ask-input";
/** 内置头像角色(ui/components/avatar.js 的 BOT_CHARS);blue 是主角 */
@@ -7,7 +7,10 @@ export const BOT_AVATARS = ["blue", "yellow", "green", "red", "purple", "orange"
export type BotAvatarKey = (typeof BOT_AVATARS)[number];
export interface BotSettings {
- /** 权限预设:readonly = 只读(不能改文件、命令只读沙箱);workspace = 可写本机器人工作区(默认),越界操作需审批 */
+ /**
+ * 权限预设:readonly = 只读(不能改文件、命令只读沙箱);workspace = 可写本机器人工作区(默认),越界操作需审批;
+ * full = 完全权限:命令不进沙箱、不再请求提权,以用户身份读写任何文件,只有递归删除仍要用户确认
+ */
permission: PermissionPreset;
memory: {
enabled: boolean;
@@ -57,7 +60,7 @@ export function normalizeSettings(raw: unknown): BotSettings {
const limit = Number(bg.limitUsd);
const b = (v: unknown, d: boolean) => (typeof v === "boolean" ? v : d);
return {
- permission: r.permission === "readonly" ? "readonly" : "workspace",
+ permission: r.permission === "readonly" || r.permission === "full" ? r.permission : "workspace",
memory: {
enabled: b(m.enabled, DEFAULT_SETTINGS.memory.enabled),
review: b(m.review, DEFAULT_SETTINGS.memory.review),
@@ -79,6 +82,7 @@ export function normalizeSettings(raw: unknown): BotSettings {
};
}
+/** DSH 的沙箱模式。full 用 danger-full-access,但宿主会把它的审批策略从 never 改成 ask(递归删除还要问,见 host.ts) */
export function permissionMode(p: PermissionPreset): string {
- return p === "readonly" ? "read-only" : "workspace-write";
+ return p === "readonly" ? "read-only" : p === "full" ? "danger-full-access" : "workspace-write";
}
diff --git a/src/core/runtime.ts b/src/core/runtime.ts
index 70f4b47..c5cc107 100644
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@ -217,7 +217,10 @@ export class BotRuntime {
statusText(botId: string, convId: string, convModel: string, botModel: string): string {
const m = convModel || botModel || this.opts.defaultModel() || "(自动:第一个可用模型)";
const a = this.opts.agent;
- const mode = a?.available ? "代理模式(DeepSeek Harness,工作区沙箱)" : "纯对话模式";
+ const perm = a?.available ? a.settings(botId).permission : undefined;
+ const mode = !a?.available ? "纯对话模式" : `代理模式(DeepSeek Harness,${perm === "full" ? "完全权限:不经沙箱" : perm === "readonly" ? "只读沙箱" : "工作区沙箱"})`;
+ // 完全权限:每次 /status 都提醒风险
+ const full = perm === "full" ? ["注意:完全权限下命令以你的用户身份直接运行,可以读写你电脑上的任何文件(包括 AnyModelBot 自己的数据);只有递归删除仍会先问你。在机器人设置里可以改回「工作区可写」。"] : [];
const pend = a ? a.approvals.pending(convId).map((r) => `${r.kind === "approval" ? "待批准" : "待回答"} ${r.code}`) : [];
const cui = a?.available ? a.computerUse(botId) : undefined;
const cu = cui ? [`电脑操作:${cui.backend === "codex" ? "Codex 桥" : "Cua Driver"},${cui.active ? "已启用" : "未启用"}——${cui.reason}`, ...(cui.notice && cui.enabled ? [cui.notice] : [])] : [];
@@ -226,7 +229,7 @@ export class BotRuntime {
const ps = a?.available ? pwshStatusLine(pwshProbe.snapshot()) : "";
const turn = a?.turnsInProgress.get(convId);
const busy = turn ? [busyLine(turn.since, turn.lastProgress, turn.activity.steps)] : [];
- return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...host, ...(ps ? [ps] : []), ...busy, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
+ return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...full, ...host, ...(ps ? [ps] : []), ...busy, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
}
/** 卡片按钮回调:批准/拒绝/选择选项。 */
diff --git a/test/agent.integration.test.ts b/test/agent.integration.test.ts
index 1883e97..c863f05 100644
--- a/test/agent.integration.test.ts
+++ b/test/agent.integration.test.ts
@@ -165,12 +165,14 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
const rejects: Record<string, "always" | "after-tool" | "busy"> = {};
const hung: http.ServerResponse[] = [];
let base = "";
+ /** 工作区与数据目录之外的目录(完全权限测试用) */
+ let outside = "";
/** 根据最后一条用户消息与之后的工具结果数量决定下一步 */
function plan(messages: any[]): Step {
let lastUser = -1;
for (let i = messages.length - 1; i >= 0; i--) {
- if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|NATIVES|LOOKIMG|HANG|COUNTER|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }
+ if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|NATIVES|LOOKIMG|HANG|COUNTER|OUTWRITE|RMRF|RMWS|CHILDRM|SUBRM|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }
}
const user = textOf(messages[lastUser]?.content);
const tools = messages.slice(lastUser + 1).filter((m) => m.role === "tool");
@@ -198,6 +200,19 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
]],
[/COUNTER/, [{ name: "bash", args: { description: "run", command: "echo ran >> counter.txt && wc -l < counter.txt" } }]],
[/LOOPBACK/, [{ name: "bash", args: { description: "run", command: `python3 -c "import urllib.request as u\ntry:\n print('API', u.urlopen('${base}/amb/api/status').status)\nexcept Exception as e:\n print('API', getattr(e,'code',e))"` } }]],
+ // 完全权限:写工作区外的目录、读宿主数据目录、显式要求 danger-full-access
+ [/OUTWRITE/, [
+ { name: "bash", args: { description: "run", command: `echo out-$((40+2)) > ${outside}/marker.txt; cat ${outside}/marker.txt; cat ${path.join(dataDir, "anymodel.db")} >/dev/null 2>&1 && echo DB-READABLE || echo DB-HIDDEN` } },
+ { name: "bash", args: { description: "run", command: "echo escalated-$((40+2))", sandbox_permissions: "danger-full-access", justification: "测试提权" } },
+ ]],
+ // 普通删除直接执行,递归删除先问
+ [/RMRF/, [
+ { name: "bash", args: { description: "run", command: `rm ${outside}/single.txt && echo single-gone` } },
+ { name: "bash", args: { description: "run", command: `rm -rf ${outside}/victim && echo victim-gone` } },
+ ]],
+ [/RMWS/, [{ name: "bash", args: { description: "run", command: "mkdir -p tree/sub && touch tree/sub/f && rm -rf tree && echo tree-gone" } }]],
+ [/CHILDRM/, [{ name: "bash", args: { description: "run", command: `rm -rf ${outside}/victim2 && echo victim2-gone` } }]],
+ [/SUBRM/, [{ name: "subagent", args: { description: "delete", prompt: "CHILDRM now" } }]],
];
for (const [re, steps] of scripts) {
if (!re.test(user)) continue;
@@ -258,6 +273,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
res.end();
});
dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-agent-"));
+ outside = fs.mkdtempSync(path.join(os.tmpdir(), "amb-outside-"));
app = new App(
loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_WEIXIN_API_BASE: "http://127.0.0.1:9", AMB_DEFAULT_MODEL: "mock-agent" } }),
{ printQrToTerminal: false },
@@ -273,6 +289,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
await app?.stop();
await llm?.close();
fs.rmSync(dataDir, { recursive: true, force: true });
+ fs.rmSync(outside, { recursive: true, force: true });
});
const chat = async (text: string) => {
@@ -649,4 +666,98 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
expect(mine.map((c) => `${c.api}:${c.error ?? "ok"}`)).toEqual(mine.map(() => "responses:ok"));
expect(mine[0].body.input.filter((i: any) => i.type === "function_call_output")).toHaveLength(1);
}, 180_000);
+
+ // —— 完全权限:不进沙箱、不请求提权;递归删除仍经审批 ——
+ const setPermission = async (permission: string) => {
+ const r = (await api("/bots/default/settings", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ permission }) })) as any;
+ expect(r.settings.permission).toBe(permission);
+ };
+ const approvalCount = () => app.store.listApprovals({ limit: 500 }).length;
+ const pendingApproval = async () => {
+ for (let i = 0; i < 300; i++) {
+ const row = ((await api("/approvals?status=pending")) as any).approvals[0];
+ if (row) return row;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ return undefined;
+ };
+
+ it("workspace (default): writes outside the workspace stay in the sandbox, escalation asks", async () => {
+ const pending = chat("OUTWRITE workspace");
+ // 第二步显式要 danger-full-access:工作区模式下要审批(这里拒绝)
+ const row = await pendingApproval();
+ expect(row?.tool).toBe("bash");
+ await api(`/approvals/${row.id}/deny`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
+ const r = await pending;
+ expect(r.reply).toContain("DB-HIDDEN");
+ expect(r.reply).not.toContain("escalated-42");
+ expect(fs.existsSync(path.join(outside, "marker.txt"))).toBe(false);
+ }, 120_000);
+
+ it("full: commands run unsandboxed with no approval prompt; the loopback API stays blocked", async () => {
+ await setPermission("full");
+ const before = approvalCount();
+ const r = await chat("OUTWRITE full");
+ expect(r.reply).toContain("out-42");
+ expect(r.reply).toContain("DB-READABLE");
+ expect(r.reply).toContain("escalated-42");
+ expect(fs.readFileSync(path.join(outside, "marker.txt"), "utf8").trim()).toBe("out-42");
+ expect(approvalCount()).toBe(before);
+ expect(r.prompts).toEqual([]);
+ expect((await chat("LOOPBACK full")).reply).toContain("API 403");
+ expect((await chat("/status")).reply).toMatch(/运行方式:代理模式(DeepSeek Harness,完全权限:不经沙箱)\n注意:完全权限下命令以你的用户身份直接运行/);
+ }, 180_000);
+
+ it("full: rm -rf asks first; deny keeps the directory, a plain rm does not ask", async () => {
+ fs.writeFileSync(path.join(outside, "single.txt"), "x");
+ fs.mkdirSync(path.join(outside, "victim", "sub"), { recursive: true });
+ fs.writeFileSync(path.join(outside, "victim", "sub", "f.txt"), "keep me");
+ const pending = chat("RMRF deny");
+ const row = await pendingApproval();
+ expect(row).toMatchObject({ tool: "bash", reason: "递归删除,需要你确认(rm -rf)" });
+ expect(row.detail).toContain(`rm -rf ${outside}/victim`);
+ // 第一步的普通删除已经执行了,没有问
+ expect(fs.existsSync(path.join(outside, "single.txt"))).toBe(false);
+ expect(fs.existsSync(path.join(outside, "victim"))).toBe(true);
+ const no = await fetch(`${base}/amb/api/approvals/${row.id}/deny`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
+ expect(no.status).toBe(200);
+ const r = await pending;
+ expect(r.reply).toContain("single-gone");
+ expect(r.reply).toMatch(/rejected/);
+ expect(r.reply).not.toContain("victim-gone");
+ expect(fs.readFileSync(path.join(outside, "victim", "sub", "f.txt"), "utf8")).toBe("keep me");
+ expect(r.prompts[0]?.prompt).toMatch(new RegExp(`需批准: bash \`rm -rf ${outside}/victim && echo victim-gone\` — 回复 y ${row.code} / n ${row.code}`));
+ }, 180_000);
+
+ it("full: approving the recursive delete runs it once", async () => {
+ fs.writeFileSync(path.join(outside, "single.txt"), "x");
+ const pending = chat("RMRF allow");
+ const row = await pendingApproval();
+ expect(row?.detail).toContain("rm -rf");
+ const ok = await fetch(`${base}/amb/api/approvals/${row.id}/approve`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
+ expect(ok.status).toBe(200);
+ const r = await pending;
+ expect(r.reply).toContain("victim-gone");
+ expect(fs.existsSync(path.join(outside, "victim"))).toBe(false);
+ expect(app.store.getApproval(row.id)!.status).toBe("allowed");
+ }, 180_000);
+
+ it("full: a subagent's recursive delete is gated too", async () => {
+ fs.mkdirSync(path.join(outside, "victim2", "sub"), { recursive: true });
+ const pending = chat("SUBRM please");
+ const row = await pendingApproval();
+ expect(row).toMatchObject({ tool: "bash", reason: "递归删除,需要你确认(rm -rf)" });
+ await api(`/approvals/${row.id}/deny`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
+ await pending;
+ expect(fs.existsSync(path.join(outside, "victim2", "sub"))).toBe(true);
+ }, 180_000);
+
+ it("back to workspace: recursive deletes inside the workspace run without asking, as before", async () => {
+ await setPermission("workspace");
+ const before = approvalCount();
+ const r = await chat("RMWS check");
+ expect(r.reply).toContain("tree-gone");
+ expect(approvalCount()).toBe(before);
+ expect((await chat("/status")).reply).toContain("运行方式:代理模式(DeepSeek Harness,工作区沙箱)");
+ }, 180_000);
});
diff --git a/test/agent.unit.test.ts b/test/agent.unit.test.ts
index 6d725b0..128dcdf 100644
--- a/test/agent.unit.test.ts
+++ b/test/agent.unit.test.ts
@@ -11,6 +11,7 @@ import { AgentBridge, BOT_HEADER, type ProxyEvent, type Rejection } from "../src
import { ApiFallbacks, shapeRejection } from "../src/agent/api-fallback.js";
import { ActivityLog } from "../src/agent/activity.js";
import { listen } from "./helpers.js";
+import { normalizeSettings } from "../src/agent/settings.js";
let dir: string;
let store: Store;
@@ -436,3 +437,36 @@ describe("agent API fallback", () => {
expect(log.steps).toEqual([expect.objectContaining({ kind: "retry", title: "改用 Chat Completions 重试", summary: "openai-responses 被拒:HTTP 400: Unsupported parameter", status: "ok" })]);
});
});
+
+describe("full access patch", () => {
+ const patch = (permission: "readonly" | "workspace" | "full") => {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-patch-"));
+ const settings = normalizeSettings({ permission, computerUse: { enabled: false } });
+ const host = new AgentHost({ botId: "b", dataDir, runtimeDir: "/rt", bridge: { url: "http://127.0.0.1:1" } as any, store: new Store(":memory:"), settings: () => settings });
+ fs.mkdirSync(host.home, { recursive: true });
+ const text = fs.readFileSync((host as any).writePatch("m"), "utf8");
+ const env = (host as any).env();
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ return { text, env };
+ };
+ it("full: danger-full-access, the delete gate, and approvals still answerable (ask, not never)", () => {
+ const { text, env } = patch("full");
+ expect(env.DSH_PERMISSION_MODE).toBe("danger-full-access");
+ // 闸门是插件 insert 列表的最后一项,后面是顶层的行补丁
+ expect(text).toContain(' - id: amb-delete-gate\n name: "/rt/plugins/amb-delete-gate.mjs"\n- id: approval\n config:\n policy: ask\n- id: permission\n');
+ expect(text).toContain("danger-full-access: { sandbox: danger-full-access, approval: ask }");
+ expect(text).not.toMatch(/approval: never/);
+ // 网页/渠道的审批、读围栏照旧
+ expect(text).toContain("- id: amb-bridge");
+ expect(text).toContain("- id: amb-permission");
+ expect(JSON.parse(env.AMB_DENY_READ)).toHaveLength(1);
+ });
+ it("other presets keep DSH's own permission rows", () => {
+ for (const p of ["workspace", "readonly"] as const) {
+ const { text, env } = patch(p);
+ expect(env.DSH_PERMISSION_MODE).toBe(p === "readonly" ? "read-only" : "workspace-write");
+ expect(text).not.toContain("amb-delete-gate");
+ expect(text).not.toMatch(/^- id: (approval|permission)$/m);
+ }
+ });
+});
diff --git a/test/delete-gate.unit.test.ts b/test/delete-gate.unit.test.ts
new file mode 100644
index 0000000..44193f4
--- /dev/null
+++ b/test/delete-gate.unit.test.ts
@@ -0,0 +1,331 @@
+/** 完全权限下的递归删除闸门:哪些命令要问、哪些直接执行;插件钩子只在完全权限下生效。 */
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+const plugin = path.join(__dirname, "..", "dsh-runtime", "plugins", "amb-delete-gate.mjs");
+const load = async (): Promise<any> => import(plugin + `?t=${Math.random()}`);
+const ps64 = (s: string) => Buffer.from(s, "utf16le").toString("base64");
+
+// bash 工具(Linux / macOS):必须问
+const BASH_ASK = [
+ "rm -r build",
+ "rm -R build",
+ "rm -rf build",
+ "rm -fr build",
+ "rm -Rf build",
+ "rm -rfv build",
+ "rm -f -r build",
+ "rm --recursive build",
+ "rm --recursive --force build",
+ "rm --rec build", // getopt 认长选项前缀
+ "rm build -rf", // GNU rm 允许选项写在后面
+ "rm -r -- build",
+ "/bin/rm -rf build",
+ "/usr/bin/rm -rf build",
+ "\\rm -rf build",
+ "'rm' -rf build",
+ '"rm" -rf build',
+ "r''m -rf build",
+ "sudo rm -rf /var/tmp/x",
+ "sudo -u root rm -rf x",
+ "doas rm -rf x",
+ "env FOO=1 rm -rf x",
+ "FOO=1 rm -rf x",
+ "nice -n 10 rm -rf x",
+ "timeout 10 rm -rf x",
+ "command rm -rf x",
+ "exec rm -rf x",
+ "busybox rm -rf x",
+ "cd /tmp && rm -rf x",
+ "ls; rm -rf x",
+ "true || rm -rf x",
+ "make && rm -rf dist &",
+ "rm -rf x > /dev/null 2>&1",
+ "(cd a && rm -rf b)",
+ "{ rm -rf x; }",
+ "if [ -d x ]; then rm -rf x; fi",
+ "for d in a b; do rm -r \"$d\"; done",
+ "echo $(rm -rf x)",
+ "echo `rm -rf x`",
+ "$(which rm) -rf x",
+ "bash -c 'rm -rf x'",
+ 'sh -c "rm -rf x"',
+ "bash -lc 'cd /tmp; rm -rf x'",
+ "zsh -c 'rm -r x'",
+ "eval \"rm -rf x\"",
+ "ssh host 'rm -rf /srv/x'",
+ "ssh host rm -rf /srv/x",
+ "docker exec c rm -rf /data",
+ "docker exec c sh -c 'rm -rf /data'",
+ "watch rm -rf x",
+ "rm \\\n -rf x",
+ "find . -name node_modules -type d -prune -exec rm -rf '{}' +",
+ "find . -type f -name '*.log' -delete",
+ "find /tmp/x -delete",
+ "find . -name '*.o' -exec rm {} \\;",
+ "find . -name '*.o' -execdir rm -f {} +",
+ "find . -name '*.o' | xargs rm",
+ "find . -name '*.o' -print0 | xargs -0 rm -f",
+ "ls | xargs -I{} rm -r {}",
+ "cat list.txt | xargs -n1 rm -rf",
+ "ls | parallel rm -r",
+ "git clean -fdx",
+ "git clean -fd",
+ "git clean -xfd",
+ "git clean --force -d",
+ "git clean -f",
+ "git -C repo clean -fdx",
+ "git -c core.x=y clean -ffdx",
+ "git rm -r old",
+ "git rm -rf old",
+ "git submodule foreach 'rm -rf build'",
+ "git rebase --exec 'rm -rf x' main",
+ "tar --remove-files -czf a.tgz dir",
+ "zip -rm a.zip dir",
+ "rsync -a --delete src/ dst/",
+ "rsync -av --delete-after src/ dst/",
+ "rsync -a --del src/ dst/",
+ "npx rimraf dist",
+ "rimraf dist",
+ "pnpm dlx rimraf dist",
+ "python3 -c 'import shutil; shutil.rmtree(\"x\")'",
+ "python3 -c \"from shutil import rmtree; rmtree('x')\"",
+ "python3 -c \"import subprocess; subprocess.run(['rm', '-rf', 'x'])\"",
+ "python3 -c \"import os; os.system('rm -rf x')\"",
+ "node -e \"require('fs').rmSync('x', { recursive: true, force: true })\"",
+ "node -e \"fs.promises.rm('x', {recursive:true})\"",
+ "node -e \"require('fs').rmdirSync('x', {recursive: true})\"",
+ "node -e \"require('child_process').execSync('rm -rf x')\"",
+ "perl -MFile::Path=remove_tree -e 'remove_tree(\"x\")'",
+ "perl -MFile::Path -e 'rmtree(\"x\")'",
+ "ruby -rfileutils -e 'FileUtils.rm_rf(\"x\")'",
+ "ruby -e 'FileUtils.rm_r(\"x\")'",
+ "go run main.go # os.RemoveAll",
+ "rm -rf $DIR",
+ "rm $FLAGS build", // 变量可能展开成 -r
+ "rm -f ${OUT}",
+ "rm $(cat dirs.txt)",
+ "srm -r secret",
+ "pwsh -Command 'Remove-Item x -Recurse'",
+ "cmd.exe /c 'rd /s /q C:\\x'",
+ "cat > clean.sh <<'EOF'\nrm -rf build\nEOF\nbash clean.sh",
+ // 宁可多问:引号里的文字也当命令查
+ "echo 'rm -rf is dangerous'",
+ "git commit -m 'stop using rm -r here'",
+];
+
+// bash 工具:直接执行(不问)
+const BASH_OK = [
+ "rm file.txt",
+ "rm -f file.txt",
+ "rm -i file.txt",
+ "rm -v a.log b.log",
+ "rm -d emptydir",
+ "rm -f \"$tmp\"",
+ "rm -- -file",
+ "rmdir emptydir",
+ "rmdir -p a/b/c",
+ "unlink file.txt",
+ "ls -R",
+ "ls -la",
+ "cp -r a b",
+ "mv a b",
+ "grep -rn rm .",
+ "grep -r 'TODO' src",
+ "find . -name '*.py'",
+ "find . -type d -name rm",
+ "git rm file.txt",
+ "git rm -r --cached build",
+ "git -C repo rm -r --cached build",
+ "git clean -n",
+ "git clean -nd",
+ "git clean --dry-run -fd",
+ "git status",
+ "git log --grep clean",
+ "ls -R | grep rm",
+ "npm uninstall rimraf",
+ "tar -czf a.tgz dir",
+ "zip -r a.zip dir",
+ "chmod -R 755 . && rm a.txt",
+ "docker rm -f c1",
+ "npm install rimraf",
+ "npm i -D rimraf",
+ "npm run build",
+ "rsync -a src/ dst/",
+ "python3 -c 'print(1)'",
+ "echo hello > out.txt",
+ "mkdir -p a/b && touch a/b/c",
+ "cat README.md | head -5",
+ "ls -R | head",
+ "",
+ " ",
+];
+
+// pwsh 工具(Windows):必须问
+const PS_ASK = [
+ "Remove-Item C:\\x -Recurse",
+ "Remove-Item -Path C:\\x -Recurse -Force",
+ "Remove-Item C:\\x -Recurse:$true",
+ "Remove-Item C:\\x -recurse",
+ "Remove-Item C:\\x -RECURSE",
+ "Remove-Item C:\\x -r",
+ "Remove-Item C:\\x -R",
+ "Remove-Item C:\\x -Rec",
+ "Remove-Item C:\\x -recurs",
+ "Remove-Item C:\\x \u2013Recurse", // en dash
+ "Remove-Item C:\\x \u2014Recurse", // em dash
+ "remove-item -LiteralPath 'C:\\x y' -Force -Recurse",
+ "Microsoft.PowerShell.Management\\Remove-Item C:\\x -Recurse",
+ "& 'Remove-Item' C:\\x -Recurse",
+ "rm C:\\x -r -fo",
+ "rm -r C:\\x",
+ "rm -rf C:\\x",
+ "rm -Recurse -Force C:\\x",
+ "del C:\\x -Recurse",
+ "erase C:\\x -Recurse",
+ "ri C:\\x -r",
+ "rd C:\\x -Recurse",
+ "rmdir C:\\x -Recurse -Force",
+ "Re`move-Item C:\\x -Re`curse",
+ "$p = @{ Recurse = $true }; Remove-Item C:\\x @p",
+ "Get-ChildItem C:\\x -Recurse | Remove-Item -Force",
+ "gci -r *.tmp | rm",
+ "Get-ChildItem C:\\x -Recurse -File | ForEach-Object { Remove-Item $_.FullName }",
+ "gci C:\\x -r | % { $_.Delete() }",
+ "Get-ChildItem C:\\x | Remove-Item -Recurse -Force",
+ "cmd /c rd /s /q C:\\x",
+ "cmd /c \"rd /s /q C:\\x\"",
+ "cmd.exe /C \"rmdir /S /Q C:\\x\"",
+ "cmd /c rd/s/q C:\\x",
+ "cmd /c del /s /q C:\\x\\*.tmp",
+ "cmd /c del /f/s/q C:\\x",
+ "cmd /c erase /s C:\\x\\*",
+ "cmd /c r^d /s /q C:\\x",
+ "Start-Process cmd -ArgumentList '/c rd /s /q C:\\x' -Wait",
+ "Invoke-Expression 'Remove-Item C:\\x -Recurse'",
+ "iex \"Remove-Item C:\\x -Recurse\"",
+ "[System.IO.Directory]::Delete('C:\\x', $true)",
+ "[IO.Directory]::Delete('C:\\x', $true)",
+ "(Get-Item C:\\x).Delete($true)",
+ "robocopy C:\\empty C:\\x /MIR",
+ "robocopy C:\\a C:\\b /PURGE",
+ "git clean -fdx",
+ "npx rimraf dist",
+ `pwsh -NoProfile -EncodedCommand ${ps64("Remove-Item C:\\x -Recurse")}`,
+ `powershell -enc ${ps64("Remove-Item C:\\x -Recurse")}`,
+ `powershell.exe -e ${ps64("rm -r C:\\x")}`,
+ "powershell -Command \"Remove-Item C:\\x -Recurse\"",
+ "if (Test-Path C:\\x) { Remove-Item C:\\x -Recurse -Force }",
+ "if ($?) { rd C:\\x -r }",
+ "Remove-Item -Path \"$env:USERPROFILE\\proj\\node_modules\" -Recurse -Force -ErrorAction SilentlyContinue",
+ "Get-ChildItem -Path C:\\x -Include *.tmp -Recurse | Remove-Item",
+ "cmd /c dir C:\\x /s /b | del",
+ "Remove-Item C:\\x -Recurse -WhatIf", // 宁可多问
+];
+
+// pwsh 工具:直接执行(不问)
+const PS_OK = [
+ "Remove-Item C:\\x\\file.txt",
+ "Remove-Item C:\\x\\file.txt -Force",
+ "rm C:\\x\\file.txt -Force",
+ "rm C:\\x\\file.txt -fo",
+ "del C:\\x\\file.txt",
+ "Remove-Item $path -ErrorAction SilentlyContinue",
+ "Remove-Item -LiteralPath $p -Confirm:$false",
+ "Get-ChildItem C:\\x -Recurse | Select-String foo",
+ "Get-ChildItem -Recurse -Filter *.cs | Measure-Object",
+ "Get-ChildItem -Recurse | Where-Object { $_.Name -like 'rm' }",
+ "gci C:\\x *.log | Remove-Item",
+ "Copy-Item C:\\a C:\\b -Recurse",
+ "New-Item -ItemType Directory C:\\x -Force",
+ "cmd /c dir /s /b",
+ "cmd /c del C:\\x\\a.txt",
+ "rmdir C:\\x\\empty",
+ "robocopy C:\\a C:\\b /E",
+ "Remove-ItemProperty -Path HKCU:\\x -Name y",
+ "git rm -r --cached build",
+ `pwsh -EncodedCommand ${ps64("Get-ChildItem C:\\x")}`,
+ "Write-Output 'hello'",
+];
+
+describe("recursiveDelete matcher", () => {
+ it.each(BASH_ASK)("bash asks: %s", async (cmd) => {
+ expect((await load()).recursiveDelete(cmd, { shell: "posix" })).toBeTruthy();
+ });
+ it.each(BASH_OK)("bash runs: %s", async (cmd) => {
+ expect((await load()).recursiveDelete(cmd, { shell: "posix" })).toBeUndefined();
+ });
+ it.each(PS_ASK)("pwsh asks: %s", async (cmd) => {
+ expect((await load()).recursiveDelete(cmd, { shell: "ps" })).toBeTruthy();
+ });
+ it.each(PS_OK)("pwsh runs: %s", async (cmd) => {
+ expect((await load()).recursiveDelete(cmd, { shell: "ps" })).toBeUndefined();
+ });
+
+ it("checks scripts named on the command line", async () => {
+ const { recursiveDelete } = await load();
+ const files: Record<string, string> = { "clean.sh": "#!/bin/sh\nrm -rf build\n", "ok.sh": "echo hi\n", "tools/x.ps1": "Remove-Item C:\\x -Recurse\n", "y.py": "import shutil\nshutil.rmtree('x')\n" };
+ const read = (p: string) => files[p.replace(/^\.[\\/]/, "")];
+ expect(recursiveDelete("bash clean.sh", { read })).toBe("clean.sh: rm -rf");
+ expect(recursiveDelete("./clean.sh --all", { read })).toBe("./clean.sh: rm -rf");
+ expect(recursiveDelete("sh ok.sh && echo done", { read })).toBeUndefined();
+ expect(recursiveDelete("& tools/x.ps1", { shell: "ps", read })).toBeTruthy();
+ expect(recursiveDelete("python3 y.py", { read })).toBe("y.py: rmtree");
+ expect(recursiveDelete("bash -x clean.sh", { read })).toBe("clean.sh: rm -rf");
+ expect(recursiveDelete("chmod +x clean.sh && ./clean.sh", { read })).toBe("./clean.sh: rm -rf");
+ expect(recursiveDelete("pwsh -NoProfile -File tools/x.ps1", { shell: "ps", read })).toBeTruthy();
+ // 只是读脚本(cat、grep)不问;读不到的脚本也不问
+ expect(recursiveDelete("cat clean.sh", { read })).toBeUndefined();
+ expect(recursiveDelete("grep -n build clean.sh", { read })).toBeUndefined();
+ expect(recursiveDelete("bash missing.sh", { read })).toBeUndefined();
+ });
+
+ it("says what matched", async () => {
+ const { recursiveDelete } = await load();
+ expect(recursiveDelete("sudo rm -rf /x")).toBe("rm -rf");
+ expect(recursiveDelete("Remove-Item C:\\x -Recurse", { shell: "ps" })).toBe("Remove-Item -Recurse");
+ expect(recursiveDelete("cmd /c rd /s /q C:\\x", { shell: "ps" })).toBe("rd /s");
+ expect(recursiveDelete("git clean -fdx")).toBe("git clean");
+ expect(recursiveDelete("find . -delete")).toBe("find -delete");
+ });
+});
+
+describe("delete gate plugin", () => {
+ const run = async (mode: string | undefined, exec: any, downstream: any = { kind: "allow" }) => {
+ const prev = process.env.DSH_PERMISSION_MODE;
+ if (mode) process.env.DSH_PERMISSION_MODE = mode;
+ else delete process.env.DSH_PERMISSION_MODE;
+ let hook: any;
+ (await load()).apply({ on: (_ev: string, fn: any) => (hook = fn) });
+ if (prev === undefined) delete process.env.DSH_PERMISSION_MODE;
+ else process.env.DSH_PERMISSION_MODE = prev;
+ return hook ? hook(exec, async () => downstream) : { kind: "allow", noHook: true };
+ };
+ const bash = (command: string) => ({ name: "bash", arguments: { description: "x", command } });
+
+ it("only loads for full access", async () => {
+ expect(await run("workspace-write", bash("rm -rf x"))).toMatchObject({ noHook: true });
+ expect(await run("read-only", bash("rm -rf x"))).toMatchObject({ noHook: true });
+ expect(await run(undefined, bash("rm -rf x"))).toMatchObject({ noHook: true });
+ });
+
+ it("turns recursive deletes into an approval request and lets everything else through", async () => {
+ const ask = await run("danger-full-access", bash("rm -rf build"));
+ expect(ask).toMatchObject({ kind: "ask", displayReason: { zh: "递归删除,需要你确认(rm -rf)" } });
+ expect(await run("danger-full-access", bash("rm build/a.txt"))).toEqual({ kind: "allow" });
+ expect(await run("danger-full-access", bash("echo hi > /etc/x"))).toEqual({ kind: "allow" });
+ // pwsh 按 PowerShell 的规则:rm -Force 不是递归
+ expect(await run("danger-full-access", { name: "pwsh", arguments: { command: "rm C:\\x\\a.txt -Force" } })).toEqual({ kind: "allow" });
+ expect((await run("danger-full-access", { name: "pwsh", arguments: { command: "rm C:\\x -r" } })).kind).toBe("ask");
+ // 参数是 JSON 字符串也认
+ expect((await run("danger-full-access", { name: "bash", arguments: JSON.stringify({ command: "rm -r x" }) })).kind).toBe("ask");
+ // 没有 command 的工具不管
+ expect(await run("danger-full-access", { name: "read", arguments: { file_path: "rm -rf" } })).toEqual({ kind: "allow" });
+ });
+
+ it("keeps a downstream deny or ask as is", async () => {
+ expect(await run("danger-full-access", bash("rm -rf x"), { kind: "deny", reason: "no" })).toEqual({ kind: "deny", reason: "no" });
+ const other = { kind: "ask", reason: "computer use" };
+ expect(await run("danger-full-access", bash("rm -rf x"), other)).toBe(other);
+ });
+});
diff --git a/test/phase3.unit.test.ts b/test/phase3.unit.test.ts
index bae363c..9b9473a 100644
--- a/test/phase3.unit.test.ts
+++ b/test/phase3.unit.test.ts
@@ -88,7 +88,7 @@ describe("steward", () => {
describe("settings", () => {
it("normalizes with defaults and clamps unknown values", () => {
expect(normalizeSettings(undefined)).toEqual(DEFAULT_SETTINGS);
- const s = normalizeSettings({ permission: "full", memory: { review: false }, computerUse: { approval: "never" } });
+ const s = normalizeSettings({ permission: "root", memory: { review: false }, computerUse: { approval: "never" } });
expect(s.permission).toBe("workspace");
expect(s.memory).toEqual({ enabled: true, review: false, teamWrite: false });
expect(s.computerUse).toEqual({ enabled: true, backend: "cua", approval: "auto" });
@@ -103,6 +103,15 @@ describe("settings", () => {
expect(permissionMode("readonly")).toBe("read-only");
expect(permissionMode("workspace")).toBe("workspace-write");
});
+ it("permission presets: full is kept, anything unknown falls back to the workspace default", () => {
+ expect(normalizeSettings({ permission: "full" }).permission).toBe("full");
+ expect(normalizeSettings({ permission: "readonly" }).permission).toBe("readonly");
+ expect(normalizeSettings({ permission: "workspace" }).permission).toBe("workspace");
+ for (const v of [undefined, null, "", "FULL", "danger-full-access", "bypass", 1, true, {}]) expect(normalizeSettings({ permission: v }).permission).toBe("workspace");
+ expect(normalizeSettings({}).permission).toBe(DEFAULT_SETTINGS.permission);
+ expect(DEFAULT_SETTINGS.permission).toBe("workspace");
+ expect(permissionMode("full")).toBe("danger-full-access");
+ });
it("store persists settings and migrates", () => {
const store = new Store(path.join(dir, "t.db"));
const b = store.createBot({ name: "x" } as any);