@uncarved/jade 0.2.1 → 0.3.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 (213) hide show
  1. package/README.md +64 -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 +233 -85
  30. package/plugins/approval/plugin.json +1 -1
  31. package/plugins/approval/policy.ts +2 -1
  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 +6 -4
  49. package/plugins/fs/index.ts +2 -3
  50. package/plugins/fs/renderers.ts +1 -1
  51. package/plugins/hooks/index.ts +152 -0
  52. package/plugins/hooks/plugin.json +14 -0
  53. package/plugins/keys/index.ts +2 -18
  54. package/plugins/mcp/index.ts +40 -12
  55. package/plugins/mcp/install.ts +139 -0
  56. package/plugins/mcp/mcp.ts +2 -1
  57. package/plugins/mcp/plugin.json +1 -1
  58. package/plugins/mcp/project.ts +37 -1
  59. package/plugins/memory/index.ts +4 -9
  60. package/plugins/memory/plugin.json +1 -1
  61. package/plugins/mentions/index.ts +2 -2
  62. package/plugins/models/configure.ts +258 -150
  63. package/plugins/models/context.ts +2 -2
  64. package/plugins/models/index.ts +35 -42
  65. package/plugins/models/plugin.json +1 -1
  66. package/plugins/models/provider.ts +22 -4
  67. package/plugins/models/saved.ts +8 -4
  68. package/plugins/modes/index.ts +2 -17
  69. package/plugins/plugins/index.ts +2 -2
  70. package/plugins/print/index.ts +36 -6
  71. package/plugins/print/plugin.json +1 -0
  72. package/plugins/prompts/index.ts +22 -14
  73. package/plugins/{memory → prompts}/notes.ts +21 -9
  74. package/plugins/prompts/plugin.json +8 -2
  75. package/plugins/prompts/prompts.ts +5 -4
  76. package/plugins/renderers/index.ts +2 -43
  77. package/plugins/repeats/index.ts +1 -1
  78. package/plugins/schedule/index.ts +2 -2
  79. package/plugins/scratch/index.ts +2 -3
  80. package/plugins/screenshot/index.ts +26 -13
  81. package/plugins/screenshot/plugin.json +1 -1
  82. package/plugins/sessions/index.ts +2 -17
  83. package/plugins/shell/index.ts +56 -6
  84. package/plugins/shell/plugin.json +3 -1
  85. package/plugins/shell/renderers.ts +1 -1
  86. package/plugins/shell/service.ts +2 -13
  87. package/plugins/shell/shell.ts +31 -16
  88. package/plugins/skills/index.ts +172 -37
  89. package/plugins/skills/install.ts +212 -0
  90. package/plugins/skills/plugin.json +3 -2
  91. package/plugins/skills/project.ts +38 -1
  92. package/plugins/skills/skills.ts +28 -9
  93. package/plugins/steer/index.ts +142 -0
  94. package/plugins/steer/plugin.json +8 -0
  95. package/plugins/suggest/index.ts +16 -11
  96. package/plugins/suggest/plugin.json +1 -1
  97. package/plugins/task/index.ts +7 -16
  98. package/plugins/task/plugin.json +9 -2
  99. package/plugins/task/subagent.ts +23 -5
  100. package/plugins/todo/index.ts +2 -2
  101. package/plugins/tui/editor.ts +10 -2
  102. package/plugins/tui/frontend.ts +103 -21
  103. package/plugins/tui/index.ts +3 -8
  104. package/plugins/tui/markdown.ts +51 -6
  105. package/plugins/tui/mascot.ts +505 -0
  106. package/plugins/tui/plugin.json +2 -2
  107. package/plugins/tui/screen.ts +6 -0
  108. package/plugins/tui/transcript.ts +17 -2
  109. package/plugins/tui/tui.ts +321 -90
  110. package/plugins/undo/checkpoint.ts +2 -2
  111. package/plugins/undo/index.ts +84 -26
  112. package/plugins/undo/plugin.json +8 -2
  113. package/plugins/undo/snapshot.ts +129 -0
  114. package/plugins/update/index.ts +11 -15
  115. package/plugins/update/plugin.json +2 -1
  116. package/plugins/web/index.ts +2 -5
  117. package/plugins/web/renderers.ts +1 -1
  118. package/plugins-dist/approval/index.js +217 -51
  119. package/plugins-dist/approval/plugin.json +1 -1
  120. package/plugins-dist/ask/index.js +1 -1
  121. package/plugins-dist/budget/index.js +1 -1
  122. package/plugins-dist/checks/checks.js +2 -1
  123. package/plugins-dist/checks/index.js +1 -1
  124. package/plugins-dist/commands/index.js +1 -1
  125. package/plugins-dist/compact/compact.js +6 -1
  126. package/plugins-dist/compact/index.js +12 -8
  127. package/plugins-dist/continue/index.js +1 -1
  128. package/plugins-dist/cost/index.js +135 -0
  129. package/plugins-dist/cost/plugin.json +16 -0
  130. package/plugins-dist/custom-commands/index.js +86 -0
  131. package/plugins-dist/custom-commands/plugin.json +12 -0
  132. package/plugins-dist/editor/index.js +89 -0
  133. package/plugins-dist/editor/plugin.json +21 -0
  134. package/plugins-dist/fs/fs.js +34 -6
  135. package/plugins-dist/fs/grep.js +5 -3
  136. package/plugins-dist/fs/index.js +1 -1
  137. package/plugins-dist/hooks/index.js +145 -0
  138. package/plugins-dist/hooks/plugin.json +19 -0
  139. package/plugins-dist/keys/index.js +1 -1
  140. package/plugins-dist/mcp/index.js +41 -9
  141. package/plugins-dist/mcp/install.js +160 -0
  142. package/plugins-dist/mcp/mcp.js +2 -1
  143. package/plugins-dist/mcp/plugin.json +2 -1
  144. package/plugins-dist/mcp/project.js +42 -1
  145. package/plugins-dist/memory/index.js +3 -5
  146. package/plugins-dist/memory/plugin.json +1 -1
  147. package/plugins-dist/mentions/index.js +1 -1
  148. package/plugins-dist/models/configure.js +252 -151
  149. package/plugins-dist/models/context.js +2 -2
  150. package/plugins-dist/models/index.js +37 -14
  151. package/plugins-dist/models/plugin.json +1 -1
  152. package/plugins-dist/models/provider.js +4 -2
  153. package/plugins-dist/models/saved.js +9 -4
  154. package/plugins-dist/modes/index.js +1 -1
  155. package/plugins-dist/plugins/index.js +1 -1
  156. package/plugins-dist/print/index.js +37 -3
  157. package/plugins-dist/print/plugin.json +3 -0
  158. package/plugins-dist/prompts/index.js +22 -3
  159. package/plugins-dist/{memory → prompts}/notes.js +10 -7
  160. package/plugins-dist/prompts/plugin.json +8 -2
  161. package/plugins-dist/prompts/prompts.js +5 -4
  162. package/plugins-dist/renderers/index.js +1 -1
  163. package/plugins-dist/repeats/index.js +1 -1
  164. package/plugins-dist/schedule/index.js +1 -1
  165. package/plugins-dist/scratch/index.js +1 -1
  166. package/plugins-dist/screenshot/index.js +25 -11
  167. package/plugins-dist/screenshot/plugin.json +1 -1
  168. package/plugins-dist/sessions/index.js +1 -1
  169. package/plugins-dist/shell/index.js +55 -3
  170. package/plugins-dist/shell/plugin.json +3 -1
  171. package/plugins-dist/shell/shell.js +26 -8
  172. package/plugins-dist/skills/index.js +184 -35
  173. package/plugins-dist/skills/install.js +178 -0
  174. package/plugins-dist/skills/plugin.json +6 -2
  175. package/plugins-dist/skills/project.js +43 -1
  176. package/plugins-dist/skills/skills.js +27 -10
  177. package/plugins-dist/steer/index.js +135 -0
  178. package/plugins-dist/steer/plugin.json +12 -0
  179. package/plugins-dist/suggest/index.js +15 -9
  180. package/plugins-dist/suggest/plugin.json +1 -1
  181. package/plugins-dist/task/index.js +6 -4
  182. package/plugins-dist/task/plugin.json +10 -2
  183. package/plugins-dist/task/subagent.js +20 -5
  184. package/plugins-dist/todo/index.js +1 -1
  185. package/plugins-dist/tui/editor.js +7 -2
  186. package/plugins-dist/tui/frontend.js +107 -13
  187. package/plugins-dist/tui/index.js +2 -1
  188. package/plugins-dist/tui/markdown.js +48 -6
  189. package/plugins-dist/tui/mascot.js +439 -0
  190. package/plugins-dist/tui/plugin.json +3 -2
  191. package/plugins-dist/tui/screen.js +2 -0
  192. package/plugins-dist/tui/transcript.js +16 -1
  193. package/plugins-dist/tui/tui.js +302 -81
  194. package/plugins-dist/undo/checkpoint.js +1 -1
  195. package/plugins-dist/undo/index.js +91 -24
  196. package/plugins-dist/undo/plugin.json +10 -3
  197. package/plugins-dist/undo/snapshot.js +111 -0
  198. package/plugins-dist/update/index.js +9 -10
  199. package/plugins-dist/update/plugin.json +4 -1
  200. package/plugins-dist/web/index.js +1 -1
  201. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  202. package/sdk/python/jade_plugin.py +8 -0
  203. package/src/api.ts +7 -262
  204. package/src/fetch.ts +18 -16
  205. package/src/host.ts +49 -1
  206. package/src/index.ts +1 -1
  207. package/src/main.ts +23 -5
  208. package/src/remote.ts +2 -0
  209. package/src/session.ts +134 -15
  210. package/src/source.ts +2 -11
  211. package/src/update.ts +16 -10
  212. package/plugins/undo/notes.ts +0 -43
  213. 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,155 @@ 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 rule = rules.ruleFor(call);
