@uncarved/jade 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/dist/api.d.ts +1 -1
  2. package/dist/api.js +1 -1
  3. package/dist/host.d.ts +2 -0
  4. package/dist/host.js +39 -5
  5. package/dist/host.js.map +1 -1
  6. package/dist/remote.js +5 -0
  7. package/dist/remote.js.map +1 -1
  8. package/dist/session.d.ts +7 -0
  9. package/dist/session.js +482 -27
  10. package/dist/session.js.map +1 -1
  11. package/package.json +4 -4
  12. package/plugins/approval/index.ts +36 -14
  13. package/plugins/approval/policy.ts +15 -10
  14. package/plugins/approval/review.ts +9 -5
  15. package/plugins/checks/checks.ts +10 -7
  16. package/plugins/checks/index.ts +13 -13
  17. package/plugins/checks/plugin.json +1 -1
  18. package/plugins/checks/project.ts +37 -38
  19. package/plugins/commands/index.ts +27 -3
  20. package/plugins/compact/compact.ts +13 -5
  21. package/plugins/compact/index.ts +20 -3
  22. package/plugins/compact/style.ts +13 -14
  23. package/plugins/completions/index.ts +35 -0
  24. package/plugins/completions/plugin.json +7 -0
  25. package/plugins/copy/index.ts +46 -0
  26. package/plugins/copy/plugin.json +7 -0
  27. package/plugins/editor/index.ts +10 -4
  28. package/plugins/fs/diff.ts +7 -6
  29. package/plugins/fs/fs.ts +8 -4
  30. package/plugins/fs/grep.ts +42 -9
  31. package/plugins/fs/index.ts +2 -7
  32. package/plugins/fs/plugin.json +1 -1
  33. package/plugins/fs/renderers.ts +16 -15
  34. package/plugins/fs/style.ts +16 -15
  35. package/plugins/hooks/index.ts +3 -2
  36. package/plugins/keys/index.ts +5 -1
  37. package/plugins/mcp/index.ts +197 -78
  38. package/plugins/mcp/install.ts +5 -3
  39. package/plugins/mcp/mcp.ts +163 -11
  40. package/plugins/mcp/plugin.json +2 -1
  41. package/plugins/mcp/project.ts +47 -50
  42. package/plugins/memory/index.ts +4 -4
  43. package/plugins/memory/style.ts +13 -14
  44. package/plugins/mentions/candidates.ts +67 -0
  45. package/plugins/mentions/index.ts +12 -5
  46. package/plugins/mentions/plugin.json +1 -1
  47. package/plugins/mentions/style.ts +13 -14
  48. package/plugins/models/configure.ts +10 -9
  49. package/plugins/models/index.ts +27 -1
  50. package/plugins/modes/index.ts +13 -2
  51. package/plugins/print/index.ts +7 -4
  52. package/plugins/prompts/index.ts +0 -0
  53. package/plugins/renderers/index.ts +10 -5
  54. package/plugins/repeats/index.ts +8 -8
  55. package/plugins/schedule/index.ts +2 -0
  56. package/plugins/screenshot/browser.ts +10 -0
  57. package/plugins/sessions/index.ts +48 -2
  58. package/plugins/shell/index.ts +20 -25
  59. package/plugins/shell/plugin.json +1 -2
  60. package/plugins/shell/renderers.ts +9 -7
  61. package/plugins/shell/shell.ts +3 -1
  62. package/plugins/skills/index.ts +28 -19
  63. package/plugins/skills/project.ts +12 -7
  64. package/plugins/steer/index.ts +5 -4
  65. package/plugins/task/index.ts +80 -50
  66. package/plugins/task/plugin.json +6 -2
  67. package/plugins/task/style.ts +13 -14
  68. package/plugins/task/subagent.ts +67 -184
  69. package/plugins/todo/index.ts +39 -9
  70. package/plugins/tools/index.ts +9 -2
  71. package/plugins/tui/frontend.ts +139 -89
  72. package/plugins/tui/index.ts +2 -3
  73. package/plugins/tui/mentions.ts +11 -80
  74. package/plugins/tui/plugin.json +1 -1
  75. package/plugins/tui/screen.ts +55 -5
  76. package/plugins/tui/transcript.ts +17 -7
  77. package/plugins/tui/tui.ts +337 -101
  78. package/plugins/tui/vendor.ts +1 -1
  79. package/plugins/undo/checkpoint.ts +5 -3
  80. package/plugins/undo/index.ts +43 -14
  81. package/plugins/undo/style.ts +13 -14
  82. package/plugins/web/index.ts +7 -18
  83. package/plugins/web/plugin.json +1 -1
  84. package/plugins-dist/approval/index.js +363 -418
  85. package/plugins-dist/approval/policy.js +391 -508
  86. package/plugins-dist/approval/review.js +132 -158
  87. package/plugins-dist/approval/schema.js +50 -55
  88. package/plugins-dist/ask/index.js +115 -129
  89. package/plugins-dist/budget/index.js +27 -31
  90. package/plugins-dist/checks/checks.js +293 -329
  91. package/plugins-dist/checks/index.js +119 -139
  92. package/plugins-dist/checks/plugin.json +2 -1
  93. package/plugins-dist/checks/project.js +57 -65
  94. package/plugins-dist/commands/index.js +47 -29
  95. package/plugins-dist/compact/compact.js +233 -249
  96. package/plugins-dist/compact/index.js +98 -95
  97. package/plugins-dist/compact/style.js +9 -14
  98. package/plugins-dist/completions/index.js +30 -0
  99. package/plugins-dist/completions/plugin.json +9 -0
  100. package/plugins-dist/continue/index.js +40 -52
  101. package/plugins-dist/copy/index.js +40 -0
  102. package/plugins-dist/copy/plugin.json +9 -0
  103. package/plugins-dist/cost/index.js +98 -115
  104. package/plugins-dist/custom-commands/index.js +55 -72
  105. package/plugins-dist/editor/index.js +64 -72
  106. package/plugins-dist/fs/diff.js +111 -124
  107. package/plugins-dist/fs/fs.js +426 -469
  108. package/plugins-dist/fs/grep.js +262 -253
  109. package/plugins-dist/fs/index.js +20 -34
  110. package/plugins-dist/fs/plugin.json +1 -2
  111. package/plugins-dist/fs/renderers.js +100 -112
  112. package/plugins-dist/fs/style.js +11 -15
  113. package/plugins-dist/fs/sys.js +31 -43
  114. package/plugins-dist/hooks/index.js +107 -127
  115. package/plugins-dist/keys/index.js +27 -31
  116. package/plugins-dist/mcp/index.js +271 -199
  117. package/plugins-dist/mcp/install.js +123 -137
  118. package/plugins-dist/mcp/mcp.js +638 -577
  119. package/plugins-dist/mcp/plugin.json +3 -1
  120. package/plugins-dist/mcp/project.js +98 -115
  121. package/plugins-dist/memory/index.js +83 -88
  122. package/plugins-dist/memory/memory.js +111 -128
  123. package/plugins-dist/memory/style.js +9 -14
  124. package/plugins-dist/mentions/attach.js +91 -99
  125. package/plugins-dist/mentions/candidates.js +49 -0
  126. package/plugins-dist/mentions/index.js +71 -81
  127. package/plugins-dist/mentions/plugin.json +2 -1
  128. package/plugins-dist/mentions/style.js +9 -14
  129. package/plugins-dist/models/config.js +29 -43
  130. package/plugins-dist/models/configure.js +392 -473
  131. package/plugins-dist/models/context.js +14 -22
  132. package/plugins-dist/models/index.js +182 -189
  133. package/plugins-dist/models/provider.js +243 -307
  134. package/plugins-dist/models/saved.js +59 -71
  135. package/plugins-dist/modes/index.js +138 -165
  136. package/plugins-dist/plugins/index.js +34 -34
  137. package/plugins-dist/print/index.js +192 -175
  138. package/plugins-dist/prompts/index.js +81 -89
  139. package/plugins-dist/prompts/notes.js +31 -37
  140. package/plugins-dist/prompts/prompts.js +155 -193
  141. package/plugins-dist/prompts/results.js +40 -53
  142. package/plugins-dist/prompts/sys.js +39 -50
  143. package/plugins-dist/renderers/index.js +32 -32
  144. package/plugins-dist/repeats/index.js +131 -174
  145. package/plugins-dist/schedule/cron.js +49 -56
  146. package/plugins-dist/schedule/index.js +229 -247
  147. package/plugins-dist/schedule/store.js +93 -109
  148. package/plugins-dist/scratch/index.js +12 -18
  149. package/plugins-dist/screenshot/browser.js +136 -154
  150. package/plugins-dist/screenshot/index.js +37 -46
  151. package/plugins-dist/screenshot/sys.js +53 -65
  152. package/plugins-dist/screenshot/tool.js +98 -126
  153. package/plugins-dist/sessions/index.js +149 -117
  154. package/plugins-dist/shell/index.js +115 -135
  155. package/plugins-dist/shell/plugin.json +1 -2
  156. package/plugins-dist/shell/renderers.js +28 -33
  157. package/plugins-dist/shell/service.js +17 -23
  158. package/plugins-dist/shell/shell.js +307 -362
  159. package/plugins-dist/shell/sys.js +64 -79
  160. package/plugins-dist/skills/index.js +193 -211
  161. package/plugins-dist/skills/install.js +122 -149
  162. package/plugins-dist/skills/project.js +65 -73
  163. package/plugins-dist/skills/skills.js +135 -171
  164. package/plugins-dist/steer/index.js +108 -125
  165. package/plugins-dist/suggest/index.js +235 -259
  166. package/plugins-dist/task/index.js +130 -117
  167. package/plugins-dist/task/plugin.json +5 -2
  168. package/plugins-dist/task/style.js +9 -14
  169. package/plugins-dist/task/subagent.js +156 -279
  170. package/plugins-dist/todo/index.js +79 -63
  171. package/plugins-dist/tools/index.js +36 -42
  172. package/plugins-dist/tui/editor.js +145 -160
  173. package/plugins-dist/tui/frontend.js +639 -678
  174. package/plugins-dist/tui/history.js +34 -37
  175. package/plugins-dist/tui/index.js +16 -18
  176. package/plugins-dist/tui/markdown.js +203 -247
  177. package/plugins-dist/tui/mascot.js +266 -355
  178. package/plugins-dist/tui/mentions.js +67 -144
  179. package/plugins-dist/tui/plugin.json +1 -2
  180. package/plugins-dist/tui/render.js +35 -45
  181. package/plugins-dist/tui/screen.js +197 -180
  182. package/plugins-dist/tui/transcript.js +436 -468
  183. package/plugins-dist/tui/tui.js +1554 -1656
  184. package/plugins-dist/undo/checkpoint.js +95 -118
  185. package/plugins-dist/undo/index.js +185 -192
  186. package/plugins-dist/undo/snapshot.js +83 -99
  187. package/plugins-dist/undo/style.js +9 -14
  188. package/plugins-dist/update/index.js +26 -28
  189. package/plugins-dist/web/env.js +55 -68
  190. package/plugins-dist/web/index.js +80 -110
  191. package/plugins-dist/web/plugin.json +1 -2
  192. package/plugins-dist/web/renderers.js +4 -5
  193. package/plugins-dist/web/web.js +514 -593
  194. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  195. package/sdk/python/jade_plugin.py +9 -2
  196. package/src/api.ts +1 -1
  197. package/src/host.ts +39 -4
  198. package/src/remote.ts +6 -1
  199. package/src/session.ts +489 -34
