@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,210 +1,203 @@
1
- // jade/undo:/undo 把模型上一轮改过的文件恢复原样(再执行一次撤销更早的一轮)。
2
- //
3
- // jade/fs 不再保存检查点,这里自己观察:tool.before 在 write_file / edit_file / multi_edit 执行前记下文件原来的内容,
4
- // tool.after 在执行成功后记下新内容的哈希,存成快照(checkpoint.ts)。tool.before 在审批之前执行,
5
- // 所以等用户批准期间别人对文件的改动会算进"原来的内容"。
6
- // shell 命令改的文件:在 git 仓库里,每轮第一次 bash 之前给工作区拍一张快照(snapshot.ts),撤销时把之后变了的文件恢复回去。
7
1
  import { readFile } from "node:fs/promises";
8
2
  import { realpathSync } from "node:fs";
9
3
  import path from "node:path";
10
4
  import { definePlugin } from "@uncarved/jade-api";
11
5
  import { Checkpoints, lastTurnChanges, safe, sha256, turnToolNames } from "./checkpoint.js";
12
6
  import { Snapshots } from "./snapshot.js";
13
- import { dim, green } from "./style.js";
14
- /** 会改文件、参数里有 path 的工具 */
15
- export const WRITE_TOOLS = new Set(["write_file", "edit_file", "multi_edit"]);
16
- /** 没有工作区快照(不在 git 仓库里、配置关掉了)时,shell 命令改了什么无从得知,撤销不了;这一轮跑过时提醒一句 */
7
+ import { dim, ok } from "./style.js";
17
8
  const SHELL_NOTE = "This turn also ran shell commands; what they changed is not undone.";
18
- /** 拍工作区快照的时限;过了这一轮就没有快照(不影响命令执行) */
19
- const SNAPSHOT_TIMEOUT_MS = 60_000;
20
- /** 对话框和结果里最多列出这么多个文件 */
9
+ const SNAPSHOT_TIMEOUT_MS = 60000;
21
10
  const MAX_LISTED = 30;
22
- /** 比较两个路径是不是同一个文件用的写法:git 给的和工具参数里的大小写、斜杠、短文件名可能不同 */
23
11
  function same(p) {
24
- const full = path.join(realPath(path.dirname(p)), path.basename(p));
25
- return process.platform === "win32" ? full.toLowerCase() : full;
12
+ const full = path.join(realPath(path.dirname(p)), path.basename(p));
13
+ return process.platform === "win32" ? full.toLowerCase() : full;
26
14
  }
27
- /** 显示用:工作目录内的路径用相对形式,统一为正斜杠 */
28
15
  function display(cwd, full) {
29
- const rel = path.relative(cwd, full);
30
- const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
31
- return shown.split(path.sep).join("/");
16
+ const rel = path.relative(cwd, full);
17
+ const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
18
+ return shown.split(path.sep).join("/");
32
19
  }
33
20
  function realPath(p) {
34
- try {
35
- return realpathSync.native(p);
36
- }
37
- catch {
38
- return path.resolve(p);
39
- }
21
+ try {
22
+ return realpathSync.native(p);
23
+ } catch {
24
+ return path.resolve(p);
25
+ }
40
26
  }
41
- /** 文件现在的内容;不存在时 null */
27
+ const decidedBy = new Map;
28
+ const links = new Map;
42
29
  async function contentOf(file) {
43
- try {
44
- return await readFile(file, "utf8");
45
- }
46
- catch (e) {
47
- if (e.code === "ENOENT")
48
- return null;
49
- throw e;
50
- }
30
+ try {
31
+ return await readFile(file, "utf8");
32
+ } catch (e) {
33
+ if (e.code === "ENOENT")
34
+ return null;
35
+ throw e;
36
+ }
51
37
  }