206
+ const shown = (await preview(renderers, call)) ?? detail(call);
207
+ const expired = new AbortController();
208
+ const timer = setTimeout(() => expired.abort(), askTimeoutMs);
209
+ let got;
210
+ try {
211
+ got = await ask(ui, {
212
+ title: `Allow ${call.name}?`,
213
+ // 审查转给用户的:先说为什么
214
+ detail: asked.why ? `${asked.why}\n\n${shown}` : shown,
215
+ options: [
216
+ { label: "Allow once", value: "once" },
217
+ // 别的插件要问的调用不能"总是允许":这里的规则管不到它的关卡
218
+ ...(asked.mine
219
+ ? [
220
+ { label: `Always allow ${describeRule(rule)} in this session`, value: "always" },
221
+ { label: `Always allow ${describeRule(rule)} in this directory, in every session`, value: "forever" },
222
+ ]
223
+ : []),
224
+ { label: "Deny", value: "deny" },
225
+ ],
226
+ }, AbortSignal.any([signal, expired.signal, ctx.signal]));
227
+ }
228
+ finally {
229
+ clearTimeout(timer);
230
+ }
231
+ if (expired.signal.aborted) {
232
+ 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.` };
233
+ }
234
+ if (got?.answer === "always" && asked.mine) {
235
+ added.push(rule);
236
+ return { approved: true, answer: "always", by: got.by };
237
+ }
238
+ if (got?.answer === "forever" && asked.mine) {
239
+ forever.push(rule);
240
+ try {
241
+ await addForever(foreverFile, ctx.cwd, rule);
242
+ ui?.notify(`${describeRule(rule)} is now always allowed in ${ctx.cwd}. To ask again, remove it from ${foreverFile}`, "info");
243
+ }
244
+ catch (e) {
245
+ ui?.notify(`could not save the rule to ${foreverFile} (${e instanceof Error ? e.message : String(e)}); it only applies to this session`, "warning");
246
+ }
247
+ return { approved: true, answer: "forever", by: got.by };
248
+ }
249
+ if (got !== undefined && got.answer !== "deny")
250
+ return { approved: true, answer: "once", by: got.by };
251
+ if (got?.said)
252
+ return { approved: false, answer: "deny", by: got.by, reason: `The user denied this tool call and said: ${got.said}` };
253
+ 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." };
254
+ };
255
+ /** 一个要问的调用:得出回答,交给会话。出错也要回答(拒绝),否则这一轮一直等着 */
256
+ const settle = async (asked, signal) => {
257
+ const toolUseId = asked.call.toolUseId;
258
+ let verdict;
259
+ try {
260
+ verdict = await decide(asked, signal);
261
+ }
262
+ catch (e) {
263
+ verdict = { approved: false, answer: "deny", by: "error", reason: `Asking for approval failed: ${e instanceof Error ? e.message : String(e)}` };
264
+ }
265
+ // 这一轮已经结束(被中断):回答作废
266
+ if (signal.aborted)
267
+ return;
268
+ answered.set(toolUseId, { answer: verdict.answer, by: verdict.by });
269
+ // 不等它:它要到内核再次停下才 resolve,后面排着的问题可能就是内核在等的
270
+ void Promise.resolve()
271
+ .then(() => ctx.session.send({ kind: "approval", toolUseId, approved: verdict.approved, ...(verdict.reason ? { reason: verdict.reason } : {}) }))
272
+ .catch(() => void answered.delete(toolUseId));
273
+ };
274
+ ctx.kernel.hook({
275
+ kind: "observe",
276
+ point: "event",
277
+ fn: async (e, hook) => {
278
+ if (e.type === "tool.decided") {
279
+ const d = e.data;
280
+ const asked = seen.get(d.toolUseId);
281
+ seen.delete(d.toolUseId);
282
+ if (d.decision !== "ask" || !asked)
283
+ return;
284
+ // 不在这里等回答:observe 要马上返回,内核才能停下来等
285
+ handled.add(d.toolUseId);
286
+ const signal = turn.signal;
287
+ asking = asking.then(() => settle(asked, signal));
288
+ }
289
+ else if (e.type === "input.received") {
290
+ const d = e.data;
291
+ if (d.kind !== "approval")
292
+ return;
293
+ const a = answered.get(d.toolUseId);
294
+ if (!a)
295
+ return;
296
+ answered.delete(d.toolUseId);
297
+ // 内核只记同意或拒绝:选了什么、谁回答的(终端、哪个渠道、规则、超时)记在这里
298
+ await hook.emit("answered", { toolUseId: d.toolUseId, ...a });
299
+ if (a.answer === "always")
300
+ await hook.record(RULES_KEY, merged(hook.derived[RULES_KEY] ?? []));
301
+ }
302
+ else if (e.type === "turn.ended") {
303
+ turn.abort(new Error("the turn ended"));
304
+ turn = new AbortController();
305
+ seen.clear();
306
+ answered.clear();
307
+ handled.clear();
308
+ }
309
+ },
310
+ });
311
+ // 恢复一个上次停在等审批的会话(进程被杀、崩溃):那些调用的关卡是上一个进程跑的,这里没见过。
312
+ // 内核恢复时再发一次 awaiting,据此重新问。只知道调用的名字和参数(工具的声明只有关卡拿得到),
313
+ // 所以当作别的关卡要问的:只有"允许一次"和"拒绝",不重新套规则
314
+ ctx.session.subscribe((n) => {
315
+ if (n.type !== "awaiting")
316
+ return;
317
+ const waiting = n.toolUseIds.filter((t) => !handled.has(t) && !seen.has(t));
318
+ if (waiting.length === 0)
319
+ return;
320
+ const batch = ctx.session.state().batch;
321
+ const signal = turn.signal;
322
+ for (const toolUseId of waiting) {
323
+ const c = batch.find((x) => x.toolUseId === toolUseId && x.decision === "ask");
324
+ if (!c)
325
+ continue;
326
+ handled.add(toolUseId);
327
+ asking = asking.then(() => settle({ call: { toolUseId, name: c.name, input: c.input } }, signal));
328
+ }
329
+ });
198
330
  },
199
331
  });
200
332
  /** allowRead、allowWrite:把目录登记进 roots,调用方的作用域关闭时撤销 */
@@ -214,7 +346,7 @@ function allow(caller, name, roots, dir) {
214
346
  return remove;
215
347
  }
216
348
  /**
217
- * 把问题同时交给终端(能提问时)和所有审批渠道,返回先到的回答,然后中止其余的。
349
+ * 把问题同时交给终端(能提问时)和所有审批渠道,返回先到的回答和回答的人("terminal" 或渠道的插件 id),然后中止其余的。
218
350
  * 终端里取消(undefined)算拒绝;渠道返回 undefined、不认识的值或出错算它不回答。都不回答时返回 undefined(拒绝)
219
351
  */
220
352
  async function ask(ui, request, signal) {
@@ -224,12 +356,20 @@ async function ask(ui, request, signal) {
224
356
  try {
225
357
  return await new Promise((resolve, reject) => {
226
358
  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) {
359
+ if (ui?.interactive) {
360
+ // 终端里多一项:拒绝并说明。选了它再问一句话,取消或什么都没写就是普通的拒绝
361
+ const options = [...request.options, { label: "Deny, and tell the agent what to do instead", value: EXPLAIN }];
362
+ channels.push(ui.select({ ...request, options }, done.signal).then(async (a) => {
363
+ if (a !== EXPLAIN)
364
+ return { answer: a !== undefined && ANSWERS.includes(a) ? a : "deny", by: "terminal" };
365
+ const said = (await ui.input({ title: "What should the agent do instead?" }, done.signal))?.trim();
366
+ return { answer: "deny", by: "terminal", ...(said ? { said } : {}) };
367
+ }));
368
+ }
369
+ for (const [approver, by] of approvers) {
230
370
  channels.push(Promise.resolve()
231
371
  .then(() => approver(request, done.signal))
232
- .then((a) => (typeof a === "string" && ANSWERS.includes(a) ? a : NONE), () => NONE));
372
+ .then((a) => (typeof a === "string" && ANSWERS.includes(a) ? { answer: a, by } : NONE), () => NONE));
233
373
  }
234
374
  let pending = channels.length;
235
375
  if (pending === 0)
@@ -250,6 +390,32 @@ async function ask(ui, request, signal) {
250
390
  }
251
391
  }
252
392
  const NONE = Symbol("no answer");
393
+ /** approvals.json:工作目录 → 在这个目录里总是允许的规则。读不了或格式不对时当作没有 */
394
+ async function readForever(file) {
395
+ try {
396
+ const data = JSON.parse(await readFile(file, "utf8"));
397
+ if (!data || typeof data !== "object" || Array.isArray(data))
398
+ return {};
399
+ const out = {};
400
+ for (const [dir, rules] of Object.entries(data)) {
401
+ if (Array.isArray(rules))
402
+ out[dir] = rules.filter((r) => !!r && typeof r === "object" && typeof r.tool === "string");
403
+ }
404
+ return out;
405
+ }
406
+ catch {
407
+ return {};
408
+ }
409
+ }
410
+ async function addForever(file, cwd, rule) {
411
+ const all = await readForever(file);
412
+ const rules = all[cwd] ?? [];
413
+ if (!rules.some((r) => JSON.stringify(r) === JSON.stringify(rule)))
414
+ rules.push(rule);
415
+ all[cwd] = rules;
416
+ await mkdir(path.dirname(file), { recursive: true });
417
+ await writeFile(file, `${JSON.stringify(all, null, 2)}\n`);
418
+ }
253
419
  /**
254
420
  * 工具自己登记的审批预览(例如文件修改的 diff)。没有登记、返回的不是文字、或者出错时返回 undefined,
255
421
  * 用下面的 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": [
@@ -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.";
@@ -0,0 +1,135 @@
1
+ // jade/cost:按配置的单价把会话的 token 用量换算成钱,显示在状态栏上;/cost 列出每个模型用了多少。
2
+ //
3
+ // 单价不内置(价格会变,兼容服务上的模型名也各不相同),写在 $JADE_HOME/config.json,单位是每百万 token(下面的数字只是示例):
4
+ //
5
+ // { "jade/cost": { "prices": { "claude-opus": { "input": 15, "output": 75, "cacheRead": 1.5, "cacheWrite": 18.75 } } } }
6
+ //
7
+ // 键是模型名或它的前缀(最长的前缀算数);cacheRead、cacheWrite 不写时按 input 算。没有配置单价的模型只计 token,不计钱。
8
+ // 用量来自日志:模型的每次回复,以及插件自己发的请求(压缩的总结、auto 模式的审查、子 Agent),后者不知道用的是哪个模型,
9
+ // 按会话当前的模型算。状态栏的合计每轮结束时记进 derived,恢复会话后接着算;/cost 每次从整份日志重算。
10
+ import { definePlugin } from "@uncarved/jade-api";
11
+ const KEY = "jade/cost/usage";
12
+ /** 插件自己发的请求没有记模型名时记在这个名字下,算钱时按当前模型 */
13
+ const UNKNOWN = "";
14
+ /** 配置里的 prices;写错的条目忽略 */
15
+ export function parsePrices(value) {
16
+ const out = {};
17
+ if (!value || typeof value !== "object" || Array.isArray(value))
18
+ return out;
19
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
20
+ for (const [model, raw] of Object.entries(value)) {
21
+ const p = (raw ?? {});
22
+ const input = num(p.input);
23
+ const output = num(p.output);
24
+ if (input === undefined || output === undefined)
25
+ continue;
26
+ const cacheRead = num(p.cacheRead);
27
+ const cacheWrite = num(p.cacheWrite);
28
+ out[model] = { input, output, ...(cacheRead !== undefined ? { cacheRead } : {}), ...(cacheWrite !== undefined ? { cacheWrite } : {}) };
29
+ }
30
+ return out;
31
+ }
32
+ /** 模型的单价:名字完全相同的,否则最长的前缀 */
33
+ export function priceOf(prices, model) {
34
+ let best;
35
+ for (const key of Object.keys(prices))
36
+ if (model.startsWith(key) && (best === undefined || key.length > best.length))
37
+ best = key;
38
+ return best === undefined ? undefined : prices[best];
39
+ }
40
+ /** 一份用量按单价是多少钱。inputTokens 含缓存命中和写入的部分(Usage 的约定) */
41
+ export function costOf(u, p) {
42
+ const plain = Math.max(0, u.inputTokens - u.cacheReadTokens - u.cacheWriteTokens);
43
+ return (plain * p.input + u.cacheReadTokens * (p.cacheRead ?? p.input) + u.cacheWriteTokens * (p.cacheWrite ?? p.input) + u.outputTokens * p.output) / 1_000_000;
44
+ }
45
+ /** 一个事件带来的用量和它的模型;不带用量的事件 undefined */
46
+ function usageIn(e) {
47
+ const usage = e.data?.usage;
48
+ if (!usage || typeof usage !== "object")
49
+ return undefined;
50
+ if (e.type === "model.responded")
51
+ return { model: e.origin.by === "model" ? e.origin.model : UNKNOWN, usage };
52
+ return e.origin.by === "plugin" ? { model: UNKNOWN, usage } : undefined;
53
+ }
54
+ function add(totals, model, u) {
55
+ const t = (totals[model] ??= { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 });
56
+ for (const k of Object.keys(t)) {
57
+ const v = u[k];
58
+ if (typeof v === "number" && Number.isFinite(v))
59
+ t[k] += v;
60
+ }
61
+ }
62
+ /** 合计的钱;一个有单价的模型都没有时 undefined */
63
+ function total(totals, prices, current) {
64
+ let sum;
65
+ for (const [model, u] of Object.entries(totals)) {
66
+ const p = priceOf(prices, model === UNKNOWN ? (current ?? "") : model);
67
+ if (p)
68
+ sum = (sum ?? 0) + costOf(u, p);
69
+ }
70
+ return sum;
71
+ }
72
+ const money = (n) => `$${n < 0.01 && n > 0 ? n.toFixed(4) : n.toFixed(2)}`;
73
+ const tokens = (n) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(2)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
74
+ export default definePlugin({
75
+ process(ctx) {
76
+ const prices = parsePrices(ctx.config.prices);
77
+ ctx.service("commands@1")?.register({
78
+ name: "cost",
79
+ description: "show this session's token usage per model, and what it cost at the configured prices",
80
+ instant: true,
81
+ async run(_args, { sessions }) {
82
+ const s = sessions.current;
83
+ if (!s)
84
+ return "No session is open.";
85
+ const totals = {};
86
+ for (const e of await s.history()) {
87
+ const u = usageIn(e);
88
+ if (u)
89
+ add(totals, u.model, u.usage);
90
+ }
91
+ const current = ctx.service("models@1")?.current()?.model;
92
+ const rows = Object.entries(totals).map(([model, u]) => {
93
+ const p = priceOf(prices, model === UNKNOWN ? (current ?? "") : model);
94
+ const cached = u.cacheReadTokens ? `, ${tokens(u.cacheReadTokens)} from cache` : "";
95
+ return `${model === UNKNOWN ? "plugin requests (compaction, review, sub-agents)" : model}: ${tokens(u.inputTokens)} in${cached}, ${tokens(u.outputTokens)} out${p ? ` · ${money(costOf(u, p))}` : ""}`;
96
+ });
97
+ if (rows.length === 0)
98
+ return "No model usage in this session yet.";
99
+ const sum = total(totals, prices, current);
100
+ const hint = `No price is configured for ${sum === undefined ? "these models" : "some of these models"}: add {"jade/cost": {"prices": {"<model name or prefix>": {"input": <$ per million tokens>, "output": <$>}}}} to ${ctx.home}/config.json`;
101
+ const unpriced = Object.keys(totals).some((m) => !priceOf(prices, m === UNKNOWN ? (current ?? "") : m));
102
+ return [...rows, ...(sum !== undefined ? [`Total: ${money(sum)}`] : []), ...(unpriced ? [hint] : [])].join("\n");
103
+ },
104
+ });
105
+ },
106
+ session(ctx) {
107
+ const prices = parsePrices(ctx.config.prices);
108
+ // 没有配置单价、或者前端没有状态栏:不用算
109
+ if (Object.keys(prices).length === 0 || !ctx.status)
110
+ return;
111
+ const models = ctx.service("models@1");
112
+ let totals;
113
+ const show = () => {
114
+ const sum = total(totals ?? {}, prices, models?.current()?.model);
115
+ ctx.status?.(sum === undefined ? undefined : money(sum));
116
+ };
117
+ ctx.kernel.hook({
118
+ kind: "observe",
119
+ point: "event",
120
+ fn: async (e, hook) => {
121
+ // 恢复的会话:从上次记下的合计接着算
122
+ totals ??= structuredClone(hook.derived[KEY] ?? {});
123
+ const u = usageIn(e);
124
+ if (u) {
125
+ add(totals, u.model, u.usage);
126
+ show();
127
+ }
128
+ else if (e.type === "turn.ended") {
129
+ show();
130
+ await hook.record(KEY, totals);
131
+ }
132
+ },
133
+ });
134
+ },
135
+ });