@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,457 +1,402 @@
1
- // jade/approval:审批。tool.before 把路径统一成绝对路径,tool.gate 按模式和规则决定:允许、拒绝,或者要问用户(ask)。
2
- // 关卡不等用户:所有关卡合并的结果是 ask 时(日志里的 tool.decided),内核停下来等人工审批,这里才经 ui@1 问用户,
3
- // 把回答作为 approval 输入交给会话。别的插件的关卡要问时也由这里问。谁回答的、选了什么记成 jade/approval/answered 事件。
4
- // auto 模式下规则判断不了、本来要问的调用先让模型审一次(review.ts):它只能放行或转给用户,不能替用户拒绝。
5
- //
6
- // 没有这个插件(停用、坏掉、被隔离)时,核心的兜底关卡拒绝所有非只读工具(第 7 节),所以这里出错不会放行。
7
- // 用户选的"总是允许"记进日志(derived),恢复会话后仍然有效;选"在这个目录里总是允许"的记在
8
- // $JADE_HOME/state/approvals.json(按工作目录),以后在这个目录里开的会话都有效。模式是进程级的,来自配置,可以经 approval@1 改。
9
1
  import { mkdir, readFile, writeFile } from "node:fs/promises";
10
2
  import path from "node:path";
11
3
  import { definePlugin } from "@uncarved/jade-api";
12
4
  import { describeRule, MODES, policy } from "./policy.js";
13
5
  import { reviewer } from "./review.js";
14
6
  const ANSWERS = ["once", "always", "forever", "deny"];
15
- /** 只有终端里有的一项:拒绝,并写一句话告诉模型该怎么做 */
16
7
  const EXPLAIN = "explain";
17
- /** derived 里保存"总是允许"规则的键 */
18
8
  const RULES_KEY = "jade/approval/rules";
19
- /** 等用户回答的默认时限,过了按拒绝处理。配置 askTimeoutMinutes 可以改 */
20
9
  const ASK_TIMEOUT_MS = 24 * 60 * 60 * 1000;
21
- /** askTimeoutMinutes 的上限:定时器最长约 24.8 天 */
22
10
  const MAX_ASK_TIMEOUT_MINUTES = 7 * 24 * 60;
23
- /** 关卡的时限:auto 模式的审查最长一分钟(review.ts),比 hook 默认的 30 秒长 */
24
- const GATE_TIMEOUT_MS = 2 * 60_000;
11
+ const GATE_TIMEOUT_MS = 2 * 60000;
25
12
  const MAX_DETAIL_CHARS = 2000;
26
- /** 等工具的审批预览的时限,过了就用默认的 detail */
27
13
  const PREVIEW_TIMEOUT_MS = 5000;
28
- /**
29
- * 带 URL 的只读工具审查放行之后,完全相同的调用不再审查。不按主机记:同一主机上换一个路径或查询参数
30
- * 就能把本地数据带出去,正是审查要拦的
31
- */
32
14
  const reviewedKey = (call) => {
33
- const url = call.input?.url;
34
- if (call.tool.effect !== "read" || typeof url !== "string")
35
- return undefined;
36
- return `${call.name} ${JSON.stringify(call.input)}`;
15
+ const url = call.input?.url;
16
+ if (call.tool.effect !== "read" || typeof url !== "string")
17
+ return;
18
+ return `${call.name} ${JSON.stringify(call.input)}`;
37
19
  };
38
20
  let mode = "ask";
39
- /** 配置里写错的模式:第一个会话打开时告诉用户(process 里可能还拿不到 ui@1:它的提供者可能排在后面激活) */
40
21
  let badMode;
41
22
  let askTimeoutMs = ASK_TIMEOUT_MS;
42
- /** 配置里写错的 askTimeoutMinutes,和 badMode 一样在第一个会话打开时告诉用户 */
43
23
  let badTimeout;
44
- /** 经 allowRead 登记的目录;policy 每次判断时读它 */
45
24
  const readRoots = [];
46
- /** 经 allowWrite 登记的目录;policy 每次判断时读它 */
47
25
  const writeRoots = [];