52
38
  export default definePlugin({
53
- process(ctx) {
54
- const checkpoints = new Checkpoints(path.join(ctx.home, "checkpoints"));
55
- const cwd = realPath(ctx.cwd);
56
- ctx.service("commands@1")?.register({
57
- name: "undo",
58
- 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)",
59
- async run(_args, { sessions, ui, signal }) {
60
- const s = sessions.current;
61
- if (!s)
62
- return "No session is open.";
63
- const snapshots = new Snapshots(path.join(ctx.home, "checkpoints", safe(s.id)), ctx.cwd);
64
- const undone = await checkpoints.undone(s.id);
65
- const snaps = await snapshots.list();
66
- const entries = [...(await checkpoints.list(s.id)), ...snaps].sort((x, y) => y.at - x.at);
67
- /** 这一轮文件工具的快照(最新的在前)、命令之前的工作区快照、工作区在那之后变了的文件 */
68
- let cps;
69
- let snap;
70
- let tree;
71
- for (;;) {
72
- const hits = lastTurnChanges(s.state.messages, entries, undone);
73
- cps = hits.filter((h) => "path" in h);
74
- snap = hits.find((h) => "tree" in h);
75
- tree = snap ? await snapshots.changed(snap.tree) : [];
76
- if (!snap || cps.length > 0 || tree.length > 0)
77
- break;
78
- // 命令什么都没改(或者已经改回去了)的一轮:没有可撤销的,看更早的一轮
79
- undone.add(snap.toolUseId);
80
- await checkpoints.markUndone(s.id, [snap.toolUseId]);
81
- }
82
- // 这个会话里拍到过快照,说明命令的改动撤销得了,不用提醒
83
- if (cps.length === 0 && !snap)
84
- return dim(snaps.length === 0 && turnToolNames(s.state.messages).has("bash") ? `Nothing to undo. ${SHELL_NOTE}` : "Nothing to undo.");
85
- // 没拍到快照(不在 git 仓库里、配置关掉了)的那一轮跑过命令时提醒一句
86
- const shellToo = !snap && turnToolNames(s.state.messages, cps[0].toolUseId).has("bash");
87
- // 工作区快照覆盖到的文件按快照恢复(那是命令动它之前的内容):拍快照之后文件工具对它的修改不再单独恢复
88
- const inTree = new Set(tree.map((c) => same(c.path)));
89
- const fileCps = cps.filter((cp) => !(snap && cp.at > snap.at && inTree.has(same(cp.path))));
90
- /** 文件 → 这一轮最早的快照(恢复成它的 before);cps 是最新的在前 */
91
- const files = new Map();
92
- for (const cp of fileCps)
93
- files.set(cp.path, cp);
94
- /** 要恢复的全部文件:路径 → 恢复之后还在不在。先按工作区快照,再按文件快照(它更早,说了算) */
95
- const plan = new Map();
96
- for (const c of tree)
97
- plan.set(same(c.path), { path: c.path, gone: c.added });
98
- for (const cp of files.values())
99
- plan.set(same(cp.path), { path: cp.path, gone: cp.before === null });
100
- // 恢复前就算好显示的名字:恢复时会删掉 agent 新建的文件。文件可能已经不在了(agent 删掉的):解析它所在的目录
101
- const shown = new Map([...plan.values()].map((f) => [f.path, display(cwd, path.join(realPath(path.dirname(f.path)), path.basename(f.path)))]));
102
- const show = (p) => shown.get(p) ?? display(cwd, p);
103
- // 只有最新一次写入之后的内容能和文件现在的样子比较
104
- const latest = new Map();
105
- for (const cp of fileCps)
106
- if (!latest.has(cp.path))
107
- latest.set(cp.path, cp);
108
- const changed = [];
109
- // 工作区快照之后变了的文件多半是命令改的,下面的问题里一起说明,不算"别人改过"
110
- for (const cp of latest.values())
111
- if (!inTree.has(same(cp.path)) && !(await checkpoints.unchangedSince(cp)))
112
- changed.push(show(cp.path));
113
- const rows = [...plan.values()].map((f) => ` ${f.gone ? "delete " : "restore"} ${show(f.path)}`);
114
- const list = rows.length > MAX_LISTED ? [...rows.slice(0, MAX_LISTED), ` … ${rows.length - MAX_LISTED} more`].join("\n") : rows.join("\n");
115
- if (plan.size > 1 || changed.length > 0 || tree.length > 0) {
116
- const ok = await ui.select({
117
- title: changed.length > 0
118
- ? `${changed.join(", ")} changed since the agent wrote ${changed.length > 1 ? "them" : "it"}. Undo anyway and discard those changes too?`
119
- : tree.length > 0
120
- ? `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.`
121
- : `Undo the agent's last turn of changes (${plan.size} files)?`,
122
- detail: list,
123
- options: [
124
- { label: "No", value: "no" },
125
- { label: changed.length > 0 ? "Yes, undo anyway" : "Yes, undo", value: "yes" },
126
- ],
127
- }, signal);
128
- if (ok !== "yes")
129
- return;
130
- }
131
- if (snap)
132
- await snapshots.restore(snap.tree, tree);
133
- // 最新的先恢复:同一个文件最后恢复成这一轮最早的 before
134
- for (const cp of fileCps)
135
- await checkpoints.restore(cp);
136
- await checkpoints.markUndone(s.id, [...cps.map((c) => c.toolUseId), ...(snap ? [snap.toolUseId] : [])]);
137
- 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`));
138
- if (plan.size > MAX_LISTED)
139
- what.push(`and ${plan.size - MAX_LISTED} more files`);
140
- ctx.service("prompts@1")?.note(s.id, `The user undid your changes from your last turn: ${what.join("; ")}. Read these files again before changing them.`);
141
- 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:`;
142
- return green(title) + "\n" + dim(list) + (shellToo ? `\n${dim(SHELL_NOTE)}` : "");
143
- },
144
- });
145
- },
146
- session(ctx) {
147
- const checkpoints = new Checkpoints(path.join(ctx.home, "checkpoints"));
148
- const sessionId = ctx.session.id;
149
- /** toolUseId → 执行前的内容,执行成功后存成快照 */
150
- const before = new Map();
151
- const snapshots = new Snapshots(path.join(ctx.home, "checkpoints", safe(sessionId)), ctx.cwd);
152
- /** 这一轮已经拍过工作区快照 */
153
- let snapped = false;
154
- ctx.kernel.hook({
155
- kind: "transform",
156
- point: "tool.before",
157
- // 排在 jade/approval 把路径换成绝对路径之后;出错时只是没有快照,不影响工具执行
158
- order: 50,
159
- optional: true,
160
- // 第一次给大仓库拍快照要把每个文件算一遍哈希
161
- timeoutMs: SNAPSHOT_TIMEOUT_MS,
162
- fn: async (call) => {
163
- // 每轮第一次跑命令之前给工作区拍一张快照:命令改了什么,/undo 时和它一比就知道
164
- if (call.name === "bash" && ctx.config.shell !== false && !snapped) {
165
- snapped = true;
166
- const tree = await snapshots.take();
167
- if (tree)
168
- await snapshots.save({ toolUseId: call.toolUseId, tree, at: performance.timeOrigin + performance.now() });
169
- return;
170
- }
171
- if (!WRITE_TOOLS.has(call.name))
172
- return;
173
- const p = call.input?.path;
174
- if (typeof p !== "string")
175
- return;
176
- const full = path.resolve(ctx.cwd, p);
177
- before.set(call.toolUseId, { tool: call.name, path: full, before: await contentOf(full) });
178
- },
179
- });
180
- ctx.kernel.hook({
181
- kind: "transform",
182
- point: "tool.after",
183
- optional: true,
184
- fn: async (out) => {
185
- const snap = before.get(out.call.toolUseId);
186
- if (!snap)
187
- return;
188
- before.delete(out.call.toolUseId);
189
- if (out.isError)
190
- return;
191
- const after = await contentOf(snap.path);
192
- // 内容没变(例如同样的内容重复写入)不算修改
193
- if (after === snap.before)
194
- return;
195
- await checkpoints.save(sessionId, { toolUseId: out.call.toolUseId, ...snap, afterHash: sha256(after ?? "") });
196
- },
197
- });
198
- // 被拒绝、被中断的调用不经过 tool.after:一轮结束时还留着的都不会再用到,不然整个文件的内容一直占着内存
199
- ctx.kernel.hook({
200
- kind: "observe",
201
- point: "event",
202
- fn: (e) => {
203
- if (e.type !== "turn.ended")
204
- return;
205
- before.clear();
206
- snapped = false;
207
- },
208
- });
209
- },
39
+ process(ctx) {
40
+ const checkpoints = new Checkpoints(path.join(ctx.home, "checkpoints"));
41
+ const cwd = realPath(ctx.cwd);
42
+ ctx.service("commands@1")?.register({
43
+ name: "undo",
44
+ 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)",
45
+ async run(_args, { sessions, ui, signal }) {
46
+ const s = sessions.current;
47
+ if (!s)
48
+ return "No session is open.";
49
+ const snapshots = new Snapshots(path.join(ctx.home, "checkpoints", safe(s.id)), ctx.cwd);
50
+ const undone = await checkpoints.undone(s.id);
51
+ const snaps = await snapshots.list();
52
+ const entries = [...await checkpoints.list(s.id), ...snaps].sort((x, y) => y.at - x.at);
53
+ let cps;
54
+ let snap;
55
+ let tree;
56
+ for (;; ) {
57
+ const hits = lastTurnChanges(s.state.messages, entries, undone);
58
+ cps = hits.filter((h) => ("path" in h));
59
+ snap = hits.find((h) => ("tree" in h));
60
+ tree = snap ? await snapshots.changed(snap.tree) : [];
61
+ if (!snap || cps.length > 0 || tree.length > 0)
62
+ break;
63
+ undone.add(snap.toolUseId);
64
+ await checkpoints.markUndone(s.id, [snap.toolUseId]);
65
+ }
66
+ const ranShell = (names) => [...names].some((n) => s.tool(n)?.meta?.shell !== undefined);
67
+ if (cps.length === 0 && !snap)
68
+ return dim(snaps.length === 0 && ranShell(turnToolNames(s.state.messages)) ? `Nothing to undo. ${SHELL_NOTE}` : "Nothing to undo.");
69
+ const shellToo = !snap && ranShell(turnToolNames(s.state.messages, cps[0].toolUseId));
70
+ const inTree = new Set(tree.map((c) => same(c.path)));
71
+ const fileCps = cps.filter((cp) => !(snap && cp.at > snap.at && inTree.has(same(cp.path))));
72
+ const files = new Map;
73
+ for (const cp of fileCps)
74
+ files.set(cp.path, cp);
75
+ const plan = new Map;
76
+ for (const c of tree)
77
+ plan.set(same(c.path), { path: c.path, gone: c.added });
78
+ for (const cp of files.values())
79
+ plan.set(same(cp.path), { path: cp.path, gone: cp.before === null });
80
+ const shown = new Map([...plan.values()].map((f) => [f.path, display(cwd, path.join(realPath(path.dirname(f.path)), path.basename(f.path)))]));
81
+ const show = (p) => shown.get(p) ?? display(cwd, p);
82
+ const latest = new Map;
83
+ for (const cp of fileCps)
84
+ if (!latest.has(cp.path))
85
+ latest.set(cp.path, cp);
86
+ const changed = [];
87
+ for (const cp of latest.values())
88
+ if (!inTree.has(same(cp.path)) && !await checkpoints.unchangedSince(cp))
89
+ changed.push(show(cp.path));
90
+ const rows = [...plan.values()].map((f) => ` ${f.gone ? "delete " : "restore"} ${show(f.path)}`);
91
+ const list = rows.length > MAX_LISTED ? [...rows.slice(0, MAX_LISTED), ` … ${rows.length - MAX_LISTED} more`].join(`
92
+ `) : rows.join(`
93
+ `);
94
+ if (plan.size > 1 || changed.length > 0 || tree.length > 0) {
95
+ const ok = await ui.select({
96
+ title: changed.length > 0 ? `${changed.join(", ")} changed since the agent wrote ${changed.length > 1 ? "them" : "it"}. Undo anyway and discard those changes too?` : tree.length > 0 ? `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.` : `Undo the agent's last turn of changes (${plan.size} files)?`,
97
+ detail: list,
98
+ options: [
99
+ { label: "No", value: "no" },
100
+ { label: changed.length > 0 ? "Yes, undo anyway" : "Yes, undo", value: "yes" }
101
+ ]
102
+ }, signal);
103
+ if (ok !== "yes")
104
+ return;
105
+ }
106
+ if (snap)
107
+ await snapshots.restore(snap.tree, tree);
108
+ for (const cp of fileCps)
109
+ await checkpoints.restore(cp);
110
+ await checkpoints.markUndone(s.id, [...cps.map((c) => c.toolUseId), ...snap ? [snap.toolUseId] : []]);
111
+ 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`);
112
+ if (plan.size > MAX_LISTED)
113
+ what.push(`and ${plan.size - MAX_LISTED} more files`);
114
+ ctx.service("prompts@1")?.note(s.id, `The user undid your changes from your last turn: ${what.join("; ")}. Read these files again before changing them.`);
115
+ 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:`;
116
+ return [ok(title), `
117
+ `, dim(list), ...shellToo ? [`
118
+ `, dim(SHELL_NOTE)] : []];
119
+ }
120
+ });
121
+ },
122
+ session(ctx) {
123
+ const checkpoints = new Checkpoints(path.join(ctx.home, "checkpoints"));
124
+ const sessionId = ctx.session.id;
125
+ const decided = new Map;
126
+ decidedBy.set(sessionId, decided);
127
+ const link = () => {
128
+ const p = ctx.session.parent;
129
+ if (!p)
130
+ return { root: sessionId };
131
+ const up = links.get(p.sessionId)?.();
132
+ if (up?.via)
133
+ return up;
134
+ const via = decidedBy.get(p.sessionId)?.get(p.eventId);
135
+ return { root: up?.root ?? p.sessionId, ...via ? { via } : {} };
136
+ };
137
+ links.set(sessionId, link);
138
+ ctx.effect(() => () => {
139
+ if (decidedBy.get(sessionId) === decided)
140
+ decidedBy.delete(sessionId);
141
+ if (links.get(sessionId) === link)
142
+ links.delete(sessionId);
143
+ });
144
+ const before = new Map;
145
+ const snapshots = new Snapshots(path.join(ctx.home, "checkpoints", safe(sessionId)), ctx.cwd);
146
+ let snapped = false;
147
+ ctx.kernel.hook({
148
+ kind: "transform",
149
+ point: "tool.before",
150
+ order: 50,
151
+ optional: true,
152
+ timeoutMs: SNAPSHOT_TIMEOUT_MS,
153
+ fn: async (call) => {
154
+ const meta = ctx.session.tool(call.name)?.meta;
155
+ if (meta?.shell !== undefined && ctx.config.shell !== false && !snapped && !ctx.session.parent) {
156
+ snapped = true;
157
+ const tree = await snapshots.take();
158
+ if (tree)
159
+ await snapshots.save({ toolUseId: call.toolUseId, tree, at: performance.timeOrigin + performance.now() });
160
+ return;
161
+ }
162
+ if (meta?.writes === undefined)
163
+ return;
164
+ const p = call.input?.[meta.writes];
165
+ if (typeof p !== "string")
166
+ return;
167
+ const full = path.resolve(ctx.cwd, p);
168
+ before.set(call.toolUseId, { tool: call.name, path: full, before: await contentOf(full) });
169
+ }
170
+ });
171
+ ctx.kernel.hook({
172
+ kind: "transform",
173
+ point: "tool.after",
174
+ optional: true,
175
+ fn: async (out) => {
176
+ const snap = before.get(out.call.toolUseId);
177
+ if (!snap)
178
+ return;
179
+ before.delete(out.call.toolUseId);
180
+ if (out.isError)
181
+ return;
182
+ const after = await contentOf(snap.path);
183
+ if (after === snap.before)
184
+ return;
185
+ const { root, via } = link();
186
+ await checkpoints.save(root, { toolUseId: out.call.toolUseId, ...snap, afterHash: sha256(after ?? ""), ...via ? { via } : {} });
187
+ }
188
+ });
189
+ ctx.kernel.hook({
190
+ kind: "observe",
191
+ point: "event",
192
+ fn: (e) => {
193
+ if (e.type === "tool.decided")
194
+ decided.set(e.id, e.data.toolUseId);
195
+ if (e.type !== "turn.ended")
196
+ return;
197
+ before.clear();
198
+ decided.clear();
199
+ snapped = false;
200
+ }
201
+ });
202
+ }
210
203
  });
