@uncarved/jade 0.2.1 → 0.3.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 (227) hide show
  1. package/README.md +65 -2
  2. package/assets/logo.svg +1 -0
  3. package/bin/jade.js +4 -0
  4. package/dist/api.d.ts +5 -250
  5. package/dist/api.js +5 -7
  6. package/dist/api.js.map +1 -1
  7. package/dist/fetch.d.ts +8 -0
  8. package/dist/fetch.js +19 -17
  9. package/dist/fetch.js.map +1 -1
  10. package/dist/host.d.ts +12 -1
  11. package/dist/host.js +49 -1
  12. package/dist/host.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/main.js +26 -4
  17. package/dist/main.js.map +1 -1
  18. package/dist/remote.js +4 -0
  19. package/dist/remote.js.map +1 -1
  20. package/dist/session.d.ts +2 -0
  21. package/dist/session.js +133 -13
  22. package/dist/session.js.map +1 -1
  23. package/dist/source.d.ts +2 -10
  24. package/dist/source.js.map +1 -1
  25. package/dist/update.d.ts +8 -20
  26. package/dist/update.js +12 -1
  27. package/dist/update.js.map +1 -1
  28. package/package.json +4 -2
  29. package/plugins/approval/index.ts +236 -85
  30. package/plugins/approval/plugin.json +1 -1
  31. package/plugins/approval/policy.ts +36 -17
  32. package/plugins/approval/review.ts +1 -1
  33. package/plugins/ask/index.ts +2 -2
  34. package/plugins/budget/index.ts +1 -1
  35. package/plugins/checks/checks.ts +3 -2
  36. package/plugins/checks/index.ts +2 -5
  37. package/plugins/commands/index.ts +2 -44
  38. package/plugins/compact/compact.ts +8 -3
  39. package/plugins/compact/index.ts +13 -16
  40. package/plugins/continue/index.ts +1 -1
  41. package/plugins/cost/index.ts +143 -0
  42. package/plugins/cost/plugin.json +13 -0
  43. package/plugins/custom-commands/index.ts +85 -0
  44. package/plugins/custom-commands/plugin.json +8 -0
  45. package/plugins/editor/index.ts +88 -0
  46. package/plugins/editor/plugin.json +17 -0
  47. package/plugins/fs/fs.ts +33 -6
  48. package/plugins/fs/grep.ts +19 -7
  49. package/plugins/fs/index.ts +6 -7
  50. package/plugins/fs/plugin.json +1 -1
  51. package/plugins/fs/renderers.ts +1 -1
  52. package/plugins/hooks/index.ts +152 -0
  53. package/plugins/hooks/plugin.json +14 -0
  54. package/plugins/keys/index.ts +2 -18
  55. package/plugins/mcp/index.ts +43 -15
  56. package/plugins/mcp/install.ts +139 -0
  57. package/plugins/mcp/mcp.ts +2 -1
  58. package/plugins/mcp/plugin.json +1 -1
  59. package/plugins/mcp/project.ts +37 -1
  60. package/plugins/memory/index.ts +4 -9
  61. package/plugins/memory/plugin.json +1 -1
  62. package/plugins/mentions/index.ts +2 -2
  63. package/plugins/models/configure.ts +258 -150
  64. package/plugins/models/context.ts +2 -2
  65. package/plugins/models/index.ts +39 -45
  66. package/plugins/models/plugin.json +1 -1
  67. package/plugins/models/provider.ts +34 -5
  68. package/plugins/models/saved.ts +8 -4
  69. package/plugins/modes/index.ts +2 -17
  70. package/plugins/plugins/index.ts +2 -2
  71. package/plugins/print/index.ts +36 -6
  72. package/plugins/print/plugin.json +1 -0
  73. package/plugins/prompts/index.ts +22 -14
  74. package/plugins/{memory → prompts}/notes.ts +21 -9
  75. package/plugins/prompts/plugin.json +8 -2
  76. package/plugins/prompts/prompts.ts +5 -4
  77. package/plugins/renderers/index.ts +2 -43
  78. package/plugins/repeats/index.ts +32 -2
  79. package/plugins/schedule/index.ts +2 -2
  80. package/plugins/scratch/index.ts +2 -3
  81. package/plugins/screenshot/browser.ts +221 -0
  82. package/plugins/screenshot/index.ts +29 -15
  83. package/plugins/screenshot/plugin.json +1 -1
  84. package/plugins/screenshot/tool.ts +27 -51
  85. package/plugins/sessions/index.ts +2 -17
  86. package/plugins/shell/index.ts +115 -7
  87. package/plugins/shell/plugin.json +3 -1
  88. package/plugins/shell/renderers.ts +1 -1
  89. package/plugins/shell/service.ts +2 -13
  90. package/plugins/shell/shell.ts +119 -47
  91. package/plugins/skills/index.ts +172 -37
  92. package/plugins/skills/install.ts +212 -0
  93. package/plugins/skills/plugin.json +3 -2
  94. package/plugins/skills/project.ts +38 -1
  95. package/plugins/skills/skills.ts +28 -9
  96. package/plugins/steer/index.ts +142 -0
  97. package/plugins/steer/plugin.json +8 -0
  98. package/plugins/suggest/index.ts +16 -11
  99. package/plugins/suggest/plugin.json +1 -1
  100. package/plugins/task/index.ts +18 -57
  101. package/plugins/task/plugin.json +9 -3
  102. package/plugins/task/subagent.ts +25 -7
  103. package/plugins/todo/index.ts +2 -2
  104. package/plugins/tools/index.ts +50 -0
  105. package/plugins/tools/plugin.json +7 -0
  106. package/plugins/tui/editor.ts +10 -2
  107. package/plugins/tui/frontend.ts +129 -23
  108. package/plugins/tui/index.ts +3 -8
  109. package/plugins/tui/markdown.ts +51 -6
  110. package/plugins/tui/mascot.ts +506 -0
  111. package/plugins/tui/plugin.json +2 -2
  112. package/plugins/tui/screen.ts +6 -0
  113. package/plugins/tui/transcript.ts +17 -2
  114. package/plugins/tui/tui.ts +344 -97
  115. package/plugins/undo/checkpoint.ts +2 -2
  116. package/plugins/undo/index.ts +84 -26
  117. package/plugins/undo/plugin.json +8 -2
  118. package/plugins/undo/snapshot.ts +129 -0
  119. package/plugins/update/index.ts +11 -15
  120. package/plugins/update/plugin.json +2 -1
  121. package/plugins/web/index.ts +8 -11
  122. package/plugins/web/plugin.json +1 -1
  123. package/plugins/web/renderers.ts +1 -1
  124. package/plugins-dist/approval/index.js +221 -51
  125. package/plugins-dist/approval/plugin.json +1 -1
  126. package/plugins-dist/approval/policy.js +30 -15
  127. package/plugins-dist/ask/index.js +1 -1
  128. package/plugins-dist/budget/index.js +1 -1
  129. package/plugins-dist/checks/checks.js +2 -1
  130. package/plugins-dist/checks/index.js +1 -1
  131. package/plugins-dist/commands/index.js +1 -1
  132. package/plugins-dist/compact/compact.js +6 -1
  133. package/plugins-dist/compact/index.js +12 -8
  134. package/plugins-dist/continue/index.js +1 -1
  135. package/plugins-dist/cost/index.js +135 -0
  136. package/plugins-dist/cost/plugin.json +16 -0
  137. package/plugins-dist/custom-commands/index.js +86 -0
  138. package/plugins-dist/custom-commands/plugin.json +12 -0
  139. package/plugins-dist/editor/index.js +89 -0
  140. package/plugins-dist/editor/plugin.json +21 -0
  141. package/plugins-dist/fs/fs.js +34 -6
  142. package/plugins-dist/fs/grep.js +17 -6
  143. package/plugins-dist/fs/index.js +6 -6
  144. package/plugins-dist/fs/plugin.json +1 -1
  145. package/plugins-dist/hooks/index.js +145 -0
  146. package/plugins-dist/hooks/plugin.json +19 -0
  147. package/plugins-dist/keys/index.js +1 -1
  148. package/plugins-dist/mcp/index.js +45 -13
  149. package/plugins-dist/mcp/install.js +160 -0
  150. package/plugins-dist/mcp/mcp.js +2 -1
  151. package/plugins-dist/mcp/plugin.json +2 -1
  152. package/plugins-dist/mcp/project.js +42 -1
  153. package/plugins-dist/memory/index.js +3 -5
  154. package/plugins-dist/memory/plugin.json +1 -1
  155. package/plugins-dist/mentions/index.js +1 -1
  156. package/plugins-dist/models/configure.js +252 -151
  157. package/plugins-dist/models/context.js +2 -2
  158. package/plugins-dist/models/index.js +41 -17
  159. package/plugins-dist/models/plugin.json +1 -1
  160. package/plugins-dist/models/provider.js +17 -3
  161. package/plugins-dist/models/saved.js +9 -4
  162. package/plugins-dist/modes/index.js +1 -1
  163. package/plugins-dist/plugins/index.js +1 -1
  164. package/plugins-dist/print/index.js +37 -3
  165. package/plugins-dist/print/plugin.json +3 -0
  166. package/plugins-dist/prompts/index.js +22 -3
  167. package/plugins-dist/{memory → prompts}/notes.js +10 -7
  168. package/plugins-dist/prompts/plugin.json +8 -2
  169. package/plugins-dist/prompts/prompts.js +5 -4
  170. package/plugins-dist/renderers/index.js +1 -1
  171. package/plugins-dist/repeats/index.js +28 -2
  172. package/plugins-dist/schedule/index.js +1 -1
  173. package/plugins-dist/scratch/index.js +1 -1
  174. package/plugins-dist/screenshot/browser.js +187 -0
  175. package/plugins-dist/screenshot/index.js +28 -13
  176. package/plugins-dist/screenshot/plugin.json +1 -1
  177. package/plugins-dist/screenshot/tool.js +27 -49
  178. package/plugins-dist/sessions/index.js +1 -1
  179. package/plugins-dist/shell/index.js +119 -4
  180. package/plugins-dist/shell/plugin.json +3 -1
  181. package/plugins-dist/shell/shell.js +106 -36
  182. package/plugins-dist/skills/index.js +184 -35
  183. package/plugins-dist/skills/install.js +178 -0
  184. package/plugins-dist/skills/plugin.json +6 -2
  185. package/plugins-dist/skills/project.js +43 -1
  186. package/plugins-dist/skills/skills.js +27 -10
  187. package/plugins-dist/steer/index.js +135 -0
  188. package/plugins-dist/steer/plugin.json +12 -0
  189. package/plugins-dist/suggest/index.js +15 -9
  190. package/plugins-dist/suggest/plugin.json +1 -1
  191. package/plugins-dist/task/index.js +17 -46
  192. package/plugins-dist/task/plugin.json +11 -5
  193. package/plugins-dist/task/subagent.js +21 -6
  194. package/plugins-dist/todo/index.js +1 -1
  195. package/plugins-dist/tools/index.js +49 -0
  196. package/plugins-dist/tools/plugin.json +9 -0
  197. package/plugins-dist/tui/editor.js +7 -2
  198. package/plugins-dist/tui/frontend.js +134 -15
  199. package/plugins-dist/tui/index.js +2 -1
  200. package/plugins-dist/tui/markdown.js +48 -6
  201. package/plugins-dist/tui/mascot.js +441 -0
  202. package/plugins-dist/tui/plugin.json +3 -2
  203. package/plugins-dist/tui/screen.js +2 -0
  204. package/plugins-dist/tui/transcript.js +16 -1
  205. package/plugins-dist/tui/tui.js +320 -88
  206. package/plugins-dist/tui/vendor.js +1388 -1088
  207. package/plugins-dist/undo/checkpoint.js +1 -1
  208. package/plugins-dist/undo/index.js +91 -24
  209. package/plugins-dist/undo/plugin.json +10 -3
  210. package/plugins-dist/undo/snapshot.js +111 -0
  211. package/plugins-dist/update/index.js +9 -10
  212. package/plugins-dist/update/plugin.json +4 -1
  213. package/plugins-dist/web/index.js +7 -7
  214. package/plugins-dist/web/plugin.json +1 -1
  215. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  216. package/sdk/python/jade_plugin.py +8 -0
  217. package/src/api.ts +7 -262
  218. package/src/fetch.ts +18 -16
  219. package/src/host.ts +49 -1
  220. package/src/index.ts +1 -1
  221. package/src/main.ts +23 -5
  222. package/src/remote.ts +2 -0
  223. package/src/session.ts +134 -15
  224. package/src/source.ts +2 -11
  225. package/src/update.ts +16 -10
  226. package/plugins/undo/notes.ts +0 -43
  227. package/plugins-dist/undo/notes.js +0 -36
