@uncarved/jade 0.4.0 → 0.4.2
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.
- package/README.md +279 -278
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/session.js +16 -3
- package/dist/session.js.map +1 -1
- package/package.json +3 -3
- package/plugins/mentions/candidates.ts +14 -0
- package/plugins/mentions/index.ts +2 -2
- package/plugins/models/configure.ts +61 -3
- package/plugins/models/index.ts +62 -5
- package/plugins/models/plugin.json +1 -1
- package/plugins/models/provider.ts +55 -9
- package/plugins/models/saved.ts +1 -1
- package/plugins/prompts/index.ts +0 -0
- package/plugins/schedule/index.ts +3 -1
- package/plugins/screenshot/browser.ts +1 -1
- package/plugins/shell/index.ts +8 -4
- package/plugins/shell/plugin.json +2 -1
- package/plugins/shell/shell.ts +33 -7
- package/plugins/steer/index.ts +1 -1
- package/plugins/todo/index.ts +6 -10
- package/plugins/tui/frontend.ts +6 -2
- package/plugins/tui/markdown.ts +10 -8
- package/plugins/tui/mentions.ts +10 -0
- package/plugins/tui/transcript.ts +14 -17
- package/plugins/tui/tui.ts +13 -12
- package/plugins/tui/width.ts +240 -0
- package/plugins/undo/checkpoint.ts +3 -1
- package/plugins/undo/index.ts +132 -22
- package/plugins/undo/plugin.json +1 -0
- package/plugins/undo/snapshot.ts +87 -14
- package/plugins-dist/mentions/candidates.js +6 -0
- package/plugins-dist/mentions/index.js +2 -2
- package/plugins-dist/models/configure.js +51 -2
- package/plugins-dist/models/index.js +58 -4
- package/plugins-dist/models/plugin.json +2 -1
- package/plugins-dist/models/provider.js +43 -8
- package/plugins-dist/models/saved.js +1 -1
- package/plugins-dist/prompts/index.js +6 -1
- package/plugins-dist/schedule/index.js +1 -0
- package/plugins-dist/screenshot/browser.js +1 -1
- package/plugins-dist/shell/index.js +12 -10
- package/plugins-dist/shell/plugin.json +2 -1
- package/plugins-dist/shell/shell.js +21 -7
- package/plugins-dist/steer/index.js +1 -1
- package/plugins-dist/todo/index.js +3 -8
- package/plugins-dist/tui/frontend.js +5 -2
- package/plugins-dist/tui/markdown.js +11 -9
- package/plugins-dist/tui/mentions.js +6 -0
- package/plugins-dist/tui/transcript.js +9 -12
- package/plugins-dist/tui/tui.js +10 -9
- package/plugins-dist/tui/width.js +219 -0
- package/plugins-dist/undo/checkpoint.js +3 -1
- package/plugins-dist/undo/index.js +111 -15
- package/plugins-dist/undo/plugin.json +3 -0
- package/plugins-dist/undo/snapshot.js +62 -11
- package/src/api.ts +1 -1
- package/src/session.ts +13 -3
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// 显示宽度和折行的快路径。string-width / wrap-ansi 对每个非 ASCII 字符都要过 Intl.Segmenter 和 Unicode 属性正则,
|
|
2
|
+
// 中文一行要零点几毫秒(ASCII 的上百倍),长对话恢复、缩放、展开详情时会卡。
|
|
3
|
+
// 常用字符(ASCII、拉丁补充、标点符号、制表符、CJK、假名、谚文音节、全角)各自成一个字素簇,宽度可以逐个码点查表;
|
|
4
|
+
// 只含这些字符和 jade 自己的颜色码时走这里,结果和库逐字节一致(见 test/tui-width.test.ts),其余情况交回给库。
|
|
5
|
+
|
|
6
|
+
import stringWidth from "string-width";
|
|
7
|
+
import wrapAnsi from "wrap-ansi";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 不会和前后字符组成一个字素簇、NFC 规范化不改变的码点:组合附加符号、零宽字符、变体选择符、谚文字母、代理项都不在里面。
|
|
11
|
+
* 2329、232A 规范化后会变成 3008、3009,302A–302F、3099–309A 是组合附加符号。导出给测试用
|
|
12
|
+
*/
|
|
13
|
+
export function standalone(c: number): boolean {
|
|
14
|
+
if (c < 0x7f) return c >= 0x20;
|
|
15
|
+
if (c < 0x2010) return c >= 0xa0 && c <= 0xff && c !== 0xad;
|
|
16
|
+
if (c <= 0x2027) return true;
|
|
17
|
+
if (c >= 0x2030 && c <= 0x205e) return true;
|
|
18
|
+
if (c >= 0x2190 && c <= 0x27bf) return c !== 0x2329 && c !== 0x232a;
|
|
19
|
+
if (c >= 0x2e80 && c <= 0x2fdf) return true;
|
|
20
|
+
if (c >= 0x3000 && c <= 0x30ff) return !(c >= 0x302a && c <= 0x302f) && c !== 0x3099 && c !== 0x309a;
|
|
21
|
+
if (c >= 0x3100 && c <= 0x9fff) return true;
|
|
22
|
+
if (c >= 0xac00 && c <= 0xd7a3) return true;
|
|
23
|
+
return (c >= 0xff01 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** standalone 码点的宽度加一(0 表示还没算),按需用 string-width 算出来存着 */
|
|
27
|
+
const widths = new Uint8Array(0x10000);
|
|
28
|
+
function charWidth(c: number): number {
|
|
29
|
+
let w = widths[c]!;
|
|
30
|
+
if (w === 0) widths[c] = w = stringWidth(String.fromCharCode(c)) + 1;
|
|
31
|
+
return w - 1;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 颜色码:jade 的样式只用单个参数的 SGR(screen.ts 的 paint) */
|
|
35
|
+
const SGR = /\x1b\[(\d{1,2})m/y;
|
|
36
|
+
|
|
37
|
+
/** 从 i 开始的颜色码,返回它的参数和长度;不是 jade 用的那几种时返回 undefined */
|
|
38
|
+
function sgrAt(s: string, i: number): { code: number; length: number } | undefined {
|
|
39
|
+
SGR.lastIndex = i;
|
|
40
|
+
const m = SGR.exec(s);
|
|
41
|
+
if (!m) return undefined;
|
|
42
|
+
const code = Number(m[1]);
|
|
43
|
+
return CLOSE_OF.has(code) || RESETS.has(code) ? { code, length: m[0].length } : undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 样式码 → 关闭码(wrap-ansi 经 ansi-styles 得到的同一张表) */
|
|
47
|
+
const CLOSE_OF = new Map<number, number>([
|
|
48
|
+
[1, 22], [2, 22], [3, 23], [4, 24], [9, 29],
|
|
49
|
+
...[30, 31, 32, 33, 34, 35, 36, 37, 90, 91, 92, 93, 94, 95, 96, 97].map((c) => [c, 39] as [number, number]),
|
|
50
|
+
]);
|
|
51
|
+
const RESETS = new Set([22, 23, 24, 29, 39]);
|
|
52
|
+
|
|
53
|
+
/** 快路径能处理时的显示宽度(忽略颜色码),否则 undefined */
|
|
54
|
+
function fastWidth(s: string): number | undefined {
|
|
55
|
+
let w = 0;
|
|
56
|
+
for (let i = 0; i < s.length; i++) {
|
|
57
|
+
const c = s.charCodeAt(i);
|
|
58
|
+
if (c === 0x1b) {
|
|
59
|
+
const m = sgrAt(s, i);
|
|
60
|
+
if (!m) return undefined;
|
|
61
|
+
i += m.length - 1;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (!standalone(c)) return undefined;
|
|
65
|
+
w += c < 0x7f ? 1 : charWidth(c);
|
|
66
|
+
}
|
|
67
|
+
return w;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 显示宽度,和 string-width 一致 */
|
|
71
|
+
export function visibleWidth(s: string): number {
|
|
72
|
+
return fastWidth(s) ?? stringWidth(s);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface Token {
|
|
76
|
+
value: string;
|
|
77
|
+
width: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface Word {
|
|
81
|
+
tokens: Token[];
|
|
82
|
+
value: string;
|
|
83
|
+
width: number;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** 按空格拆成词;颜色码跟着所在的词。有快路径处理不了的字符时返回 undefined */
|
|
87
|
+
function words(line: string): Word[] | undefined {
|
|
88
|
+
let word: Word = { tokens: [], value: "", width: 0 };
|
|
89
|
+
const out = [word];
|
|
90
|
+
for (let i = 0; i < line.length; i++) {
|
|
91
|
+
const c = line.charCodeAt(i);
|
|
92
|
+
if (c === 0x20) {
|
|
93
|
+
word = { tokens: [], value: "", width: 0 };
|
|
94
|
+
out.push(word);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
let token: Token;
|
|
98
|
+
if (c === 0x1b) {
|
|
99
|
+
const m = sgrAt(line, i);
|
|
100
|
+
if (!m) return undefined;
|
|
101
|
+
token = { value: line.slice(i, i + m.length), width: 0 };
|
|
102
|
+
i += m.length - 1;
|
|
103
|
+
} else {
|
|
104
|
+
if (!standalone(c)) return undefined;
|
|
105
|
+
token = { value: line[i]!, width: c < 0x7f ? 1 : charWidth(c) };
|
|
106
|
+
}
|
|
107
|
+
word.tokens.push(token);
|
|
108
|
+
word.value += token.value;
|
|
109
|
+
word.width += token.width;
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** wrap-ansi 的 wrapWord:长词逐个字符往下排,返回最后一行的宽度 */
|
|
115
|
+
function wrapWord(rows: string[], tokens: Token[], columns: number, rowWidth: number): number {
|
|
116
|
+
let visible = rowWidth;
|
|
117
|
+
tokens.forEach((t, i) => {
|
|
118
|
+
if (t.width > 0 && visible > 0 && visible + t.width > columns) {
|
|
119
|
+
rows.push("");
|
|
120
|
+
visible = 0;
|
|
121
|
+
}
|
|
122
|
+
rows[rows.length - 1] += t.value;
|
|
123
|
+
visible += t.width;
|
|
124
|
+
if (visible === columns && i < tokens.length - 1) {
|
|
125
|
+
rows.push("");
|
|
126
|
+
visible = 0;
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
if (!visible && rows.at(-1)!.length > 0 && rows.length > 1) rows[rows.length - 2] += rows.pop()!;
|
|
130
|
+
return fastWidth(rows.at(-1)!)!;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
interface Style {
|
|
134
|
+
family: string;
|
|
135
|
+
open: number;
|
|
136
|
+
close: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** wrap-ansi 对一个样式码的处理:关闭码去掉对应的样式,打开码换掉同类的样式并排到最后 */
|
|
140
|
+
function applySgr(code: number, active: Style[], resetsOnly = false) {
|
|
141
|
+
if (code === 39) {
|
|
142
|
+
const i = active.findIndex((s) => s.family === "foreground");
|
|
143
|
+
if (i !== -1) active.splice(i, 1);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (RESETS.has(code)) {
|
|
147
|
+
for (let i = active.length - 1; i >= 0; i--) if (active[i]!.family.startsWith("modifier-") && active[i]!.close === code) active.splice(i, 1);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (resetsOnly) return;
|
|
151
|
+
const close = CLOSE_OF.get(code)!;
|
|
152
|
+
const family = close === 39 ? "foreground" : `modifier-${code}`;
|
|
153
|
+
const i = active.findIndex((s) => s.family === family);
|
|
154
|
+
if (i !== -1) active.splice(i, 1);
|
|
155
|
+
active.push({ family, open: code, close });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** wrap-ansi 的 restoreStylesAcrossRows:每个折行处先关掉还开着的样式,下一行开头再打开 */
|
|
159
|
+
function restoreStyles(s: string): string {
|
|
160
|
+
let out = "";
|
|
161
|
+
const active: Style[] = [];
|
|
162
|
+
let copied = 0;
|
|
163
|
+
let i = 0;
|
|
164
|
+
while (i < s.length) {
|
|
165
|
+
const c = s.charCodeAt(i);
|
|
166
|
+
if (c === 0x1b) {
|
|
167
|
+
const m = sgrAt(s, i)!;
|
|
168
|
+
applySgr(m.code, active);
|
|
169
|
+
i += m.length;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (c !== 0x0a) {
|
|
173
|
+
i++;
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
out += s.slice(copied, i);
|
|
177
|
+
if (i > copied) out += [...active].reverse().map((st) => `\x1b[${st.close}m`).join("");
|
|
178
|
+
out += "\n";
|
|
179
|
+
copied = ++i;
|
|
180
|
+
if (i < s.length && s[i] !== "\n") {
|
|
181
|
+
const opening = [...active];
|
|
182
|
+
for (let j = i, m = sgrAt(s, j); m; j += m.length, m = sgrAt(s, j)) applySgr(m.code, opening, true);
|
|
183
|
+
out += opening.map((st) => `\x1b[${st.open}m`).join("");
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return out + s.slice(copied);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** wrap-ansi 对一行(不含换行和制表符)的 hard、trim: false 折法;快路径处理不了时返回 undefined */
|
|
190
|
+
function fastWrap(line: string, columns: number): string[] | undefined {
|
|
191
|
+
const width = fastWidth(line);
|
|
192
|
+
if (width === undefined) return undefined;
|
|
193
|
+
if (width <= columns) return [line];
|
|
194
|
+
const list = words(line)!;
|
|
195
|
+
const rows = [""];
|
|
196
|
+
let rowLength = 0;
|
|
197
|
+
list.forEach((word, k) => {
|
|
198
|
+
if (k > 0) {
|
|
199
|
+
if (rowLength >= columns) {
|
|
200
|
+
rows.push("");
|
|
201
|
+
rowLength = 0;
|
|
202
|
+
}
|
|
203
|
+
rows[rows.length - 1] += " ";
|
|
204
|
+
rowLength++;
|
|
205
|
+
}
|
|
206
|
+
if (word.width > columns) {
|
|
207
|
+
const remaining = columns - rowLength;
|
|
208
|
+
const thisLine = 1 + Math.floor((word.width - remaining - 1) / columns);
|
|
209
|
+
const nextLine = Math.floor((word.width - 1) / columns);
|
|
210
|
+
if (nextLine < thisLine) {
|
|
211
|
+
rows.push("");
|
|
212
|
+
rowLength = 0;
|
|
213
|
+
}
|
|
214
|
+
rowLength = wrapWord(rows, word.tokens, columns, rowLength);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (rowLength + word.width > columns && rowLength > 0 && word.width > 0) {
|
|
218
|
+
rows.push("");
|
|
219
|
+
rowLength = 0;
|
|
220
|
+
}
|
|
221
|
+
rows[rows.length - 1] += word.value;
|
|
222
|
+
rowLength += word.width;
|
|
223
|
+
});
|
|
224
|
+
return line.includes("\x1b") ? restoreStyles(rows.join("\n")).split("\n") : rows;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const WRAP = { hard: true, trim: false } as const;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* 按原来的行分组折行:每一项是一个原来的行折成的若干行,连起来和 wrapAnsi(text, width, { hard: true, trim: false }).split("\n") 一样。
|
|
231
|
+
* text 里不能有制表符;有 \r 时(wrap-ansi 会把 \r\n 当成一个换行)返回 undefined
|
|
232
|
+
*/
|
|
233
|
+
export function wrapLines(text: string, width: number): string[][] | undefined {
|
|
234
|
+
if (text.includes("\r")) return undefined;
|
|
235
|
+
return text.split("\n").map((line) => fastWrap(line, width) ?? wrapAnsi(line, width, WRAP).split("\n"));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 和 wrapAnsi(text, width, { hard: true, trim: false }).split("\n") 一样,常用字符走快路径;text 里不能有制表符 */
|
|
239
|
+
export const wrapText = (text: string, width: number): string[] =>
|
|
240
|
+
wrapLines(text, width)?.flat() ?? wrapAnsi(text, width, WRAP).split("\n");
|
|
@@ -52,7 +52,9 @@ export class Checkpoints {
|
|
|
52
52
|
for (const n of names) {
|
|
53
53
|
if (!n.endsWith(".json") || n === UNDONE) continue;
|
|
54
54
|
try {
|
|
55
|
-
|
|
55
|
+
const cp = JSON.parse(await readFile(path.join(dir, n), "utf8")) as Partial<Checkpoint> | null;
|
|
56
|
+
// 同一个目录里还有别的文件(工作区快照的 snapshots.json):只认快照的样子
|
|
57
|
+
if (typeof cp?.toolUseId === "string" && typeof cp.path === "string" && typeof cp.at === "number") out.push(cp as Checkpoint);
|
|
56
58
|
} catch {
|
|
57
59
|
// 写到一半的快照,忽略
|
|
58
60
|
}
|
package/plugins/undo/index.ts
CHANGED
|
@@ -3,16 +3,19 @@
|
|
|
3
3
|
// jade/fs 不再保存检查点,这里自己观察:tool.before 在写文件的工具(meta.writes,例如 write_file)执行前记下文件原来的内容,
|
|
4
4
|
// tool.after 在执行成功后记下新内容的哈希,存成快照(checkpoint.ts)。tool.before 在审批之前执行,
|
|
5
5
|
// 所以等用户批准期间别人对文件的改动会算进"原来的内容"。
|
|
6
|
-
// shell 命令改的文件:在 git 仓库里,每轮第一次执行命令(meta.shell,例如 bash)之前给工作区拍一张快照(snapshot.ts
|
|
6
|
+
// shell 命令改的文件:在 git 仓库里,每轮第一次执行命令(meta.shell,例如 bash)之前给工作区拍一张快照(snapshot.ts),一轮结束时再拍一张,
|
|
7
|
+
// 撤销时把这两张之间变了的文件恢复回去。子 Agent 的命令算在根会话的这一轮里:整棵会话树一轮只在第一次跑命令之前拍一张。
|
|
8
|
+
// undo@1:用户自己执行的命令(/sh)前后各拍一张,单独算一步撤销。
|
|
7
9
|
// 认工具靠它注册时给的 meta,不认工具名:换掉提供文件工具的插件照样能撤销。
|
|
8
10
|
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
9
12
|
import { readFile } from "node:fs/promises";
|
|
10
13
|
import { realpathSync } from "node:fs";
|
|
11
14
|
import path from "node:path";
|
|
12
|
-
import { definePlugin } from "@uncarved/jade-api";
|
|
13
|
-
import type { Commands, Prompts } from "@uncarved/jade-api/services";
|
|
15
|
+
import { definePlugin, type UI } from "@uncarved/jade-api";
|
|
16
|
+
import type { Commands, Prompts, Undo } from "@uncarved/jade-api/services";
|
|
14
17
|
import { Checkpoints, lastTurnChanges, safe, sha256, turnToolNames, type Checkpoint } from "./checkpoint.ts";
|
|
15
|
-
import {
|
|
18
|
+
import { snapshotsAt, type Change, type Snapshot, type Snapshots } from "./snapshot.ts";
|
|
16
19
|
import { dim, ok } from "./style.ts";
|
|
17
20
|
|
|
18
21
|
/** 没有工作区快照(不在 git 仓库里、配置关掉了)时,shell 命令改了什么无从得知,撤销不了;这一轮跑过时提醒一句 */
|
|
@@ -47,6 +50,28 @@ function realPath(p: string): string {
|
|
|
47
50
|
const decidedBy = new Map<string, Map<string, string>>();
|
|
48
51
|
/** 打开着的会话:会话 id → 它的改动记在哪个根会话、算作根会话里哪次调用的 */
|
|
49
52
|
const links = new Map<string, () => { root: string; via?: string }>();
|
|
53
|
+
/** 根会话 id → 这一轮的工作区快照:整棵会话树(包括并行的子 Agent)第一次跑命令之前拍的那张。根会话这一轮结束时清掉 */
|
|
54
|
+
const turnSnaps = new Map<string, Promise<{ snapshots: Snapshots; toolUseId: string } | undefined>>();
|
|
55
|
+
/** 根会话 id → 正在给这一轮的快照补拍结束时的 tree:/undo、下一张快照先等它 */
|
|
56
|
+
const closing = new Map<string, Promise<void>>();
|
|
57
|
+
|
|
58
|
+
const now = () => performance.timeOrigin + performance.now();
|
|
59
|
+
/** 会话的工作区快照(子 Agent 的记在根会话里) */
|
|
60
|
+
const snapshotsOf = (home: string, sessionId: string, cwd: string) => snapshotsAt(path.join(home, "checkpoints", safe(sessionId)), cwd);
|
|
61
|
+
|
|
62
|
+
/** 根会话这一轮结束:拍过快照的话补上结束时的 tree。返回补拍完成 */
|
|
63
|
+
function closeTurn(root: string): Promise<void> | undefined {
|
|
64
|
+
const p = turnSnaps.get(root);
|
|
65
|
+
if (!p) return undefined;
|
|
66
|
+
turnSnaps.delete(root);
|
|
67
|
+
const done = p
|
|
68
|
+
.then((r) => r?.snapshots.close(r.toolUseId))
|
|
69
|
+
.catch(() => {
|
|
70
|
+
// 补拍不了:撤销时退回到和工作区现在的样子比
|
|
71
|
+
});
|
|
72
|
+
closing.set(root, done);
|
|
73
|
+
return done;
|
|
74
|
+
}
|
|
50
75
|
|
|
51
76
|
/** 文件现在的内容;不存在时 null */
|
|
52
77
|
async function contentOf(file: string): Promise<string | null> {
|
|
@@ -62,25 +87,92 @@ export default definePlugin({
|
|
|
62
87
|
process(ctx) {
|
|
63
88
|
const checkpoints = new Checkpoints(path.join(ctx.home, "checkpoints"));
|
|
64
89
|
const cwd = realPath(ctx.cwd);
|
|
90
|
+
ctx.provide("undo@1", {
|
|
91
|
+
async track(session, label, fn) {
|
|
92
|
+
if (ctx.config.shell === false) return fn();
|
|
93
|
+
const snapshots = snapshotsOf(ctx.home, session, ctx.cwd);
|
|
94
|
+
await closing.get(session);
|
|
95
|
+
let id: string | undefined;
|
|
96
|
+
try {
|
|
97
|
+
const tree = await snapshots.take();
|
|
98
|
+
if (tree) {
|
|
99
|
+
id = `user-${randomUUID()}`;
|
|
100
|
+
await snapshots.save({ toolUseId: id, tree, label, at: now() });
|
|
101
|
+
}
|
|
102
|
+
} catch {
|
|
103
|
+
// 拍不了快照:照样执行,只是撤销不了
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
return await fn();
|
|
107
|
+
} finally {
|
|
108
|
+
if (id) await snapshots.close(id).catch(() => {});
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
} satisfies Undo);
|
|
112
|
+
/** 文件的显示名:恢复前算好(恢复时会删掉新建的文件)。文件可能已经不在了:解析它所在的目录 */
|
|
113
|
+
const shownName = (p: string) => display(cwd, path.join(realPath(path.dirname(p)), path.basename(p)));
|
|
114
|
+
/** 撤销用户自己执行的命令(undo@1.track 记下的一步) */
|
|
115
|
+
const undoRun = async (sessionId: string, snapshots: Snapshots, run: Snapshot, { changes, conflicts }: { changes: Change[]; conflicts: Set<string> }, ui: UI, signal: AbortSignal) => {
|
|
116
|
+
const shown = new Map(changes.map((c) => [c.path, shownName(c.path)]));
|
|
117
|
+
const rows = changes.map((c) => ` ${c.added ? "delete " : "restore"} ${shown.get(c.path)}`);
|
|
118
|
+
const list = rows.length > MAX_LISTED ? [...rows.slice(0, MAX_LISTED), ` … ${rows.length - MAX_LISTED} more`].join("\n") : rows.join("\n");
|
|
119
|
+
const changed = changes.filter((c) => conflicts.has(c.path)).map((c) => shown.get(c.path)!);
|
|
120
|
+
const files = `${changes.length} file${changes.length > 1 ? "s" : ""}`;
|
|
121
|
+
const answer = await ui.select(
|
|
122
|
+
{
|
|
123
|
+
title:
|
|
124
|
+
changed.length > 0
|
|
125
|
+
? `${changed.join(", ")} changed since your command ${run.label} ran. Undo it anyway and discard those changes too?`
|
|
126
|
+
: `Undo your command ${run.label} (${files})?`,
|
|
127
|
+
detail: list,
|
|
128
|
+
options: [
|
|
129
|
+
{ label: "No", value: "no" },
|
|
130
|
+
{ label: changed.length > 0 ? "Yes, undo anyway" : "Yes, undo", value: "yes" },
|
|
131
|
+
],
|
|
132
|
+
},
|
|
133
|
+
signal,
|
|
134
|
+
);
|
|
135
|
+
if (answer !== "yes") return;
|
|
136
|
+
await snapshots.restore(run.tree, changes);
|
|
137
|
+
await checkpoints.markUndone(sessionId, [run.toolUseId]);
|
|
138
|
+
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)}`));
|
|
139
|
+
if (changes.length > MAX_LISTED) what.push(`and ${changes.length - MAX_LISTED} more files`);
|
|
140
|
+
ctx.service<Prompts>("prompts@1")?.note(sessionId, `The user undid what their own shell command ${run.label} changed: ${what.join("; ")}. Read these files again before changing them.`);
|
|
141
|
+
return [ok(`Undid your command ${run.label} (${files}):`), "\n", dim(list)];
|
|
142
|
+
};
|
|
65
143
|
ctx.service<Commands>("commands@1")?.register({
|
|
66
144
|
name: "undo",
|
|
67
145
|
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)",
|
|
68
146
|
async run(_args, { sessions, ui, signal }) {
|
|
69
147
|
const s = sessions.current;
|
|
70
148
|
if (!s) return "No session is open.";
|
|
71
|
-
|
|
149
|
+
await closing.get(s.id);
|
|
150
|
+
const snapshots = snapshotsOf(ctx.home, s.id, ctx.cwd);
|
|
72
151
|
const undone = await checkpoints.undone(s.id);
|
|
73
152
|
const snaps = await snapshots.list();
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
153
|
+
/** 用户自己执行的命令,最新的在前:不属于哪一轮,按时间和 Agent 的轮次排先后 */
|
|
154
|
+
const runs = snaps.filter((x) => x.label !== undefined);
|
|
155
|
+
const entries = [...(await checkpoints.list(s.id)), ...snaps.filter((x) => x.label === undefined)].sort((x, y) => y.at - x.at);
|
|
156
|
+
/** 这一轮文件工具的快照(最新的在前)、命令之前的工作区快照、撤销它要动的文件、其中之后又被改过的 */
|
|
157
|
+
let cps: Checkpoint[] = [];
|
|
77
158
|
let snap: Snapshot | undefined;
|
|
78
|
-
let tree: Change[];
|
|
159
|
+
let tree: Change[] = [];
|
|
160
|
+
let conflicts = new Set<string>();
|
|
79
161
|
for (;;) {
|
|
80
162
|
const hits = lastTurnChanges<Checkpoint | Snapshot>(s.state.messages, entries, undone);
|
|
163
|
+
// 用户的命令比这一轮的改动新(例如这一轮之后跑的 !npm i):先撤销它。它引出的那一轮比它晚,先撤那一轮
|
|
164
|
+
const run = runs.find((r) => !undone.has(r.toolUseId));
|
|
165
|
+
if (run && (hits.length === 0 || run.at > Math.min(...hits.map((h) => h.at)))) {
|
|
166
|
+
const found = await snapshots.changes(run);
|
|
167
|
+
if (found.changes.length > 0) return undoRun(s.id, snapshots, run, found, ui, signal);
|
|
168
|
+
// 命令什么都没改(或者已经改回去了):看更早的
|
|
169
|
+
undone.add(run.toolUseId);
|
|
170
|
+
await checkpoints.markUndone(s.id, [run.toolUseId]);
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
81
173
|
cps = hits.filter((h): h is Checkpoint => "path" in h);
|
|
82
174
|
snap = hits.find((h): h is Snapshot => "tree" in h);
|
|
83
|
-
tree = snap ? await snapshots.
|
|
175
|
+
({ changes: tree, conflicts } = snap ? await snapshots.changes(snap) : { changes: [], conflicts: new Set<string>() });
|
|
84
176
|
if (!snap || cps.length > 0 || tree.length > 0) break;
|
|
85
177
|
// 命令什么都没改(或者已经改回去了)的一轮:没有可撤销的,看更早的一轮
|
|
86
178
|
undone.add(snap.toolUseId);
|
|
@@ -108,8 +200,9 @@ export default definePlugin({
|
|
|
108
200
|
const latest = new Map<string, Checkpoint>();
|
|
109
201
|
for (const cp of fileCps) if (!latest.has(cp.path)) latest.set(cp.path, cp);
|
|
110
202
|
const changed: string[] = [];
|
|
111
|
-
//
|
|
203
|
+
// 工作区快照覆盖到的文件按快照判断:这一轮结束之后又变了的才算"别人改过"
|
|
112
204
|
for (const cp of latest.values()) if (!inTree.has(same(cp.path)) && !(await checkpoints.unchangedSince(cp))) changed.push(show(cp.path));
|
|
205
|
+
for (const c of tree) if (conflicts.has(c.path)) changed.push(show(c.path));
|
|
113
206
|
const rows = [...plan.values()].map((f) => ` ${f.gone ? "delete " : "restore"} ${show(f.path)}`);
|
|
114
207
|
const list = rows.length > MAX_LISTED ? [...rows.slice(0, MAX_LISTED), ` … ${rows.length - MAX_LISTED} more`].join("\n") : rows.join("\n");
|
|
115
208
|
if (plan.size > 1 || changed.length > 0 || tree.length > 0) {
|
|
@@ -119,7 +212,7 @@ export default definePlugin({
|
|
|
119
212
|
changed.length > 0
|
|
120
213
|
? `${changed.join(", ")} changed since the agent wrote ${changed.length > 1 ? "them" : "it"}. Undo anyway and discard those changes too?`
|
|
121
214
|
: tree.length > 0
|
|
122
|
-
? `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
|
|
215
|
+
? `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."}`
|
|
123
216
|
: `Undo the agent's last turn of changes (${plan.size} files)?`,
|
|
124
217
|
detail: list,
|
|
125
218
|
options: [
|
|
@@ -165,12 +258,30 @@ export default definePlugin({
|
|
|
165
258
|
void ctx.effect(() => () => {
|
|
166
259
|
if (decidedBy.get(sessionId) === decided) decidedBy.delete(sessionId);
|
|
167
260
|
if (links.get(sessionId) === link) links.delete(sessionId);
|
|
261
|
+
if (!ctx.session.parent) closeTurn(sessionId);
|
|
168
262
|
});
|
|
169
263
|
/** toolUseId → 执行前的内容,执行成功后存成快照 */
|
|
170
264
|
const before = new Map<string, { tool: string; path: string; before: string | null }>();
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
265
|
+
/**
|
|
266
|
+
* 这一轮第一次跑命令之前给工作区拍快照:整棵会话树(根会话和它这一轮开的子 Agent)共用一张,记在根会话里。
|
|
267
|
+
* 并行的子 Agent 同时要跑命令时等同一张拍完
|
|
268
|
+
*/
|
|
269
|
+
const beforeCommand = (toolUseId: string) => {
|
|
270
|
+
const { root, via } = link();
|
|
271
|
+
let p = turnSnaps.get(root);
|
|
272
|
+
if (!p) {
|
|
273
|
+
const snapshots = snapshotsOf(ctx.home, root, ctx.cwd);
|
|
274
|
+
p = (async () => {
|
|
275
|
+
await closing.get(root);
|
|
276
|
+
const tree = await snapshots.take();
|
|
277
|
+
if (!tree) return undefined;
|
|
278
|
+
await snapshots.save({ toolUseId, tree, at: now(), ...(via ? { via } : {}) });
|
|
279
|
+
return { snapshots, toolUseId };
|
|
280
|
+
})().catch(() => undefined);
|
|
281
|
+
turnSnaps.set(root, p);
|
|
282
|
+
}
|
|
283
|
+
return p;
|
|
284
|
+
};
|
|
174
285
|
|
|
175
286
|
ctx.kernel.hook({
|
|
176
287
|
kind: "transform",
|
|
@@ -182,12 +293,9 @@ export default definePlugin({
|
|
|
182
293
|
timeoutMs: SNAPSHOT_TIMEOUT_MS,
|
|
183
294
|
fn: async (call) => {
|
|
184
295
|
const meta = ctx.session.tool(call.name)?.meta;
|
|
185
|
-
// 每轮第一次跑命令之前给工作区拍一张快照:命令改了什么,/undo
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
snapped = true;
|
|
189
|
-
const tree = await snapshots.take();
|
|
190
|
-
if (tree) await snapshots.save({ toolUseId: call.toolUseId, tree, at: performance.timeOrigin + performance.now() });
|
|
296
|
+
// 每轮第一次跑命令之前给工作区拍一张快照:命令改了什么,/undo 时和它一比就知道
|
|
297
|
+
if (meta?.shell !== undefined && ctx.config.shell !== false) {
|
|
298
|
+
await beforeCommand(call.toolUseId);
|
|
191
299
|
return;
|
|
192
300
|
}
|
|
193
301
|
if (meta?.writes === undefined) return;
|
|
@@ -223,7 +331,9 @@ export default definePlugin({
|
|
|
223
331
|
before.clear();
|
|
224
332
|
// 只有这一轮里开的子会话查它(子会话在打开它的那次调用里结束)
|
|
225
333
|
decided.clear();
|
|
226
|
-
|
|
334
|
+
// 子会话结束不算:它的命令属于根会话这一轮。
|
|
335
|
+
// 返回补拍:内核等 observe 完成才交还这一轮(5.1),之后用户再动的文件不会被拍进这一轮
|
|
336
|
+
if (!ctx.session.parent) return closeTurn(sessionId);
|
|
227
337
|
},
|
|
228
338
|
});
|
|
229
339
|
},
|
package/plugins/undo/plugin.json
CHANGED
package/plugins/undo/snapshot.ts
CHANGED
|
@@ -4,16 +4,24 @@
|
|
|
4
4
|
// 项目自己的 .git(暂存区、提交、stash)一点不碰。只在 git 仓库里做:要靠 .gitignore 跳过 node_modules 这类目录,
|
|
5
5
|
// 对象库借用项目的(alternates),已经提交过的内容不再存一份。被忽略的文件不在快照里,撤销不了。
|
|
6
6
|
// 快照是 tree 对象,不建提交;哪一轮对应哪个 tree 记在 snapshots.json。
|
|
7
|
+
// 一轮结束时再拍一张(after):撤销时只动这一轮之内变了的文件,之后别人(用户的 /sh、手改)动过的不会被一起冲掉,而是先问。
|
|
8
|
+
// 同一个影子仓库的操作在进程内排队:并行的子 Agent、/undo 都会用它,git 的 index.lock 不能并发。
|
|
7
9
|
|
|
8
10
|
import { execFile } from "node:child_process";
|
|
9
11
|
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
10
12
|
import path from "node:path";
|
|
11
13
|
|
|
12
14
|
export interface Snapshot {
|
|
13
|
-
/** 这一轮第一次 bash 调用的 toolUseId:/undo
|
|
15
|
+
/** 这一轮第一次 bash 调用的 toolUseId:/undo 按它找到是哪一轮。用户自己执行的命令(label)是生成的 id */
|
|
14
16
|
toolUseId: string;
|
|
15
|
-
/** 影子仓库里的 tree */
|
|
17
|
+
/** 影子仓库里的 tree:命令之前 */
|
|
16
18
|
tree: string;
|
|
19
|
+
/** 一轮(或用户的命令)结束时的 tree;没有时(旧记录、进程中途退出)撤销时和工作区现在的样子比 */
|
|
20
|
+
after?: string;
|
|
21
|
+
/** 子 Agent 拍的:根会话里打开它的那次调用(同 Checkpoint.via) */
|
|
22
|
+
via?: string;
|
|
23
|
+
/** 有它的是用户自己执行的命令(例如 /sh 的 "$ npm i"),单独算一步撤销,不属于哪一轮 */
|
|
24
|
+
label?: string;
|
|
17
25
|
/** 拍下的时间,和 Checkpoint.at 同一个钟 */
|
|
18
26
|
at: number;
|
|
19
27
|
}
|
|
@@ -29,6 +37,29 @@ const FILE = "snapshots.json";
|
|
|
29
37
|
/** 一次 git 命令最多带这么多路径:Windows 的命令行长度有限 */
|
|
30
38
|
const CHUNK = 100;
|
|
31
39
|
|
|
40
|
+
/** 影子仓库目录 → 排在最后的操作 */
|
|
41
|
+
const queues = new Map<string, Promise<unknown>>();
|
|
42
|
+
/** 同一个目录的操作一个接一个执行(前一个失败不影响后一个) */
|
|
43
|
+
function serial<T>(key: string, fn: () => Promise<T>): Promise<T> {
|
|
44
|
+
const next = (queues.get(key) ?? Promise.resolve()).then(fn, fn);
|
|
45
|
+
const tail = next.catch(() => {});
|
|
46
|
+
queues.set(key, tail);
|
|
47
|
+
void tail.then(() => {
|
|
48
|
+
if (queues.get(key) === tail) queues.delete(key);
|
|
49
|
+
});
|
|
50
|
+
return next;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 同一个目录共用一个实例:影子仓库只准备一次 */
|
|
54
|
+
const instances = new Map<string, Snapshots>();
|
|
55
|
+
/** dir:会话的快照目录;cwd:会话的工作目录 */
|
|
56
|
+
export function snapshotsAt(dir: string, cwd: string): Snapshots {
|
|
57
|
+
const key = `${dir}|${cwd}`;
|
|
58
|
+
let s = instances.get(key);
|
|
59
|
+
if (!s) instances.set(key, (s = new Snapshots(dir, cwd)));
|
|
60
|
+
return s;
|
|
61
|
+
}
|
|
62
|
+
|
|
32
63
|
export class Snapshots {
|
|
33
64
|
readonly #dir: string;
|
|
34
65
|
readonly #cwd: string;
|
|
@@ -72,8 +103,16 @@ export class Snapshots {
|
|
|
72
103
|
})());
|
|
73
104
|
}
|
|
74
105
|
|
|
106
|
+
#serial<T>(fn: () => Promise<T>): Promise<T> {
|
|
107
|
+
return serial(this.#dir, fn);
|
|
108
|
+
}
|
|
109
|
+
|
|
75
110
|
/** 给工作区拍一张快照,返回 tree;不在 git 仓库里时 undefined */
|
|
76
|
-
|
|
111
|
+
take(): Promise<string | undefined> {
|
|
112
|
+
return this.#serial(() => this.#take());
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async #take(): Promise<string | undefined> {
|
|
77
116
|
const r = await this.#prepare();
|
|
78
117
|
if (!r) return undefined;
|
|
79
118
|
await git(["add", "-A", "--ignore-errors", "."], { cwd: r.root, env: r.env }).catch(() => {
|
|
@@ -82,12 +121,26 @@ export class Snapshots {
|
|
|
82
121
|
return (await git(["write-tree"], { cwd: r.root, env: r.env })).trim();
|
|
83
122
|
}
|
|
84
123
|
|
|
85
|
-
/**
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
124
|
+
/**
|
|
125
|
+
* 撤销这张快照要动的文件,和其中之后又被改过的(conflicts,绝对路径)。
|
|
126
|
+
* 有 after 时是 tree 到 after 之间变了的文件,工作区现在和 after 不一样的算之后改过;
|
|
127
|
+
* 没有时(旧记录、进程中途退出)是 tree 到现在变了的文件,分不出哪些是之后改的
|
|
128
|
+
*/
|
|
129
|
+
changes(snap: Pick<Snapshot, "tree" | "after">): Promise<{ changes: Change[]; conflicts: Set<string> }> {
|
|
130
|
+
return this.#serial(async () => {
|
|
131
|
+
const r = await this.#prepare();
|
|
132
|
+
const now = await this.#take();
|
|
133
|
+
if (!r || !now) return { changes: [], conflicts: new Set<string>() };
|
|
134
|
+
const end = snap.after ?? now;
|
|
135
|
+
const changes = await this.#diff(r, snap.tree, end);
|
|
136
|
+
const later = new Set((await this.#diff(r, end, now)).map((c) => c.path));
|
|
137
|
+
return { changes, conflicts: new Set(changes.map((c) => c.path).filter((p) => later.has(p))) };
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async #diff(r: { env: NodeJS.ProcessEnv; root: string }, from: string, to: string): Promise<Change[]> {
|
|
142
|
+
if (from === to) return [];
|
|
143
|
+
const out = await git(["diff-tree", "-r", "--no-renames", "--name-status", "-z", from, to], { cwd: r.root, env: r.env });
|
|
91
144
|
const parts = out.split("\0");
|
|
92
145
|
const changes: Change[] = [];
|
|
93
146
|
for (let i = 0; i + 1 < parts.length; i += 2) changes.push({ path: path.join(r.root, parts[i + 1]!), added: parts[i] === "A" });
|
|
@@ -95,7 +148,11 @@ export class Snapshots {
|
|
|
95
148
|
}
|
|
96
149
|
|
|
97
150
|
/** 把这些文件恢复成快照 tree 里的样子:之后新出现的删掉,其余的取回 */
|
|
98
|
-
|
|
151
|
+
restore(tree: string, changes: readonly Change[]): Promise<void> {
|
|
152
|
+
return this.#serial(() => this.#restore(tree, changes));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async #restore(tree: string, changes: readonly Change[]): Promise<void> {
|
|
99
156
|
const r = await this.#prepare();
|
|
100
157
|
if (!r) return;
|
|
101
158
|
for (const c of changes) if (c.added) await rm(c.path, { force: true });
|
|
@@ -106,7 +163,11 @@ export class Snapshots {
|
|
|
106
163
|
}
|
|
107
164
|
|
|
108
165
|
/** 本会话记下的快照,最新的在前 */
|
|
109
|
-
|
|
166
|
+
list(): Promise<Snapshot[]> {
|
|
167
|
+
return this.#serial(() => this.#list());
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async #list(): Promise<Snapshot[]> {
|
|
110
171
|
try {
|
|
111
172
|
const all = JSON.parse(await readFile(path.join(this.#dir, FILE), "utf8")) as unknown;
|
|
112
173
|
return Array.isArray(all) ? (all as Snapshot[]).sort((a, b) => b.at - a.at) : [];
|
|
@@ -115,10 +176,22 @@ export class Snapshots {
|
|
|
115
176
|
}
|
|
116
177
|
}
|
|
117
178
|
|
|
118
|
-
|
|
119
|
-
|
|
179
|
+
save(snapshot: Snapshot): Promise<void> {
|
|
180
|
+
return this.#serial(async () => this.#write([snapshot, ...(await this.#list())]));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 给这张快照补上结束时的 tree(现在工作区的样子) */
|
|
184
|
+
close(toolUseId: string): Promise<void> {
|
|
185
|
+
return this.#serial(async () => {
|
|
186
|
+
const after = await this.#take();
|
|
187
|
+
if (!after) return;
|
|
188
|
+
await this.#write((await this.#list()).map((s) => (s.toolUseId === toolUseId ? { ...s, after } : s)));
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async #write(all: Snapshot[]): Promise<void> {
|
|
120
193
|
await mkdir(this.#dir, { recursive: true });
|
|
121
|
-
await writeFile(path.join(this.#dir, FILE), JSON.stringify(
|
|
194
|
+
await writeFile(path.join(this.#dir, FILE), JSON.stringify(all));
|
|
122
195
|
}
|
|
123
196
|
}
|
|
124
197
|
|