@uncarved/jade 0.3.1 → 0.4.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 (206) 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 +490 -29
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +36 -14
  14. package/plugins/approval/policy.ts +15 -10
  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 +42 -9
  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 +47 -12
  50. package/plugins/models/index.ts +27 -1
  51. package/plugins/models/provider.ts +24 -0
  52. package/plugins/models/saved.ts +1 -1
  53. package/plugins/modes/index.ts +13 -2
  54. package/plugins/print/index.ts +7 -4
  55. package/plugins/prompts/index.ts +0 -0
  56. package/plugins/renderers/index.ts +10 -5
  57. package/plugins/repeats/index.ts +8 -8
  58. package/plugins/schedule/index.ts +5 -1
  59. package/plugins/screenshot/browser.ts +10 -0
  60. package/plugins/sessions/index.ts +48 -2
  61. package/plugins/shell/index.ts +27 -28
  62. package/plugins/shell/plugin.json +1 -1
  63. package/plugins/shell/renderers.ts +9 -7
  64. package/plugins/shell/shell.ts +3 -1
  65. package/plugins/skills/index.ts +28 -19
  66. package/plugins/skills/project.ts +12 -7
  67. package/plugins/steer/index.ts +5 -4
  68. package/plugins/task/index.ts +80 -50
  69. package/plugins/task/plugin.json +6 -2
  70. package/plugins/task/style.ts +13 -14
  71. package/plugins/task/subagent.ts +67 -184
  72. package/plugins/todo/index.ts +39 -9
  73. package/plugins/tools/index.ts +9 -2
  74. package/plugins/tui/frontend.ts +139 -89
  75. package/plugins/tui/index.ts +2 -3
  76. package/plugins/tui/mentions.ts +11 -80
  77. package/plugins/tui/plugin.json +1 -1
  78. package/plugins/tui/screen.ts +55 -5
  79. package/plugins/tui/transcript.ts +17 -7
  80. package/plugins/tui/tui.ts +337 -101
  81. package/plugins/tui/vendor.ts +1 -1
  82. package/plugins/undo/checkpoint.ts +8 -4
  83. package/plugins/undo/index.ts +170 -31
  84. package/plugins/undo/plugin.json +1 -0
  85. package/plugins/undo/snapshot.ts +87 -14
  86. package/plugins/undo/style.ts +13 -14
  87. package/plugins/web/index.ts +7 -18
  88. package/plugins/web/plugin.json +1 -1
  89. package/plugins-dist/approval/index.js +363 -418
  90. package/plugins-dist/approval/policy.js +391 -508
  91. package/plugins-dist/approval/review.js +132 -158
  92. package/plugins-dist/approval/schema.js +50 -55
  93. package/plugins-dist/ask/index.js +115 -129
  94. package/plugins-dist/budget/index.js +27 -31
  95. package/plugins-dist/checks/checks.js +293 -329
  96. package/plugins-dist/checks/index.js +119 -139
  97. package/plugins-dist/checks/plugin.json +2 -1
  98. package/plugins-dist/checks/project.js +57 -65
  99. package/plugins-dist/commands/index.js +47 -29
  100. package/plugins-dist/compact/compact.js +233 -249
  101. package/plugins-dist/compact/index.js +98 -95
  102. package/plugins-dist/compact/style.js +9 -14
  103. package/plugins-dist/completions/index.js +30 -0
  104. package/plugins-dist/completions/plugin.json +9 -0
  105. package/plugins-dist/continue/index.js +40 -52
  106. package/plugins-dist/copy/index.js +40 -0
  107. package/plugins-dist/copy/plugin.json +9 -0
  108. package/plugins-dist/cost/index.js +98 -115
  109. package/plugins-dist/custom-commands/index.js +55 -72
  110. package/plugins-dist/editor/index.js +64 -72
  111. package/plugins-dist/fs/diff.js +111 -124
  112. package/plugins-dist/fs/fs.js +426 -469
  113. package/plugins-dist/fs/grep.js +262 -253
  114. package/plugins-dist/fs/index.js +20 -34
  115. package/plugins-dist/fs/plugin.json +1 -2
  116. package/plugins-dist/fs/renderers.js +100 -112
  117. package/plugins-dist/fs/style.js +11 -15
  118. package/plugins-dist/fs/sys.js +31 -43
  119. package/plugins-dist/hooks/index.js +107 -127
  120. package/plugins-dist/keys/index.js +27 -31
  121. package/plugins-dist/mcp/index.js +271 -199
  122. package/plugins-dist/mcp/install.js +123 -137
  123. package/plugins-dist/mcp/mcp.js +638 -577
  124. package/plugins-dist/mcp/plugin.json +3 -1
  125. package/plugins-dist/mcp/project.js +98 -115
  126. package/plugins-dist/memory/index.js +83 -88
  127. package/plugins-dist/memory/memory.js +111 -128
  128. package/plugins-dist/memory/style.js +9 -14
  129. package/plugins-dist/mentions/attach.js +91 -99
  130. package/plugins-dist/mentions/candidates.js +49 -0
  131. package/plugins-dist/mentions/index.js +71 -81
  132. package/plugins-dist/mentions/plugin.json +2 -1
  133. package/plugins-dist/mentions/style.js +9 -14
  134. package/plugins-dist/models/config.js +29 -43
  135. package/plugins-dist/models/configure.js +421 -474
  136. package/plugins-dist/models/context.js +14 -22
  137. package/plugins-dist/models/index.js +182 -189
  138. package/plugins-dist/models/provider.js +263 -307
  139. package/plugins-dist/models/saved.js +60 -72
  140. package/plugins-dist/modes/index.js +138 -165
  141. package/plugins-dist/plugins/index.js +34 -34
  142. package/plugins-dist/print/index.js +192 -175
  143. package/plugins-dist/prompts/index.js +86 -89
  144. package/plugins-dist/prompts/notes.js +31 -37
  145. package/plugins-dist/prompts/prompts.js +155 -193
  146. package/plugins-dist/prompts/results.js +40 -53
  147. package/plugins-dist/prompts/sys.js +39 -50
  148. package/plugins-dist/renderers/index.js +32 -32
  149. package/plugins-dist/repeats/index.js +131 -174
  150. package/plugins-dist/schedule/cron.js +49 -56
  151. package/plugins-dist/schedule/index.js +230 -247
  152. package/plugins-dist/schedule/store.js +93 -109
  153. package/plugins-dist/scratch/index.js +12 -18
  154. package/plugins-dist/screenshot/browser.js +136 -154
  155. package/plugins-dist/screenshot/index.js +37 -46
  156. package/plugins-dist/screenshot/sys.js +53 -65
  157. package/plugins-dist/screenshot/tool.js +98 -126
  158. package/plugins-dist/sessions/index.js +149 -117
  159. package/plugins-dist/shell/index.js +117 -135
  160. package/plugins-dist/shell/plugin.json +1 -1
  161. package/plugins-dist/shell/renderers.js +28 -33
  162. package/plugins-dist/shell/service.js +17 -23
  163. package/plugins-dist/shell/shell.js +307 -362
  164. package/plugins-dist/shell/sys.js +64 -79
  165. package/plugins-dist/skills/index.js +193 -211
  166. package/plugins-dist/skills/install.js +122 -149
  167. package/plugins-dist/skills/project.js +65 -73
  168. package/plugins-dist/skills/skills.js +135 -171
  169. package/plugins-dist/steer/index.js +108 -125
  170. package/plugins-dist/suggest/index.js +235 -259
  171. package/plugins-dist/task/index.js +130 -117
  172. package/plugins-dist/task/plugin.json +5 -2
  173. package/plugins-dist/task/style.js +9 -14
  174. package/plugins-dist/task/subagent.js +156 -279
  175. package/plugins-dist/todo/index.js +79 -63
  176. package/plugins-dist/tools/index.js +36 -42
  177. package/plugins-dist/tui/editor.js +145 -160
  178. package/plugins-dist/tui/frontend.js +639 -678
  179. package/plugins-dist/tui/history.js +34 -37
  180. package/plugins-dist/tui/index.js +16 -18
  181. package/plugins-dist/tui/markdown.js +203 -247
  182. package/plugins-dist/tui/mascot.js +266 -355
  183. package/plugins-dist/tui/mentions.js +67 -144
  184. package/plugins-dist/tui/plugin.json +1 -2
  185. package/plugins-dist/tui/render.js +35 -45
  186. package/plugins-dist/tui/screen.js +197 -180
  187. package/plugins-dist/tui/transcript.js +436 -468
  188. package/plugins-dist/tui/tui.js +1554 -1656
  189. package/plugins-dist/tui/vendor.js +1088 -1388
  190. package/plugins-dist/undo/checkpoint.js +97 -118
  191. package/plugins-dist/undo/index.js +281 -192
  192. package/plugins-dist/undo/plugin.json +3 -0
  193. package/plugins-dist/undo/snapshot.js +134 -99
  194. package/plugins-dist/undo/style.js +9 -14
  195. package/plugins-dist/update/index.js +26 -28
  196. package/plugins-dist/web/env.js +55 -68
  197. package/plugins-dist/web/index.js +80 -110
  198. package/plugins-dist/web/plugin.json +1 -2
  199. package/plugins-dist/web/renderers.js +4 -5
  200. package/plugins-dist/web/web.js +514 -593
  201. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  202. package/sdk/python/jade_plugin.py +9 -2
  203. package/src/api.ts +1 -1
  204. package/src/host.ts +39 -4
  205. package/src/remote.ts +6 -1
  206. package/src/session.ts +496 -36