@@ -1,19 +1,27 @@
1
- // jade/approval:审批。tool.before 把路径统一成绝对路径,tool.gate 按模式和规则决定,要问时经 ui@1 问用户。
1
+ // jade/approval:审批。tool.before 把路径统一成绝对路径,tool.gate 按模式和规则决定:允许、拒绝,或者要问用户(ask)。
2
+ // 关卡不等用户:所有关卡合并的结果是 ask 时(日志里的 tool.decided),内核停下来等人工审批,这里才经 ui@1 问用户,
3
+ // 把回答作为 approval 输入交给会话。别的插件的关卡要问时也由这里问。谁回答的、选了什么记成 jade/approval/answered 事件。
2
4
  // auto 模式下规则判断不了、本来要问的调用先让模型审一次(review.ts):它只能放行或转给用户,不能替用户拒绝。
3
5
  //
4
6
  // 没有这个插件(停用、坏掉、被隔离)时,核心的兜底关卡拒绝所有非只读工具(第 7 节),所以这里出错不会放行。
5
- // 用户选的"总是允许"记进日志(derived),恢复会话后仍然有效;模式是进程级的,来自配置,可以经 approval@1 改。
7
+ // 用户选的"总是允许"记进日志(derived),恢复会话后仍然有效;选"在这个目录里总是允许"的记在
8
+ // $JADE_HOME/state/approvals.json(按工作目录),以后在这个目录里开的会话都有效。模式是进程级的,来自配置,可以经 approval@1 改。
9
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
6
10
  import path from "node:path";