48
- /** 经 addApprover 登记的审批渠道 → 登记它的插件 */
49
- const approvers = new Map();
50
- /** 打开着的会话:会话 id → 判断只读调用能不能不问就执行(allows) */
51
- const sessionChecks = new Map();
26
+ const approvers = new Map;
27
+ const sessionChecks = new Map;
28
+ const sessionRules = new Map;
52
29
  export default definePlugin({
53
- process(ctx) {
54
- const configured = ctx.config.mode;
55
- if (typeof configured === "string" && MODES.includes(configured))
56
- mode = configured;
57
- else if (configured !== undefined)
58
- badMode = JSON.stringify(configured);
59
- const minutes = ctx.config.askTimeoutMinutes;
60
- askTimeoutMs = ASK_TIMEOUT_MS;
61
- badTimeout = undefined;
62
- if (typeof minutes === "number" && Number.isFinite(minutes) && minutes > 0 && minutes <= MAX_ASK_TIMEOUT_MINUTES)
63
- askTimeoutMs = minutes * 60_000;
64
- else if (minutes !== undefined)
65
- badTimeout = JSON.stringify(minutes);
66
- ctx.provide("approval@1", (caller) => ({
67
- mode: () => mode,
68
- setMode(next) {
69
- if (!MODES.includes(next))
70
- throw new Error(`mode must be one of ${MODES.join(", ")}`);
71
- mode = next;
72
- },
73
- allowRead: (dir) => allow(caller, "allowRead", readRoots, dir),
74
- allowWrite: (dir) => allow(caller, "allowWrite", writeRoots, dir),
75
- addApprover(approver) {
76
- if (caller.layer === "project")
77
- throw new Error("approval.addApprover: project plugins cannot answer approvals");
78
- if (typeof approver !== "function")
79
- throw new Error("approval.addApprover: approver must be a function");
80
- approvers.set(approver, caller.plugin);
81
- const remove = () => void approvers.delete(approver);
82
- caller.onDispose(remove);
83
- return remove;
84
- },
85
- allows: (session, call) => call.tool !== undefined && (sessionChecks.get(session)?.(call) ?? false),
86
- }));
87
- },
88
- async session(ctx) {
89
- const rules = policy({ cwd: ctx.cwd, readRoots, writeRoots });
90
- const ui = ctx.service("ui@1");
91
- if (badMode !== undefined) {
92
- ui?.notify(`jade/approval: mode must be one of ${MODES.join(", ")}, got ${badMode}; using ask`, "warning");
93
- badMode = undefined;
30
+ process(ctx) {
31
+ const configured = ctx.config.mode;
32
+ if (typeof configured === "string" && MODES.includes(configured))
33
+ mode = configured;
34
+ else if (configured !== undefined)
35
+ badMode = JSON.stringify(configured);
36
+ const minutes = ctx.config.askTimeoutMinutes;
37
+ askTimeoutMs = ASK_TIMEOUT_MS;
38
+ badTimeout = undefined;
39
+ if (typeof minutes === "number" && Number.isFinite(minutes) && minutes > 0 && minutes <= MAX_ASK_TIMEOUT_MINUTES)
40
+ askTimeoutMs = minutes * 60000;
41
+ else if (minutes !== undefined)
42
+ badTimeout = JSON.stringify(minutes);
43
+ ctx.provide("approval@1", (caller) => ({
44
+ mode: () => mode,
45
+ setMode(next) {
46
+ if (!MODES.includes(next))
47
+ throw new Error(`mode must be one of ${MODES.join(", ")}`);
48
+ mode = next;
49
+ },
50
+ allowRead: (dir) => allow(caller, "allowRead", readRoots, dir),
51
+ allowWrite: (dir) => allow(caller, "allowWrite", writeRoots, dir),
52
+ addApprover(approver) {
53
+ if (caller.layer === "project")
54
+ throw new Error("approval.addApprover: project plugins cannot answer approvals");
55
+ if (typeof approver !== "function")
56
+ throw new Error("approval.addApprover: approver must be a function");
57
+ approvers.set(approver, caller.plugin);
58
+ const remove = () => void approvers.delete(approver);
59
+ caller.onDispose(remove);
60
+ return remove;
61
+ },
62
+ allows: (session, call) => call.tool !== undefined && (sessionChecks.get(session)?.(call) ?? false)
63
+ }));
64
+ },
65
+ async session(ctx) {
66
+ const rules = policy({ cwd: ctx.cwd, readRoots, writeRoots, shell: (t) => ctx.session.tool(t)?.meta?.shell });
67
+ const ui = ctx.service("ui@1");
68
+ if (badMode !== undefined) {
69
+ ui?.notify(`jade/approval: mode must be one of ${MODES.join(", ")}, got ${badMode}; using ask`, "warning");
70
+ badMode = undefined;
71
+ }
72
+ if (badTimeout !== undefined) {
73
+ ui?.notify(`jade/approval: askTimeoutMinutes must be a number of minutes between 0 and ${MAX_ASK_TIMEOUT_MINUTES}, got ${badTimeout}; using 24 hours`, "warning");
74
+ badTimeout = undefined;
75
+ }
76
+ const renderers = ctx.service("renderers@1");
77
+ const models = ctx.service("models@1");
78
+ const reviewing = models !== undefined && ctx.config.review !== false;
79
+ const recent = { messages: [] };
80
+ if (reviewing) {
81
+ ctx.kernel.hook({
82
+ kind: "transform",
83
+ point: "context.build",
84
+ fn: (req) => {
85
+ recent.messages = req.messages;
86
+ return req;
87
+ }
88
+ });
89
+ }
90
+ const review = reviewing ? reviewer({ models, cwd: ctx.cwd, writeRoots: () => writeRoots, messages: () => recent.messages, meta: (t) => ctx.session.tool(t)?.meta }) : undefined;
91
+ const reviewedCalls = new Set;
92
+ let warned = false;
93
+ const added = [];
94
+ let asking = Promise.resolve();
95
+ let logged = [];
96
+ const merged = (from) => [...from, ...added.filter((r) => !from.some((l) => JSON.stringify(l) === JSON.stringify(r)))];
97
+ const foreverFile = path.join(ctx.home, "state", "approvals.json");
98
+ const forever = (await readForever(foreverFile))[ctx.cwd] ?? [];
99
+ const parent = ctx.session.parent?.sessionId;
100
+ const inherited = () => parent ? sessionRules.get(parent)?.() ?? [] : [];
101
+ const saved = () => [...forever, ...merged(logged), ...inherited()];
102
+ const seen = new Map;
103
+ const answered = new Map;
104
+ const handled = new Set;
105
+ let turn = new AbortController;
106
+ const canAsk = () => ui?.interactive === true || approvers.size > 0;
107
+ const nobody = (name) => `${name} needs the user's approval, but nobody can approve it in this non-interactive run. Do not retry it; tell the user what you wanted to do.`;
108
+ const id = ctx.session.id;
109
+ const check = (call) => rules.decide(call, { mode: mode === "yolo" && call.tool.effect === "read" ? "yolo" : "readonly", rules: [...forever, ...logged, ...added, ...inherited()] }).decision === "allow";
110
+ sessionChecks.set(id, check);
111
+ sessionRules.set(id, saved);
112
+ await ctx.effect(() => () => {
113
+ if (sessionChecks.get(id) === check)
114
+ sessionChecks.delete(id);
115
+ if (sessionRules.get(id) === saved)
116
+ sessionRules.delete(id);
117
+ });
118
+ ctx.kernel.hook({
119
+ kind: "transform",
120
+ point: "tool.before",
121
+ fn: (call, hook) => {
122
+ logged = hook.derived[RULES_KEY] ?? [];
123
+ return { ...call, input: rules.absolutePath(call.input) };
124
+ }
125
+ });
126
+ ctx.kernel.hook({
127
+ kind: "gate",
128
+ point: "tool.gate",
129
+ timeoutMs: GATE_TIMEOUT_MS,
130
+ fn: async (call, hook) => {
131
+ seen.set(call.toolUseId, { call });
132
+ const result = rules.decide(call, { mode, rules: saved() });
133
+ if (result.decision !== "ask")
134
+ return result;
135
+ let why;
136
+ if (review && mode === "auto") {
137
+ const key = reviewedKey(call);
138
+ if (key !== undefined && reviewedCalls.has(key))
139
+ return { decision: "allow", reason: "This exact call was already approved in this session." };
140
+ const verdict = await review(call, hook.signal);
141
+ if (verdict.usage)
142
+ await hook.emit("reviewed", { toolUseId: call.toolUseId, usage: verdict.usage });
143
+ if (verdict.decision === "allow") {
144
+ if (key !== undefined)
145
+ reviewedCalls.add(key);
146
+ return { decision: "allow", reason: verdict.reason };
147
+ }
148
+ why = verdict.reason;
94
149
  }
95
- if (badTimeout !== undefined) {
96
- ui?.notify(`jade/approval: askTimeoutMinutes must be a number of minutes between 0 and ${MAX_ASK_TIMEOUT_MINUTES}, got ${badTimeout}; using 24 hours`, "warning");
97
- badTimeout = undefined;
150
+ if (!canAsk()) {
151
+ if (!warned) {
152
+ warned = true;
153
+ ui?.notify(`${call.name} needs approval, but this jade cannot ask. To let it make changes in the working directory, ` + `set {"jade/approval": {"mode": "auto"}} in ${ctx.home}/config.json`, "warning");
154
+ }
155
+ return { decision: "deny", reason: nobody(call.name) };
98
156
  }
99
- const renderers = ctx.service("renderers@1");
100
- // auto 模式的审查用当前配置的模型;没有 models@1(模型插件被停用)或者配置里关掉时不做审查
101
- const models = ctx.service("models@1");
102
- const reviewing = models !== undefined && ctx.config.review !== false;
103
- /** 最近一次请求里的消息:auto 模式的审查从中取用户最近的请求 */
104
- const recent = { messages: [] };
105
- if (reviewing) {
106
- ctx.kernel.hook({
107
- kind: "transform",
108
- point: "context.build",
109
- fn: (req) => {
110
- recent.messages = req.messages;
111
- return req;
112
- },
113
- });
157
+ seen.set(call.toolUseId, { call, mine: call, ...why ? { why } : {} });
158
+ return { decision: "ask" };
159
+ }
160
+ });
161
+ const decide = async (asked, signal) => {
162
+ const { call } = asked;
163
+ if (asked.mine) {
164
+ const again = rules.decide(asked.mine, { mode, rules: saved() });
165
+ if (again.decision === "allow")
166
+ return { approved: true, answer: "allow", by: "rule" };
167
+ if (again.decision === "deny")
168
+ return { approved: false, answer: "deny", by: "rule", reason: again.reason };
169
+ }
170
+ if (!canAsk())
171
+ return { approved: false, answer: "deny", by: "nobody", reason: nobody(call.name) };
172
+ const allow = rules.rulesFor(call);
173
+ const described = allow.map(describeRule).join(", ");
174
+ const covers = asked.mine ? `"Always allow" covers: ${allow.length === 1 && allow[0].command !== undefined ? `${allow[0].tool}, this exact command only` : described}
175
+
176
+ ` : "";
177
+ const shown = [covers, await preview(renderers, call) ?? detail(call)];
178
+ const expired = new AbortController;
179
+ const timer = setTimeout(() => expired.abort(), askTimeoutMs);
180
+ let got;
181
+ try {
182
+ got = await ask(ui, {
183
+ title: `Allow ${call.name}?`,
184
+ detail: asked.why ? [asked.why, `
185
+
186
+ `, shown] : shown,
187
+ options: [
188
+ { label: "Allow once", value: "once" },
189
+ ...asked.mine ? [
190
+ { label: "Always allow in this session", value: "always" },
191
+ { label: "Always allow in this directory, in every session", value: "forever" }
192
+ ] : [],
193
+ { label: "Deny", value: "deny" }
194
+ ]
195
+ }, AbortSignal.any([signal, expired.signal, ctx.signal]));
196
+ } finally {
197
+ clearTimeout(timer);
198
+ }
199
+ if (expired.signal.aborted) {
200
+ return { approved: false, answer: "deny", by: "timeout", reason: `Nobody answered the approval request for ${call.name} in time. Do not retry it; tell the user what you wanted to do.` };
201
+ }
202
+ if (got?.cancelled)
203
+ return { approved: false, answer: "deny", by: "terminal", stop: true };
204
+ if (got?.answer === "always" && asked.mine) {
205
+ added.push(...allow);
206
+ return { approved: true, answer: "always", by: got.by };
207
+ }
208
+ if (got?.answer === "forever" && asked.mine) {
209
+ forever.push(...allow);
210
+ try {
211
+ await addForever(foreverFile, ctx.cwd, allow);
212
+ ui?.notify(`${described} is now always allowed in ${ctx.cwd}. To ask again, remove it from ${foreverFile}`, "info");
213
+ } catch (e) {
214
+ ui?.notify(`could not save the rule to ${foreverFile} (${e instanceof Error ? e.message : String(e)}); it only applies to this session`, "warning");
114
215
  }
115
- const review = reviewing ? reviewer({ models: models, cwd: ctx.cwd, writeRoots: () => writeRoots, messages: () => recent.messages }) : undefined;
116
- /** 本会话里审查过一次、放行了的调用 */
117
- const reviewedCalls = new Set();
118
- let warned = false;
119
- /** 本进程里刚选的"总是允许":记进日志之前(要等看到那条 approval 输入)就要生效 */
120
- const added = [];
121
- /** 一次只问一个问题;排在后面的问之前重新判断,前面刚选的"总是允许"可能已经覆盖它 */
122
- let asking = Promise.resolve();
123
- /** 日志里记下的"总是允许"规则,每次调用工具前取一次:子 Agent 在工具执行期间经 allows 用它 */
124
- let logged = [];
125
- const merged = (from) => [...from, ...added.filter((r) => !from.some((l) => JSON.stringify(l) === JSON.stringify(r)))];
126
- /** "在这个目录里总是允许"的规则:会话打开时从文件读,本会话里新选的也加进来 */
127
- const foreverFile = path.join(ctx.home, "state", "approvals.json");
128
- const forever = (await readForever(foreverFile))[ctx.cwd] ?? [];
129
- const saved = () => [...forever, ...merged(logged)];
130
- /** 这一轮里关卡看过、还没有决定的调用 */
131
- const seen = new Map();
132
- /** 已经交给会话的回答:在日志里看到那条 approval 输入时记一条 answered 事件 */
133
- const answered = new Map();
134
- /** 这一轮里已经在问、或者问过的调用 */
135
- const handled = new Set();
136
- /** 这一轮结束(包括被中断)时中止还开着的问题 */
137
- let turn = new AbortController();
138
- const canAsk = () => ui?.interactive === true || approvers.size > 0;
139
- const nobody = (name) => `${name} needs the user's approval, but nobody can approve it in this non-interactive run. Do not retry it; tell the user what you wanted to do.`;
140
- const id = ctx.session.id;
141
- const check = (call) => rules.decide(call, { mode: mode === "yolo" && call.tool.effect === "read" ? "yolo" : "readonly", rules: [...forever, ...logged, ...added] }).decision === "allow";
142
- sessionChecks.set(id, check);
143
- await ctx.effect(() => () => {
144
- if (sessionChecks.get(id) === check)
145
- sessionChecks.delete(id);
146
- });
147
- ctx.kernel.hook({
148
- kind: "transform",
149
- point: "tool.before",
150
- fn: (call, hook) => {
151
- logged = hook.derived[RULES_KEY] ?? [];
152
- return { ...call, input: rules.absolutePath(call.input) };
153
- },
154
- });
155
- ctx.kernel.hook({
156
- kind: "gate",
157
- point: "tool.gate",
158
- timeoutMs: GATE_TIMEOUT_MS,
159
- fn: async (call, hook) => {
160
- seen.set(call.toolUseId, { call });
161
- const result = rules.decide(call, { mode, rules: saved() });
162
- if (result.decision !== "ask")
163
- return result;
164
- // auto 模式:规则判断不了、本来要问的调用先让模型审一次。审查只能放行或转给用户,不会替用户拒绝
165
- let why;
166
- if (review && mode === "auto") {
167
- const key = reviewedKey(call);
168
- if (key !== undefined && reviewedCalls.has(key))
169
- return { decision: "allow", reason: "This exact call was already approved in this session." };
170
- const verdict = await review(call, hook.signal);
171
- // 审查调用不经过 model.responded,用量只能记在这里,界面据此计入会话用量
172
- if (verdict.usage)
173
- await hook.emit("reviewed", { toolUseId: call.toolUseId, usage: verdict.usage });
174
- if (verdict.decision === "allow") {
175
- if (key !== undefined)
176
- reviewedCalls.add(key);
177
- return { decision: "allow", reason: verdict.reason };
178
- }
179
- why = verdict.reason;
180
- }
181
- if (!canAsk()) {
182
- if (!warned) {
183
- warned = true;
184
- ui?.notify(`${call.name} needs approval, but this jade cannot ask. To let it make changes in the working directory, ` +
185
- `set {"jade/approval": {"mode": "auto"}} in ${ctx.home}/config.json`, "warning");
186
- }
187
- return { decision: "deny", reason: nobody(call.name) };
188
- }
189
- seen.set(call.toolUseId, { call, mine: call, ...(why ? { why } : {}) });
190
- return { decision: "ask" };
191
- },
192
- });
193
- /** 问用户(或按刚加的规则直接决定),返回交给内核的回答 */
194
- const decide = async (asked, signal) => {
195
- const { call } = asked;
196
- if (asked.mine) {
197
- const again = rules.decide(asked.mine, { mode, rules: saved() });
198
- if (again.decision === "allow")
199
- return { approved: true, answer: "allow", by: "rule" };
200
- if (again.decision === "deny")
201
- return { approved: false, answer: "deny", by: "rule", reason: again.reason };
202
- }
203
- if (!canAsk())
204
- return { approved: false, answer: "deny", by: "nobody", reason: nobody(call.name) };
205
- const allow = rules.rulesFor(call);
206
- const described = allow.map(describeRule).join(", ");
207
- // "总是允许"的范围只在正文里写一次:写进选项里时,长命令会把两个选项句尾的区别(本会话 / 这个目录)挤出屏幕
208
- const covers = asked.mine ? `"Always allow" covers: ${allow.length === 1 && allow[0].command !== undefined ? `${allow[0].tool}, this exact command only` : described}\n\n` : "";
209
- const shown = covers + ((await preview(renderers, call)) ?? detail(call));
210
- const expired = new AbortController();
211
- const timer = setTimeout(() => expired.abort(), askTimeoutMs);
212
- let got;
213
- try {
214
- got = await ask(ui, {
215
- title: `Allow ${call.name}?`,
216
- // 审查转给用户的:先说为什么
217
- detail: asked.why ? `${asked.why}\n\n${shown}` : shown,
218
- options: [
219
- { label: "Allow once", value: "once" },
220
- // 别的插件要问的调用不能"总是允许":这里的规则管不到它的关卡
221
- ...(asked.mine
222
- ? [
223
- { label: "Always allow in this session", value: "always" },
224
- { label: "Always allow in this directory, in every session", value: "forever" },
225
- ]
226
- : []),
227
- { label: "Deny", value: "deny" },
228
- ],
229
- }, AbortSignal.any([signal, expired.signal, ctx.signal]));
230
- }
231
- finally {
232
- clearTimeout(timer);
233
- }
234
- if (expired.signal.aborted) {
235
- return { approved: false, answer: "deny", by: "timeout", reason: `Nobody answered the approval request for ${call.name} in time. Do not retry it; tell the user what you wanted to do.` };
236
- }
237
- if (got?.answer === "always" && asked.mine) {
238
- added.push(...allow);
239
- return { approved: true, answer: "always", by: got.by };
240
- }
241
- if (got?.answer === "forever" && asked.mine) {
242
- forever.push(...allow);
243
- try {
244
- await addForever(foreverFile, ctx.cwd, allow);
245
- ui?.notify(`${described} is now always allowed in ${ctx.cwd}. To ask again, remove it from ${foreverFile}`, "info");
246
- }
247
- catch (e) {
248
- ui?.notify(`could not save the rule to ${foreverFile} (${e instanceof Error ? e.message : String(e)}); it only applies to this session`, "warning");
249
- }
250
- return { approved: true, answer: "forever", by: got.by };
251
- }
252
- if (got !== undefined && got.answer !== "deny")
253
- return { approved: true, answer: "once", by: got.by };
254
- if (got?.said)
255
- return { approved: false, answer: "deny", by: got.by, reason: `The user denied this tool call and said: ${got.said}` };
256
- return { approved: false, answer: "deny", by: got?.by ?? "nobody", reason: "The user denied this tool call. Do not retry it unchanged: adjust, or ask what to do instead." };
257
- };
258
- /** 一个要问的调用:得出回答,交给会话。出错也要回答(拒绝),否则这一轮一直等着 */
259
- const settle = async (asked, signal) => {
260
- const toolUseId = asked.call.toolUseId;
261
- let verdict;
262
- try {
263
- verdict = await decide(asked, signal);
264
- }
265
- catch (e) {
266
- verdict = { approved: false, answer: "deny", by: "error", reason: `Asking for approval failed: ${e instanceof Error ? e.message : String(e)}` };
267
- }
268
- // 这一轮已经结束(被中断):回答作废
269
- if (signal.aborted)
270
- return;
271
- answered.set(toolUseId, { answer: verdict.answer, by: verdict.by });
272
- // 不等它:它要到内核再次停下才 resolve,后面排着的问题可能就是内核在等的
273
- void Promise.resolve()
274
- .then(() => ctx.session.send({ kind: "approval", toolUseId, approved: verdict.approved, ...(verdict.reason ? { reason: verdict.reason } : {}) }))
275
- .catch(() => void answered.delete(toolUseId));
276
- };
277
- ctx.kernel.hook({
278
- kind: "observe",
279
- point: "event",
280
- fn: async (e, hook) => {
281
- if (e.type === "tool.decided") {
282
- const d = e.data;
283
- const asked = seen.get(d.toolUseId);
284
- seen.delete(d.toolUseId);
285
- if (d.decision !== "ask" || !asked)
286
- return;
287
- // 不在这里等回答:observe 要马上返回,内核才能停下来等
288
- handled.add(d.toolUseId);
289
- const signal = turn.signal;
290
- asking = asking.then(() => settle(asked, signal));
291
- }
292
- else if (e.type === "input.received") {
293
- const d = e.data;
294
- if (d.kind !== "approval")
295
- return;
296
- const a = answered.get(d.toolUseId);
297
- if (!a)
298
- return;
299
- answered.delete(d.toolUseId);
300
- // 内核只记同意或拒绝:选了什么、谁回答的(终端、哪个渠道、规则、超时)记在这里
301
- await hook.emit("answered", { toolUseId: d.toolUseId, ...a });
302
- if (a.answer === "always")
303
- await hook.record(RULES_KEY, merged(hook.derived[RULES_KEY] ?? []));
304
- }
305
- else if (e.type === "turn.ended") {
306
- turn.abort(new Error("the turn ended"));
307
- turn = new AbortController();
308
- seen.clear();
309
- answered.clear();
310
- handled.clear();
311
- }
312
- },
313
- });
314
- // 恢复一个上次停在等审批的会话(进程被杀、崩溃):那些调用的关卡是上一个进程跑的,这里没见过。
315
- // 内核恢复时再发一次 awaiting,据此重新问。只知道调用的名字和参数(工具的声明只有关卡拿得到),
316
- // 所以当作别的关卡要问的:只有"允许一次"和"拒绝",不重新套规则
317
- ctx.session.subscribe((n) => {
318
- if (n.type !== "awaiting")
319
- return;
320
- const waiting = n.toolUseIds.filter((t) => !handled.has(t) && !seen.has(t));
321
- if (waiting.length === 0)
322
- return;
323
- const batch = ctx.session.state().batch;
324
- const signal = turn.signal;
325
- for (const toolUseId of waiting) {
326
- const c = batch.find((x) => x.toolUseId === toolUseId && x.decision === "ask");
327
- if (!c)
328
- continue;
329
- handled.add(toolUseId);
330
- asking = asking.then(() => settle({ call: { toolUseId, name: c.name, input: c.input } }, signal));
331
- }
332
- });
333
- },
216
+ return { approved: true, answer: "forever", by: got.by };
217
+ }
218
+ if (got !== undefined && got.answer !== "deny")
219
+ return { approved: true, answer: "once", by: got.by };
220
+ if (got?.said)
221
+ return { approved: false, answer: "deny", by: got.by, reason: `The user denied this tool call and said: ${got.said}` };
222
+ return { approved: false, answer: "deny", by: got?.by ?? "nobody", reason: "The user denied this tool call. Do not retry it unchanged: adjust, or ask what to do instead." };
223
+ };
224
+ const settle = async (asked, signal) => {
225
+ const toolUseId = asked.call.toolUseId;
226
+ let verdict;
227
+ try {
228
+ verdict = await decide(asked, signal);
229
+ } catch (e) {
230
+ verdict = { approved: false, answer: "deny", by: "error", reason: `Asking for approval failed: ${e instanceof Error ? e.message : String(e)}` };
231
+ }
232
+ if (signal.aborted)
233
+ return;
234
+ if (verdict.stop)
235
+ return ctx.session.abort("the user cancelled the approval request");
236
+ answered.set(toolUseId, { answer: verdict.answer, by: verdict.by });
237
+ Promise.resolve().then(() => ctx.session.send({ kind: "approval", toolUseId, approved: verdict.approved, ...verdict.reason ? { reason: verdict.reason } : {} })).catch(() => void answered.delete(toolUseId));
238
+ };
239
+ ctx.kernel.hook({
240
+ kind: "observe",
241
+ point: "event",
242
+ fn: async (e, hook) => {
243
+ if (e.type === "tool.decided") {
244
+ const d = e.data;
245
+ const asked = seen.get(d.toolUseId);
246
+ seen.delete(d.toolUseId);
247
+ if (d.decision !== "ask" || !asked)
248
+ return;
249
+ handled.add(d.toolUseId);
250
+ const signal = turn.signal;
251
+ asking = asking.then(() => settle(asked, signal));
252
+ } else if (e.type === "input.received") {
253
+ const d = e.data;
254
+ if (d.kind !== "approval")
255
+ return;
256
+ const a = answered.get(d.toolUseId);
257
+ if (!a)
258
+ return;
259
+ answered.delete(d.toolUseId);
260
+ await hook.emit("answered", { toolUseId: d.toolUseId, ...a });
261
+ if (a.answer === "always")
262
+ await hook.record(RULES_KEY, merged(hook.derived[RULES_KEY] ?? []));
263
+ } else if (e.type === "turn.ended") {
264
+ turn.abort(new Error("the turn ended"));
265
+ turn = new AbortController;
266
+ seen.clear();
267
+ answered.clear();
268
+ handled.clear();
269
+ }
270
+ }
271
+ });
272
+ ctx.session.subscribe((n) => {
273
+ if (n.type !== "awaiting")
274
+ return;
275
+ const waiting = n.toolUseIds.filter((t) => !handled.has(t) && !seen.has(t));
276
+ if (waiting.length === 0)
277
+ return;
278
+ const batch = ctx.session.state().batch;
279
+ const signal = turn.signal;
280
+ for (const toolUseId of waiting) {
281
+ const c = batch.find((x) => x.toolUseId === toolUseId && x.decision === "ask");
282
+ if (!c)
283
+ continue;
284
+ handled.add(toolUseId);
285
+ asking = asking.then(() => settle({ call: { toolUseId, name: c.name, input: c.input } }, signal));
286
+ }
287
+ });
288
+ }
334
289
  });
335
- /** allowRead、allowWrite:把目录登记进 roots,调用方的作用域关闭时撤销 */
336
290
  function allow(caller, name, roots, dir) {
337
- if (caller.layer === "project")
338
- throw new Error(`approval.${name}: project plugins cannot widen what runs without asking`);
339
- if (typeof dir !== "string" || !path.isAbsolute(dir))
340
- throw new Error(`approval.${name}: dir must be an absolute path`);
341
- const root = path.resolve(dir);
342
- roots.push(root);
343
- const remove = () => {
344
- const i = roots.indexOf(root);
345
- if (i !== -1)
346
- roots.splice(i, 1);
347
- };
348
- caller.onDispose(remove);
349
- return remove;
291
+ if (caller.layer === "project")
292
+ throw new Error(`approval.${name}: project plugins cannot widen what runs without asking`);
293
+ if (typeof dir !== "string" || !path.isAbsolute(dir))
294
+ throw new Error(`approval.${name}: dir must be an absolute path`);
295
+ const root = path.resolve(dir);
296
+ roots.push(root);
297
+ const remove = () => {
298
+ const i = roots.indexOf(root);
299
+ if (i !== -1)
300
+ roots.splice(i, 1);
301
+ };
302
+ caller.onDispose(remove);
303
+ return remove;
350
304
  }
351
- /**
352
- * 把问题同时交给终端(能提问时)和所有审批渠道,返回先到的回答和回答的人("terminal" 或渠道的插件 id),然后中止其余的。
353
- * 终端里取消(undefined)算拒绝;渠道返回 undefined、不认识的值或出错算它不回答。都不回答时返回 undefined(拒绝)
354
- */
355
305
  async function ask(ui, request, signal) {
356
- const done = new AbortController();
357
- const stop = () => done.abort(signal.reason);
358
- signal.addEventListener("abort", stop, { once: true });
359
- try {
360
- return await new Promise((resolve, reject) => {
361
- const channels = [];
362
- if (ui?.interactive) {
363
- // 终端里多一项:拒绝并说明。选了它再问一句话,取消或什么都没写就是普通的拒绝
364
- const options = [...request.options, { label: "Deny, and say what to do instead", value: EXPLAIN }];
365
- channels.push(ui.select({ ...request, options }, done.signal).then(async (a) => {
366
- if (a !== EXPLAIN)
367
- return { answer: a !== undefined && ANSWERS.includes(a) ? a : "deny", by: "terminal" };
368
- const said = (await ui.input({ title: "What should the agent do instead?" }, done.signal))?.trim();
369
- return { answer: "deny", by: "terminal", ...(said ? { said } : {}) };
370
- }));
371
- }
372
- for (const [approver, by] of approvers) {
373
- channels.push(Promise.resolve()
374
- .then(() => approver(request, done.signal))
375
- .then((a) => (typeof a === "string" && ANSWERS.includes(a) ? { answer: a, by } : NONE), () => NONE));
376
- }
377
- let pending = channels.length;
378
- if (pending === 0)
379
- return resolve(undefined);
380
- for (const c of channels) {
381
- c.then((a) => {
382
- if (a !== NONE)
383
- resolve(a);
384
- else if (--pending === 0)
385
- resolve(undefined);
386
- }, reject);
387
- }
388
- });
389
- }
390
- finally {
391
- signal.removeEventListener("abort", stop);
392
- done.abort(new Error("answered"));
393
- }
306
+ const done = new AbortController;
307
+ const stop = () => done.abort(signal.reason);
308
+ signal.addEventListener("abort", stop, { once: true });
309
+ try {
310
+ return await new Promise((resolve, reject) => {
311
+ const channels = [];
312
+ if (ui?.interactive) {
313
+ const options = [...request.options, { label: "Deny, and say what to do instead", value: EXPLAIN }];
314
+ channels.push(ui.select({ ...request, options }, done.signal).then(async (a) => {
315
+ if (a === undefined && !done.signal.aborted)
316
+ return { answer: "deny", by: "terminal", cancelled: true };
317
+ if (a !== EXPLAIN)
318
+ return { answer: a !== undefined && ANSWERS.includes(a) ? a : "deny", by: "terminal" };
319
+ const said = (await ui.input({ title: "What should the agent do instead?" }, done.signal))?.trim();
320
+ return { answer: "deny", by: "terminal", ...said ? { said } : {} };
321
+ }));
322
+ }
323
+ for (const [approver, by] of approvers) {
324
+ channels.push(Promise.resolve().then(() => approver(request, done.signal)).then((a) => typeof a === "string" && ANSWERS.includes(a) ? { answer: a, by } : NONE, () => NONE));
325
+ }
326
+ let pending = channels.length;
327
+ if (pending === 0)
328
+ return resolve(undefined);
329
+ for (const c of channels) {
330
+ c.then((a) => {
331
+ if (a !== NONE)
332
+ resolve(a);
333
+ else if (--pending === 0)
334
+ resolve(undefined);
335
+ }, reject);
336
+ }
337
+ });
338
+ } finally {
339
+ signal.removeEventListener("abort", stop);
340
+ done.abort(new Error("answered"));
341
+ }
394
342
  }
395
343
  const NONE = Symbol("no answer");
396
- /** approvals.json:工作目录 → 在这个目录里总是允许的规则。读不了或格式不对时当作没有 */
397
344
  async function readForever(file) {
398
- try {
399
- const data = JSON.parse(await readFile(file, "utf8"));
400
- if (!data || typeof data !== "object" || Array.isArray(data))
401
- return {};
402
- const out = {};
403
- for (const [dir, rules] of Object.entries(data)) {
404
- if (Array.isArray(rules))
405
- out[dir] = rules.filter((r) => !!r && typeof r === "object" && typeof r.tool === "string");
406
- }
407
- return out;
408
- }
409
- catch {
410
- return {};
345
+ try {
346
+ const data = JSON.parse(await readFile(file, "utf8"));
347
+ if (!data || typeof data !== "object" || Array.isArray(data))
348
+ return {};
349
+ const out = {};
350
+ for (const [dir, rules] of Object.entries(data)) {
351
+ if (Array.isArray(rules))
352
+ out[dir] = rules.filter((r) => !!r && typeof r === "object" && typeof r.tool === "string");
411
353
  }
354
+ return out;
355
+ } catch {
356
+ return {};
357
+ }
412
358
  }
413
359
  async function addForever(file, cwd, add) {
414
- const all = await readForever(file);
415
- const rules = all[cwd] ?? [];
416
- for (const rule of add)
417
- if (!rules.some((r) => JSON.stringify(r) === JSON.stringify(rule)))
418
- rules.push(rule);
419
- all[cwd] = rules;
420
- await mkdir(path.dirname(file), { recursive: true });
421
- await writeFile(file, `${JSON.stringify(all, null, 2)}\n`);
360
+ const all = await readForever(file);
361
+ const rules = all[cwd] ?? [];
362
+ for (const rule of add)
363
+ if (!rules.some((r) => JSON.stringify(r) === JSON.stringify(rule)))
364
+ rules.push(rule);
365
+ all[cwd] = rules;
366
+ await mkdir(path.dirname(file), { recursive: true });
367
+ await writeFile(file, `${JSON.stringify(all, null, 2)}
368
+ `);
422
369
  }
423
- /**
424
- * 工具自己登记的审批预览(例如文件修改的 diff)。没有登记、返回的不是文字、或者出错时返回 undefined,
425
- * 用下面的 detail:预览是别的插件的代码,它坏了不能让审批卡住或失败
426
- */
427
370
  async function preview(renderers, call) {
428
- let timer;
429
- try {
430
- // 预览可能读文件、算 diff;一直不返回时也要能问用户
431
- const late = new Promise((resolve) => {
432
- timer = setTimeout(() => resolve(undefined), PREVIEW_TIMEOUT_MS);
433
- });
434
- const text = await Promise.race([Promise.resolve(renderers?.forTool(call.name)?.renderer.preview?.(call.input)), late]);
435
- return typeof text === "string" ? text : undefined;
436
- }
437
- catch {
438
- return undefined;
439
- }
440
- finally {
441
- clearTimeout(timer);
442
- }
371
+ let timer;
372
+ try {
373
+ const late = new Promise((resolve) => {
374
+ timer = setTimeout(() => resolve(undefined), PREVIEW_TIMEOUT_MS);
375
+ });
376
+ const text = await Promise.race([Promise.resolve(renderers?.forTool(call.name)?.renderer.preview?.(call.input)), late]);
377
+ return typeof text === "string" || typeof text === "object" && text !== null ? text : undefined;
378
+ } catch {
379
+ return;
380
+ } finally {
381
+ clearTimeout(timer);
382
+ }
443
383
  }
444
- /** 给用户看的调用内容:命令、路径和要写的内容,太长的截断 */
445
384
  function detail(call) {
446
- const input = call.input;
447
- let text;
448
- if (typeof input?.command === "string")
449
- text = input.command;
450
- else if (typeof input?.path === "string" && typeof input.content === "string")
451
- text = `${input.path}\n\n${input.content}`;
452
- else if (typeof input?.path === "string" && typeof input.old_string === "string")
453
- text = `${input.path}\n\n- ${input.old_string}\n+ ${String(input.new_string)}`;
454
- else
455
- text = JSON.stringify(input, null, 2);
456
- return text.length > MAX_DETAIL_CHARS ? `${text.slice(0, MAX_DETAIL_CHARS)}\n… (${text.length - MAX_DETAIL_CHARS} more characters)` : text;
385
+ const input = call.input;
386
+ let text;
387
+ if (typeof input?.command === "string")
388
+ text = input.command;
389
+ else if (typeof input?.path === "string" && typeof input.content === "string")
390
+ text = `${input.path}
391
+
392
+ ${input.content}`;
393
+ else if (typeof input?.path === "string" && typeof input.old_string === "string")
394
+ text = `${input.path}
395
+
396
+ - ${input.old_string}
397
+ + ${String(input.new_string)}`;
398
+ else
399
+ text = JSON.stringify(input, null, 2);
400
+ return text.length > MAX_DETAIL_CHARS ? `${text.slice(0, MAX_DETAIL_CHARS)}
401
+ … (${text.length - MAX_DETAIL_CHARS} more characters)` : text;
457
402
  }