@uncarved/jade 0.0.0-stage → 0.1.1

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