@@ -1,565 +1,448 @@
1
- // 审批规则:按模式、工具的 effect、路径和"总是允许"的规则决定一次工具调用是放行、拒绝还是问用户。
2
- // 纯判断,不碰界面和日志;那些在 index.ts。
3
- //
4
- // 带 url 参数的只读工具(web_fetch)也要问:网页里的提示注入可以让模型把读到的内容拼进 URL 发出去。
5
- // 指向本机的 URL(localhost 上的开发服务器,截图最常见的用途)不问:数据不会离开这台机器。
6
1
  import { realpathSync, statSync } from "node:fs";
7
2
  import path from "node:path";
8
3
  import { validate } from "./schema.js";
9
- /**
10
- * 权限模式。ask:改东西先问;auto:工作目录里的改动和只建目录、碰文件的命令不问;
11
- * plan:不改任何东西,拒绝时告诉模型先给出计划;readonly:不改任何东西(子 Agent 用);yolo:什么都不问
12
- */
13
4
  export const MODES = ["ask", "auto", "plan", "readonly", "yolo"];
14
- /** 显示用 */
15
5
  export function describeRule(r) {
16
- if (r.command !== undefined)
17
- return `${r.tool} "${r.command}"`;
18
- if (r.prefix !== undefined)
19
- return `${r.tool} "${r.prefix}…"`;
20
- if (r.dir !== undefined)
21
- return `${r.tool} in ${r.dir}`;
22
- if (r.host !== undefined)
23
- return `${r.tool} from ${r.host}`;
24
- return r.tool;
6
+ if (r.command !== undefined)
7
+ return `${r.tool} "${r.command}"`;
8
+ if (r.prefix !== undefined)
9
+ return `${r.tool} "${r.prefix}…"`;
10
+ if (r.dir !== undefined)
11
+ return `${r.tool} in ${r.dir}`;
12
+ if (r.host !== undefined)
13
+ return `${r.tool} from ${r.host}`;
14
+ return r.tool;
25
15
  }
26
- /** 白名单命令里会写文件或执行其他程序的参数 */
27
16
  const UNSAFE_ARGS = [/\s--(output|pre|pre-glob|ext-diff|textconv|open-files-in-pager)(=|\s|$)/];
28
- /** 不管参数是什么都只读的命令(路径另外检查) */
29
- const READ_ANY = new Set(("ls pwd cat head tail wc echo printf which whoami file stat du df basename dirname realpath readlink " +
30
- "cut tr nl column comm diff cmp md5sum sha1sum sha256sum sha512sum cksum od hexdump strings tac rev fold expand paste join " +
31
- "uname id groups true false seq printenv grep egrep fgrep rg jq type").split(" "));
32
- /** 带 --version 之类的参数时只读的命令 */
17
+ const READ_ANY = new Set(("ls pwd cat head tail wc echo printf which whoami file stat du df basename dirname realpath readlink " + "cut tr nl column comm diff cmp md5sum sha1sum sha256sum sha512sum cksum od hexdump strings tac rev fold expand paste join " + "uname id groups true false seq printenv grep egrep fgrep rg jq type").split(" "));
33
18
  const VERSIONED = new Set("node bun deno python python3 pip pip3 go cargo rustc tsc npm pnpm yarn npx java javac gcc g++ clang make cmake git ruby php dotnet uv".split(" "));
34
19
  const VERSION_ARGS = new Set(["--version", "-v", "-V", "version"]);
35
- /** 只读的 git 子命令;其余的(branch、tag、stash……)要看参数 */
36
- const GIT_READ = new Set(("status diff log show blame annotate ls-files shortlog describe rev-parse rev-list merge-base name-rev " +
37
- "cat-file ls-tree for-each-ref show-ref count-objects check-ignore grep whatchanged show-branch").split(" "));
38
- /** find 里会删除、写文件或执行程序的表达式 */
20
+ const GIT_READ = new Set(("status diff log show blame annotate ls-files shortlog describe rev-parse rev-list merge-base name-rev " + "cat-file ls-tree for-each-ref show-ref count-objects check-ignore grep whatchanged show-branch").split(" "));
39
21
  const FIND_UNSAFE = /^-(exec|execdir|ok|okdir|delete|fprint|fprint0|fprintf|fls)$/;