7
- import { definePlugin } from "../../dist/api.js";
11
+ import { definePlugin } from "@uncarved/jade-api";
8
12
  import { describeRule, MODES, policy } from "./policy.js";
9
13
  import { reviewer } from "./review.js";
10
- const ANSWERS = ["once", "always", "deny"];
14
+ const ANSWERS = ["once", "always", "forever", "deny"];
15
+ /** 只有终端里有的一项:拒绝,并写一句话告诉模型该怎么做 */
16
+ const EXPLAIN = "explain";
11
17
  /** derived 里保存"总是允许"规则的键 */
12
18
  const RULES_KEY = "jade/approval/rules";
13
- /** 等用户回答的默认时限:内核要求 hook 有有限的超时,超时按拒绝处理。配置 askTimeoutMinutes 可以改 */
19
+ /** 等用户回答的默认时限,过了按拒绝处理。配置 askTimeoutMinutes 可以改 */
14
20
  const ASK_TIMEOUT_MS = 24 * 60 * 60 * 1000;
15
- /** askTimeoutMinutes 的上限:内核的定时器最长约 24.8 天 */
21
+ /** askTimeoutMinutes 的上限:定时器最长约 24.8 天 */
16
22
  const MAX_ASK_TIMEOUT_MINUTES = 7 * 24 * 60;