@@ -1,210 +1,299 @@
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),撤销时把之后变了的文件恢复回去。
1
+ import { randomUUID } from "node:crypto";
7
2
  import { readFile } from "node:fs/promises";
8
3
  import { realpathSync } from "node:fs";
9
4
  import path from "node:path";
10
5
  import { definePlugin } from "@uncarved/jade-api";
11
6
  import { Checkpoints, lastTurnChanges, safe, sha256, turnToolNames } from "./checkpoint.js";
12
- 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 { snapshotsAt } from "./snapshot.js";
8
+ import { dim, ok } from "./style.js";
17
9
  const SHELL_NOTE = "This turn also ran shell commands; what they changed is not undone.";
18
- /** 拍工作区快照的时限;过了这一轮就没有快照(不影响命令执行) */
19
- const SNAPSHOT_TIMEOUT_MS = 60_000;
20
- /** 对话框和结果里最多列出这么多个文件 */
10
+ const SNAPSHOT_TIMEOUT_MS = 60000;
21
11
  const MAX_LISTED = 30;
22
- /** 比较两个路径是不是同一个文件用的写法:git 给的和工具参数里的大小写、斜杠、短文件名可能不同 */
23
12
  function same(p) {
24
- const full = path.join(realPath(path.dirname(p)), path.basename(p));
25
- return process.platform === "win32" ? full.toLowerCase() : full;
13
+ const full = path.join(realPath(path.dirname(p)), path.basename(p));
14
+ return process.platform === "win32" ? full.toLowerCase() : full;
26
15
  }
