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