23
+ /** 关卡的时限:auto 模式的审查最长一分钟(review.ts),比 hook 默认的 30 秒长 */
24
+ const GATE_TIMEOUT_MS = 2 * 60_000;
17
25
  const MAX_DETAIL_CHARS = 2000;
18
26
  /** 等工具的审批预览的时限,过了就用默认的 detail */
19
27
  const PREVIEW_TIMEOUT_MS = 5000;
@@ -37,8 +45,8 @@ let badTimeout;
37
45
  const readRoots = [];
38
46
  /** 经 allowWrite 登记的目录;policy 每次判断时读它 */
39
47
  const writeRoots = [];
40
- /** 经 addApprover 登记的审批渠道 */
41
- const approvers = new Set();
48
+ /** 经 addApprover 登记的审批渠道 → 登记它的插件 */
49
+ const approvers = new Map();
42
50
  /** 打开着的会话:会话 id → 判断只读调用能不能不问就执行(allows) */
43
51
  const sessionChecks = new Map();
44
52
  export default definePlugin({
@@ -69,12 +77,12 @@ export default definePlugin({
69
77
  throw new Error("approval.addApprover: project plugins cannot answer approvals");
70
78
  if (typeof approver !== "function")
71
79
  throw new Error("approval.addApprover: approver must be a function");
72
- approvers.add(approver);
80
+ approvers.set(approver, caller.plugin);
73
81
  const remove = () => void approvers.delete(approver);
74
82
  caller.onDispose(remove);
75
83
  return remove;
76
84
  },
77
- allows: (session, call) => call.tool?.effect === "read" && (sessionChecks.get(session)?.(call) ?? false),
85
+ allows: (session, call) => call.tool !== undefined && (sessionChecks.get(session)?.(call) ?? false),
78
86
  }));
79
87
  },