27
- /** 显示用:工作目录内的路径用相对形式,统一为正斜杠 */
28
16
  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("/");
17
+ const rel = path.relative(cwd, full);
18
+ const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
19
+ return shown.split(path.sep).join("/");
32
20
  }
33
21
  function realPath(p) {
34
- try {
35
- return realpathSync.native(p);
36
- }
37
- catch {
38
- return path.resolve(p);
39
- }
22
+ try {
23
+ return realpathSync.native(p);
24
+ } catch {
25
+ return path.resolve(p);
26
+ }
27
+ }
28
+ const decidedBy = new Map;
29
+ const links = new Map;
30
+ const turnSnaps = new Map;
31
+ const closing = new Map;
32
+ const now = () => performance.timeOrigin + performance.now();
33
+ const snapshotsOf = (home, sessionId, cwd) => snapshotsAt(path.join(home, "checkpoints", safe(sessionId)), cwd);
34
+ function closeTurn(root) {
35
+ const p = turnSnaps.get(root);
36
+ if (!p)
37
+ return;
38
+ turnSnaps.delete(root);
39
+ const done = p.then((r) => r?.snapshots.close(r.toolUseId)).catch(() => {});
40
+ closing.set(root, done);
41
+ return done;
40
42
  }
41
- /** 文件现在的内容;不存在时 null */
42
43
  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
- }
44
+ try {
45
+ return await readFile(file, "utf8");
46
+ } catch (e) {
47
+ if (e.code === "ENOENT")
48
+ return null;
49
+ throw e;
50
+ }
51
51
  }
