@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
@@ -101,7 +101,7 @@ const UNDONE = "undone.json";
101
101
  * 最近一轮还有没撤销的修改的快照(最新的在前)。一轮从一条用户自己写的消息开始;
102
102
  * 只有工具结果、或者只有插件、宿主加的说明(例如自动续写的提示)的消息不算新的一轮。没有可撤销的返回空数组
103
103
  */
104
- export function lastTurnChanges(messages: readonly Message[], checkpoints: readonly Checkpoint[], undone: ReadonlySet<string>): Checkpoint[] {
104
+ export function lastTurnChanges<T extends { toolUseId: string }>(messages: readonly Message[], checkpoints: readonly T[], undone: ReadonlySet<string>): T[] {
105
105
  const pending = checkpoints.filter((c) => !undone.has(c.toolUseId));
106
106
  if (pending.length === 0) return [];
107
107
  let ids = new Set<string>();
@@ -146,4 +146,4 @@ export function turnToolNames(messages: readonly Message[], toolUseId?: string):
146
146
  }
147
147
 
148
148
  /** 会话和工具调用的 id 用作文件名 */
149
- const safe = (id: string) => id.replace(/[^A-Za-z0-9_.-]/g, "_");
149
+ export const safe = (id: string) => id.replace(/[^A-Za-z0-9_.-]/g, "_");
@@ -3,23 +3,32 @@
3
3
  // jade/fs 不再保存检查点,这里自己观察:tool.before 在 write_file / edit_file / multi_edit 执行前记下文件原来的内容,
4
4
  // tool.after 在执行成功后记下新内容的哈希,存成快照(checkpoint.ts)。tool.before 在审批之前执行,
5
5
  // 所以等用户批准期间别人对文件的改动会算进"原来的内容"。
6
+ // shell 命令改的文件:在 git 仓库里,每轮第一次 bash 之前给工作区拍一张快照(snapshot.ts),撤销时把之后变了的文件恢复回去。
6
7
 
7
8
  import { readFile } from "node:fs/promises";
8
9
  import { realpathSync } from "node:fs";
9
10
  import path from "node:path";
10
- import { definePlugin } from "../../src/api.ts";
11
- import type { Commands } from "../commands/index.ts";
12
- import { Checkpoints, lastTurnChanges, sha256, turnToolNames, type Checkpoint } from "./checkpoint.ts";
13
- import { Notes } from "./notes.ts";
11
+ import { definePlugin } from "@uncarved/jade-api";
12
+ import type { Commands, Prompts } from "@uncarved/jade-api/services";
13
+ import { Checkpoints, lastTurnChanges, safe, sha256, turnToolNames, type Checkpoint } from "./checkpoint.ts";
14
+ import { Snapshots, type Change, type Snapshot } from "./snapshot.ts";
14
15
  import { dim, green } from "./style.ts";
15
16
 
16
17
  /** 会改文件、参数里有 path 的工具 */
17
18
  export const WRITE_TOOLS = new Set(["write_file", "edit_file", "multi_edit"]);
18
19
 
19
- /** shell 命令改了什么无从得知,撤销不了;这一轮跑过时提醒一句 */
20
+ /** 没有工作区快照(不在 git 仓库里、配置关掉了)时,shell 命令改了什么无从得知,撤销不了;这一轮跑过时提醒一句 */
20
21
  const SHELL_NOTE = "This turn also ran shell commands; what they changed is not undone.";
22
+ /** 拍工作区快照的时限;过了这一轮就没有快照(不影响命令执行) */
23
+ const SNAPSHOT_TIMEOUT_MS = 60_000;
24
+ /** 对话框和结果里最多列出这么多个文件 */
25
+ const MAX_LISTED = 30;
21
26
 
22
- const notes = new Notes();
27
+ /** 比较两个路径是不是同一个文件用的写法:git 给的和工具参数里的大小写、斜杠、短文件名可能不同 */
28
+ function same(p: string): string {
29
+ const full = path.join(realPath(path.dirname(p)), path.basename(p));
30
+ return process.platform === "win32" ? full.toLowerCase() : full;
31
+ }
23
32
 
24
33
  /** 显示用:工作目录内的路径用相对形式,统一为正斜杠 */
25
34
  function display(cwd: string, full: string): string {
@@ -52,33 +61,62 @@ export default definePlugin({
52
61
  const cwd = realPath(ctx.cwd);
53
62
  ctx.service<Commands>("commands@1")?.register({
54
63
  name: "undo",
55
- description: "restore the files the agent wrote or edited in its last turn, not changes made by shell commands (run again to go further back)",
64
+ description: "restore the files the agent changed in its last turn; in a git repository that includes what its shell commands changed (run again to go further back)",
56
65
  async run(_args, { sessions, ui, signal }) {
57
66
  const s = sessions.current;
58
67
  if (!s) return "No session is open.";
68
+ const snapshots = new Snapshots(path.join(ctx.home, "checkpoints", safe(s.id)), ctx.cwd);
59
69
  const undone = await checkpoints.undone(s.id);
60
- const cps = lastTurnChanges(s.state.messages, await checkpoints.list(s.id), undone);
61
- if (cps.length === 0) return dim(turnToolNames(s.state.messages).has("bash") ? `Nothing to undo. ${SHELL_NOTE}` : "Nothing to undo.");
62
- const shellToo = turnToolNames(s.state.messages, cps[0]!.toolUseId).has("bash");
70
+ const snaps = await snapshots.list();
71
+ const entries = [...(await checkpoints.list(s.id)), ...snaps].sort((x, y) => y.at - x.at);
72
+ /** 这一轮文件工具的快照(最新的在前)、命令之前的工作区快照、工作区在那之后变了的文件 */
73
+ let cps: Checkpoint[];
74
+ let snap: Snapshot | undefined;
75
+ let tree: Change[];
76
+ for (;;) {
77
+ const hits = lastTurnChanges<Checkpoint | Snapshot>(s.state.messages, entries, undone);
78
+ cps = hits.filter((h): h is Checkpoint => "path" in h);
79
+ snap = hits.find((h): h is Snapshot => "tree" in h);
80
+ tree = snap ? await snapshots.changed(snap.tree) : [];
81
+ if (!snap || cps.length > 0 || tree.length > 0) break;
82
+ // 命令什么都没改(或者已经改回去了)的一轮:没有可撤销的,看更早的一轮
83
+ undone.add(snap.toolUseId);
84
+ await checkpoints.markUndone(s.id, [snap.toolUseId]);
85
+ }
86
+ // 这个会话里拍到过快照,说明命令的改动撤销得了,不用提醒
87
+ if (cps.length === 0 && !snap) return dim(snaps.length === 0 && turnToolNames(s.state.messages).has("bash") ? `Nothing to undo. ${SHELL_NOTE}` : "Nothing to undo.");
88
+ // 没拍到快照(不在 git 仓库里、配置关掉了)的那一轮跑过命令时提醒一句
89
+ const shellToo = !snap && turnToolNames(s.state.messages, cps[0]!.toolUseId).has("bash");
90
+ // 工作区快照覆盖到的文件按快照恢复(那是命令动它之前的内容):拍快照之后文件工具对它的修改不再单独恢复
91
+ const inTree = new Set(tree.map((c) => same(c.path)));
92
+ const fileCps = cps.filter((cp) => !(snap && cp.at > snap.at && inTree.has(same(cp.path))));
63
93
  /** 文件 → 这一轮最早的快照(恢复成它的 before);cps 是最新的在前 */
64
94
  const files = new Map<string, Checkpoint>();
65
- for (const cp of cps) files.set(cp.path, cp);
95
+ for (const cp of fileCps) files.set(cp.path, cp);
96
+ /** 要恢复的全部文件:路径 → 恢复之后还在不在。先按工作区快照,再按文件快照(它更早,说了算) */
97
+ const plan = new Map<string, { path: string; gone: boolean }>();
98
+ for (const c of tree) plan.set(same(c.path), { path: c.path, gone: c.added });
99
+ for (const cp of files.values()) plan.set(same(cp.path), { path: cp.path, gone: cp.before === null });
66
100
  // 恢复前就算好显示的名字:恢复时会删掉 agent 新建的文件。文件可能已经不在了(agent 删掉的):解析它所在的目录
67
- const shown = new Map([...files.keys()].map((p) => [p, display(cwd, path.join(realPath(path.dirname(p)), path.basename(p)))]));
101
+ const shown = new Map([...plan.values()].map((f) => [f.path, display(cwd, path.join(realPath(path.dirname(f.path)), path.basename(f.path)))]));
68
102
  const show = (p: string) => shown.get(p) ?? display(cwd, p);
69
103
  // 只有最新一次写入之后的内容能和文件现在的样子比较
70
104
  const latest = new Map<string, Checkpoint>();
71
- for (const cp of cps) if (!latest.has(cp.path)) latest.set(cp.path, cp);
105
+ for (const cp of fileCps) if (!latest.has(cp.path)) latest.set(cp.path, cp);
72
106
  const changed: string[] = [];
73
- for (const cp of latest.values()) if (!(await checkpoints.unchangedSince(cp))) changed.push(show(cp.path));
74
- const list = [...files.values()].map((cp) => ` ${cp.before === null ? "delete " : "restore"} ${show(cp.path)}`).join("\n");
75
- if (files.size > 1 || changed.length > 0) {
107
+ // 工作区快照之后变了的文件多半是命令改的,下面的问题里一起说明,不算"别人改过"
108
+ for (const cp of latest.values()) if (!inTree.has(same(cp.path)) && !(await checkpoints.unchangedSince(cp))) changed.push(show(cp.path));
109
+ const rows = [...plan.values()].map((f) => ` ${f.gone ? "delete " : "restore"} ${show(f.path)}`);
110
+ const list = rows.length > MAX_LISTED ? [...rows.slice(0, MAX_LISTED), ` … ${rows.length - MAX_LISTED} more`].join("\n") : rows.join("\n");
111
+ if (plan.size > 1 || changed.length > 0 || tree.length > 0) {
76
112
  const ok = await ui.select(
77
113
  {
78
114
  title:
79
115
  changed.length > 0
80
116
  ? `${changed.join(", ")} changed since the agent wrote ${changed.length > 1 ? "them" : "it"}. Undo anyway and discard those changes too?`
81
- : `Undo the agent's last turn of changes (${files.size} files)?`,
117
+ : tree.length > 0
118
+ ? `Undo the agent's last turn (${plan.size} file${plan.size > 1 ? "s" : ""})? It ran shell commands: these files go back to how they were before the first command, and edits you made to them since then are lost too.`
119
+ : `Undo the agent's last turn of changes (${plan.size} files)?`,
82
120
  detail: list,
83
121
  options: [
84
122
  { label: "No", value: "no" },
@@ -89,14 +127,15 @@ export default definePlugin({
89
127
  );
90
128
  if (ok !== "yes") return;
91
129
  }
130
+ if (snap) await snapshots.restore(snap.tree, tree);
92
131
  // 最新的先恢复:同一个文件最后恢复成这一轮最早的 before
93
- for (const cp of cps) await checkpoints.restore(cp);
94
- await checkpoints.markUndone(s.id, cps.map((c) => c.toolUseId));
95
- const what = [...files.values()].map((cp) =>
96
- cp.before === null ? `deleted ${show(cp.path)} (you had created it)` : `restored ${show(cp.path)} to its content before your changes`,
97
- );
98
- notes.add(s.id, `The user undid your changes from your last turn: ${what.join("; ")}. Read these files again before changing them.`);
99
- return green(`Undid ${cps.length} change${cps.length > 1 ? "s" : ""} from the last turn:`) + "\n" + dim(list) + (shellToo ? `\n${dim(SHELL_NOTE)}` : "");
132
+ for (const cp of fileCps) await checkpoints.restore(cp);
133
+ await checkpoints.markUndone(s.id, [...cps.map((c) => c.toolUseId), ...(snap ? [snap.toolUseId] : [])]);
134
+ const what = [...plan.values()].slice(0, MAX_LISTED).map((f) => (f.gone ? `deleted ${show(f.path)} (you had created it)` : `restored ${show(f.path)} to its content before your changes`));
135
+ if (plan.size > MAX_LISTED) what.push(`and ${plan.size - MAX_LISTED} more files`);
136
+ ctx.service<Prompts>("prompts@1")?.note(s.id, `The user undid your changes from your last turn: ${what.join("; ")}. Read these files again before changing them.`);
137
+ const title = snap ? `Undid the last turn (${plan.size} file${plan.size > 1 ? "s" : ""}):` : `Undid ${cps.length} change${cps.length > 1 ? "s" : ""} from the last turn:`;
138
+ return green(title) + "\n" + dim(list) + (shellToo ? `\n${dim(SHELL_NOTE)}` : "");
100
139
  },
101
140
  });
102
141
  },
@@ -106,6 +145,9 @@ export default definePlugin({
106
145
  const sessionId = ctx.session.id;
107
146
  /** toolUseId → 执行前的内容,执行成功后存成快照 */
108
147
  const before = new Map<string, { tool: string; path: string; before: string | null }>();
148
+ const snapshots = new Snapshots(path.join(ctx.home, "checkpoints", safe(sessionId)), ctx.cwd);
149
+ /** 这一轮已经拍过工作区快照 */
150
+ let snapped = false;
109
151
 
110
152
  ctx.kernel.hook({
111
153
  kind: "transform",
@@ -113,7 +155,16 @@ export default definePlugin({
113
155
  // 排在 jade/approval 把路径换成绝对路径之后;出错时只是没有快照,不影响工具执行
114
156
  order: 50,
115
157
  optional: true,
158
+ // 第一次给大仓库拍快照要把每个文件算一遍哈希
159
+ timeoutMs: SNAPSHOT_TIMEOUT_MS,
116
160
  fn: async (call) => {
161
+ // 每轮第一次跑命令之前给工作区拍一张快照:命令改了什么,/undo 时和它一比就知道
162
+ if (call.name === "bash" && ctx.config.shell !== false && !snapped) {
163
+ snapped = true;
164
+ const tree = await snapshots.take();
165
+ if (tree) await snapshots.save({ toolUseId: call.toolUseId, tree, at: performance.timeOrigin + performance.now() });
166
+ return;
167
+ }
117
168
  if (!WRITE_TOOLS.has(call.name)) return;
118
169
  const p = (call.input as { path?: unknown } | null)?.path;
119
170
  if (typeof p !== "string") return;
@@ -137,7 +188,14 @@ export default definePlugin({
137
188
  },
138
189
  });
139
190
  // 被拒绝、被中断的调用不经过 tool.after:一轮结束时还留着的都不会再用到,不然整个文件的内容一直占着内存
140
- ctx.kernel.hook({ kind: "observe", point: "event", fn: (e) => void (e.type === "turn.ended" && before.clear()) });
141
- ctx.kernel.hook(notes.hook(sessionId, ctx.plugin, ctx.plugin));
191
+ ctx.kernel.hook({
192
+ kind: "observe",
193
+ point: "event",
194
+ fn: (e) => {
195
+ if (e.type !== "turn.ended") return;
196
+ before.clear();
197
+ snapped = false;
198
+ },
199
+ });
142
200
  },
143
201
  });
@@ -1,7 +1,13 @@
1
1
  {
2
2
  "id": "jade/undo",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "optional": ["commands@1"]
6
+ "optional": ["commands@1", "prompts@1"],
7
+ "config": {
8
+ "shell": {
9
+ "default": true,
10
+ "description": "in a git repository, snapshot the working tree before the first shell command of each turn so that /undo also restores what the commands changed; false turns this off"
11
+ }
12
+ }
7
13
  }
@@ -0,0 +1,129 @@
1
+ // 工作区快照:shell 命令改了什么无从得知,所以每轮第一次跑命令之前给整个工作区拍一张快照,/undo 时把之后变了的文件恢复回去。
2
+ //
3
+ // 快照存在 $JADE_HOME 里的一个影子 git 仓库(<dir>/shadow/.git),工作区指向项目的仓库根目录:
4
+ // 项目自己的 .git(暂存区、提交、stash)一点不碰。只在 git 仓库里做:要靠 .gitignore 跳过 node_modules 这类目录,
5
+ // 对象库借用项目的(alternates),已经提交过的内容不再存一份。被忽略的文件不在快照里,撤销不了。
6
+ // 快照是 tree 对象,不建提交;哪一轮对应哪个 tree 记在 snapshots.json。
7
+
8
+ import { execFile } from "node:child_process";
9
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
10
+ import path from "node:path";
11
+
12
+ export interface Snapshot {
13
+ /** 这一轮第一次 bash 调用的 toolUseId:/undo 按它找到是哪一轮 */
14
+ toolUseId: string;
15
+ /** 影子仓库里的 tree */
16
+ tree: string;
17
+ /** 拍下的时间,和 Checkpoint.at 同一个钟 */
18
+ at: number;
19
+ }
20
+
21
+ /** 快照之后变了的一个文件。added:之后新出现的(撤销时删掉);其余的恢复成快照里的内容 */
22
+ export interface Change {
23
+ /** 绝对路径 */
24
+ path: string;
25
+ added: boolean;
26
+ }
27
+
28
+ const FILE = "snapshots.json";
29
+ /** 一次 git 命令最多带这么多路径:Windows 的命令行长度有限 */
30
+ const CHUNK = 100;
31
+
32
+ export class Snapshots {
33
+ readonly #dir: string;
34
+ readonly #cwd: string;
35
+ /** 影子仓库准备好之后的 git 环境;不在 git 仓库里(或没有 git)时 undefined */
36
+ #ready: Promise<{ env: NodeJS.ProcessEnv; root: string } | undefined> | undefined;
37
+
38
+ /** dir:这个会话的快照目录;cwd:会话的工作目录 */
39
+ constructor(dir: string, cwd: string) {
40
+ this.#dir = dir;
41
+ this.#cwd = cwd;
42
+ }
43
+
44
+ #prepare(): Promise<{ env: NodeJS.ProcessEnv; root: string } | undefined> {
45
+ return (this.#ready ??= (async () => {
46
+ let root: string;
47
+ let objects: string;
48
+ try {
49
+ root = path.resolve((await git(["rev-parse", "--show-toplevel"], { cwd: this.#cwd })).trim());
50
+ objects = path.resolve(this.#cwd, (await git(["rev-parse", "--git-common-dir"], { cwd: this.#cwd })).trim(), "objects");
51
+ } catch {
52
+ return undefined;
53
+ }
54
+ const shadow = path.join(this.#dir, "shadow");
55
+ const gitDir = path.join(shadow, ".git");
56
+ const env: NodeJS.ProcessEnv = { ...process.env, GIT_DIR: gitDir, GIT_WORK_TREE: root };
57
+ delete env.GIT_INDEX_FILE;
58
+ try {
59
+ await readFile(path.join(gitDir, "HEAD"));
60
+ } catch {
61
+ await mkdir(shadow, { recursive: true });
62
+ await git(["init", "--quiet", shadow], { cwd: shadow });
63
+ // 原样存、原样取:不做换行转换,不跑 LFS 之类的 filter。info/attributes 比工作区里的 .gitattributes 优先
64
+ await mkdir(path.join(gitDir, "info"), { recursive: true });
65
+ await writeFile(path.join(gitDir, "info", "attributes"), "* -text -eol -filter -ident -working-tree-encoding\n");
66
+ await writeFile(path.join(gitDir, "objects", "info", "alternates"), `${objects.split(path.sep).join("/")}\n`);
67
+ for (const [k, v] of [["core.autocrlf", "false"], ["core.safecrlf", "false"], ["core.longpaths", "true"], ["gc.auto", "0"]]) {
68
+ await git(["config", k!, v!], { cwd: root, env });
69
+ }
70
+ }
71
+ return { env, root };
72
+ })());
73
+ }
74
+
75
+ /** 给工作区拍一张快照,返回 tree;不在 git 仓库里时 undefined */
76
+ async take(): Promise<string | undefined> {
77
+ const r = await this.#prepare();
78
+ if (!r) return undefined;
79
+ await git(["add", "-A", "--ignore-errors", "."], { cwd: r.root, env: r.env }).catch(() => {
80
+ // 有的文件加不进去(被别的程序锁着、嵌套的仓库):其余的照样拍
81
+ });
82
+ return (await git(["write-tree"], { cwd: r.root, env: r.env })).trim();
83
+ }
84
+
85
+ /** 工作区现在和快照 tree 相比变了的文件 */
86
+ async changed(tree: string): Promise<Change[]> {
87
+ const r = await this.#prepare();
88
+ const now = await this.take();
89
+ if (!r || !now || now === tree) return [];
90
+ const out = await git(["diff-tree", "-r", "--no-renames", "--name-status", "-z", tree, now], { cwd: r.root, env: r.env });
91
+ const parts = out.split("\0");
92
+ const changes: Change[] = [];
93
+ for (let i = 0; i + 1 < parts.length; i += 2) changes.push({ path: path.join(r.root, parts[i + 1]!), added: parts[i] === "A" });
94
+ return changes;
95
+ }
96
+
97
+ /** 把这些文件恢复成快照 tree 里的样子:之后新出现的删掉,其余的取回 */
98
+ async restore(tree: string, changes: readonly Change[]): Promise<void> {
99
+ const r = await this.#prepare();
100
+ if (!r) return;
101
+ for (const c of changes) if (c.added) await rm(c.path, { force: true });
102
+ const back = changes.filter((c) => !c.added).map((c) => path.relative(r.root, c.path).split(path.sep).join("/"));
103
+ for (let i = 0; i < back.length; i += CHUNK) {
104
+ await git(["--literal-pathspecs", "checkout", tree, "--", ...back.slice(i, i + CHUNK)], { cwd: r.root, env: r.env });
105
+ }
106
+ }
107
+
108
+ /** 本会话记下的快照,最新的在前 */
109
+ async list(): Promise<Snapshot[]> {
110
+ try {
111
+ const all = JSON.parse(await readFile(path.join(this.#dir, FILE), "utf8")) as unknown;
112
+ return Array.isArray(all) ? (all as Snapshot[]).sort((a, b) => b.at - a.at) : [];
113
+ } catch {
114
+ return [];
115
+ }
116
+ }
117
+
118
+ async save(snapshot: Snapshot): Promise<void> {
119
+ const all = await this.list();
120
+ await mkdir(this.#dir, { recursive: true });
121
+ await writeFile(path.join(this.#dir, FILE), JSON.stringify([snapshot, ...all]));
122
+ }
123
+ }
124
+
125
+ function git(args: string[], opts: { cwd: string; env?: NodeJS.ProcessEnv }): Promise<string> {
126
+ return new Promise((resolve, reject) => {
127
+ execFile("git", args, { cwd: opts.cwd, env: opts.env, maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (err, stdout) => (err ? reject(err) : resolve(stdout)));
128
+ });
129
+ }
@@ -1,29 +1,25 @@
1
1
  // jade/update:启动时(每天最多一次)查 npm 上有没有更新的 jade,有就在后台升级,下次启动生效;
2
2
  // 配置 auto 为 false 或 JADE_AUTO_UPDATE=off 时只提示。仓库里的开发版和 npm link 既不提示也不升级。
3
- // 查询和升级都用核心的 src/update.ts,和 jade update 是同一套;不想要它就 jade plugins disable jade/update。
3
+ // 查询和升级经核心的 update@1 服务,和 jade update 是同一套;不想要它就 jade plugins disable jade/update。
4
4
 
5
- import { definePlugin, type UI } from "../../src/api.ts";
6
- import { autoUpdate, autoUpdateEnabled, detectInstall, newerVersion, VERSION, type Install } from "../../src/update.ts";
5
+ import { definePlugin, type UI, type Updater } from "@uncarved/jade-api";
7
6
 
8
7
  export interface CheckOptions {
9
- home: string;
8
+ /** 核心的 update@1 */
9
+ update: Updater;
10
10
  auto: boolean;
11
11
  notify: (message: string, level?: "info" | "warning") => void;
12
- install?: Install;
13
- /** 测试用 */
14
- latest?: () => Promise<string>;
15
- command?: string[];
16
12
  }
17
13
 
18
14
  /** 查一次,按结果提示;出什么错都不打扰用户 */
19
15
  export async function checkForUpdate(o: CheckOptions): Promise<void> {
20
- const install = o.install ?? detectInstall();
21
- if (install.kind === "dev") return;
22
- const latest = await newerVersion(o.home, o.latest ? { latest: o.latest } : {}).catch(() => undefined);
16
+ const { update } = o;
17
+ if (update.install === "dev") return;
18
+ const latest = await update.newer().catch(() => undefined);
23
19
  if (!latest) return;
24
- const manual = () => o.notify(`jade ${latest} is available (you have ${VERSION}); run jade update`);
25
- if (!o.auto || !autoUpdateEnabled()) return manual();
26
- const result = await autoUpdate(o.home, latest, { install, ...(o.command ? { command: o.command } : {}) }).catch(() => undefined);
20
+ const manual = () => o.notify(`jade ${latest} is available (you have ${update.version}); run jade update`);
21
+ if (!o.auto || !update.autoEnabled()) return manual();
22
+ const result = await update.upgrade(latest).catch(() => undefined);
27
23
  if (result?.status === "installed") o.notify(`jade ${latest} was installed in the background; restart jade to use it`);
28
24
  else if (result?.status === "failed") o.notify(`automatic update to jade ${latest} failed (see ${result.log}); run jade update`, "warning");
29
25
  else if (result?.status !== "skipped" || result.why !== "busy") manual();
@@ -35,6 +31,6 @@ export default definePlugin({
35
31
  // 不能提问的前端(jade -p)是脚本在用,不提示也不升级
36
32
  if (!ui?.interactive) return;
37
33
  // 作用域关闭后 ui 失效,再提示会抛错:那时也没人看了
38
- void checkForUpdate({ home: ctx.home, auto: ctx.config.auto !== false, notify: (m, level) => ui.notify(m, level) }).catch(() => {});
34
+ void checkForUpdate({ update: ctx.require<Updater>("update@1"), auto: ctx.config.auto !== false, notify: (m, level) => ui.notify(m, level) }).catch(() => {});
39
35
  },
40
36
  });
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "id": "jade/update",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
+ "requires": ["update@1"],
6
7
  "optional": ["ui@1"],
7
8
  "config": {
8
9
  "auto": {
@@ -5,11 +5,8 @@
5
5
  // 不用重开会话;会话的工具清单在创建时就定了。
6
6
 
7
7
  import path from "node:path";
8
- import { definePlugin, type ScopeContext, type UI } from "../../src/api.ts";
9
- import type { Commands } from "../commands/index.ts";
10
- import type { Prompts } from "../prompts/index.ts";
11
- import type { Renderers } from "../renderers/index.ts";
12
- import type { Task } from "../task/index.ts";
8
+ import { definePlugin, type ScopeContext, type UI } from "@uncarved/jade-api";
9
+ import type { Commands, Prompts, Renderers, Tools } from "@uncarved/jade-api/services";
13
10
  import { envWithFile, updateEnvFile, type Env } from "./env.ts";
14
11
  import { webRenderers } from "./renderers.ts";
15
12
  import { parseOrder, parseResults, SEARCH_PROVIDERS, webTools } from "./web.ts";
@@ -101,14 +98,14 @@ export default definePlugin({
101
98
  const web = webTools({ ...opts, env: () => keys ?? env });
102
99
  for (const tool of web.tools) ctx.kernel.tool(tool);
103
100
 
104
- // 子 Agent(jade/task)也能查网页:另一套实例;web_search 只在配置了搜索服务时给它。
105
- // web_fetch 带 url 参数,子 Agent 每次都要问用户(URL 能把读到的内容带出去)。
106
- // jade/task 被隔离时它的服务已失效:子 Agent 没有 web 工具,web 工具本身照常
101
+ // 嵌套 Agent(例如 jade/task 的子 Agent)也能查网页:另一套实例;web_search 只在配置了搜索服务时给它。
102
+ // web_fetch 带 url 参数,jade/task 的子 Agent 每次都要问用户(URL 能把读到的内容带出去)。
103
+ // jade/tools 被隔离时它的服务已失效:嵌套 Agent 没有 web 工具,web 工具本身照常
107
104
  try {
108
- const task = ctx.service<Task>("task@1");
109
- if (task) {
105
+ const shared = ctx.service<Tools>("tools@1");
106
+ if (shared) {
110
107
  const sub = webTools({ ...opts, env: () => keys ?? env });
111
- for (const tool of sub.tools) task.tool(tool, tool.name === "web_search" ? { when: () => sub.search().length > 0 } : {});
108
+ for (const tool of sub.tools) shared.register(tool, tool.name === "web_search" ? { when: () => sub.search().length > 0 } : {});
112
109
  }
113
110
  } catch {}
114
111
 
@@ -3,7 +3,7 @@
3
3
  "version": "0.3.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "optional": ["ui@1", "commands@1", "prompts@1", "renderers@1", "task@1"],
6
+ "optional": ["ui@1", "commands@1", "prompts@1", "renderers@1", "tools@1"],
7
7
  "config": {
8
8
  "search": {
9
9
  "description": "search services to use, in order: a list or comma-separated names (tinyfish, anysearch, tavily, exa, firecrawl, jina); default: every service with an API key. Keys are read from the environment and $JADE_HOME/.env (/search sets them). $JADE_SEARCH still works"
@@ -1,6 +1,6 @@
1
1
  // web_fetch、web_search 在对话里怎么显示(登记到 renderers@1)。从旧 jade 的 ui/renderers.ts 移植。
2
2
 
3
- import type { ToolRenderer } from "../renderers/index.ts";
3
+ import type { ToolRenderer } from "@uncarved/jade-api/services";
4
4
 
5
5
  const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
6
6
  const args = (input: unknown) => (input !== null && typeof input === "object" ? input : {}) as Record<string, unknown>;