80
88
  async session(ctx) {
@@ -108,14 +116,29 @@ export default definePlugin({
108
116
  /** 本会话里审查过一次、放行了的调用 */
109
117
  const reviewedCalls = new Set();
110
118
  let warned = false;
111
- /** 本进程里刚选的"总是允许":并发的关卡拿到的 derived 是各自开始时的快照,可能还没有它 */
119
+ /** 本进程里刚选的"总是允许":记进日志之前(要等看到那条 approval 输入)就要生效 */
112
120
  const added = [];
113
121
  /** 一次只问一个问题;排在后面的问之前重新判断,前面刚选的"总是允许"可能已经覆盖它 */
114
122
  let asking = Promise.resolve();
115
123
  /** 日志里记下的"总是允许"规则,每次调用工具前取一次:子 Agent 在工具执行期间经 allows 用它 */
116
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.`;
117
140
  const id = ctx.session.id;
118
- const check = (call) => rules.decide(call, { mode: mode === "yolo" ? "yolo" : "readonly", rules: [...logged, ...added] }).decision === "allow";
141
+ const check = (call) => rules.decide(call, { mode: mode === "yolo" && call.tool.effect === "read" ? "yolo" : "readonly", rules: [...forever, ...logged, ...added] }).decision === "allow";
119
142
  sessionChecks.set(id, check);
120
143
  await ctx.effect(() => () => {
121
144
  if (sessionChecks.get(id) === check)
@@ -132,12 +155,9 @@ export default definePlugin({
132
155
  ctx.kernel.hook({
133
156
  kind: "gate",
134
157
  point: "tool.gate",
135
- timeoutMs: askTimeoutMs,
158
+ timeoutMs: GATE_TIMEOUT_MS,
136
159
  fn: async (call, hook) => {
137
- const saved = () => {
138
- const logged = hook.derived[RULES_KEY] ?? [];
139
- return [...logged, ...added.filter((r) => !logged.some((l) => JSON.stringify(l) === JSON.stringify(r)))];
140
- };
160
+ seen.set(call.toolUseId, { call });
141
161
  const result = rules.decide(call, { mode, rules: saved() });
142
162
  if (result.decision !== "ask")
143
163
  return result;
@@ -158,43 +178,158 @@ export default definePlugin({
158
178
  }
159
179
  why = verdict.reason;
160
180
  }
161
- if (!ui?.interactive && approvers.size === 0) {
181
+ if (!canAsk()) {
162
182
  if (!warned) {
163
183
  warned = true;
164
184
  ui?.notify(`${call.name} needs approval, but this jade cannot ask. To let it make changes in the working directory, ` +
165
185
  `set {"jade/approval": {"mode": "auto"}} in ${ctx.home}/config.json`, "warning");
166
186
  }
167
- return { decision: "deny", reason: `${call.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.` };
187
+ return { decision: "deny", reason: nobody(call.name) };
168
188
  }
169
- const turn = asking.then(async () => {
170
- const again = rules.decide(call, { mode, rules: saved() });
171
- if (again.decision !== "ask")
172
- return again;
173
- const rule = rules.ruleFor(call);
174
- const shown = (await preview(renderers, call)) ?? detail(call);
175
- const answer = await ask(ui, {
176
- title: `Allow ${call.name}?`,
177
- // 审查转给用户的:先说为什么
178
- detail: why ? `${why}\n\n${shown}` : shown,
179
- options: [
180
- { label: "Allow once", value: "once" },
181
- { label: `Always allow ${describeRule(rule)} in this session`, value: "always" },
182
- { label: "Deny", value: "deny" },
183
- ],
184
- }, hook.signal);
185
- if (answer === "always") {
186
- added.push(rule);
187
- await hook.record(RULES_KEY, saved());
188
- return { decision: "allow" };
189
- }
190
- if (answer === "once")
191
- return { decision: "allow" };
192
- return { decision: "deny", reason: "The user denied this tool call. Do not retry it unchanged: adjust, or ask what to do instead." };
193
- });
194
- asking = turn.catch(() => { });
195
- return turn;
189
+ seen.set(call.toolUseId, { call, mine: call, ...(why ? { why } : {}) });
190
+ return { decision: "ask" };
196
191
  },
197
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
+ });
198
333
  },
199
334
  });
200
335
  /** allowRead、allowWrite:把目录登记进 roots,调用方的作用域关闭时撤销 */
@@ -214,7 +349,7 @@ function allow(caller, name, roots, dir) {
214
349
  return remove;
215
350
  }
216
351
  /**
217
- * 把问题同时交给终端(能提问时)和所有审批渠道,返回先到的回答,然后中止其余的。
352
+ * 把问题同时交给终端(能提问时)和所有审批渠道,返回先到的回答和回答的人("terminal" 或渠道的插件 id),然后中止其余的。
218
353
  * 终端里取消(undefined)算拒绝;渠道返回 undefined、不认识的值或出错算它不回答。都不回答时返回 undefined(拒绝)
219
354
  */
220
355
  async function ask(ui, request, signal) {
@@ -224,12 +359,20 @@ async function ask(ui, request, signal) {
224
359
  try {
225
360
  return await new Promise((resolve, reject) => {
226
361
  const channels = [];
227
- if (ui?.interactive)
228
- channels.push(ui.select(request, done.signal).then((a) => (a !== undefined && ANSWERS.includes(a) ? a : "deny")));
229
- for (const approver of approvers) {
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) {
230
373
  channels.push(Promise.resolve()
231
374
  .then(() => approver(request, done.signal))
232
- .then((a) => (typeof a === "string" && ANSWERS.includes(a) ? a : NONE), () => NONE));
375
+ .then((a) => (typeof a === "string" && ANSWERS.includes(a) ? { answer: a, by } : NONE), () => NONE));
233
376
  }
234
377
  let pending = channels.length;
235
378
  if (pending === 0)
@@ -250,6 +393,33 @@ async function ask(ui, request, signal) {
250
393
  }
251
394
  }
252
395
  const NONE = Symbol("no answer");
396
+ /** approvals.json:工作目录 → 在这个目录里总是允许的规则。读不了或格式不对时当作没有 */
397
+ 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 {};
411
+ }
412
+ }
413
+ 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`);
422
+ }
253
423
  /**
254
424
  * 工具自己登记的审批预览(例如文件修改的 diff)。没有登记、返回的不是文字、或者出错时返回 undefined,
255
425
  * 用下面的 detail:预览是别的插件的代码,它坏了不能让审批卡住或失败
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "jade/approval",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.js",
6
6
  "provides": [
@@ -2,6 +2,7 @@
2
2
  // 纯判断,不碰界面和日志;那些在 index.ts。
3
3
  //
4
4
  // 带 url 参数的只读工具(web_fetch)也要问:网页里的提示注入可以让模型把读到的内容拼进 URL 发出去。
5
+ // 指向本机的 URL(localhost 上的开发服务器,截图最常见的用途)不问:数据不会离开这台机器。
5
6
  import { realpathSync, statSync } from "node:fs";
6
7
  import path from "node:path";
7
8
  import { validate } from "./schema.js";
@@ -329,21 +330,33 @@ function prefixCovers(words, prefix) {
329
330
  }
330
331
  /**
331
332
  * bash 的"总是允许"默认规则:一般取前两个词("cargo build"、"git commit"),
332
- * 运行脚本的命令取三个词("npm run build")。第二个词就是选项("rm -rf x")、只有一个词、
333
- * 或者分不了词时,只允许这一条命令本身
333
+ * 运行脚本的命令取三个词("npm run build")。第二个词就是选项("rm -rf x")、只有一个词时,只允许这一条命令本身。
334
+ * 复合命令("git add -A && git commit -m …"、"bun test 2>&1 | tail -20")里每条不是只读的命令各记一条:
335
+ * 关卡对复合命令逐条判断,所以下次换了提交信息、换了组合也不用再问。
336
+ * 分不了词、有输出重定向、或者不是只读的命令带输入重定向时,只允许整条命令原文
334
337
  */
335
- export function bashRule(command) {
336
- const exact = { tool: "bash", command: command.trim() };
337
- // 复合命令里只有一条不是只读命令("bun test 2>&1 | tail -20")时,规则取它;关卡对复合命令逐条判断
338
+ export function bashRules(command) {
339
+ const exact = [{ tool: "bash", command: command.trim() }];
338
340
  const cmds = shellCommands(command);
339
341
  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)
342
+ if (!cmds || !unsafe || unsafe.length === 0 || !cmds.every(quietOutputs) || unsafe.some((c) => c.inputs.length > 0))
341
343
  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
+ // 只有一条命令、又只能按原文记时,记整条原文(和关卡比较的是同一个字符串)
345
+ if (cmds.length === 1 && !prefixOf(unsafe[0].words))
344
346
  return exact;
347
+ const rules = unsafe.map((c) => {
348
+ const prefix = prefixOf(c.words);
349
+ return prefix ? { tool: "bash", prefix } : { tool: "bash", command: joined(c.words) };
350
+ });
351
+ return rules.filter((r, i) => rules.findIndex((o) => o.prefix === r.prefix && o.command === r.command) === i);
352
+ }
353
+ /** 一条简单命令的前缀规则;只能按原文记时返回 undefined */
354
+ function prefixOf(all) {
355
+ const words = all.map((w) => w.value);
356
+ if (words.length < 2 || words[1].startsWith("-") || words.some((w) => DANGEROUS_ARGS.test(w)))
357
+ return undefined;
345
358
  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(" ") };
359
+ return words.slice(0, n).join(" ");
347
360
  }
348
361
  const hostOf = (url) => {
349
362
  try {
@@ -353,6 +366,8 @@ const hostOf = (url) => {
353
366
  return undefined;
354
367
  }
355
368
  };
369
+ /** 本机的地址:localhost、127.x.x.x、::1(URL 会把 127.1 这类写法规范成 127.0.0.1) */
370
+ const isLoopback = (host) => host !== undefined && (host === "localhost" || host.endsWith(".localhost") || /^127(\.\d{1,3}){3}$/.test(host) || host === "[::1]");
356
371
  /**
357
372
  * Windows 上 bash 工具跑的是 Git Bash,模型常把路径写成 /c/Users/...(MSYS 的写法)。
358
373
  * path.resolve 会把它当成当前盘符下的 \c\Users\...,判断成工作目录之外,只读命令也要确认。
@@ -465,14 +480,14 @@ export function policy(opts) {
465
480
  return input;
466
481
  return { ...input, path: path.resolve(opts.cwd, input.path) };
467
482
  },
468
- ruleFor(call) {
483
+ rulesFor(call) {
469
484
  if (call.name === "bash")
470
- return bashRule(String(call.input.command ?? ""));
485
+ return bashRules(String(call.input.command ?? ""));
471
486
  const input = call.input;
472
487
  if (typeof input?.url === "string") {
473
488
  const host = hostOf(input.url);
474
489
  if (host)
475
- return { tool: call.name, host };
490
+ return [{ tool: call.name, host }];
476
491
  }
477
492
  if (typeof input?.path === "string" && !inside(input.path)) {
478
493
  const full = path.resolve(opts.cwd, input.path);
@@ -483,9 +498,9 @@ export function policy(opts) {
483
498
  catch {
484
499
  // 还不存在的文件
485
500
  }
486
- return { tool: call.name, dir: isDir ? full : path.dirname(full) };
501
+ return [{ tool: call.name, dir: isDir ? full : path.dirname(full) }];
487
502
  }
488
- return { tool: call.name };
503
+ return [{ tool: call.name }];
489
504
  },
490
505
  decide(call, { mode, rules }) {
491
506
  const { tool } = call;
@@ -496,7 +511,7 @@ export function policy(opts) {
496
511
  const outside = (typeof input.path === "string" && !inside(input.path)) ||
497
512
  (call.name === "glob" && typeof input.pattern === "string" && globEscapes(input.pattern));
498
513
  /** 会把参数发到网络上的只读工具 */
499
- const network = typeof input.url === "string";
514
+ const network = typeof input.url === "string" && !isLoopback(hostOf(input.url));
500
515
  const covers = (r) => {
501
516
  if (r.tool !== call.name)
502
517
  return false;
@@ -3,7 +3,7 @@
3
3
  // 每个问题给几个选项让用户选,也可以自己输入回答。对话框经 ui@1,不再由宿主私下传入。
4
4
  // 前端不能提问(-p、非终端)时不提供这个工具,提示词里也就不会提到它(jade/prompts 按工具是否存在取舍)。
5
5
  // 从旧 jade 的 tools/ask.ts 和 main.ts 的 askUser 移植。
6
- import { definePlugin } from "../../dist/api.js";
6
+ import { definePlugin } from "@uncarved/jade-api";
7
7
  const MAX_QUESTIONS = 4;
8
8
  /** 选项的值是序号,"其他" 的值不会和它重复 */
9
9
  const OTHER = "other";
@@ -1,6 +1,6 @@
1
1
  // jade/budget:一轮里模型回复的次数达到上限就停下(turn.continue 关卡拒绝,这一轮以 stopped 结束)。
2
2
  // 从旧 jade 的 plugins/budget.ts 移植;上限来自配置 maxSteps。
3
- import { definePlugin } from "../../dist/api.js";
3
+ import { definePlugin } from "@uncarved/jade-api";
4
4
  const DEFAULT_STEPS = 100;
5
5
  /** 本轮(最近一条用户输入之后)模型已经回复了几次 */
6
6
  export function stepsThisTurn(s) {
@@ -75,7 +75,8 @@ function findUp(dir, root, name) {
75
75
  * 后面认不出路径的行(多行说明、代码片段)归到它下面;第一个问题之前的行单独算一个没有文件的问题
76
76
  */
77
77
  export function parseProblems(output, cwd) {
78
- const START = /^\s*((?:[A-Za-z]:[\\/])?[^\s:()][^:()]*?)(?:\(\d+,\d+\)|:\d+(?::\d+)?)(?=[:\s]|$)/;
78
+ // 路径里可以有括号(Next.js 的 app/(group)/page.tsx),只是不能以括号开头
79
+ const START = /^\s*((?:[A-Za-z]:[\\/])?[^\s:()][^:]*?)(?:\(\d+,\d+\)|:\d+(?::\d+)?)(?=[:\s]|$)/;
79
80
  const out = [];
80
81
  let cur;
81
82
  for (const line of output.split(/\r?\n/)) {
@@ -9,7 +9,7 @@
9
9
  // yolo 模式不问;不能提问时不运行没确认过的命令。
10
10
  import { createHash } from "node:crypto";
11
11
  import path from "node:path";
12
- import { definePlugin } from "../../dist/api.js";
12
+ import { definePlugin } from "@uncarved/jade-api";
13
13
  import { changedFiles, checks } from "./checks.js";
14
14
  import { bold, dim, display, realPath, repoRoot, TrustFile, yellow } from "./project.js";
15
15
  /** 确认记录:同一个目录里的同一条命令只问一次。和旧 jade 的算法相同 */
@@ -1,6 +1,6 @@
1
1
  // jade/commands:斜杠命令的注册表。只登记,不执行:前端解析输入、带着自己的上下文调用 run。
2
2
  // 每个调用方一个实例,调用方关闭(停用、被隔离、换会话时的会话作用域)时它注册的命令自动撤销。
3
- import { definePlugin } from "../../dist/api.js";
3
+ import { definePlugin } from "@uncarved/jade-api";
4
4
  const NAME = /^[a-z0-9][a-z0-9_-]*$/i;
5
5
  const registry = new Map();
6
6
  export default definePlugin({
@@ -83,6 +83,7 @@ const total = (u) => (u?.inputTokens === undefined ? undefined : u.inputTokens +
83
83
  export function compactor(opts) {
84
84
  const id = opts.id ?? "jade/compact";
85
85
  let forced = false;
86
+ let focus;
86
87
  /** 最近一次投影:它对应的消息条数和压缩状态;收到回复后补上真实用量 */
87
88
  let last;
88
89
  let pending;
@@ -143,6 +144,8 @@ export function compactor(opts) {
143
144
  }
144
145
  }
145
146
  forced = false;
147
+ const asked = focus;
148
+ focus = undefined;
146
149
  const res = await opts.complete({
147
150
  system: [{ text: SUMMARY_SYSTEM, stability: "stable", origin: { by: "plugin", id }, trust: "trusted" }],
148
151
  messages: [
@@ -156,6 +159,7 @@ export function compactor(opts) {
156
159
  origin: { by: "plugin", id },
157
160
  trust: "untrusted",
158
161
  },
162
+ ...(asked ? [{ kind: "text", text: `The user asked that the summary pay particular attention to: ${asked}`, origin: { by: "plugin", id }, trust: "trusted" }] : []),
159
163
  ],
160
164
  },
161
165
  ],
@@ -185,8 +189,9 @@ export function compactor(opts) {
185
189
  last = { ...pending, tokens: total(e.data.usage) };
186
190
  pending = undefined;
187
191
  },
188
- request() {
192
+ request(what) {
189
193
  forced = true;
194
+ focus = what;
190
195
  },
191
196
  };
192
197
  }
@@ -1,6 +1,6 @@
1
1
  // jade/compact:历史接近上下文窗口时压缩投影(见 compact.ts);/compact 让下一次请求前总结一次;
2
2
  // 请求因为超出上下文窗口失败时,压缩后用 { kind: "retry" } 重试一次(session.afterTurn,设计 4.3)。
3
- import { definePlugin } from "../../dist/api.js";
3
+ import { definePlugin } from "@uncarved/jade-api";
4
4
  import { compactor, compactThreshold, isContextOverflow, parseTokens } from "./compact.js";
5
5
  import { dim } from "./style.js";
6
6
  /** 认不出窗口时的阈值 */
@@ -22,20 +22,21 @@ function thresholdFor(config, models) {
22
22
  return compactThreshold(m.contextWindow, m.kind === "anthropic" ? ANTHROPIC_REPLY_TOKENS : 0);
23
23
  };
24
24
  }
25
- /** /compact 请求过的会话:下一次投影时无论是否超过阈值都总结一次 */
26
- const requested = new Set();
25
+ /** /compact 请求过的会话:下一次投影时无论是否超过阈值都总结一次。值是命令后面写的、要总结特别留意的事 */
26
+ const requested = new Map();
27
27
  export default definePlugin({
28
28
  process(ctx) {
29
29
  ctx.provide("compact@1", { threshold: thresholdFor(ctx.config, ctx.require("models@1")) });
30
30
  const commands = ctx.service("commands@1");
31
31
  commands?.register({
32
32
  name: "compact",
33
- description: "compact the history before the next request",
34
- run(_args, c) {
33
+ args: "[what to keep]",
34
+ description: "compact the history before the next request; text after the command tells the summary what to pay attention to",
35
+ run(args, c) {
35
36
  const s = c.sessions.current;
36
37
  if (!s)
37
38
  return "No session is open.";
38
- requested.add(s.id);
39
+ requested.set(s.id, args.trim());
39
40
  return dim("History will be compacted before the next request.");
40
41
  },
41
42
  });
@@ -65,8 +66,11 @@ export default definePlugin({
65
66
  order: 100,
66
67
  timeoutMs: SUMMARY_TIMEOUT_MS,
67
68
  fn: (messages, hook) => {
68
- if (requested.delete(id))
69
- c.request();
69
+ const focus = requested.get(id);
70
+ if (focus !== undefined) {
71
+ requested.delete(id);
72
+ c.request(focus || undefined);
73
+ }
70
74
  return c.project(messages, hook);
71
75
  },
72
76
  });
@@ -4,7 +4,7 @@
4
4
  // 每次用户输入之后最多续写 maxContinues 次。从旧 jade 的 plugins/turns.ts 的 continueTurns 移植。
5
5
  //
6
6
  // 旧 jade 的"上下文溢出后压缩重试"不在这里:不压缩就重试只会再溢出一次,整件事归 jade/compact。
7
- import { definePlugin } from "../../dist/api.js";
7
+ import { definePlugin } from "@uncarved/jade-api";
8
8
  export const DEFAULT_CONTINUES = 3;
9
9
  export const CONTINUE_NOTE = "Your previous reply was cut off because it reached the output token limit. Continue from where you stopped. " +
10
10
  "If you were writing a large file or edit, split it into several smaller write_file/edit_file calls.";