52
52
  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
- },
53
+ process(ctx) {
54
+ const checkpoints = new Checkpoints(path.join(ctx.home, "checkpoints"));
55
+ const cwd = realPath(ctx.cwd);
56
+ ctx.provide("undo@1", {
57
+ async track(session, label, fn) {
58
+ if (ctx.config.shell === false)
59
+ return fn();
60
+ const snapshots = snapshotsOf(ctx.home, session, ctx.cwd);
61
+ await closing.get(session);
62
+ let id;
63
+ try {
64
+ const tree = await snapshots.take();
65
+ if (tree) {
66
+ id = `user-${randomUUID()}`;
67
+ await snapshots.save({ toolUseId: id, tree, label, at: now() });
68
+ }
69
+ } catch {}
70
+ try {
71
+ return await fn();
72
+ } finally {
73
+ if (id)
74
+ await snapshots.close(id).catch(() => {});
75
+ }
76
+ }
77
+ });
78
+ const shownName = (p) => display(cwd, path.join(realPath(path.dirname(p)), path.basename(p)));
79
+ const undoRun = async (sessionId, snapshots, run, { changes, conflicts }, ui, signal) => {
80
+ const shown = new Map(changes.map((c) => [c.path, shownName(c.path)]));
81
+ const rows = changes.map((c) => ` ${c.added ? "delete " : "restore"} ${shown.get(c.path)}`);
82
+ const list = rows.length > MAX_LISTED ? [...rows.slice(0, MAX_LISTED), ` … ${rows.length - MAX_LISTED} more`].join(`
83
+ `) : rows.join(`
84
+ `);
85
+ const changed = changes.filter((c) => conflicts.has(c.path)).map((c) => shown.get(c.path));
86
+ const files = `${changes.length} file${changes.length > 1 ? "s" : ""}`;
87
+ const answer = await ui.select({
88
+ title: changed.length > 0 ? `${changed.join(", ")} changed since your command ${run.label} ran. Undo it anyway and discard those changes too?` : `Undo your command ${run.label} (${files})?`,
89
+ detail: list,
90
+ options: [
91
+ { label: "No", value: "no" },
92
+ { label: changed.length > 0 ? "Yes, undo anyway" : "Yes, undo", value: "yes" }
93
+ ]
94
+ }, signal);
95
+ if (answer !== "yes")
96
+ return;
97
+ await snapshots.restore(run.tree, changes);
98
+ await checkpoints.markUndone(sessionId, [run.toolUseId]);
99
+ const what = changes.slice(0, MAX_LISTED).map((c) => c.added ? `deleted ${shown.get(c.path)} (the command had created it)` : `restored ${shown.get(c.path)}`);
100
+ if (changes.length > MAX_LISTED)
101
+ what.push(`and ${changes.length - MAX_LISTED} more files`);
102
+ ctx.service("prompts@1")?.note(sessionId, `The user undid what their own shell command ${run.label} changed: ${what.join("; ")}. Read these files again before changing them.`);
103
+ return [ok(`Undid your command ${run.label} (${files}):`), `
104
+ `, dim(list)];
105
+ };
106
+ ctx.service("commands@1")?.register({
107
+ name: "undo",
108
+ 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)",
109
+ async run(_args, { sessions, ui, signal }) {
110
+ const s = sessions.current;
111
+ if (!s)
112
+ return "No session is open.";
113
+ await closing.get(s.id);
114
+ const snapshots = snapshotsOf(ctx.home, s.id, ctx.cwd);
115
+ const undone = await checkpoints.undone(s.id);
116
+ const snaps = await snapshots.list();
117
+ const runs = snaps.filter((x) => x.label !== undefined);
118
+ const entries = [...await checkpoints.list(s.id), ...snaps.filter((x) => x.label === undefined)].sort((x, y) => y.at - x.at);
119
+ let cps = [];
120
+ let snap;
121
+ let tree = [];
122
+ let conflicts = new Set;
123
+ for (;; ) {
124
+ const hits = lastTurnChanges(s.state.messages, entries, undone);
125
+ const run = runs.find((r) => !undone.has(r.toolUseId));
126
+ if (run && (hits.length === 0 || run.at > Math.min(...hits.map((h) => h.at)))) {
127
+ const found = await snapshots.changes(run);
128
+ if (found.changes.length > 0)
129
+ return undoRun(s.id, snapshots, run, found, ui, signal);
130
+ undone.add(run.toolUseId);
131
+ await checkpoints.markUndone(s.id, [run.toolUseId]);
132
+ continue;
133
+ }
134
+ cps = hits.filter((h) => ("path" in h));
135
+ snap = hits.find((h) => ("tree" in h));
136
+ ({ changes: tree, conflicts } = snap ? await snapshots.changes(snap) : { changes: [], conflicts: new Set });
137
+ if (!snap || cps.length > 0 || tree.length > 0)
138
+ break;
139
+ undone.add(snap.toolUseId);
140
+ await checkpoints.markUndone(s.id, [snap.toolUseId]);
141
+ }
142
+ const ranShell = (names) => [...names].some((n) => s.tool(n)?.meta?.shell !== undefined);
143
+ if (cps.length === 0 && !snap)
144
+ return dim(snaps.length === 0 && ranShell(turnToolNames(s.state.messages)) ? `Nothing to undo. ${SHELL_NOTE}` : "Nothing to undo.");
145
+ const shellToo = !snap && ranShell(turnToolNames(s.state.messages, cps[0].toolUseId));
146
+ const inTree = new Set(tree.map((c) => same(c.path)));
147
+ const fileCps = cps.filter((cp) => !(snap && cp.at > snap.at && inTree.has(same(cp.path))));
148
+ const files = new Map;
149
+ for (const cp of fileCps)
150
+ files.set(cp.path, cp);
151
+ const plan = new Map;
152
+ for (const c of tree)
153
+ plan.set(same(c.path), { path: c.path, gone: c.added });
154
+ for (const cp of files.values())
155
+ plan.set(same(cp.path), { path: cp.path, gone: cp.before === null });
156
+ const shown = new Map([...plan.values()].map((f) => [f.path, display(cwd, path.join(realPath(path.dirname(f.path)), path.basename(f.path)))]));
157
+ const show = (p) => shown.get(p) ?? display(cwd, p);
158
+ const latest = new Map;
159
+ for (const cp of fileCps)
160
+ if (!latest.has(cp.path))
161
+ latest.set(cp.path, cp);
162
+ const changed = [];
163
+ for (const cp of latest.values())
164
+ if (!inTree.has(same(cp.path)) && !await checkpoints.unchangedSince(cp))
165
+ changed.push(show(cp.path));
166
+ for (const c of tree)
167
+ if (conflicts.has(c.path))
168
+ changed.push(show(c.path));
169
+ const rows = [...plan.values()].map((f) => ` ${f.gone ? "delete " : "restore"} ${show(f.path)}`);
170
+ const list = rows.length > MAX_LISTED ? [...rows.slice(0, MAX_LISTED), ` … ${rows.length - MAX_LISTED} more`].join(`
171
+ `) : rows.join(`
172
+ `);
173
+ if (plan.size > 1 || changed.length > 0 || tree.length > 0) {
174
+ const ok = await ui.select({
175
+ 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${snap?.after ? "." : ", and edits you made to them since then are lost too."}` : `Undo the agent's last turn of changes (${plan.size} files)?`,
176
+ detail: list,
177
+ options: [
178
+ { label: "No", value: "no" },
179
+ { label: changed.length > 0 ? "Yes, undo anyway" : "Yes, undo", value: "yes" }
180
+ ]
181
+ }, signal);
182
+ if (ok !== "yes")
183
+ return;
184
+ }
185
+ if (snap)
186
+ await snapshots.restore(snap.tree, tree);
187
+ for (const cp of fileCps)
188
+ await checkpoints.restore(cp);
189
+ await checkpoints.markUndone(s.id, [...cps.map((c) => c.toolUseId), ...snap ? [snap.toolUseId] : []]);
190
+ 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`);
191
+ if (plan.size > MAX_LISTED)
192
+ what.push(`and ${plan.size - MAX_LISTED} more files`);
193
+ 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.`);
194
+ 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:`;
195
+ return [ok(title), `
196
+ `, dim(list), ...shellToo ? [`
197
+ `, dim(SHELL_NOTE)] : []];
198
+ }
199
+ });
200
+ },
201
+ session(ctx) {
202
+ const checkpoints = new Checkpoints(path.join(ctx.home, "checkpoints"));
203
+ const sessionId = ctx.session.id;
204
+ const decided = new Map;
205
+ decidedBy.set(sessionId, decided);
206
+ const link = () => {
207
+ const p = ctx.session.parent;
208
+ if (!p)
209
+ return { root: sessionId };
210
+ const up = links.get(p.sessionId)?.();
211
+ if (up?.via)
212
+ return up;
213
+ const via = decidedBy.get(p.sessionId)?.get(p.eventId);
214
+ return { root: up?.root ?? p.sessionId, ...via ? { via } : {} };
215
+ };
216
+ links.set(sessionId, link);
217
+ ctx.effect(() => () => {
218
+ if (decidedBy.get(sessionId) === decided)
219
+ decidedBy.delete(sessionId);
220
+ if (links.get(sessionId) === link)
221
+ links.delete(sessionId);
222
+ if (!ctx.session.parent)
223
+ closeTurn(sessionId);
224
+ });
225
+ const before = new Map;
226
+ const beforeCommand = (toolUseId) => {
227
+ const { root, via } = link();
228
+ let p = turnSnaps.get(root);
229
+ if (!p) {
230
+ const snapshots = snapshotsOf(ctx.home, root, ctx.cwd);
231
+ p = (async () => {
232
+ await closing.get(root);
233
+ const tree = await snapshots.take();
234
+ if (!tree)
235
+ return;
236
+ await snapshots.save({ toolUseId, tree, at: now(), ...via ? { via } : {} });
237
+ return { snapshots, toolUseId };
238
+ })().catch(() => {
239
+ return;
208
240
  });
209
- },
241
+ turnSnaps.set(root, p);
242
+ }
243
+ return p;
244
+ };
245
+ ctx.kernel.hook({
246
+ kind: "transform",
247
+ point: "tool.before",
248
+ order: 50,
249
+ optional: true,
250
+ timeoutMs: SNAPSHOT_TIMEOUT_MS,
251
+ fn: async (call) => {
252
+ const meta = ctx.session.tool(call.name)?.meta;
253
+ if (meta?.shell !== undefined && ctx.config.shell !== false) {
254
+ await beforeCommand(call.toolUseId);
255
+ return;
256
+ }
257
+ if (meta?.writes === undefined)
258
+ return;
259
+ const p = call.input?.[meta.writes];
260
+ if (typeof p !== "string")
261
+ return;
262
+ const full = path.resolve(ctx.cwd, p);
263
+ before.set(call.toolUseId, { tool: call.name, path: full, before: await contentOf(full) });
264
+ }
265
+ });
266
+ ctx.kernel.hook({
267
+ kind: "transform",
268
+ point: "tool.after",
269
+ optional: true,
270
+ fn: async (out) => {
271
+ const snap = before.get(out.call.toolUseId);
272
+ if (!snap)
273
+ return;
274
+ before.delete(out.call.toolUseId);
275
+ if (out.isError)
276
+ return;
277
+ const after = await contentOf(snap.path);
278
+ if (after === snap.before)
279
+ return;
280
+ const { root, via } = link();
281
+ await checkpoints.save(root, { toolUseId: out.call.toolUseId, ...snap, afterHash: sha256(after ?? ""), ...via ? { via } : {} });
282
+ }
283
+ });
284
+ ctx.kernel.hook({
285
+ kind: "observe",
286
+ point: "event",
287
+ fn: (e) => {
288
+ if (e.type === "tool.decided")
289
+ decided.set(e.id, e.data.toolUseId);
290
+ if (e.type !== "turn.ended")
291
+ return;
292
+ before.clear();
293
+ decided.clear();
294
+ if (!ctx.session.parent)
295
+ return closeTurn(sessionId);
296
+ }
297
+ });
298
+ }
210
299
  });
@@ -3,6 +3,9 @@
3
3
  "version": "0.3.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.js",
6
+ "provides": [
7
+ "undo@1"
8
+ ],
6
9
  "optional": [
7
10
  "commands@1",
8
11
  "prompts@1"