@uncarved/jade 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +482 -27
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +49 -24
  14. package/plugins/approval/policy.ts +48 -25
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +55 -12
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +10 -9
  50. package/plugins/models/index.ts +31 -4
  51. package/plugins/models/provider.ts +12 -1
  52. package/plugins/modes/index.ts +13 -2
  53. package/plugins/print/index.ts +7 -4
  54. package/plugins/prompts/index.ts +0 -0
  55. package/plugins/renderers/index.ts +10 -5
  56. package/plugins/repeats/index.ts +39 -9
  57. package/plugins/schedule/index.ts +2 -0
  58. package/plugins/screenshot/browser.ts +231 -0
  59. package/plugins/screenshot/index.ts +3 -2
  60. package/plugins/screenshot/tool.ts +27 -51
  61. package/plugins/sessions/index.ts +48 -2
  62. package/plugins/shell/index.ts +75 -22
  63. package/plugins/shell/plugin.json +1 -2
  64. package/plugins/shell/renderers.ts +9 -7
  65. package/plugins/shell/shell.ts +93 -34
  66. package/plugins/skills/index.ts +28 -19
  67. package/plugins/skills/project.ts +12 -7
  68. package/plugins/steer/index.ts +5 -4
  69. package/plugins/task/index.ts +81 -81
  70. package/plugins/task/plugin.json +5 -2
  71. package/plugins/task/style.ts +13 -14
  72. package/plugins/task/subagent.ts +67 -184
  73. package/plugins/todo/index.ts +39 -9
  74. package/plugins/tools/index.ts +57 -0
  75. package/plugins/tools/plugin.json +7 -0
  76. package/plugins/tui/frontend.ts +161 -87
  77. package/plugins/tui/index.ts +2 -3
  78. package/plugins/tui/mascot.ts +8 -7
  79. package/plugins/tui/mentions.ts +11 -80
  80. package/plugins/tui/plugin.json +1 -1
  81. package/plugins/tui/screen.ts +55 -5
  82. package/plugins/tui/transcript.ts +17 -7
  83. package/plugins/tui/tui.ts +356 -104
  84. package/plugins/tui/vendor.ts +1 -1
  85. package/plugins/undo/checkpoint.ts +5 -3
  86. package/plugins/undo/index.ts +43 -14
  87. package/plugins/undo/style.ts +13 -14
  88. package/plugins/web/index.ts +7 -18
  89. package/plugins/web/plugin.json +1 -1
  90. package/plugins-dist/approval/index.js +363 -414
  91. package/plugins-dist/approval/policy.js +395 -497
  92. package/plugins-dist/approval/review.js +132 -158
  93. package/plugins-dist/approval/schema.js +50 -55
  94. package/plugins-dist/ask/index.js +115 -129
  95. package/plugins-dist/budget/index.js +27 -31
  96. package/plugins-dist/checks/checks.js +293 -329
  97. package/plugins-dist/checks/index.js +119 -139
  98. package/plugins-dist/checks/plugin.json +2 -1
  99. package/plugins-dist/checks/project.js +57 -65
  100. package/plugins-dist/commands/index.js +47 -29
  101. package/plugins-dist/compact/compact.js +233 -249
  102. package/plugins-dist/compact/index.js +98 -95
  103. package/plugins-dist/compact/style.js +9 -14
  104. package/plugins-dist/completions/index.js +30 -0
  105. package/plugins-dist/completions/plugin.json +9 -0
  106. package/plugins-dist/continue/index.js +40 -52
  107. package/plugins-dist/copy/index.js +40 -0
  108. package/plugins-dist/copy/plugin.json +9 -0
  109. package/plugins-dist/cost/index.js +98 -115
  110. package/plugins-dist/custom-commands/index.js +55 -72
  111. package/plugins-dist/editor/index.js +64 -72
  112. package/plugins-dist/fs/diff.js +111 -124
  113. package/plugins-dist/fs/fs.js +426 -469
  114. package/plugins-dist/fs/grep.js +262 -244
  115. package/plugins-dist/fs/index.js +20 -34
  116. package/plugins-dist/fs/plugin.json +1 -2
  117. package/plugins-dist/fs/renderers.js +100 -112
  118. package/plugins-dist/fs/style.js +11 -15
  119. package/plugins-dist/fs/sys.js +31 -43
  120. package/plugins-dist/hooks/index.js +107 -127
  121. package/plugins-dist/keys/index.js +27 -31
  122. package/plugins-dist/mcp/index.js +271 -199
  123. package/plugins-dist/mcp/install.js +123 -137
  124. package/plugins-dist/mcp/mcp.js +638 -577
  125. package/plugins-dist/mcp/plugin.json +3 -1
  126. package/plugins-dist/mcp/project.js +98 -115
  127. package/plugins-dist/memory/index.js +83 -88
  128. package/plugins-dist/memory/memory.js +111 -128
  129. package/plugins-dist/memory/style.js +9 -14
  130. package/plugins-dist/mentions/attach.js +91 -99
  131. package/plugins-dist/mentions/candidates.js +49 -0
  132. package/plugins-dist/mentions/index.js +71 -81
  133. package/plugins-dist/mentions/plugin.json +2 -1
  134. package/plugins-dist/mentions/style.js +9 -14
  135. package/plugins-dist/models/config.js +29 -43
  136. package/plugins-dist/models/configure.js +392 -473
  137. package/plugins-dist/models/context.js +14 -22
  138. package/plugins-dist/models/index.js +182 -188
  139. package/plugins-dist/models/provider.js +243 -295
  140. package/plugins-dist/models/saved.js +59 -71
  141. package/plugins-dist/modes/index.js +138 -165
  142. package/plugins-dist/plugins/index.js +34 -34
  143. package/plugins-dist/print/index.js +192 -175
  144. package/plugins-dist/prompts/index.js +81 -89
  145. package/plugins-dist/prompts/notes.js +31 -37
  146. package/plugins-dist/prompts/prompts.js +155 -193
  147. package/plugins-dist/prompts/results.js +40 -53
  148. package/plugins-dist/prompts/sys.js +39 -50
  149. package/plugins-dist/renderers/index.js +32 -32
  150. package/plugins-dist/repeats/index.js +134 -151
  151. package/plugins-dist/schedule/cron.js +49 -56
  152. package/plugins-dist/schedule/index.js +229 -247
  153. package/plugins-dist/schedule/store.js +93 -109
  154. package/plugins-dist/scratch/index.js +12 -18
  155. package/plugins-dist/screenshot/browser.js +169 -0
  156. package/plugins-dist/screenshot/index.js +37 -45
  157. package/plugins-dist/screenshot/sys.js +53 -65
  158. package/plugins-dist/screenshot/tool.js +101 -151
  159. package/plugins-dist/sessions/index.js +149 -117
  160. package/plugins-dist/shell/index.js +117 -74
  161. package/plugins-dist/shell/plugin.json +1 -2
  162. package/plugins-dist/shell/renderers.js +28 -33
  163. package/plugins-dist/shell/service.js +17 -23
  164. package/plugins-dist/shell/shell.js +317 -320
  165. package/plugins-dist/shell/sys.js +64 -79
  166. package/plugins-dist/skills/index.js +193 -211
  167. package/plugins-dist/skills/install.js +122 -149
  168. package/plugins-dist/skills/project.js +65 -73
  169. package/plugins-dist/skills/skills.js +135 -171
  170. package/plugins-dist/steer/index.js +108 -125
  171. package/plugins-dist/suggest/index.js +235 -259
  172. package/plugins-dist/task/index.js +130 -148
  173. package/plugins-dist/task/plugin.json +5 -4
  174. package/plugins-dist/task/style.js +9 -14
  175. package/plugins-dist/task/subagent.js +156 -279
  176. package/plugins-dist/todo/index.js +79 -63
  177. package/plugins-dist/tools/index.js +43 -0
  178. package/plugins-dist/tools/plugin.json +9 -0
  179. package/plugins-dist/tui/editor.js +145 -160
  180. package/plugins-dist/tui/frontend.js +641 -655
  181. package/plugins-dist/tui/history.js +34 -37
  182. package/plugins-dist/tui/index.js +16 -18
  183. package/plugins-dist/tui/markdown.js +203 -247
  184. package/plugins-dist/tui/mascot.js +266 -353
  185. package/plugins-dist/tui/mentions.js +67 -144
  186. package/plugins-dist/tui/plugin.json +1 -2
  187. package/plugins-dist/tui/render.js +35 -45
  188. package/plugins-dist/tui/screen.js +197 -180
  189. package/plugins-dist/tui/transcript.js +436 -468
  190. package/plugins-dist/tui/tui.js +1554 -1645
  191. package/plugins-dist/tui/vendor.js +1388 -1088
  192. package/plugins-dist/undo/checkpoint.js +95 -118
  193. package/plugins-dist/undo/index.js +185 -192
  194. package/plugins-dist/undo/snapshot.js +83 -99
  195. package/plugins-dist/undo/style.js +9 -14
  196. package/plugins-dist/update/index.js +26 -28
  197. package/plugins-dist/web/env.js +55 -68
  198. package/plugins-dist/web/index.js +80 -110
  199. package/plugins-dist/web/plugin.json +1 -2
  200. package/plugins-dist/web/renderers.js +4 -5
  201. package/plugins-dist/web/web.js +514 -593
  202. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  203. package/sdk/python/jade_plugin.py +9 -2
  204. package/src/api.ts +1 -1
  205. package/src/host.ts +39 -4
  206. package/src/remote.ts +6 -1
  207. package/src/session.ts +489 -34