40
- /** sed -n 只打印行号范围的脚本:10p、10,20p、$p */
41
22
  const SED_PRINT = /^(\d+|\$)(,(\d+|\$))?p$/;
42
- /**
43
- * 用默认程序打开后只是查看的文件:浏览器、图片查看器、PDF 阅读器、文本编辑器。
44
- * 不含 .js(Windows 默认用 WSH 执行)、.bat、.lnk、.url 这类打开就会执行或跳转的
45
- */
46
23
  const VIEWABLE = /\.(html?|svg|png|jpe?g|gif|webp|bmp|ico|pdf|md|txt)$/i;
47
- /**
48
- * 打开文件给用户看的命令:start "" <文件>(Windows,Git 自带的 /usr/bin/start)、open <文件>(macOS)、xdg-open <文件>。
49
- * 只认一个本地文件、扩展名是 VIEWABLE 的形式;路径在不在工作目录里由调用方另外检查。
50
- * URL(会把内容带到网络上)、选项、cmd 会特殊处理的字符都不认
51
- */
52
24
  function opensForViewing(name, args) {
53
- let files;
54
- if (name === "start")
55
- files = args[0] === "" ? args.slice(1) : args;
56
- else if (name === "xdg-open" || (name === "open" && process.platform === "darwin"))
57
- files = args;
58
- else
59
- return false;
60
- if (files.length !== 1)
61
- return false;
62
- const f = files[0];
63
- // 盘符(D:\、D:/)之外的 xxx: 都当成 URL 或协议
64
- const scheme = /^[a-z][a-z0-9+.-]*:/i.test(f) && !/^[a-z]:[\\/]/i.test(f);
65
- // cmd 的 start 把 /wait、/b 这样的词当成开关;/d/x.html 这种 Git Bash 路径不算
66
- const startSwitch = name === "start" && /^\/[^/]*$/.test(f);
67
- return !scheme && !startSwitch && !f.startsWith("-") && !/[%^&|<>"!]/.test(f) && VIEWABLE.test(f);
25
+ let files;
26
+ if (name === "start")
27
+ files = args[0] === "" ? args.slice(1) : args;
28
+ else if (name === "xdg-open" || name === "open" && process.platform === "darwin")
29
+ files = args;
30
+ else
31
+ return false;
32
+ if (files.length !== 1)
33
+ return false;
34
+ const f = files[0];
35
+ const scheme = /^[a-z][a-z0-9+.-]*:/i.test(f) && !/^[a-z]:[\\/]/i.test(f);
36
+ const startSwitch = name === "start" && /^\/[^/]*$/.test(f);
37
+ return !scheme && !startSwitch && !f.startsWith("-") && !/[%^&|<>"!]/.test(f) && VIEWABLE.test(f);
68
38
  }
69
39
  const positional = (args) => args.filter((a) => !a.startsWith("-"));
70
40
  const onlyFlags = (args, allowed) => args.every((a) => allowed.includes(a));
71
41
  function gitKind(args) {
72
- let i = 0;
73
- while (args[i] === "--no-pager")
74
- i++;
75
- const sub = args[i];
76
- const rest = args.slice(i + 1);
77
- if (sub === undefined)
78
- return undefined;
79
- if (VERSION_ARGS.has(sub) && rest.length === 0)
80
- return "read";
81
- if (GIT_READ.has(sub))
82
- return sub === "grep" && rest.some((a) => /^-[a-zA-Z]*O/.test(a)) ? undefined : "read";
83
- // 带参数的 branch、tag 可能删除、重命名、创建,只放行列出的形式
84
- if (sub === "branch")
85
- return onlyFlags(rest, ["-a", "-r", "-v", "-vv", "--all", "--remotes", "--list", "--show-current"]) ? "read" : undefined;
86
- if (sub === "tag")
87
- return onlyFlags(rest, ["-l", "--list", "-n"]) ? "read" : undefined;
88
- if (sub === "remote")
89
- return onlyFlags(rest, ["-v", "--verbose"]) ? "read" : undefined;
90
- if (sub === "stash" || sub === "worktree")
91
- return rest[0] === "list" || (sub === "stash" && rest[0] === "show") ? "read" : undefined;
92
- if (sub === "submodule")
93
- return rest[0] === "status" ? "read" : undefined;
94
- if (sub === "reflog")
95
- return rest.length === 0 || rest[0] === "show" || /^-/.test(rest[0]) ? "read" : undefined;
96
- if (sub === "config")
97
- return rest.length > 0 && ["--get", "--get-all", "--get-regexp", "--list", "-l"].includes(rest[0]) ? "read" : undefined;
98
- return undefined;
42
+ let i = 0;
43
+ while (args[i] === "--no-pager")
44
+ i++;
45
+ const sub = args[i];
46
+ const rest = args.slice(i + 1);
47
+ if (sub === undefined)
48
+ return;
49
+ if (VERSION_ARGS.has(sub) && rest.length === 0)
50
+ return "read";
51
+ if (GIT_READ.has(sub))
52
+ return sub === "grep" && rest.some((a) => /^-[a-zA-Z]*O/.test(a)) ? undefined : "read";
53
+ if (sub === "branch")
54
+ return onlyFlags(rest, ["-a", "-r", "-v", "-vv", "--all", "--remotes", "--list", "--show-current"]) ? "read" : undefined;
55
+ if (sub === "tag")
56
+ return onlyFlags(rest, ["-l", "--list", "-n"]) ? "read" : undefined;
57
+ if (sub === "remote")
58
+ return onlyFlags(rest, ["-v", "--verbose"]) ? "read" : undefined;
59
+ if (sub === "stash" || sub === "worktree")
60
+ return rest[0] === "list" || sub === "stash" && rest[0] === "show" ? "read" : undefined;
61
+ if (sub === "submodule")
62
+ return rest[0] === "status" ? "read" : undefined;
63
+ if (sub === "reflog")
64
+ return rest.length === 0 || rest[0] === "show" || /^-/.test(rest[0]) ? "read" : undefined;
65
+ if (sub === "config")
66
+ return rest.length > 0 && ["--get", "--get-all", "--get-regexp", "--list", "-l"].includes(rest[0]) ? "read" : undefined;
67
+ return;
99
68
  }
100
- /**
101
- * 一条简单命令(已分好词)的性质:read 只读;edit 只在工作目录里建目录、碰文件,auto 模式下和改文件一样不问;
102
- * undefined 表示不认识或可能有副作用
103
- */
104
69
  export function commandKind(words) {
105
- const [first, ...args] = words;
106
- if (first === undefined)
107
- return undefined;
108
- // /usr/bin/grep、/bin/cat 就是 grep、cat;别的目录下的同名程序不认
109
- const name = first.replace(/^\/(usr\/)?bin\/(?=[^/]+$)/, "");
110
- if (UNSAFE_ARGS.some((re) => re.test(` ${args.join(" ")} `)))
111
- return undefined;
112
- if (name === "git")
113
- return gitKind(args);
114
- // 不改任何文件,按只读算;打开工作目录之外的文件照常先问
115
- if (opensForViewing(name, args))
116
- return "read";
117
- if (VERSIONED.has(name) && args.length === 1 && VERSION_ARGS.has(args[0]))
118
- return "read";
119
- if (READ_ANY.has(name)) {
120
- // file -C 会编译并写出 magic 文件
121
- if (name === "file" && args.some((a) => /^-[a-zA-Z]*C/.test(a)))
122
- return undefined;
123
- return "read";
124
- }
125
- switch (name) {
126
- case "tree":
127
- return args.some((a) => /^-[a-zA-Z]*o/.test(a)) ? undefined : "read";
128
- case "date":
129
- return args.some((a) => /^(-[a-zA-Z]*s|--set)/.test(a)) ? undefined : "read";
130
- case "hostname":
131
- return args.length === 0 ? "read" : undefined;
132
- case "sort":
133
- return args.some((a) => /^(-[a-zA-Z]*o|--compress-program)/.test(a)) ? undefined : "read";
134
- // 第二个位置参数是输出文件
135
- case "uniq":
136
- case "xxd":
137
- return positional(args).length <= 1 ? "read" : undefined;
138
- case "find":
139
- return args.some((a) => FIND_UNSAFE.test(a)) ? undefined : "read";
140
- case "sed": {
141
- // 只认 sed -n '10,20p' 文件……:sed 脚本里的 w、e 命令能写文件、执行程序,不去分析
142
- const i = args.findIndex((a) => !a.startsWith("-"));
143
- const flags = i < 0 ? args : args.slice(0, i);
144
- if (i < 0 || !flags.some((f) => ["-n", "--quiet", "--silent"].includes(f)))
145
- return undefined;
146
- if (!onlyFlags(flags, ["-n", "--quiet", "--silent", "-E", "-r"]) || !SED_PRINT.test(args[i]))
147
- return undefined;
148
- return args.slice(i + 1).some((a) => a.startsWith("-")) ? undefined : "read";
149
- }
150
- case "npm":
151
- case "pnpm":
152
- case "yarn":
153
- return ["ls", "list", "why"].includes(args[0] ?? "") ? "read" : undefined;
154
- case "mkdir":
155
- case "touch":
156
- return args.length > 0 ? "edit" : undefined;
70
+ const [first, ...args] = words;
71
+ if (first === undefined)
72
+ return;
73
+ const name = first.replace(/^\/(usr\/)?bin\/(?=[^/]+$)/, "");
74
+ if (UNSAFE_ARGS.some((re) => re.test(` ${args.join(" ")} `)))
75
+ return;
76
+ if (name === "git")
77
+ return gitKind(args);
78
+ if (opensForViewing(name, args))
79
+ return "read";
80
+ if (VERSIONED.has(name) && args.length === 1 && VERSION_ARGS.has(args[0]))
81
+ return "read";
82
+ if (READ_ANY.has(name)) {
83
+ if (name === "file" && args.some((a) => /^-[a-zA-Z]*C/.test(a)))
84
+ return;
85
+ return "read";
86
+ }
87
+ switch (name) {
88
+ case "tree":
89
+ return args.some((a) => /^-[a-zA-Z]*o/.test(a)) ? undefined : "read";
90
+ case "date":
91
+ return args.some((a) => /^(-[a-zA-Z]*s|--set)/.test(a)) ? undefined : "read";
92
+ case "hostname":
93
+ return args.length === 0 ? "read" : undefined;
94
+ case "sort":
95
+ return args.some((a) => /^(-[a-zA-Z]*o|--compress-program)/.test(a)) ? undefined : "read";
96
+ case "uniq":
97
+ case "xxd":
98
+ return positional(args).length <= 1 ? "read" : undefined;
99
+ case "find":
100
+ return args.some((a) => FIND_UNSAFE.test(a)) ? undefined : "read";
101
+ case "sed": {
102
+ const i = args.findIndex((a) => !a.startsWith("-"));
103
+ const flags = i < 0 ? args : args.slice(0, i);
104
+ if (i < 0 || !flags.some((f) => ["-n", "--quiet", "--silent"].includes(f)))
105
+ return;
106
+ if (!onlyFlags(flags, ["-n", "--quiet", "--silent", "-E", "-r"]) || !SED_PRINT.test(args[i]))
107
+ return;
108
+ return args.slice(i + 1).some((a) => a.startsWith("-")) ? undefined : "read";
157
109
  }
158
- return undefined;
110
+ case "npm":
111
+ case "pnpm":
112
+ case "yarn":
113
+ return ["ls", "list", "why"].includes(args[0] ?? "") ? "read" : undefined;
114
+ case "mkdir":
115
+ case "touch":
116
+ return args.length > 0 ? "edit" : undefined;
117
+ }
118
+ return;
159
119
  }
160
- /** 词结束的位置:空白或操作符 */
161
120
  const BOUNDARY = /[\s;&|<>]/;
162
- /**
163
- * 只认简单的 shell 语法:空白分隔的词、单引号、不含展开的双引号、未加引号的通配符、
164
- * 控制符 && || | ; 和换行、重定向 > >> < &> 和 2>&1。
165
- * 其余一切(命令替换、变量、花括号展开、转义、注释、后台 &、here-doc……)返回 undefined,调用方一律按"不安全"处理,
166
- * 这样判断用的词和 shell 实际看到的参数一致
167
- */
168
121
  function tokenize(command) {
169
- const out = [];
170
- let cur;
171
- const flush = () => {
172
- if (cur)
173
- out.push(cur);
122
+ const out = [];
123
+ let cur;
124
+ const flush = () => {
125
+ if (cur)
126
+ out.push(cur);
127
+ cur = undefined;
128
+ };
129
+ const s = command.trim();
130
+ for (let i = 0;i < s.length; ) {
131
+ const ch = s[i];
132
+ if (ch === " " || ch === "\t") {
133
+ flush();
134
+ i++;
135
+ continue;
136
+ }
137
+ if (ch === `
138
+ ` || ch === ";") {
139
+ flush();
140
+ out.push({ op: ";" });
141
+ i++;
142
+ continue;
143
+ }
144
+ if (ch === "|") {
145
+ flush();
146
+ if (s[i + 1] === "&")
147
+ return;
148
+ const two = s[i + 1] === "|";
149
+ out.push({ op: two ? "||" : "|" });
150
+ i += two ? 2 : 1;
151
+ continue;
152
+ }
153
+ if (ch === "&") {
154
+ flush();
155
+ if (s[i + 1] === "&") {
156
+ out.push({ op: "&&" });
157
+ i += 2;
158
+ continue;
159
+ }
160
+ if (s[i + 1] !== ">")
161
+ return;
162
+ i += s[i + 2] === ">" ? 3 : 2;
163
+ if (s[i] === "(" || s[i] === "&")
164
+ return;
165
+ out.push({ op: ">" });
166
+ continue;
167
+ }
168
+ if (ch === ">" || ch === "<") {
169
+ if (cur && /^\d$/.test(cur.value))
174
170
  cur = undefined;
175
- };
176
- const s = command.trim();
177
- for (let i = 0; i < s.length;) {
178
- const ch = s[i];
179
- if (ch === " " || ch === "\t") {
180
- flush();
181
- i++;
182
- continue;
183
- }
184
- if (ch === "\n" || ch === ";") {
185
- flush();
186
- out.push({ op: ";" });
187
- i++;
188
- continue;
189
- }
190
- if (ch === "|") {
191
- flush();
192
- if (s[i + 1] === "&")
193
- return undefined;
194
- const two = s[i + 1] === "|";
195
- out.push({ op: two ? "||" : "|" });
196
- i += two ? 2 : 1;
197
- continue;
198
- }
199
- if (ch === "&") {
200
- flush();
201
- if (s[i + 1] === "&") {
202
- out.push({ op: "&&" });
203
- i += 2;
204
- continue;
205
- }
206
- // &> 和 &>>:stdout、stderr 一起重定向
207
- if (s[i + 1] !== ">")
208
- return undefined;
209
- i += s[i + 2] === ">" ? 3 : 2;
210
- if (s[i] === "(" || s[i] === "&")
211
- return undefined;
212
- out.push({ op: ">" });
213
- continue;
214
- }
215
- if (ch === ">" || ch === "<") {
216
- // 紧挨在前面的一位数字是文件描述符(2>),其他的词先结束
217
- if (cur && /^\d$/.test(cur.value))
218
- cur = undefined;
219
- else
220
- flush();
221
- i++;
222
- if (ch === "<" && (s[i] === "<" || s[i] === "(" || s[i] === ">" || s[i] === "&"))
223
- return undefined;
224
- if (ch === ">" && (s[i] === ">" || s[i] === "|"))
225
- i++;
226
- if (s[i] === "(")
227
- return undefined;
228
- if (ch === ">" && s[i] === "&") {
229
- const m = /^(\d|-)/.exec(s.slice(i + 1));
230
- if (!m || (s[i + 1 + m[0].length] !== undefined && !BOUNDARY.test(s[i + 1 + m[0].length])))
231
- return undefined;
232
- i += 1 + m[0].length;
233
- out.push({ op: "dup" });
234
- continue;
235
- }
236
- out.push({ op: ch });
237
- continue;
238
- }
239
- cur ??= { value: "", glob: false };
240
- if (ch === "'" || ch === '"') {
241
- const end = s.indexOf(ch, i + 1);
242
- if (end < 0)
243
- return undefined;
244
- const inner = s.slice(i + 1, end);
245
- // 双引号里的反斜杠只在 $ ` " \ 和换行前面是转义,其他时候原样保留(Windows 路径 "D:\a\b");
246
- // 末尾的反斜杠转义的是这个引号,引号其实没有结束
247
- if (ch === '"' && (/[$`!]/.test(inner) || /\\([$`"\\\n]|$)/.test(inner)))
248
- return undefined;
249
- cur.value += inner;
250
- i = end + 1;
251
- continue;
252
- }
253
- if (/[`$()\r\\{}!#]/.test(ch))
254
- return undefined;
255
- if (/[*?[\]]/.test(ch))
256
- cur.glob = true;
257
- cur.value += ch;
171
+ else
172
+ flush();
173
+ i++;
174
+ if (ch === "<" && (s[i] === "<" || s[i] === "(" || s[i] === ">" || s[i] === "&"))
175
+ return;
176
+ if (ch === ">" && (s[i] === ">" || s[i] === "|"))
258
177
  i++;
178
+ if (s[i] === "(")
179
+ return;
180
+ if (ch === ">" && s[i] === "&") {
181
+ const m = /^(\d|-)/.exec(s.slice(i + 1));
182
+ if (!m || s[i + 1 + m[0].length] !== undefined && !BOUNDARY.test(s[i + 1 + m[0].length]))
183
+ return;
184
+ i += 1 + m[0].length;
185
+ out.push({ op: "dup" });
186
+ continue;
187
+ }
188
+ out.push({ op: ch });
189
+ continue;
190
+ }
191
+ cur ??= { value: "", glob: false };
192
+ if (ch === "'" || ch === '"') {
193
+ const end = s.indexOf(ch, i + 1);
194
+ if (end < 0)
195
+ return;
196
+ const inner = s.slice(i + 1, end);
197
+ if (ch === '"' && (/[$`!]/.test(inner) || /\\([$`"\\\n]|$)/.test(inner)))
198
+ return;
199
+ cur.value += inner;
200
+ i = end + 1;
201
+ continue;
259
202
  }
260
- flush();
261
- return out;
203
+ if (/[`$()\r\\{}!#]/.test(ch))
204
+ return;
205
+ if (/[*?[\]]/.test(ch))
206
+ cur.glob = true;
207
+ cur.value += ch;
208
+ i++;
209
+ }
210
+ flush();
211
+ return out;
262
212
  }
263
- const isWord = (t) => t !== undefined && "value" in t;
264
- /** 不含任何操作符的命令分成词;含操作符或分不了词时返回 undefined */
213
+ const isWord = (t) => t !== undefined && ("value" in t);
265
214
  export function shellWords(command) {
266
- const tokens = tokenize(command);
267
- if (!tokens || !tokens.every(isWord))
268
- return undefined;
269
- return tokens;
215
+ const tokens = tokenize(command);
216
+ if (!tokens || !tokens.every(isWord))
217
+ return;
218
+ return tokens;
270
219
  }
271
- /** 把命令按 && || | ; 拆成简单命令;有空命令或分不了词时返回 undefined */
272
220
  export function shellCommands(command) {
273
- const tokens = tokenize(command);
274
- if (!tokens)
275
- return undefined;
276
- const cmds = [];
277
- let cur = { words: [], inputs: [], outputs: [] };
278
- for (let i = 0; i < tokens.length; i++) {
279
- const t = tokens[i];
280
- if (isWord(t))
281
- cur.words.push(t);
282
- else if (t.op === "dup")
283
- continue;
284
- else if (t.op === ">" || t.op === "<") {
285
- const target = tokens[++i];
286
- if (!isWord(target))
287
- return undefined;
288
- (t.op === ">" ? cur.outputs : cur.inputs).push(target);
289
- }
290
- else {
291
- if (cur.words.length === 0)
292
- return undefined;
293
- cmds.push(cur);
294
- cur = { words: [], inputs: [], outputs: [] };
295
- }
221
+ const tokens = tokenize(command);
222
+ if (!tokens)
223
+ return;
224
+ const cmds = [];
225
+ let cur = { words: [], inputs: [], outputs: [] };
226
+ for (let i = 0;i < tokens.length; i++) {
227
+ const t = tokens[i];
228
+ if (isWord(t))
229
+ cur.words.push(t);
230
+ else if (t.op === "dup")
231
+ continue;
232
+ else if (t.op === ">" || t.op === "<") {
233
+ const target = tokens[++i];
234
+ if (!isWord(target))
235
+ return;
236
+ (t.op === ">" ? cur.outputs : cur.inputs).push(target);
237
+ } else {
238
+ if (cur.words.length === 0)
239
+ return;
240
+ cmds.push(cur);
241
+ cur = { words: [], inputs: [], outputs: [] };
296
242
  }
297
- if (cur.words.length > 0)
298
- cmds.push(cur);
299
- // 结尾可以是 ;(或换行),不能是 && || |
300
- else if (!(tokens.length > 0 && tokens.at(-1).op === ";"))
301
- return undefined;
302
- return cmds.length > 0 ? cmds : undefined;
243
+ }
244
+ if (cur.words.length > 0)
245
+ cmds.push(cur);
246
+ else if (!(tokens.length > 0 && tokens.at(-1).op === ";"))
247
+ return;
248
+ return cmds.length > 0 ? cmds : undefined;
303
249
  }
304
250
  const joined = (words) => words.map((w) => w.value).join(" ");
305
- /** 输出只能丢进 /dev/null:其他重定向会写文件 */
306
251
  const quietOutputs = (c) => c.outputs.every((w) => !w.glob && w.value === "/dev/null");
307
- /** 每条简单命令都只读(或是 cd),重定向只丢弃输出。不看路径 */
308
252
  export function isSafeCommand(command) {
309
- const cmds = shellCommands(command);
310
- return !!cmds && cmds.every((c) => quietOutputs(c) && (c.words[0].value === "cd" || commandKind(c.words.map((w) => w.value)) === "read"));
253
+ const cmds = shellCommands(command);
254
+ return !!cmds && cmds.every((c) => quietOutputs(c) && (c.words[0].value === "cd" || commandKind(c.words.map((w) => w.value)) === "read"));
311
255
  }
312
- /** 这些命令的第二个词后面跟的是要执行的东西(脚本名、子命令),前缀要带上第三个词 */
313
256
  const RUNNERS = /^(npm|pnpm|yarn|bun|npx|bunx|uv|poetry|pipenv|docker|kubectl|cargo|go|dotnet)\s+(run|exec|x|compose|tool)$/;
314
- /** 前缀规则批准过的命令再加上这些参数,性质就变了(强制、删除、跳过检查),要重新问 */
315
257
  const DANGEROUS_ARGS = /^(-f|--force|--force-with-lease|--hard|-D|--delete|--no-verify|-rf|-fr|-Rf|--prune)$|^--force[=-]/;
316
- /**
317
- * 前缀规则只匹配能完整分词、且前缀按整词对齐的命令,避免 "npm test && …" 搭便车;
318
- * 前缀之后出现危险参数(git push 之后的 --force)也不算
319
- */
320
258
  function matchesPrefix(command, prefix) {
321
- const words = shellWords(command);
322
- return !!words && prefixCovers(words, prefix);
259
+ const words = shellWords(command);
260
+ return !!words && prefixCovers(words, prefix);
323
261
  }
324
262
  function prefixCovers(words, prefix) {
325
- const c = joined(words);
326
- if (c !== prefix && !c.startsWith(prefix + " "))
327
- return false;
328
- const extra = words.slice(prefix.split(" ").length);
329
- return !extra.some((w) => DANGEROUS_ARGS.test(w.value));
263
+ const c = joined(words);
264
+ if (c !== prefix && !c.startsWith(prefix + " "))
265
+ return false;
266
+ const extra = words.slice(prefix.split(" ").length);
267
+ return !extra.some((w) => DANGEROUS_ARGS.test(w.value));
330
268
  }
331
- /**
332
- * bash 的"总是允许"默认规则:一般取前两个词("cargo build"、"git commit"),
333
- * 运行脚本的命令取三个词("npm run build")。第二个词就是选项("rm -rf x")、只有一个词时,只允许这一条命令本身。
334
- * 复合命令("git add -A && git commit -m …"、"bun test 2>&1 | tail -20")里每条不是只读的命令各记一条:
335
- * 关卡对复合命令逐条判断,所以下次换了提交信息、换了组合也不用再问。
336
- * 分不了词、有输出重定向、或者不是只读的命令带输入重定向时,只允许整条命令原文
337
- */
338
269
  export function bashRules(command) {
339
- const exact = [{ tool: "bash", command: command.trim() }];
340
- const cmds = shellCommands(command);
341
- const unsafe = cmds?.filter((c) => c.words[0].value !== "cd" && commandKind(c.words.map((w) => w.value)) !== "read");
342
- if (!cmds || !unsafe || unsafe.length === 0 || !cmds.every(quietOutputs) || unsafe.some((c) => c.inputs.length > 0))
343
- return exact;
344
- // 只有一条命令、又只能按原文记时,记整条原文(和关卡比较的是同一个字符串)
345
- if (cmds.length === 1 && !prefixOf(unsafe[0].words))
346
- return exact;
347
- const rules = unsafe.map((c) => {
348
- const prefix = prefixOf(c.words);
349
- return prefix ? { tool: "bash", prefix } : { tool: "bash", command: joined(c.words) };
350
- });
351
- return rules.filter((r, i) => rules.findIndex((o) => o.prefix === r.prefix && o.command === r.command) === i);
270
+ const exact = [{ tool: "bash", command: command.trim() }];
271
+ const cmds = shellCommands(command);
272
+ const unsafe = cmds?.filter((c) => c.words[0].value !== "cd" && commandKind(c.words.map((w) => w.value)) !== "read");
273
+ if (!cmds || !unsafe || unsafe.length === 0 || !cmds.every(quietOutputs) || unsafe.some((c) => c.inputs.length > 0))
274
+ return exact;
275
+ if (cmds.length === 1 && !prefixOf(unsafe[0].words))
276
+ return exact;
277
+ const rules = unsafe.map((c) => {
278
+ const prefix = prefixOf(c.words);
279
+ return prefix ? { tool: "bash", prefix } : { tool: "bash", command: joined(c.words) };
280
+ });
281
+ return rules.filter((r, i) => rules.findIndex((o) => o.prefix === r.prefix && o.command === r.command) === i);
352
282
  }
353
- /** 一条简单命令的前缀规则;只能按原文记时返回 undefined */
354
283
  function prefixOf(all) {
355
- const words = all.map((w) => w.value);
356
- if (words.length < 2 || words[1].startsWith("-") || words.some((w) => DANGEROUS_ARGS.test(w)))
357
- return undefined;
358
- const n = RUNNERS.test(words.slice(0, 2).join(" ")) && words.length >= 3 && !words[2].startsWith("-") ? 3 : 2;
359
- return words.slice(0, n).join(" ");
284
+ const words = all.map((w) => w.value);
285
+ if (words.length < 2 || words[1].startsWith("-") || words.some((w) => DANGEROUS_ARGS.test(w)))
286
+ return;
287
+ const n = RUNNERS.test(words.slice(0, 2).join(" ")) && words.length >= 3 && !words[2].startsWith("-") ? 3 : 2;
288
+ return words.slice(0, n).join(" ");
360
289
  }
361
290
  const hostOf = (url) => {
362
- try {
363
- return new URL(url).hostname.toLowerCase();
364
- }
365
- catch {
366
- return undefined;
367
- }
291
+ try {
292
+ return new URL(url).hostname.toLowerCase();
293
+ } catch {
294
+ return;
295
+ }
368
296
  };
369
- /** 本机的地址:localhost、127.x.x.x、::1(URL 会把 127.1 这类写法规范成 127.0.0.1) */
370
297
  const isLoopback = (host) => host !== undefined && (host === "localhost" || host.endsWith(".localhost") || /^127(\.\d{1,3}){3}$/.test(host) || host === "[::1]");
371
- /**
372
- * Windows 上 bash 工具跑的是 Git Bash,模型常把路径写成 /c/Users/...(MSYS 的写法)。
373
- * path.resolve 会把它当成当前盘符下的 \c\Users\...,判断成工作目录之外,只读命令也要确认。
374
- * 换算成 C:/Users/... 再判断;/tmp、/usr 这类 MSYS 自己的目录不换算,仍然算在外面
375
- */
376
298
  export function nativePath(p, platform = process.platform) {
377
- if (platform !== "win32")
378
- return p;
379
- const m = /^\/([a-zA-Z])(\/.*)?$/.exec(p);
380
- return m ? `${m[1].toUpperCase()}:${m[2] ?? "/"}` : p;
299
+ if (platform !== "win32")
300
+ return p;
301
+ const m = /^\/([a-zA-Z])(\/.*)?$/.exec(p);
302
+ return m ? `${m[1].toUpperCase()}:${m[2] ?? "/"}` : p;
381
303
  }
382
- /** 真实路径:解析符号链接;路径还不存在时解析最近的已存在的上级目录 */
383
304
  function real(p) {
305
+ try {
306
+ return realpathSync(p);
307
+ } catch {
308
+ const parent = path.dirname(p);
309
+ return parent === p ? p : path.join(real(parent), path.basename(p));
310
+ }
311
+ }
312
+ export function policy(opts) {
313
+ const bases = new Map;
314
+ const realBase = (dir) => {
315
+ let r = bases.get(dir);
316
+ if (r !== undefined)
317
+ return r;
384
318
  try {
385
- return realpathSync(p);
319
+ r = realpathSync(dir);
320
+ } catch {
321
+ return real(dir);
386
322
  }
387
- catch {
388
- const parent = path.dirname(p);
389
- return parent === p ? p : path.join(real(parent), path.basename(p));
323
+ bases.set(dir, r);
324
+ return r;
325
+ };
326
+ const contains = (base, target) => {
327
+ const rel = path.relative(base, target);
328
+ return rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
329
+ };
330
+ const within = (base, p) => contains(realBase(base), real(path.resolve(opts.cwd, p)));
331
+ const inside = (p) => {
332
+ const target = real(path.resolve(opts.cwd, p));
333
+ return contains(realBase(opts.cwd), target) || (opts.writeRoots ?? []).some((r) => contains(realBase(r), target));
334
+ };
335
+ const globEscapes = (pattern) => path.isAbsolute(pattern) || pattern.split(/[\\/]/).includes("..");
336
+ const mayMatchParent = (value) => value.split(/[\\/]/).some((seg) => /^[.[]/.test(seg) && /[*?[]/.test(seg));
337
+ const pathOutside = (base, p, glob) => p.startsWith("~") || !inside(path.resolve(base, nativePath(p))) || glob && mayMatchParent(p);
338
+ const argsOutside = (base, words) => words.slice(1).some((w) => {
339
+ const v = w.value;
340
+ const candidates = !v.startsWith("-") ? [v] : [v.includes("=") ? v.slice(v.indexOf("=") + 1) : "", !v.startsWith("--") && v.length > 2 ? v.slice(2) : ""];
341
+ return candidates.some((c) => c !== "" && pathOutside(base, c, w.glob));
342
+ });
343
+ const classifyBash = (command, { edits, ruled }) => {
344
+ const cmds = shellCommands(command);
345
+ if (!cmds)
346
+ return;
347
+ let base = opts.cwd;
348
+ let outside = false;
349
+ for (const c of cmds) {
350
+ if (!quietOutputs(c) || c.words[0].glob)
351
+ return;
352
+ if (c.inputs.some((w) => w.value !== "/dev/null" && pathOutside(base, w.value, w.glob)))
353
+ outside = true;
354
+ if (c.words[0].value === "cd") {
355
+ const target = c.words[1];
356
+ if (!target || c.words.length > 2 || target.glob || target.value.startsWith("-") || pathOutside(base, target.value, false))
357
+ return;
358
+ base = path.resolve(base, nativePath(target.value));
359
+ continue;
360
+ }
361
+ if (ruled?.(c.words))
362
+ continue;
363
+ const kind = commandKind(c.words.map((w) => w.value));
364
+ if (!kind || kind === "edit" && !edits)
365
+ return;
366
+ if (argsOutside(base, c.words))
367
+ outside = true;
390
368
  }
391
- }
392
- export function policy(opts) {
393
- /**
394
- * 作为范围的目录(工作目录、登记的目录、规则里的目录)的真实路径,本会话内记住:复合命令的每个参数都要和它们比,
395
- * 每次都 realpathSync 是一串同步 IO。只记已经存在的;要判断的路径本身每次都重新解析,符号链接可能随时被换掉
396
- */
397
- const bases = new Map();
398
- const realBase = (dir) => {
399
- let r = bases.get(dir);
400
- if (r !== undefined)
401
- return r;
369
+ return outside ? "outside" : "inside";
370
+ };
371
+ const bashGate = (r) => r === undefined ? undefined : { decision: r === "outside" ? "ask" : "allow" };
372
+ return {
373
+ absolutePath(input) {
374
+ if (!input || typeof input !== "object" || typeof input.path !== "string")
375
+ return input;
376
+ return { ...input, path: path.resolve(opts.cwd, input.path) };
377
+ },
378
+ rulesFor(call) {
379
+ const field = opts.shell(call.name);
380
+ if (field !== undefined)
381
+ return bashRules(String(call.input?.[field] ?? "")).map((r) => ({ ...r, tool: call.name }));
382
+ const input = call.input;
383
+ if (typeof input?.url === "string") {
384
+ const host = hostOf(input.url);
385
+ if (host)
386
+ return [{ tool: call.name, host }];
387
+ }
388
+ if (typeof input?.path === "string" && !inside(input.path)) {
389
+ const full = path.resolve(opts.cwd, input.path);
390
+ let isDir = false;
402
391
  try {
403
- r = realpathSync(dir);
404
- }
405
- catch {
406
- return real(dir);
407
- }
408
- bases.set(dir, r);
409
- return r;
410
- };
411
- /** 真实路径 target 在真实路径 base 里 */
412
- const contains = (base, target) => {
413
- const rel = path.relative(base, target);
414
- // 只有 ".." 这一段才表示上级目录,名为 "..foo" 的目录仍在里面
415
- return rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
416
- };
417
- /** p 在 base 目录里。按真实路径比较:目录里指向外面的符号链接也算外面 */
418
- const within = (base, p) => contains(realBase(base), real(path.resolve(opts.cwd, p)));
419
- const inside = (p) => {
420
- const target = real(path.resolve(opts.cwd, p));
421
- return contains(realBase(opts.cwd), target) || (opts.writeRoots ?? []).some((r) => contains(realBase(r), target));
422
- };
423
- /** glob 的 pattern 是绝对路径或含 ".." 段时,匹配范围会超出 path */
424
- const globEscapes = (pattern) => path.isAbsolute(pattern) || pattern.split(/[\\/]/).includes("..");
425
- /** 以 "." 或 "[" 开头的通配段可能匹配到 ".."(取决于 bash 版本和选项),按越界处理 */
426
- const mayMatchParent = (value) => value.split(/[\\/]/).some((seg) => /^[.[]/.test(seg) && /[*?[]/.test(seg));
427
- /** 相对 base 目录的路径 p 指向工作目录之外 */
428
- const pathOutside = (base, p, glob) => p.startsWith("~") || !inside(path.resolve(base, nativePath(p))) || (glob && mayMatchParent(p));
429
- /**
430
- * 命令参数里有指向工作目录之外的路径。选项也要看:--opt=path 的值,以及粘在短选项后面的值(-f/etc/x)
431
- */
432
- const argsOutside = (base, words) => words.slice(1).some((w) => {
433
- const v = w.value;
434
- const candidates = !v.startsWith("-")
435
- ? [v]
436
- : [v.includes("=") ? v.slice(v.indexOf("=") + 1) : "", !v.startsWith("--") && v.length > 2 ? v.slice(2) : ""];
437
- return candidates.some((c) => c !== "" && pathOutside(base, c, w.glob));
438
- });
439
- /**
440
- * 判断一条 bash 命令能不能不问就执行。复合命令(&& || | ;)要求每条简单命令都满足:
441
- * 只读命令;edits 时还可以是建目录、碰文件的命令;ruled 时还可以是"总是允许"的规则覆盖的命令。
442
- * 输出重定向只能是 /dev/null。cd 到工作目录里的目录后,后面的相对路径按新目录算。
443
- * 返回 inside(可以放行)、outside(认识,但碰到了工作目录之外的路径,先问)、undefined(不认识)
444
- */
445
- const classifyBash = (command, { edits, ruled }) => {
446
- const cmds = shellCommands(command);
447
- if (!cmds)
448
- return undefined;
449
- let base = opts.cwd;
450
- let outside = false;
451
- for (const c of cmds) {
452
- if (!quietOutputs(c) || c.words[0].glob)
453
- return undefined;
454
- if (c.inputs.some((w) => w.value !== "/dev/null" && pathOutside(base, w.value, w.glob)))
455
- outside = true;
456
- if (c.words[0].value === "cd") {
457
- const target = c.words[1];
458
- // 不带参数的 cd 回到 home;cd 到外面以后,后面的相对路径都说不清了
459
- if (!target || c.words.length > 2 || target.glob || target.value.startsWith("-") || pathOutside(base, target.value, false))
460
- return undefined;
461
- base = path.resolve(base, nativePath(target.value));
462
- continue;
463
- }
464
- // 规则覆盖的命令和原来的前缀规则一样不看路径
465
- if (ruled?.(c.words))
466
- continue;
467
- const kind = commandKind(c.words.map((w) => w.value));
468
- if (!kind || (kind === "edit" && !edits))
469
- return undefined;
470
- if (argsOutside(base, c.words))
471
- outside = true;
472
- }
473
- return outside ? "outside" : "inside";
474
- };
475
- /** 把 classifyBash 的结果变成决定 */
476
- const bashGate = (r) => r === undefined ? undefined : { decision: r === "outside" ? "ask" : "allow" };
477
- return {
478
- absolutePath(input) {
479
- if (!input || typeof input !== "object" || typeof input.path !== "string")
480
- return input;
481
- return { ...input, path: path.resolve(opts.cwd, input.path) };
482
- },
483
- rulesFor(call) {
484
- if (call.name === "bash")
485
- return bashRules(String(call.input.command ?? ""));
486
- const input = call.input;
487
- if (typeof input?.url === "string") {
488
- const host = hostOf(input.url);
489
- if (host)
490
- return [{ tool: call.name, host }];
491
- }
492
- if (typeof input?.path === "string" && !inside(input.path)) {
493
- const full = path.resolve(opts.cwd, input.path);
494
- let isDir = false;
495
- try {
496
- isDir = statSync(full).isDirectory();
497
- }
498
- catch {
499
- // 还不存在的文件
500
- }
501
- return [{ tool: call.name, dir: isDir ? full : path.dirname(full) }];
502
- }
503
- return [{ tool: call.name }];
504
- },
505
- decide(call, { mode, rules }) {
506
- const { tool } = call;
507
- const problem = validate(tool.inputSchema, call.input);
508
- if (problem)
509
- return { decision: "deny", reason: `Invalid input for ${call.name}: ${problem}. Fix the arguments and try again.` };
510
- const input = call.input;
511
- const outside = (typeof input.path === "string" && !inside(input.path)) ||
512
- (call.name === "glob" && typeof input.pattern === "string" && globEscapes(input.pattern));
513
- /** 会把参数发到网络上的只读工具 */
514
- const network = typeof input.url === "string" && !isLoopback(hostOf(input.url));
515
- const covers = (r) => {
516
- if (r.tool !== call.name)
517
- return false;
518
- if (r.command !== undefined)
519
- return (input.command ?? "").trim() === r.command;
520
- if (r.prefix !== undefined)
521
- return matchesPrefix(input.command ?? "", r.prefix);
522
- // glob 的 pattern 越界时路径本身说明不了范围,目录规则不算
523
- if (r.dir !== undefined)
524
- return typeof input.path === "string" && within(r.dir, input.path) && !(call.name === "glob" && globEscapes(input.pattern ?? ""));
525
- if (r.host !== undefined)
526
- return network && hostOf(input.url) === r.host;
527
- return !outside;
528
- };
529
- const allRules = rules;
530
- const ruled = allRules.some(covers);
531
- /** 复合命令里的一条简单命令被 bash 规则覆盖 */
532
- const ruledWords = (words) => allRules.some((r) => r.tool === "bash" &&
533
- ((r.command !== undefined && joined(words) === r.command) || (r.prefix !== undefined && prefixCovers(words, r.prefix))));
534
- const isBash = call.name === "bash";
535
- const command = input.command ?? "";
536
- if (tool.effect === "read") {
537
- const readable = !outside ||
538
- (typeof input.path === "string" && call.name !== "glob" && (opts.readRoots ?? []).some((r) => within(r, input.path)));
539
- if (mode === "yolo" || ruled || (readable && !network))
540
- return { decision: "allow" };
541
- return { decision: "ask" };
542
- }
543
- // plan:和 readonly 一样不改任何东西,只是拒绝的理由告诉模型先给出计划
544
- if (mode === "readonly" || mode === "plan") {
545
- // 只读命令也要和 read_file 一样:读工作目录之外的东西先问
546
- const gate = isBash ? bashGate(classifyBash(command, { edits: false })) : undefined;
547
- if (gate)
548
- return gate;
549
- return {
550
- decision: "deny",
551
- reason: mode === "plan"
552
- ? `The session is in plan mode, so ${call.name} is not allowed yet. Finish investigating, then present your plan for the user to approve as the plan mode instructions describe (with propose_plan when you have it).`
553
- : `The session is in read-only mode, so ${call.name} is not allowed. Describe the change instead of making it.`,
554
- };
555
- }
556
- if (mode === "yolo" || ruled)
557
- return { decision: "allow" };
558
- if (tool.effect === "write")
559
- return { decision: mode === "auto" && !outside ? "allow" : "ask" };
560
- // external
561
- const gate = isBash ? bashGate(classifyBash(command, { edits: mode === "auto", ruled: ruledWords })) : undefined;
562
- return gate ?? { decision: "ask" };
563
- },
564
- };
392
+ isDir = statSync(full).isDirectory();
393
+ } catch {}
394
+ return [{ tool: call.name, dir: isDir ? full : path.dirname(full) }];
395
+ }
396
+ return [{ tool: call.name }];
397
+ },
398
+ decide(call, { mode, rules }) {
399
+ const { tool } = call;
400
+ const problem = validate(tool.inputSchema, call.input);
401
+ if (problem)
402
+ return { decision: "deny", reason: `Invalid input for ${call.name}: ${problem}. Fix the arguments and try again.` };
403
+ const input = call.input;
404
+ const field = opts.shell(call.name);
405
+ const isShell = field !== undefined;
406
+ const command = isShell ? String(call.input[field] ?? "") : "";
407
+ const outside = typeof input.path === "string" && !inside(input.path) || call.name === "glob" && typeof input.pattern === "string" && globEscapes(input.pattern);
408
+ const network = typeof input.url === "string" && !isLoopback(hostOf(input.url));
409
+ const covers = (r) => {
410
+ if (r.tool !== call.name)
411
+ return false;
412
+ if (r.command !== undefined)
413
+ return isShell && command.trim() === r.command;
414
+ if (r.prefix !== undefined)
415
+ return isShell && matchesPrefix(command, r.prefix);
416
+ if (r.dir !== undefined)
417
+ return typeof input.path === "string" && within(r.dir, input.path) && !(call.name === "glob" && globEscapes(input.pattern ?? ""));
418
+ if (r.host !== undefined)
419
+ return network && hostOf(input.url) === r.host;
420
+ return !outside;
421
+ };
422
+ const allRules = rules;
423
+ const ruled = allRules.some(covers);
424
+ const ruledWords = (words) => allRules.some((r) => r.tool === call.name && (r.command !== undefined && joined(words) === r.command || r.prefix !== undefined && prefixCovers(words, r.prefix)));
425
+ if (tool.effect === "read") {
426
+ const readable = !outside || typeof input.path === "string" && call.name !== "glob" && (opts.readRoots ?? []).some((r) => within(r, input.path));
427
+ if (mode === "yolo" || ruled || readable && !network)
428
+ return { decision: "allow" };
429
+ return { decision: "ask" };
430
+ }
431
+ if (mode === "readonly" || mode === "plan") {
432
+ const gate = isShell ? bashGate(classifyBash(command, { edits: false })) : undefined;
433
+ if (gate)
434
+ return gate;
435
+ return {
436
+ decision: "deny",
437
+ reason: mode === "plan" ? `The session is in plan mode, so ${call.name} is not allowed yet. Finish investigating, then present your plan for the user to approve as the plan mode instructions describe (with propose_plan when you have it).` : `The session is in read-only mode, so ${call.name} is not allowed. Describe the change instead of making it.`
438
+ };
439
+ }
440
+ if (mode === "yolo" || ruled)
441
+ return { decision: "allow" };
442
+ if (tool.effect === "write")
443
+ return { decision: mode === "auto" && !outside ? "allow" : "ask" };
444
+ const gate = isShell ? bashGate(classifyBash(command, { edits: mode === "auto", ruled: ruledWords })) : undefined;
445
+ return gate ?? { decision: "ask" };
446
+ }
447
+ };
565
448
  }