@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
|
@@ -26,17 +26,11 @@ export function transcript(opts) {
|
|
|
26
26
|
if (u)
|
|
27
27
|
screen.status({ spent: { input: usage.inputTokens, output: usage.outputTokens } });
|
|
28
28
|
};
|
|
29
|
-
|
|
29
|
+
function countUsage(e) {
|
|
30
30
|
if (e.type === "model.responded")
|
|
31
31
|
addUsage(e.data.usage);
|
|
32
32
|
else if (e.origin.by === "plugin")
|
|
33
33
|
addUsage(usageOf(e.data?.usage));
|
|
34
|
-
else if (e.type === "tool.completed") {
|
|
35
|
-
const child = e.data.child;
|
|
36
|
-
if (child && opts.readLog)
|
|
37
|
-
for (const c of await opts.readLog(child.sessionId).catch(() => []))
|
|
38
|
-
await countUsage(c);
|
|
39
|
-
}
|
|
40
34
|
}
|
|
41
35
|
let reportsCache;
|
|
42
36
|
function showContext(e) {
|
|
@@ -156,12 +150,16 @@ ${bold(`› ${t.replace(/\n/g, `
|
|
|
156
150
|
const lines = text.split(`
|
|
157
151
|
`);
|
|
158
152
|
if (lines.length <= MAX_ECHO_LINES)
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
153
|
+
screen.log(shown(text));
|
|
154
|
+
else {
|
|
155
|
+
const rest = lines.slice(ECHO_HEAD_LINES);
|
|
156
|
+
screen.log(`${shown(lines.slice(0, ECHO_HEAD_LINES).join(`
|
|
162
157
|
`))}
|
|
163
158
|
${dim(`… +${rest.length} lines`)}`, { details: rest.map((l) => ` ${l}`).join(`
|
|
164
159
|
`) });
|
|
160
|
+
}
|
|
161
|
+
if (!text.startsWith("/"))
|
|
162
|
+
screen.log("");
|
|
165
163
|
},
|
|
166
164
|
reset() {
|
|
167
165
|
for (const k of Object.keys(usage))
|
|
@@ -312,7 +310,6 @@ ${bold(`› ${t.replace(/\n/g, `
|
|
|
312
310
|
}
|
|
313
311
|
case "tool.completed": {
|
|
314
312
|
const d = e.data;
|
|
315
|
-
countUsage(e);
|
|
316
313
|
activity("Working");
|
|
317
314
|
doneProgress(d.toolUseId);
|
|
318
315
|
const call = calls.get(d.toolUseId);
|
|
@@ -412,7 +409,7 @@ ${bold(`› ${t.replace(/\n/g, `
|
|
|
412
409
|
async function replay(events, show) {
|
|
413
410
|
if (!show) {
|
|
414
411
|
for (const e of events) {
|
|
415
|
-
|
|
412
|
+
countUsage(e);
|
|
416
413
|
if (e.type === "model.responded")
|
|
417
414
|
showContext(e);
|
|
418
415
|
}
|
package/plugins-dist/tui/tui.js
CHANGED
|
@@ -16,8 +16,8 @@ import {
|
|
|
16
16
|
useState,
|
|
17
17
|
useSyncExternalStore
|
|
18
18
|
} from "./vendor.js";
|
|
19
|
-
import
|
|
20
|
-
import { mentionAt, mentionText, rankPaths } from "./mentions.js";
|
|
19
|
+
import { visibleWidth } from "./width.js";
|
|
20
|
+
import { mentionAt, mentionDir, mentionText, rankPaths } from "./mentions.js";
|
|
21
21
|
import { charWidth, edit, empty, layout, moveRow, offsetAt } from "./editor.js";
|
|
22
22
|
import { expandTabs, markdownStream, softInfo, visibleRow, wrapRows } from "./markdown.js";
|
|
23
23
|
import { cells, FRAME_MS, Mascot, moodOf, nextChange, title } from "./mascot.js";
|
|
@@ -58,13 +58,13 @@ function foldable(l, width) {
|
|
|
58
58
|
}
|
|
59
59
|
const elapsed = (t) => `${Math.max(0, Math.round(((t.end ?? Date.now()) - t.start) / 1000))}s`;
|
|
60
60
|
export function tail(text, cols) {
|
|
61
|
-
if (
|
|
61
|
+
if (visibleWidth(text) <= cols)
|
|
62
62
|
return text;
|
|
63
63
|
const chars = [...text];
|
|
64
64
|
let out = "";
|
|
65
65
|
let w = 1;
|
|
66
66
|
for (let i = chars.length - 1;i >= 0; i--) {
|
|
67
|
-
const cw =
|
|
67
|
+
const cw = visibleWidth(chars[i]);
|
|
68
68
|
if (w + cw > cols)
|
|
69
69
|
break;
|
|
70
70
|
out = chars[i] + out;
|
|
@@ -78,7 +78,7 @@ function thinkingRow(t, width) {
|
|
|
78
78
|
const label = `✻ Thinking ${elapsed(t)}`;
|
|
79
79
|
const latest = t.text.split(`
|
|
80
80
|
`).findLast((l) => l.trim())?.trim().replace(/\s+/g, " ");
|
|
81
|
-
const room = width -
|
|
81
|
+
const room = width - visibleWidth(label) - 6;
|
|
82
82
|
return dim(latest && room >= 8 ? `${label} · ${tail(latest, room)}` : `${label}…`);
|
|
83
83
|
}
|
|
84
84
|
function wrapLine(l, width) {
|
|
@@ -947,7 +947,7 @@ function Spinner({ label, since }) {
|
|
|
947
947
|
const TONE = { ok: "green", warn: "yellow", error: "red", accent: "magenta" };
|
|
948
948
|
export function fitSegments(segments, width) {
|
|
949
949
|
const kept = segments.map((s) => ({ ...s }));
|
|
950
|
-
const total = () => kept.reduce((n, s, i) => n +
|
|
950
|
+
const total = () => kept.reduce((n, s, i) => n + visibleWidth(s.text) + (i ? 3 : 0), 0);
|
|
951
951
|
const steps = kept.flatMap((s) => [
|
|
952
952
|
...s.short !== undefined && s.shortAt !== undefined ? [{ s, at: s.shortAt, drop: false }] : [],
|
|
953
953
|
...s.dropAt !== undefined ? [{ s, at: s.dropAt, drop: true }] : []
|
|
@@ -1017,7 +1017,7 @@ function StatusBar({ status, width }) {
|
|
|
1017
1017
|
return h(Box, { paddingX: 1 }, h(Text, { wrap: "truncate-end" }, shown.map((s, i) => h(Text, { key: i }, i ? h(Text, { dimColor: true }, " · ") : null, h(Text, { color: s.color, dimColor: s.dim }, s.text)))));
|
|
1018
1018
|
}
|
|
1019
1019
|
function Hint({ variants, width }) {
|
|
1020
|
-
const text = variants.find((v) =>
|
|
1020
|
+
const text = variants.find((v) => visibleWidth(v) <= width) ?? variants.at(-1);
|
|
1021
1021
|
return h(Text, { dimColor: true, wrap: "truncate-end" }, text);
|
|
1022
1022
|
}
|
|
1023
1023
|
const tokens = (n) => n >= 1e6 ? `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M` : n >= 1000 ? `${(n / 1000).toFixed(n >= 1e4 ? 0 : 1)}k` : String(n);
|
|
@@ -1196,16 +1196,17 @@ function Prompt({
|
|
|
1196
1196
|
const { state, search, matches, pick, mention, found, file, results, hit } = derive();
|
|
1197
1197
|
const notice = getNotice();
|
|
1198
1198
|
const mentioning = mention?.trigger;
|
|
1199
|
+
const mentionScope = mention ? mentionDir(mention.query) : undefined;
|
|
1199
1200
|
useEffect(() => {
|
|
1200
1201
|
if (mentioning === undefined || !handlers.complete)
|
|
1201
1202
|
return;
|
|
1202
1203
|
let live = true;
|
|
1203
1204
|
setPaths([]);
|
|
1204
|
-
handlers.complete(mentioning).then((p) => void (live && setPaths(p)), () => {});
|
|
1205
|
+
handlers.complete(mentioning, mentionScope).then((p) => void (live && setPaths(p)), () => {});
|
|
1205
1206
|
return () => {
|
|
1206
1207
|
live = false;
|
|
1207
1208
|
};
|
|
1208
|
-
}, [mentioning]);
|
|
1209
|
+
}, [mentioning, mentionScope]);
|
|
1209
1210
|
const completion = completions.find((c) => c.trigger === mentioning);
|
|
1210
1211
|
const first = around(hit, results.length, menuRows);
|
|
1211
1212
|
const firstMatch = around(Math.max(0, matches.indexOf(pick)), matches.length, menuRows);
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import stringWidth from "string-width";
|
|
2
|
+
import wrapAnsi from "wrap-ansi";
|
|
3
|
+
export function standalone(c) {
|
|
4
|
+
if (c < 127)
|
|
5
|
+
return c >= 32;
|
|
6
|
+
if (c < 8208)
|
|
7
|
+
return c >= 160 && c <= 255 && c !== 173;
|
|
8
|
+
if (c <= 8231)
|
|
9
|
+
return true;
|
|
10
|
+
if (c >= 8240 && c <= 8286)
|
|
11
|
+
return true;
|
|
12
|
+
if (c >= 8592 && c <= 10175)
|
|
13
|
+
return c !== 9001 && c !== 9002;
|
|
14
|
+
if (c >= 11904 && c <= 12255)
|
|
15
|
+
return true;
|
|
16
|
+
if (c >= 12288 && c <= 12543)
|
|
17
|
+
return !(c >= 12330 && c <= 12335) && c !== 12441 && c !== 12442;
|
|
18
|
+
if (c >= 12544 && c <= 40959)
|
|
19
|
+
return true;
|
|
20
|
+
if (c >= 44032 && c <= 55203)
|
|
21
|
+
return true;
|
|
22
|
+
return c >= 65281 && c <= 65376 || c >= 65504 && c <= 65510;
|
|
23
|
+
}
|
|
24
|
+
const widths = new Uint8Array(65536);
|
|
25
|
+
function charWidth(c) {
|
|
26
|
+
let w = widths[c];
|
|
27
|
+
if (w === 0)
|
|
28
|
+
widths[c] = w = stringWidth(String.fromCharCode(c)) + 1;
|
|
29
|
+
return w - 1;
|
|
30
|
+
}
|
|
31
|
+
const SGR = /\x1b\[(\d{1,2})m/y;
|
|
32
|
+
function sgrAt(s, i) {
|
|
33
|
+
SGR.lastIndex = i;
|
|
34
|
+
const m = SGR.exec(s);
|
|
35
|
+
if (!m)
|
|
36
|
+
return;
|
|
37
|
+
const code = Number(m[1]);
|
|
38
|
+
return CLOSE_OF.has(code) || RESETS.has(code) ? { code, length: m[0].length } : undefined;
|
|
39
|
+
}
|
|
40
|
+
const CLOSE_OF = new Map([
|
|
41
|
+
[1, 22],
|
|
42
|
+
[2, 22],
|
|
43
|
+
[3, 23],
|
|
44
|
+
[4, 24],
|
|
45
|
+
[9, 29],
|
|
46
|
+
...[30, 31, 32, 33, 34, 35, 36, 37, 90, 91, 92, 93, 94, 95, 96, 97].map((c) => [c, 39])
|
|
47
|
+
]);
|
|
48
|
+
const RESETS = new Set([22, 23, 24, 29, 39]);
|
|
49
|
+
function fastWidth(s) {
|
|
50
|
+
let w = 0;
|
|
51
|
+
for (let i = 0;i < s.length; i++) {
|
|
52
|
+
const c = s.charCodeAt(i);
|
|
53
|
+
if (c === 27) {
|
|
54
|
+
const m = sgrAt(s, i);
|
|
55
|
+
if (!m)
|
|
56
|
+
return;
|
|
57
|
+
i += m.length - 1;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (!standalone(c))
|
|
61
|
+
return;
|
|
62
|
+
w += c < 127 ? 1 : charWidth(c);
|
|
63
|
+
}
|
|
64
|
+
return w;
|
|
65
|
+
}
|
|
66
|
+
export function visibleWidth(s) {
|
|
67
|
+
return fastWidth(s) ?? stringWidth(s);
|
|
68
|
+
}
|
|
69
|
+
function words(line) {
|
|
70
|
+
let word = { tokens: [], value: "", width: 0 };
|
|
71
|
+
const out = [word];
|
|
72
|
+
for (let i = 0;i < line.length; i++) {
|
|
73
|
+
const c = line.charCodeAt(i);
|
|
74
|
+
if (c === 32) {
|
|
75
|
+
word = { tokens: [], value: "", width: 0 };
|
|
76
|
+
out.push(word);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
let token;
|
|
80
|
+
if (c === 27) {
|
|
81
|
+
const m = sgrAt(line, i);
|
|
82
|
+
if (!m)
|
|
83
|
+
return;
|
|
84
|
+
token = { value: line.slice(i, i + m.length), width: 0 };
|
|
85
|
+
i += m.length - 1;
|
|
86
|
+
} else {
|
|
87
|
+
if (!standalone(c))
|
|
88
|
+
return;
|
|
89
|
+
token = { value: line[i], width: c < 127 ? 1 : charWidth(c) };
|
|
90
|
+
}
|
|
91
|
+
word.tokens.push(token);
|
|
92
|
+
word.value += token.value;
|
|
93
|
+
word.width += token.width;
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
function wrapWord(rows, tokens, columns, rowWidth) {
|
|
98
|
+
let visible = rowWidth;
|
|
99
|
+
tokens.forEach((t, i) => {
|
|
100
|
+
if (t.width > 0 && visible > 0 && visible + t.width > columns) {
|
|
101
|
+
rows.push("");
|
|
102
|
+
visible = 0;
|
|
103
|
+
}
|
|
104
|
+
rows[rows.length - 1] += t.value;
|
|
105
|
+
visible += t.width;
|
|
106
|
+
if (visible === columns && i < tokens.length - 1) {
|
|
107
|
+
rows.push("");
|
|
108
|
+
visible = 0;
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
if (!visible && rows.at(-1).length > 0 && rows.length > 1)
|
|
112
|
+
rows[rows.length - 2] += rows.pop();
|
|
113
|
+
return fastWidth(rows.at(-1));
|
|
114
|
+
}
|
|
115
|
+
function applySgr(code, active, resetsOnly = false) {
|
|
116
|
+
if (code === 39) {
|
|
117
|
+
const i = active.findIndex((s) => s.family === "foreground");
|
|
118
|
+
if (i !== -1)
|
|
119
|
+
active.splice(i, 1);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (RESETS.has(code)) {
|
|
123
|
+
for (let i = active.length - 1;i >= 0; i--)
|
|
124
|
+
if (active[i].family.startsWith("modifier-") && active[i].close === code)
|
|
125
|
+
active.splice(i, 1);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (resetsOnly)
|
|
129
|
+
return;
|
|
130
|
+
const close = CLOSE_OF.get(code);
|
|
131
|
+
const family = close === 39 ? "foreground" : `modifier-${code}`;
|
|
132
|
+
const i = active.findIndex((s) => s.family === family);
|
|
133
|
+
if (i !== -1)
|
|
134
|
+
active.splice(i, 1);
|
|
135
|
+
active.push({ family, open: code, close });
|
|
136
|
+
}
|
|
137
|
+
function restoreStyles(s) {
|
|
138
|
+
let out = "";
|
|
139
|
+
const active = [];
|
|
140
|
+
let copied = 0;
|
|
141
|
+
let i = 0;
|
|
142
|
+
while (i < s.length) {
|
|
143
|
+
const c = s.charCodeAt(i);
|
|
144
|
+
if (c === 27) {
|
|
145
|
+
const m = sgrAt(s, i);
|
|
146
|
+
applySgr(m.code, active);
|
|
147
|
+
i += m.length;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (c !== 10) {
|
|
151
|
+
i++;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
out += s.slice(copied, i);
|
|
155
|
+
if (i > copied)
|
|
156
|
+
out += [...active].reverse().map((st) => `\x1B[${st.close}m`).join("");
|
|
157
|
+
out += `
|
|
158
|
+
`;
|
|
159
|
+
copied = ++i;
|
|
160
|
+
if (i < s.length && s[i] !== `
|
|
161
|
+
`) {
|
|
162
|
+
const opening = [...active];
|
|
163
|
+
for (let j = i, m = sgrAt(s, j);m; j += m.length, m = sgrAt(s, j))
|
|
164
|
+
applySgr(m.code, opening, true);
|
|
165
|
+
out += opening.map((st) => `\x1B[${st.open}m`).join("");
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return out + s.slice(copied);
|
|
169
|
+
}
|
|
170
|
+
function fastWrap(line, columns) {
|
|
171
|
+
const width = fastWidth(line);
|
|
172
|
+
if (width === undefined)
|
|
173
|
+
return;
|
|
174
|
+
if (width <= columns)
|
|
175
|
+
return [line];
|
|
176
|
+
const list = words(line);
|
|
177
|
+
const rows = [""];
|
|
178
|
+
let rowLength = 0;
|
|
179
|
+
list.forEach((word, k) => {
|
|
180
|
+
if (k > 0) {
|
|
181
|
+
if (rowLength >= columns) {
|
|
182
|
+
rows.push("");
|
|
183
|
+
rowLength = 0;
|
|
184
|
+
}
|
|
185
|
+
rows[rows.length - 1] += " ";
|
|
186
|
+
rowLength++;
|
|
187
|
+
}
|
|
188
|
+
if (word.width > columns) {
|
|
189
|
+
const remaining = columns - rowLength;
|
|
190
|
+
const thisLine = 1 + Math.floor((word.width - remaining - 1) / columns);
|
|
191
|
+
const nextLine = Math.floor((word.width - 1) / columns);
|
|
192
|
+
if (nextLine < thisLine) {
|
|
193
|
+
rows.push("");
|
|
194
|
+
rowLength = 0;
|
|
195
|
+
}
|
|
196
|
+
rowLength = wrapWord(rows, word.tokens, columns, rowLength);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (rowLength + word.width > columns && rowLength > 0 && word.width > 0) {
|
|
200
|
+
rows.push("");
|
|
201
|
+
rowLength = 0;
|
|
202
|
+
}
|
|
203
|
+
rows[rows.length - 1] += word.value;
|
|
204
|
+
rowLength += word.width;
|
|
205
|
+
});
|
|
206
|
+
return line.includes("\x1B") ? restoreStyles(rows.join(`
|
|
207
|
+
`)).split(`
|
|
208
|
+
`) : rows;
|
|
209
|
+
}
|
|
210
|
+
const WRAP = { hard: true, trim: false };
|
|
211
|
+
export function wrapLines(text, width) {
|
|
212
|
+
if (text.includes("\r"))
|
|
213
|
+
return;
|
|
214
|
+
return text.split(`
|
|
215
|
+
`).map((line) => fastWrap(line, width) ?? wrapAnsi(line, width, WRAP).split(`
|
|
216
|
+
`));
|
|
217
|
+
}
|
|
218
|
+
export const wrapText = (text, width) => wrapLines(text, width)?.flat() ?? wrapAnsi(text, width, WRAP).split(`
|
|
219
|
+
`);
|
|
@@ -27,7 +27,9 @@ export class Checkpoints {
|
|
|
27
27
|
if (!n.endsWith(".json") || n === UNDONE)
|
|
28
28
|
continue;
|
|
29
29
|
try {
|
|
30
|
-
|
|
30
|
+
const cp = JSON.parse(await readFile(path.join(dir, n), "utf8"));
|
|
31
|
+
if (typeof cp?.toolUseId === "string" && typeof cp.path === "string" && typeof cp.at === "number")
|
|
32
|
+
out.push(cp);
|
|
31
33
|
} catch {}
|
|
32
34
|
}
|
|
33
35
|
return out.sort((a, b) => b.at - a.at);
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
1
2
|
import { readFile } from "node:fs/promises";
|
|
2
3
|
import { realpathSync } from "node:fs";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { definePlugin } from "@uncarved/jade-api";
|
|
5
6
|
import { Checkpoints, lastTurnChanges, safe, sha256, turnToolNames } from "./checkpoint.js";
|
|
6
|
-
import {
|
|
7
|
+
import { snapshotsAt } from "./snapshot.js";
|
|
7
8
|
import { dim, ok } from "./style.js";
|
|
8
9
|
const SHELL_NOTE = "This turn also ran shell commands; what they changed is not undone.";
|
|
9
10
|
const SNAPSHOT_TIMEOUT_MS = 60000;
|
|
@@ -26,6 +27,19 @@ function realPath(p) {
|
|
|
26
27
|
}
|
|
27
28
|
const decidedBy = new Map;
|
|
28
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;
|
|
42
|
+
}
|
|
29
43
|
async function contentOf(file) {
|
|
30
44
|
try {
|
|
31
45
|
return await readFile(file, "utf8");
|
|
@@ -39,6 +53,56 @@ export default definePlugin({
|
|
|
39
53
|
process(ctx) {
|
|
40
54
|
const checkpoints = new Checkpoints(path.join(ctx.home, "checkpoints"));
|
|
41
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
|
+
};
|
|
42
106
|
ctx.service("commands@1")?.register({
|
|
43
107
|
name: "undo",
|
|
44
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)",
|
|
@@ -46,18 +110,30 @@ export default definePlugin({
|
|
|
46
110
|
const s = sessions.current;
|
|
47
111
|
if (!s)
|
|
48
112
|
return "No session is open.";
|
|
49
|
-
|
|
113
|
+
await closing.get(s.id);
|
|
114
|
+
const snapshots = snapshotsOf(ctx.home, s.id, ctx.cwd);
|
|
50
115
|
const undone = await checkpoints.undone(s.id);
|
|
51
116
|
const snaps = await snapshots.list();
|
|
52
|
-
const
|
|
53
|
-
|
|
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 = [];
|
|
54
120
|
let snap;
|
|
55
|
-
let tree;
|
|
121
|
+
let tree = [];
|
|
122
|
+
let conflicts = new Set;
|
|
56
123
|
for (;; ) {
|
|
57
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
|
+
}
|
|
58
134
|
cps = hits.filter((h) => ("path" in h));
|
|
59
135
|
snap = hits.find((h) => ("tree" in h));
|
|
60
|
-
tree = snap ? await snapshots.
|
|
136
|
+
({ changes: tree, conflicts } = snap ? await snapshots.changes(snap) : { changes: [], conflicts: new Set });
|
|
61
137
|
if (!snap || cps.length > 0 || tree.length > 0)
|
|
62
138
|
break;
|
|
63
139
|
undone.add(snap.toolUseId);
|
|
@@ -87,13 +163,16 @@ export default definePlugin({
|
|
|
87
163
|
for (const cp of latest.values())
|
|
88
164
|
if (!inTree.has(same(cp.path)) && !await checkpoints.unchangedSince(cp))
|
|
89
165
|
changed.push(show(cp.path));
|
|
166
|
+
for (const c of tree)
|
|
167
|
+
if (conflicts.has(c.path))
|
|
168
|
+
changed.push(show(c.path));
|
|
90
169
|
const rows = [...plan.values()].map((f) => ` ${f.gone ? "delete " : "restore"} ${show(f.path)}`);
|
|
91
170
|
const list = rows.length > MAX_LISTED ? [...rows.slice(0, MAX_LISTED), ` … ${rows.length - MAX_LISTED} more`].join(`
|
|
92
171
|
`) : rows.join(`
|
|
93
172
|
`);
|
|
94
173
|
if (plan.size > 1 || changed.length > 0 || tree.length > 0) {
|
|
95
174
|
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
|
|
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)?`,
|
|
97
176
|
detail: list,
|
|
98
177
|
options: [
|
|
99
178
|
{ label: "No", value: "no" },
|
|
@@ -140,10 +219,29 @@ export default definePlugin({
|
|
|
140
219
|
decidedBy.delete(sessionId);
|
|
141
220
|
if (links.get(sessionId) === link)
|
|
142
221
|
links.delete(sessionId);
|
|
222
|
+
if (!ctx.session.parent)
|
|
223
|
+
closeTurn(sessionId);
|
|
143
224
|
});
|
|
144
225
|
const before = new Map;
|
|
145
|
-
const
|
|
146
|
-
|
|
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;
|
|
240
|
+
});
|
|
241
|
+
turnSnaps.set(root, p);
|
|
242
|
+
}
|
|
243
|
+
return p;
|
|
244
|
+
};
|
|
147
245
|
ctx.kernel.hook({
|
|
148
246
|
kind: "transform",
|
|
149
247
|
point: "tool.before",
|
|
@@ -152,11 +250,8 @@ export default definePlugin({
|
|
|
152
250
|
timeoutMs: SNAPSHOT_TIMEOUT_MS,
|
|
153
251
|
fn: async (call) => {
|
|
154
252
|
const meta = ctx.session.tool(call.name)?.meta;
|
|
155
|
-
if (meta?.shell !== undefined && ctx.config.shell !== false
|
|
156
|
-
|
|
157
|
-
const tree = await snapshots.take();
|
|
158
|
-
if (tree)
|
|
159
|
-
await snapshots.save({ toolUseId: call.toolUseId, tree, at: performance.timeOrigin + performance.now() });
|
|
253
|
+
if (meta?.shell !== undefined && ctx.config.shell !== false) {
|
|
254
|
+
await beforeCommand(call.toolUseId);
|
|
160
255
|
return;
|
|
161
256
|
}
|
|
162
257
|
if (meta?.writes === undefined)
|
|
@@ -196,7 +291,8 @@ export default definePlugin({
|
|
|
196
291
|
return;
|
|
197
292
|
before.clear();
|
|
198
293
|
decided.clear();
|
|
199
|
-
|
|
294
|
+
if (!ctx.session.parent)
|
|
295
|
+
return closeTurn(sessionId);
|
|
200
296
|
}
|
|
201
297
|
});
|
|
202
298
|
}
|
|
@@ -3,6 +3,25 @@ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
const FILE = "snapshots.json";
|
|
5
5
|
const CHUNK = 100;
|
|
6
|
+
const queues = new Map;
|
|
7
|
+
function serial(key, fn) {
|
|
8
|
+
const next = (queues.get(key) ?? Promise.resolve()).then(fn, fn);
|
|
9
|
+
const tail = next.catch(() => {});
|
|
10
|
+
queues.set(key, tail);
|
|
11
|
+
tail.then(() => {
|
|
12
|
+
if (queues.get(key) === tail)
|
|
13
|
+
queues.delete(key);
|
|
14
|
+
});
|
|
15
|
+
return next;
|
|
16
|
+
}
|
|
17
|
+
const instances = new Map;
|
|
18
|
+
export function snapshotsAt(dir, cwd) {
|
|
19
|
+
const key = `${dir}|${cwd}`;
|
|
20
|
+
let s = instances.get(key);
|
|
21
|
+
if (!s)
|
|
22
|
+
instances.set(key, s = new Snapshots(dir, cwd));
|
|
23
|
+
return s;
|
|
24
|
+
}
|
|
6
25
|
|
|
7
26
|
export class Snapshots {
|
|
8
27
|
#dir;
|
|
@@ -43,26 +62,45 @@ export class Snapshots {
|
|
|
43
62
|
return { env, root };
|
|
44
63
|
})();
|
|
45
64
|
}
|
|
46
|
-
|
|
65
|
+
#serial(fn) {
|
|
66
|
+
return serial(this.#dir, fn);
|
|
67
|
+
}
|
|
68
|
+
take() {
|
|
69
|
+
return this.#serial(() => this.#take());
|
|
70
|
+
}
|
|
71
|
+
async#take() {
|
|
47
72
|
const r = await this.#prepare();
|
|
48
73
|
if (!r)
|
|
49
74
|
return;
|
|
50
75
|
await git(["add", "-A", "--ignore-errors", "."], { cwd: r.root, env: r.env }).catch(() => {});
|
|
51
76
|
return (await git(["write-tree"], { cwd: r.root, env: r.env })).trim();
|
|
52
77
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
78
|
+
changes(snap) {
|
|
79
|
+
return this.#serial(async () => {
|
|
80
|
+
const r = await this.#prepare();
|
|
81
|
+
const now = await this.#take();
|
|
82
|
+
if (!r || !now)
|
|
83
|
+
return { changes: [], conflicts: new Set };
|
|
84
|
+
const end = snap.after ?? now;
|
|
85
|
+
const changes = await this.#diff(r, snap.tree, end);
|
|
86
|
+
const later = new Set((await this.#diff(r, end, now)).map((c) => c.path));
|
|
87
|
+
return { changes, conflicts: new Set(changes.map((c) => c.path).filter((p) => later.has(p))) };
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
async#diff(r, from, to) {
|
|
91
|
+
if (from === to)
|
|
57
92
|
return [];
|
|
58
|
-
const out = await git(["diff-tree", "-r", "--no-renames", "--name-status", "-z",
|
|
93
|
+
const out = await git(["diff-tree", "-r", "--no-renames", "--name-status", "-z", from, to], { cwd: r.root, env: r.env });
|
|
59
94
|
const parts = out.split("\x00");
|
|
60
95
|
const changes = [];
|
|
61
96
|
for (let i = 0;i + 1 < parts.length; i += 2)
|
|
62
97
|
changes.push({ path: path.join(r.root, parts[i + 1]), added: parts[i] === "A" });
|
|
63
98
|
return changes;
|
|
64
99
|
}
|
|
65
|
-
|
|
100
|
+
restore(tree, changes) {
|
|
101
|
+
return this.#serial(() => this.#restore(tree, changes));
|
|
102
|
+
}
|
|
103
|
+
async#restore(tree, changes) {
|
|
66
104
|
const r = await this.#prepare();
|
|
67
105
|
if (!r)
|
|
68
106
|
return;
|
|
@@ -74,7 +112,10 @@ export class Snapshots {
|
|
|
74
112
|
await git(["--literal-pathspecs", "checkout", tree, "--", ...back.slice(i, i + CHUNK)], { cwd: r.root, env: r.env });
|
|
75
113
|
}
|
|
76
114
|
}
|
|
77
|
-
|
|
115
|
+
list() {
|
|
116
|
+
return this.#serial(() => this.#list());
|
|
117
|
+
}
|
|
118
|
+
async#list() {
|
|
78
119
|
try {
|
|
79
120
|
const all = JSON.parse(await readFile(path.join(this.#dir, FILE), "utf8"));
|
|
80
121
|
return Array.isArray(all) ? all.sort((a, b) => b.at - a.at) : [];
|
|
@@ -82,10 +123,20 @@ export class Snapshots {
|
|
|
82
123
|
return [];
|
|
83
124
|
}
|
|
84
125
|
}
|
|
85
|
-
|
|
86
|
-
|
|
126
|
+
save(snapshot) {
|
|
127
|
+
return this.#serial(async () => this.#write([snapshot, ...await this.#list()]));
|
|
128
|
+
}
|
|
129
|
+
close(toolUseId) {
|
|
130
|
+
return this.#serial(async () => {
|
|
131
|
+
const after = await this.#take();
|
|
132
|
+
if (!after)
|
|
133
|
+
return;
|
|
134
|
+
await this.#write((await this.#list()).map((s) => s.toolUseId === toolUseId ? { ...s, after } : s));
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
async#write(all) {
|
|
87
138
|
await mkdir(this.#dir, { recursive: true });
|
|
88
|
-
await writeFile(path.join(this.#dir, FILE), JSON.stringify(
|
|
139
|
+
await writeFile(path.join(this.#dir, FILE), JSON.stringify(all));
|
|
89
140
|
}
|
|
90
141
|
}
|
|
91
142
|
function git(args, opts) {
|