@uncarved/jade 0.4.0 → 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.
@@ -27,7 +27,9 @@ export class Checkpoints {
27
27
  if (!n.endsWith(".json") || n === UNDONE)
28
28
  continue;
29
29
  try {
30
- out.push(JSON.parse(await readFile(path.join(dir, n), "utf8")));
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 { Snapshots } from "./snapshot.js";
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
- const snapshots = new Snapshots(path.join(ctx.home, "checkpoints", safe(s.id)), ctx.cwd);
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 entries = [...await checkpoints.list(s.id), ...snaps].sort((x, y) => y.at - x.at);
53
- let cps;
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.changed(snap.tree) : [];
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.` : `Undo the agent's last turn of changes (${plan.size} files)?`,
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 snapshots = new Snapshots(path.join(ctx.home, "checkpoints", safe(sessionId)), ctx.cwd);
146
- let snapped = false;
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 && !snapped && !ctx.session.parent) {
156
- snapped = true;
157
- const tree = await snapshots.take();
158
- if (tree)
159
- await snapshots.save({ toolUseId: call.toolUseId, tree, at: performance.timeOrigin + performance.now() });
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
- snapped = false;
294
+ if (!ctx.session.parent)
295
+ return closeTurn(sessionId);
200
296
  }
201
297
  });
202
298
  }
@@ -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"
@@ -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
- async take() {
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
- async changed(tree) {
54
- const r = await this.#prepare();
55
- const now = await this.take();
56
- if (!r || !now || now === tree)
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", tree, now], { cwd: r.root, env: r.env });
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
- async restore(tree, changes) {
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
- async list() {
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
- async save(snapshot) {
86
- const all = await this.list();
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([snapshot, ...all]));
139
+ await writeFile(path.join(this.#dir, FILE), JSON.stringify(all));
89
140
  }
90
141
  }
91
142
  function git(args, opts) {
package/src/api.ts CHANGED
@@ -5,7 +5,7 @@ import type { PluginLayer } from "@uncarved/jade-api";
5
5
  export * from "@uncarved/jade-api";
6
6
 
7
7
  /** 插件 API 的版本,插件在 plugin.json 的 api 字段里用 ^ 范围声明。和 @uncarved/jade-api 的版本一致 */
8
- export const API_VERSION = "1.3.0";
8
+ export const API_VERSION = "1.4.0";
9
9
 
10
10
  /** 来源层级,后面的层级更高(3.3) */
11
11
  export const LAYERS: readonly PluginLayer[] = ["bundled", "user", "project"];
package/src/session.ts CHANGED
@@ -267,7 +267,8 @@ class LiveSession implements Session {
267
267
  if (this.#left) return Promise.reject(this.#left);
268
268
  return new Promise((resolve, reject) => {
269
269
  this.#queue.push({ run, resolve, reject });
270
- this.#kick();
270
+ // session() 执行期间(Runtime 还没建)排进来的等 attach 再开始
271
+ if (this.#attached) this.#kick();
271
272
  });
272
273
  }
273
274
 
@@ -311,7 +312,7 @@ class LiveSession implements Session {
311
312
  this.#plugins = plugins;
312
313
  this.#use(rt);
313
314
  this.#attached = true;
314
- if (this.#after.length > 0) this.#kick();
315
+ if (this.#queue.length > 0 || this.#after.length > 0) this.#kick();
315
316
  }
316
317
 
317
318
  /** 换上一个 Runtime:通知从它转给订阅者。插件的回调以插件身份执行;出错只报告 */
@@ -379,7 +380,8 @@ class LiveSession implements Session {
379
380
  }
380
381
 
381
382
  abort(reason?: unknown): void {
382
- this.rt.abort(reason);
383
+ // Runtime 还没建(session() 执行期间、打开失败时):没有在跑的
384
+ this.rt?.abort(reason);
383
385
  // 停在等待人工审批时内核没有在跑,信号结束不了这一轮
384
386
  if (this.#turn) {
385
387
  this.#turn.stop = { reason };
@@ -497,6 +499,8 @@ export class Sessions implements SessionManager {
497
499
  ? await Runtime.resume({ store, provider, plugins, sessionId: s.id })
498
500
  : await Runtime.create({ store, provider, plugins, sessionId: s.id });
499
501
  } catch (e) {
502
+ // session() 里排进来的输入不会再执行了
503
+ s.leave();
500
504
  await this.#closeParts(s);
501
505
  throw e;
502
506
  }
@@ -587,6 +591,7 @@ export class Sessions implements SessionManager {
587
591
  for (const p of host.active()) if (p.module.session) await this.#join(s, p);
588
592
  rt = await Runtime.create({ store: s.store, provider, plugins: kernelPlugins(), sessionId: s.id, parent: child.ref });
589
593
  } catch (e) {
594
+ s.leave();
590
595
  await this.#closeParts(s);
591
596
  release();
592
597
  throw e;