@@ -1,58 +1,47 @@
1
- // 跨运行时的进程:只用 Node 的标准库,Bun 和 Node ≥22.18 下走同一套代码。
2
1
  import { spawn as nodeSpawn } from "node:child_process";
3
- const EMPTY = { async *[Symbol.asyncIterator]() { } };
4
- /**
5
- * 启动进程,等到确实启动了才返回。程序不存在(ENOENT)等启动错误会 reject,
6
- * 调用方用 try/catch 判断"没装",和 Bun.spawn 同步抛错的用法一致
7
- */
2
+ const EMPTY = { async* [Symbol.asyncIterator]() {} };
8
3
  export function spawn(cmd, opts = {}) {
9
- const child = nodeSpawn(cmd[0], cmd.slice(1), {
10
- cwd: opts.cwd,
11
- stdio: ["ignore", opts.stdout ?? "pipe", opts.stderr ?? "pipe"],
12
- detached: opts.detached ?? false,
13
- env: opts.env,
14
- // Windows 上不弹出控制台窗口
15
- windowsHide: true,
16
- });
17
- const exited = new Promise((resolve) => child.once("exit", (code) => resolve(code)));
18
- return new Promise((resolve, reject) => {
19
- child.once("error", reject);
20
- child.once("spawn", () => {
21
- child.off("error", reject);
22
- // 启动之后的错误(例如 kill 一个已经退出的进程)不应该变成未处理的异常
23
- child.on("error", () => { });
24
- resolve({
25
- pid: child.pid,
26
- stdout: child.stdout ?? EMPTY,
27
- stderr: child.stderr ?? EMPTY,
28
- exited,
29
- kill: () => void child.kill(),
30
- });
31
- });
4
+ const child = nodeSpawn(cmd[0], cmd.slice(1), {
5
+ cwd: opts.cwd,
6
+ stdio: ["ignore", opts.stdout ?? "pipe", opts.stderr ?? "pipe"],
7
+ detached: opts.detached ?? false,
8
+ env: opts.env,
9
+ windowsHide: true
10
+ });
11
+ const exited = new Promise((resolve) => child.once("exit", (code) => resolve(code)));
12
+ return new Promise((resolve, reject) => {
13
+ child.once("error", reject);
14
+ child.once("spawn", () => {
15
+ child.off("error", reject);
16
+ child.on("error", () => {});
17
+ resolve({
18
+ pid: child.pid,
19
+ stdout: child.stdout ?? EMPTY,
20
+ stderr: child.stderr ?? EMPTY,
21
+ exited,
22
+ kill: () => void child.kill()
23
+ });
32
24
  });
25
+ });
33
26
  }
34
- /** 运行一条命令,返回 stdout 文本和退出码;启动失败时 reject。超过 timeoutMs 时杀掉,退出码为 null */
35
27
  export async function run(cmd, opts = {}) {
36
- const proc = await spawn(cmd, { cwd: opts.cwd, stderr: "ignore" });
37
- let timedOut = false;
38
- const timer = opts.timeoutMs === undefined
39
- ? undefined
40
- : setTimeout(() => {
41
- timedOut = true;
42
- proc.kill();
43
- }, opts.timeoutMs);
44
- try {
45
- const [stdout, code] = await Promise.all([text(proc.stdout), proc.exited]);
46
- return { code: timedOut ? null : code, stdout };
47
- }
48
- finally {
49
- clearTimeout(timer);
50
- }
28
+ const proc = await spawn(cmd, { cwd: opts.cwd, stderr: "ignore" });
29
+ let timedOut = false;
30
+ const timer = opts.timeoutMs === undefined ? undefined : setTimeout(() => {
31
+ timedOut = true;
32
+ proc.kill();
33
+ }, opts.timeoutMs);
34
+ try {
35
+ const [stdout, code] = await Promise.all([text(proc.stdout), proc.exited]);
36
+ return { code: timedOut ? null : code, stdout };
37
+ } finally {
38
+ clearTimeout(timer);
39
+ }
51
40
  }
52
41
  export async function text(stream) {
53
- const decoder = new TextDecoder();
54
- let out = "";
55
- for await (const chunk of stream)
56
- out += decoder.decode(chunk, { stream: true });
57
- return out + decoder.decode();
42
+ const decoder = new TextDecoder;
43
+ let out = "";
44
+ for await (const chunk of stream)
45
+ out += decoder.decode(chunk, { stream: true });
46
+ return out + decoder.decode();
58
47
  }
@@ -1,36 +1,36 @@
1
- // jade/renderers:工具调用和插件事件在对话里怎么显示的注册表。前端查这里;没有登记的用前端的默认显示。
2
- // 显示的文字可以带 ANSI 颜色,前端负责过滤掉颜色之外的控制序列。
3
1
  import { definePlugin } from "@uncarved/jade-api";
4
- const tools = new Map();
5
- const events = new Map();
6
- function add(map, key, renderer, plugin, what, onDispose) {
7
- const taken = map.get(key);
8
- if (taken)
9
- throw new Error(`${what} ${key} already has a renderer from ${taken.plugin}`);
10
- const entry = { renderer, plugin };
11
- map.set(key, entry);
12
- const revoke = () => {
13
- if (map.get(key) === entry)
14
- map.delete(key);
15
- };
16
- onDispose(revoke);
17
- return revoke;
2
+ const tools = new Map;
3
+ const events = new Map;
4
+ function add(map, key, renderer, plugin, what, onDispose, report) {
5
+ const taken = map.get(key);
6
+ if (taken) {
7
+ report(`the renderer for ${what} ${key} from ${plugin} was skipped: ${taken.plugin} already registered one`);
8
+ return () => {};
9
+ }
10
+ const entry = { renderer, plugin };
11
+ map.set(key, entry);
12
+ const revoke = () => {
13
+ if (map.get(key) === entry)
14
+ map.delete(key);
15
+ };
16
+ onDispose(revoke);
17
+ return revoke;
18
18
  }
19
19
  export default definePlugin({
20
- process(ctx) {
21
- ctx.provide("renderers@1", (caller) => ({
22
- tool(renderer) {
23
- if (typeof renderer?.tool !== "string" || !renderer.tool)
24
- throw new Error("a tool renderer needs the tool name");
25
- return add(tools, renderer.tool, renderer, caller.plugin, "tool", caller.onDispose);
26
- },
27
- event(renderer) {
28
- if (typeof renderer?.event !== "string" || !renderer.event || typeof renderer.render !== "function")
29
- throw new Error("an event renderer needs the event type and render");
30
- return add(events, `${caller.plugin}/${renderer.event}`, renderer, caller.plugin, "event", caller.onDispose);
31
- },
32
- forTool: (tool) => tools.get(tool),
33
- forEvent: (type) => events.get(type),
34
- }));
35
- },
20
+ process(ctx) {
21
+ ctx.provide("renderers@1", (caller) => ({
22
+ tool(renderer) {
23
+ if (typeof renderer?.tool !== "string" || !renderer.tool)
24
+ throw new Error("a tool renderer needs the tool name");
25
+ return add(tools, renderer.tool, renderer, caller.plugin, "tool", caller.onDispose, ctx.report);
26
+ },
27
+ event(renderer) {
28
+ if (typeof renderer?.event !== "string" || !renderer.event || typeof renderer.render !== "function")
29
+ throw new Error("an event renderer needs the event type and render");
30
+ return add(events, `${caller.plugin}/${renderer.event}`, renderer, caller.plugin, "event", caller.onDispose, ctx.report);
31
+ },
32
+ forTool: (tool) => tools.get(tool),
33
+ forEvent: (type) => events.get(type)
34
+ }));
35
+ }
36
36
  });
@@ -1,165 +1,148 @@
1
- // jade/repeats:模型常常把同一个调用原样再发一遍。
2
- //
3
- // 同一次回复里参数完全相同的调用直接拒绝,不用让用户再批准一次;
4
- // 同一个调用连续失败、其间什么都没变时,在结果后面提醒模型它已经失败过几次,别再原样重试
5
- // (改了文件再跑同一条测试命令是正常的"修了再验证",从头计数);
6
- // 同一个调用已经成功执行过,之后什么都没变(没有执行过只读之外的调用,用户也没有发新消息),
7
- // 再执行一遍结果也完全一样时,在结果后面提醒模型这是重复的(反复读同一个文件、反复打开同一个网页)。
8
- // 不拒绝:也可能是在等外面的东西变化,只提醒。压缩插件清理或总结了历史后,之前的结果可能已经不在上下文里,都不算重复。
9
- // 打开文件给用户看(start、xdg-open……)会弹出新窗口:这一轮里打开过、之后什么都没改,再打开就直接拒绝。
10
- // write_file 之后什么都没改又读回同一个文件,提醒模型内容就是它写的那些。
11
- // 这些记录只在本会话的作用域里:恢复会话后从零开始,最多多重试一轮。
12
- //
13
- // 从旧 jade 的 plugins/repeats.ts 移植。
14
1
  import { createHash } from "node:crypto";
15
2
  import path from "node:path";
16
3
  import { definePlugin } from "@uncarved/jade-api";
17
4
  const ID = "jade/repeats";
18
- /** jade/compact 记录压缩结果用的派生数据键(旧 jade 的约定):记一次就说明历史被压缩过 */
19
5
  export const COMPACT_KEY = "jade/compact";
20
- /** 只打开一个文件或网址的命令:start "" x、start x、xdg-open x、open x、explorer x */
21
6
  const OPEN = /^\s*(?:start\s+""|start|xdg-open|open|explorer(?:\.exe)?)\s+(?:"([^"]+)"|'([^']+)'|([^\s"'&|;<>]+))\s*$/i;
22
- /** bash 调用打开的目标(规范化后),不是打开命令时是 undefined */
23
- export function openTarget(call, cwd) {
24
- if (call.name !== "bash")
25
- return undefined;
26
- const command = call.input?.command;
27
- if (typeof command !== "string")
28
- return undefined;
29
- const m = OPEN.exec(command);
30
- const target = m && (m[1] ?? m[2] ?? m[3]);
31
- if (!target)
32
- return undefined;
33
- return /^[a-z][a-z0-9+.-]*:\/\//i.test(target) ? target : normalize(cwd, target);
7
+ export function openTarget(call, cwd, shell) {
8
+ if (shell === undefined)
9
+ return;
10
+ const command = call.input?.[shell];
11
+ if (typeof command !== "string")
12
+ return;
13
+ const m = OPEN.exec(command);
14
+ const target = m && (m[1] ?? m[2] ?? m[3]);
15
+ if (!target)
16
+ return;
17
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(target) ? target : normalize(cwd, target);
34
18
  }
35
19
  function normalize(cwd, p) {
36
- const full = path.resolve(cwd, p);
37
- return process.platform === "win32" ? full.toLowerCase() : full;
20
+ const full = path.resolve(cwd, p);
21
+ return process.platform === "win32" ? full.toLowerCase() : full;
38
22
  }
39
- /** 提醒模型的失败次数 */
40
23
  const WARN_AFTER = 2;
41
- const hash = (content) => createHash("sha1").update(JSON.stringify(content.map((b) => (b.kind === "text" ? b.text : b)))).digest("hex");
42
- /** 会话里的 hook:model.before 数回复次数,tool.gate 拒绝重复,tool.after 加提醒,event 在用户发消息、压缩后重新计 */
24
+ const FLIP_AFTER = 3;
25
+ function replacements(call) {
26
+ const input = call.input;
27
+ const list = call.name === "edit_file" ? [input] : call.name === "multi_edit" && Array.isArray(input?.edits) ? input.edits : [];
28
+ return list.filter((e) => typeof e?.old_string === "string" && typeof e?.new_string === "string");
29
+ }
30
+ const hash = (content) => createHash("sha1").update(JSON.stringify(content.map((b) => b.kind === "text" ? b.text : b))).digest("hex");
43
31
  export function repeatsHooks(opts) {
44
- const id = opts.id ?? ID;
45
- const cwd = opts.cwd;
46
- /** 模型调用的次数,每次调用模型前加一 */
47
- let calls = 0;
48
- /** 本次回复里已经出现的调用;mutates:其中有只读之外、也不是打开文件的调用 */
49
- let current = { calls: -1, keys: new Set(), mutates: false };
50
- /** 调用 → 连续失败的次数和最近一次失败时的 version;成功一次就清掉 */
51
- const failures = new Map();
52
- /** 每执行成功一个只读之外的调用、用户每发一条消息、历史每压缩一次就加一 */
53
- let version = 0;
54
- /** 调用 → 上次成功执行后的 version 和结果 */
55
- const succeeded = new Map();
56
- /** 已放行、还没执行完的调用是不是只读的(tool.after 里拿不到工具的声明) */
57
- const readOnly = new Map();
58
- /** 每执行成功一个只读之外、也不是打开文件的调用就加一(可能改了文件) */
59
- let changes = 0;
60
- /** 本轮打开过的目标 → 打开时的 changes;用户发消息时清空 */
61
- const opened = new Map();
62
- /** 本轮用 write_file 写过的文件 → 写完时的 changes;用户发消息时清空 */
63
- const written = new Map();
64
- const key = (call) => `${call.name}\0${JSON.stringify(call.input)}`;
65
- const note = (text) => ({ kind: "text", text: `[Note from jade] ${text}`, origin: { by: "plugin", id }, trust: "trusted" });
66
- return [
67
- {
68
- kind: "transform",
69
- point: "model.before",
70
- fn: () => {
71
- calls++;
72
- },
73
- },
74
- {
75
- kind: "gate",
76
- point: "tool.gate",
77
- fn: (call) => {
78
- if (current.calls !== calls)
79
- current = { calls, keys: new Set(), mutates: false };
80
- const k = key(call);
81
- if (current.keys.has(k)) {
82
- return { decision: "deny", reason: "This call is identical to an earlier call in the same response and was not run; use that call's result." };
83
- }
84
- current.keys.add(k);
85
- const target = openTarget(call, cwd);
86
- // 同一次回复里排在前面的调用可能改了它,还没执行,不拒绝
87
- if (target !== undefined && opened.get(target) === changes && !current.mutates) {
88
- return {
89
- decision: "deny",
90
- reason: "This was already opened for the user earlier in this turn and nothing has changed since, so it was not opened again (it is still open). " +
91
- "End your turn and tell the user what you changed.",
92
- };
93
- }
94
- if (target === undefined && call.tool.effect !== "read")
95
- current.mutates = true;
96
- readOnly.set(call.toolUseId, call.tool.effect === "read");
97
- return { decision: "abstain" };
98
- },
99
- },
100
- {
101
- kind: "transform",
102
- point: "tool.after",
103
- fn: (outcome) => {
104
- const k = key(outcome.call);
105
- const read = readOnly.get(outcome.call.toolUseId) ?? false;
106
- readOnly.delete(outcome.call.toolUseId);
107
- if (!outcome.isError) {
108
- failures.delete(k);
109
- const target = openTarget(outcome.call, cwd);
110
- if (target !== undefined)
111
- opened.set(target, changes);
112
- else if (!read)
113
- changes++;
114
- const file = outcome.call.input?.path;
115
- if (outcome.call.name === "write_file" && typeof file === "string")
116
- written.set(normalize(cwd, file), changes);
117
- const readBack = outcome.call.name === "read_file" && typeof file === "string" && written.get(normalize(cwd, file)) === changes
118
- ? note("You wrote this file with write_file earlier and nothing has changed since: its content is exactly what you gave. Do not read files back to check them.")
119
- : undefined;
120
- const before = succeeded.get(k);
121
- // 只读之外的调用(包括这一个)可能改了东西,之后的调用都不算"什么都没变"
122
- if (!read)
123
- version++;
124
- const result = hash(outcome.content);
125
- const repeated = before !== undefined && before.version === (read ? version : version - 1) && before.result === result;
126
- succeeded.set(k, { version, result });
127
- if (!repeated)
128
- return readBack ? { ...outcome, content: [...outcome.content, readBack] } : undefined;
129
- const text = "This exact call already ran earlier with the same result, and nothing has changed since (no edits, no other commands, no new message from the user). " +
130
- "Do not repeat it: use what you already have, or end your turn and tell the user where things stand.";
131
- return { ...outcome, content: [...outcome.content, note(text)] };
132
- }
133
- const prev = failures.get(k);
134
- // 上次失败之后改过东西(修了代码再跑测试),重新计数
135
- const n = prev && prev.version === version ? prev.n + 1 : 1;
136
- failures.set(k, { n, version });
137
- if (n < WARN_AFTER)
138
- return;
139
- const text = `This exact call has now failed ${n} times. Do not repeat it unchanged: change the approach, or tell the user what is blocking you.`;
140
- return { ...outcome, content: [...outcome.content, note(text)] };
141
- },
142
- },
143
- {
144
- kind: "observe",
145
- point: "event",
146
- // 用户发了新消息,可能就是要再来一遍("再打开看看"),之前的记录都不算了;
147
- // 压缩之后模型可能已经看不到之前的结果,重新执行不算重复
148
- fn: (e) => {
149
- if (e.type === "derived.recorded" && e.data.key === COMPACT_KEY)
150
- version++;
151
- if (e.type === "input.received" && e.data.kind === "message") {
152
- version++;
153
- opened.clear();
154
- written.clear();
155
- }
156
- },
157
- },
158
- ];
32
+ const id = opts.id ?? ID;
33
+ const cwd = opts.cwd;
34
+ let calls = 0;
35
+ let current = { calls: -1, keys: new Set, mutates: false };
36
+ const failures = new Map;
37
+ let version = 0;
38
+ const succeeded = new Map;
39
+ const readOnly = new Map;
40
+ let changes = 0;
41
+ const opened = new Map;
42
+ const written = new Map;
43
+ const flips = new Map;
44
+ const key = (call) => `${call.name}\x00${JSON.stringify(call.input)}`;
45
+ const note = (text) => ({ kind: "text", text: `[Note from jade] ${text}`, origin: { by: "plugin", id }, trust: "trusted" });
46
+ return [
47
+ {
48
+ kind: "transform",
49
+ point: "model.before",
50
+ fn: () => {
51
+ calls++;
52
+ }
53
+ },
54
+ {
55
+ kind: "gate",
56
+ point: "tool.gate",
57
+ fn: (call) => {
58
+ if (current.calls !== calls)
59
+ current = { calls, keys: new Set, mutates: false };
60
+ const k = key(call);
61
+ if (current.keys.has(k)) {
62
+ return { decision: "deny", reason: "This call is identical to an earlier call in the same response and was not run; use that call's result." };
63
+ }
64
+ current.keys.add(k);
65
+ const target = openTarget(call, cwd, opts.shell(call.name));
66
+ if (target !== undefined && opened.get(target) === changes && !current.mutates) {
67
+ return {
68
+ decision: "deny",
69
+ reason: "This was already opened for the user earlier in this turn and nothing has changed since, so it was not opened again (it is still open). " + "End your turn and tell the user what you changed."
70
+ };
71
+ }
72
+ if (target === undefined && call.tool.effect !== "read")
73
+ current.mutates = true;
74
+ readOnly.set(call.toolUseId, call.tool.effect === "read");
75
+ return { decision: "abstain" };
76
+ }
77
+ },
78
+ {
79
+ kind: "transform",
80
+ point: "tool.after",
81
+ fn: (outcome) => {
82
+ const k = key(outcome.call);
83
+ const read = readOnly.get(outcome.call.toolUseId) ?? false;
84
+ readOnly.delete(outcome.call.toolUseId);
85
+ if (!outcome.isError) {
86
+ failures.delete(k);
87
+ const target = openTarget(outcome.call, cwd, opts.shell(outcome.call.name));
88
+ if (target !== undefined)
89
+ opened.set(target, changes);
90
+ else if (!read)
91
+ changes++;
92
+ const file = outcome.call.input?.path;
93
+ if (outcome.call.name === "write_file" && typeof file === "string")
94
+ written.set(normalize(cwd, file), changes);
95
+ const readBack = outcome.call.name === "read_file" && typeof file === "string" && written.get(normalize(cwd, file)) === changes ? note("You wrote this file with write_file earlier and nothing has changed since: its content is exactly what you gave. Do not read files back to check them.") : undefined;
96
+ let most = 0;
97
+ if (typeof file === "string") {
98
+ for (const e of replacements(outcome.call)) {
99
+ const pair = `${normalize(cwd, file)}\x00${[e.old_string, e.new_string].sort().join("\x00")}`;
100
+ const n = (flips.get(pair) ?? 0) + 1;
101
+ flips.set(pair, n);
102
+ most = Math.max(most, n);
103
+ }
104
+ }
105
+ const flipped = most >= FLIP_AFTER ? note(`You have now switched this same text back and forth ${most} times in this file. Going back and forth means what you are judging by is unreliable or incomplete. ` + "Do not flip it again: check your assumption another way (measure it, read the code involved), or tell the user what you see and ask.") : undefined;
106
+ const extra = [readBack, flipped].filter((b) => b !== undefined);
107
+ const before = succeeded.get(k);
108
+ if (!read)
109
+ version++;
110
+ const result = hash(outcome.content);
111
+ const repeated = before !== undefined && before.version === (read ? version : version - 1) && before.result === result;
112
+ succeeded.set(k, { version, result });
113
+ if (!repeated)
114
+ return extra.length > 0 ? { ...outcome, content: [...outcome.content, ...extra] } : undefined;
115
+ const text = "This exact call already ran earlier with the same result, and nothing has changed since (no edits, no other commands, no new message from the user). " + "Do not repeat it: use what you already have, or end your turn and tell the user where things stand.";
116
+ return { ...outcome, content: [...outcome.content, note(text)] };
117
+ }
118
+ const prev = failures.get(k);
119
+ const n = prev && prev.version === version ? prev.n + 1 : 1;
120
+ failures.set(k, { n, version });
121
+ if (n < WARN_AFTER)
122
+ return;
123
+ const text = `This exact call has now failed ${n} times. Do not repeat it unchanged: change the approach, or tell the user what is blocking you.`;
124
+ return { ...outcome, content: [...outcome.content, note(text)] };
125
+ }
126
+ },
127
+ {
128
+ kind: "observe",
129
+ point: "event",
130
+ fn: (e) => {
131
+ if (e.type === "derived.recorded" && e.data.key === COMPACT_KEY)
132
+ version++;
133
+ if (e.type === "input.received" && e.data.kind === "message") {
134
+ version++;
135
+ opened.clear();
136
+ written.clear();
137
+ flips.clear();
138
+ }
139
+ }
140
+ }
141
+ ];
159
142
  }
160
143
  export default definePlugin({
161
- session(ctx) {
162
- for (const h of repeatsHooks({ cwd: ctx.cwd, id: ctx.plugin }))
163
- ctx.kernel.hook(h);
164
- },
144
+ session(ctx) {
145
+ for (const h of repeatsHooks({ cwd: ctx.cwd, id: ctx.plugin, shell: (t) => ctx.session.tool(t)?.meta?.shell }))
146
+ ctx.kernel.hook(h);
147
+ }
165
148
  });
@@ -1,67 +1,60 @@
1
- // 五字段 cron(分 时 日 月 星期),按本机时区计算。支持 *、数字、a-b、/步长和逗号列表;
2
- // 星期 0 和 7 都是周日。日和星期都受限时任一匹配即可(Vixie cron 的规则),有一个以 * 开头时两者都要匹配。
3
1
  const FIELDS = [
4
- ["minute", 0, 59],
5
- ["hour", 0, 23],
6
- ["day of month", 1, 31],
7
- ["month", 1, 12],
8
- ["day of week", 0, 7],
2
+ ["minute", 0, 59],
3
+ ["hour", 0, 23],
4
+ ["day of month", 1, 31],
5
+ ["month", 1, 12],
6
+ ["day of week", 0, 7]
9
7
  ];
10
8
  function field(text, [name, min, max]) {
11
- const out = new Set();
12
- for (const item of text.split(",")) {
13
- const m = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(item);
14
- if (!m)
15
- throw new Error(`invalid ${name} field "${text}"`);
16
- const lo = m[1] === "*" ? min : Number(m[2]);
17
- const hi = m[1] === "*" ? max : m[3] !== undefined ? Number(m[3]) : m[4] !== undefined ? max : lo;
18
- const step = m[4] !== undefined ? Number(m[4]) : 1;
19
- if (lo < min || hi > max || lo > hi || step < 1)
20
- throw new Error(`${name} field "${text}" is out of range ${min}-${max}`);
21
- for (let v = lo; v <= hi; v += step)
22
- out.add(v);
23
- }
24
- return out;
9
+ const out = new Set;
10
+ for (const item of text.split(",")) {
11
+ const m = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(item);
12
+ if (!m)
13
+ throw new Error(`invalid ${name} field "${text}"`);
14
+ const lo = m[1] === "*" ? min : Number(m[2]);
15
+ const hi = m[1] === "*" ? max : m[3] !== undefined ? Number(m[3]) : m[4] !== undefined ? max : lo;
16
+ const step = m[4] !== undefined ? Number(m[4]) : 1;
17
+ if (lo < min || hi > max || lo > hi || step < 1)
18
+ throw new Error(`${name} field "${text}" is out of range ${min}-${max}`);
19
+ for (let v = lo;v <= hi; v += step)
20
+ out.add(v);
21
+ }
22
+ return out;
25
23
  }
26
24
  export function parseCron(expr) {
27
- const parts = expr.trim().split(/\s+/);
28
- if (parts.length !== 5)
29
- throw new Error(`cron needs 5 fields (minute hour day-of-month month day-of-week), got "${expr}"`);
30
- const [minute, hour, dom, month, dow] = parts.map((p, i) => field(p, FIELDS[i]));
31
- if (dow.delete(7))
32
- dow.add(0);
33
- return { minute: minute, hour: hour, dom: dom, month: month, dow: dow, domStar: parts[2].startsWith("*"), dowStar: parts[4].startsWith("*") };
25
+ const parts = expr.trim().split(/\s+/);
26
+ if (parts.length !== 5)
27
+ throw new Error(`cron needs 5 fields (minute hour day-of-month month day-of-week), got "${expr}"`);
28
+ const [minute, hour, dom, month, dow] = parts.map((p, i) => field(p, FIELDS[i]));
29
+ if (dow.delete(7))
30
+ dow.add(0);
31
+ return { minute, hour, dom, month, dow, domStar: parts[2].startsWith("*"), dowStar: parts[4].startsWith("*") };
34
32
  }
35
33
  function dayMatches(c, d) {
36
- const dom = c.dom.has(d.getDate());
37
- const dow = c.dow.has(d.getDay());
38
- return c.domStar || c.dowStar ? dom && dow : dom || dow;
34
+ const dom = c.dom.has(d.getDate());
35
+ const dow = c.dow.has(d.getDay());
36
+ return c.domStar || c.dowStar ? dom && dow : dom || dow;
39
37
  }
40
- /** from 之后(不含)第一个匹配的整分钟;五年内没有(例如 2 月 30 日)时 undefined */
41
38
  export function nextRun(expr, from) {
42
- const c = typeof expr === "string" ? parseCron(expr) : expr;
43
- const d = new Date(from);
44
- d.setSeconds(0, 0);
45
- d.setMinutes(d.getMinutes() + 1);
46
- const limit = from.getTime() + 5 * 366 * 86_400_000;
47
- while (d.getTime() < limit) {
48
- if (!c.month.has(d.getMonth() + 1)) {
49
- d.setMonth(d.getMonth() + 1, 1);
50
- d.setHours(0, 0, 0, 0);
51
- }
52
- else if (!dayMatches(c, d)) {
53
- d.setDate(d.getDate() + 1);
54
- d.setHours(0, 0, 0, 0);
55
- }
56
- else if (!c.hour.has(d.getHours())) {
57
- d.setHours(d.getHours() + 1, 0, 0, 0);
58
- }
59
- else if (!c.minute.has(d.getMinutes())) {
60
- d.setMinutes(d.getMinutes() + 1, 0, 0);
61
- }
62
- else {
63
- return d;
64
- }
39
+ const c = typeof expr === "string" ? parseCron(expr) : expr;
40
+ const d = new Date(from);
41
+ d.setSeconds(0, 0);
42
+ d.setMinutes(d.getMinutes() + 1);
43
+ const limit = from.getTime() + 5 * 366 * 86400000;
44
+ while (d.getTime() < limit) {
45
+ if (!c.month.has(d.getMonth() + 1)) {
46
+ d.setMonth(d.getMonth() + 1, 1);
47
+ d.setHours(0, 0, 0, 0);
48
+ } else if (!dayMatches(c, d)) {
49
+ d.setDate(d.getDate() + 1);
50
+ d.setHours(0, 0, 0, 0);
51
+ } else if (!c.hour.has(d.getHours())) {
52
+ d.setHours(d.getHours() + 1, 0, 0, 0);
53
+ } else if (!c.minute.has(d.getMinutes())) {
54
+ d.setMinutes(d.getMinutes() + 1, 0, 0);
55
+ } else {
56
+ return d;
65
57
  }
66
- return undefined;
58
+ }
59
+ return;
67
60
  }