@@ -1,111 +1,95 @@
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
1
  import { execFile } from "node:child_process";
8
2
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
9
3
  import path from "node:path";
10
4
  const FILE = "snapshots.json";
11
- /** 一次 git 命令最多带这么多路径:Windows 的命令行长度有限 */
12
5
  const CHUNK = 100;
6
+
13
7
  export class Snapshots {
14
- #dir;
15
- #cwd;
16
- /** 影子仓库准备好之后的 git 环境;不在 git 仓库里(或没有 git)时 undefined */
17
- #ready;
18
- /** dir:这个会话的快照目录;cwd:会话的工作目录 */
19
- constructor(dir, cwd) {
20
- this.#dir = dir;
21
- this.#cwd = cwd;
22
- }
23
- #prepare() {
24
- return (this.#ready ??= (async () => {
25
- let root;
26
- let objects;
27
- try {
28
- root = path.resolve((await git(["rev-parse", "--show-toplevel"], { cwd: this.#cwd })).trim());
29
- objects = path.resolve(this.#cwd, (await git(["rev-parse", "--git-common-dir"], { cwd: this.#cwd })).trim(), "objects");
30
- }
31
- catch {
32
- return undefined;
33
- }
34
- const shadow = path.join(this.#dir, "shadow");
35
- const gitDir = path.join(shadow, ".git");
36
- const env = { ...process.env, GIT_DIR: gitDir, GIT_WORK_TREE: root };
37
- delete env.GIT_INDEX_FILE;
38
- try {
39
- await readFile(path.join(gitDir, "HEAD"));
40
- }
41
- catch {
42
- await mkdir(shadow, { recursive: true });
43
- await git(["init", "--quiet", shadow], { cwd: shadow });
44
- // 原样存、原样取:不做换行转换,不跑 LFS 之类的 filter。info/attributes 比工作区里的 .gitattributes 优先
45
- await mkdir(path.join(gitDir, "info"), { recursive: true });
46
- await writeFile(path.join(gitDir, "info", "attributes"), "* -text -eol -filter -ident -working-tree-encoding\n");
47
- await writeFile(path.join(gitDir, "objects", "info", "alternates"), `${objects.split(path.sep).join("/")}\n`);
48
- for (const [k, v] of [["core.autocrlf", "false"], ["core.safecrlf", "false"], ["core.longpaths", "true"], ["gc.auto", "0"]]) {
49
- await git(["config", k, v], { cwd: root, env });
50
- }
51
- }
52
- return { env, root };
53
- })());
54
- }
55
- /** 给工作区拍一张快照,返回 tree;不在 git 仓库里时 undefined */
56
- async take() {
57
- const r = await this.#prepare();
58
- if (!r)
59
- return undefined;
60
- await git(["add", "-A", "--ignore-errors", "."], { cwd: r.root, env: r.env }).catch(() => {
61
- // 有的文件加不进去(被别的程序锁着、嵌套的仓库):其余的照样拍
62
- });
63
- return (await git(["write-tree"], { cwd: r.root, env: r.env })).trim();
64
- }
65
- /** 工作区现在和快照 tree 相比变了的文件 */
66
- async changed(tree) {
67
- const r = await this.#prepare();
68
- const now = await this.take();
69
- if (!r || !now || now === tree)
70
- return [];
71
- const out = await git(["diff-tree", "-r", "--no-renames", "--name-status", "-z", tree, now], { cwd: r.root, env: r.env });
72
- const parts = out.split("\0");
73
- const changes = [];
74
- for (let i = 0; i + 1 < parts.length; i += 2)
75
- changes.push({ path: path.join(r.root, parts[i + 1]), added: parts[i] === "A" });
76
- return changes;
77
- }
78
- /** 把这些文件恢复成快照 tree 里的样子:之后新出现的删掉,其余的取回 */
79
- async restore(tree, changes) {
80
- const r = await this.#prepare();
81
- if (!r)
82
- return;
83
- for (const c of changes)
84
- if (c.added)
85
- await rm(c.path, { force: true });
86
- const back = changes.filter((c) => !c.added).map((c) => path.relative(r.root, c.path).split(path.sep).join("/"));
87
- for (let i = 0; i < back.length; i += CHUNK) {
88
- await git(["--literal-pathspecs", "checkout", tree, "--", ...back.slice(i, i + CHUNK)], { cwd: r.root, env: r.env });
89
- }
90
- }
91
- /** 本会话记下的快照,最新的在前 */
92
- async list() {
93
- try {
94
- const all = JSON.parse(await readFile(path.join(this.#dir, FILE), "utf8"));
95
- return Array.isArray(all) ? all.sort((a, b) => b.at - a.at) : [];
96
- }
97
- catch {
98
- return [];
8
+ #dir;
9
+ #cwd;
10
+ #ready;
11
+ constructor(dir, cwd) {
12
+ this.#dir = dir;
13
+ this.#cwd = cwd;
14
+ }
15
+ #prepare() {
16
+ return this.#ready ??= (async () => {
17
+ let root;
18
+ let objects;
19
+ try {
20
+ root = path.resolve((await git(["rev-parse", "--show-toplevel"], { cwd: this.#cwd })).trim());
21
+ objects = path.resolve(this.#cwd, (await git(["rev-parse", "--git-common-dir"], { cwd: this.#cwd })).trim(), "objects");
22
+ } catch {
23
+ return;
24
+ }
25
+ const shadow = path.join(this.#dir, "shadow");
26
+ const gitDir = path.join(shadow, ".git");
27
+ const env = { ...process.env, GIT_DIR: gitDir, GIT_WORK_TREE: root };
28
+ delete env.GIT_INDEX_FILE;
29
+ try {
30
+ await readFile(path.join(gitDir, "HEAD"));
31
+ } catch {
32
+ await mkdir(shadow, { recursive: true });
33
+ await git(["init", "--quiet", shadow], { cwd: shadow });
34
+ await mkdir(path.join(gitDir, "info"), { recursive: true });
35
+ await writeFile(path.join(gitDir, "info", "attributes"), `* -text -eol -filter -ident -working-tree-encoding
36
+ `);
37
+ await writeFile(path.join(gitDir, "objects", "info", "alternates"), `${objects.split(path.sep).join("/")}
38
+ `);
39
+ for (const [k, v] of [["core.autocrlf", "false"], ["core.safecrlf", "false"], ["core.longpaths", "true"], ["gc.auto", "0"]]) {
40
+ await git(["config", k, v], { cwd: root, env });
99
41
  }
42
+ }
43
+ return { env, root };
44
+ })();
45
+ }
46
+ async take() {
47
+ const r = await this.#prepare();
48
+ if (!r)
49
+ return;
50
+ await git(["add", "-A", "--ignore-errors", "."], { cwd: r.root, env: r.env }).catch(() => {});
51
+ return (await git(["write-tree"], { cwd: r.root, env: r.env })).trim();
52
+ }
53
+ async changed(tree) {
54
+ const r = await this.#prepare();
55
+ const now = await this.take();
56
+ if (!r || !now || now === tree)
57
+ return [];
58
+ const out = await git(["diff-tree", "-r", "--no-renames", "--name-status", "-z", tree, now], { cwd: r.root, env: r.env });
59
+ const parts = out.split("\x00");
60
+ const changes = [];
61
+ for (let i = 0;i + 1 < parts.length; i += 2)
62
+ changes.push({ path: path.join(r.root, parts[i + 1]), added: parts[i] === "A" });
63
+ return changes;
64
+ }
65
+ async restore(tree, changes) {
66
+ const r = await this.#prepare();
67
+ if (!r)
68
+ return;
69
+ for (const c of changes)
70
+ if (c.added)
71
+ await rm(c.path, { force: true });
72
+ const back = changes.filter((c) => !c.added).map((c) => path.relative(r.root, c.path).split(path.sep).join("/"));
73
+ for (let i = 0;i < back.length; i += CHUNK) {
74
+ await git(["--literal-pathspecs", "checkout", tree, "--", ...back.slice(i, i + CHUNK)], { cwd: r.root, env: r.env });
100
75
  }
101
- async save(snapshot) {
102
- const all = await this.list();
103
- await mkdir(this.#dir, { recursive: true });
104
- await writeFile(path.join(this.#dir, FILE), JSON.stringify([snapshot, ...all]));
76
+ }
77
+ async list() {
78
+ try {
79
+ const all = JSON.parse(await readFile(path.join(this.#dir, FILE), "utf8"));
80
+ return Array.isArray(all) ? all.sort((a, b) => b.at - a.at) : [];
81
+ } catch {
82
+ return [];
105
83
  }
84
+ }
85
+ async save(snapshot) {
86
+ const all = await this.list();
87
+ await mkdir(this.#dir, { recursive: true });
88
+ await writeFile(path.join(this.#dir, FILE), JSON.stringify([snapshot, ...all]));
89
+ }
106
90
  }
107
91
  function git(args, opts) {
108
- return new Promise((resolve, reject) => {
109
- execFile("git", args, { cwd: opts.cwd, env: opts.env, maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (err, stdout) => (err ? reject(err) : resolve(stdout)));
110
- });
92
+ return new Promise((resolve, reject) => {
93
+ execFile("git", args, { cwd: opts.cwd, env: opts.env, maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (err, stdout) => err ? reject(err) : resolve(stdout));
94
+ });
111
95
  }
@@ -1,14 +1,9 @@
1
- // 显示用的小工具:截断和 ANSI 颜色。插件之间不共享代码(只能共享类型),所以这里也有一份(同 jade/fs 的 style.ts)。
2
- export const clip = (s, n) => (s.length > n ? s.slice(0, n) + "…" : s);
3
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色,见 https://no-color.org
4
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
5
- /**
6
- * 每种样式用自己的关闭码,不用 \x1b[0m 全部重置:外面套着别的样式时,后面的文字仍保持外层样式。
7
- * 里面出现同一个关闭码(例如 dim 里套 bold,两者都用 22 关闭)时紧接着重新打开外层的样式
8
- */
9
- const paint = (open, close) => (s) => colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
10
- export const dim = paint("2", "22");
11
- export const red = paint("31", "39");
12
- export const green = paint("32", "39");
13
- export const yellow = paint("33", "39");
14
- export const bold = paint("1", "22");
1
+ export const clip = (s, n) => s.length > n ? s.slice(0, n) + "…" : s;
2
+ const styled = (style) => (text) => ({ text, style });
3
+ export const dim = styled("dim");
4
+ export const bold = styled("bold");
5
+ export const ok = styled("ok");
6
+ export const warn = styled("warn");
7
+ export const error = styled("error");
8
+ export const lines = (rows) => rows.flatMap((r, i) => i ? [`
9
+ `, r] : [r]);