@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.
- package/README.md +1 -0
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/session.js +9 -3
- package/dist/session.js.map +1 -1
- package/package.json +2 -2
- package/plugins/models/configure.ts +37 -3
- package/plugins/models/provider.ts +24 -0
- package/plugins/models/saved.ts +1 -1
- package/plugins/prompts/index.ts +0 -0
- package/plugins/schedule/index.ts +3 -1
- package/plugins/shell/index.ts +8 -4
- package/plugins/shell/plugin.json +2 -1
- 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/models/configure.js +30 -2
- package/plugins-dist/models/provider.js +21 -1
- 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/shell/index.js +12 -10
- package/plugins-dist/shell/plugin.json +2 -1
- package/plugins-dist/tui/vendor.js +1088 -1388
- 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/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/src/api.ts +1 -1
- package/src/session.ts +8 -3
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
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readFile, rm, writeFile } from "node:fs/promises";
|
|
2
2
|
import { hasProvider, parseTokens } from "./config.js";
|
|
3
3
|
import { contextWindow } from "./context.js";
|
|
4
|
-
import { EFFORTS, isBuiltinKind, jsonObject, KEY_KEY, listModels, MODEL_KEY, providerInfo, providerKind, rpmFromEnv, URL_KEY, visionFromEnv } from "./provider.js";
|
|
4
|
+
import { EFFORTS, fallbacksFromEnv, isBuiltinKind, isOfficialAnthropic, jsonObject, KEY_KEY, listModels, MODEL_KEY, providerInfo, providerKind, rpmFromEnv, URL_KEY, visionFromEnv } from "./provider.js";
|
|
5
5
|
import { MODEL_SETTINGS, readSavedServices, updateEnvFile, writeSavedServices } from "./saved.js";
|
|
6
6
|
const PROVIDERS = [
|
|
7
7
|
{ kind: "openai-compat", label: "OpenAI-compatible service", hint: "any /chat/completions endpoint" },
|
|
@@ -21,6 +21,19 @@ function visionHint(env, kind) {
|
|
|
21
21
|
const v = visionSetting(env);
|
|
22
22
|
return v === undefined ? `${isBuiltinKind(kind) && kind !== "openai-compat" ? "yes" : "no"} (default)` : v ? "yes" : "no";
|
|
23
23
|
}
|
|
24
|
+
function fallbacksSetting(env) {
|
|
25
|
+
if (!env.JADE_FALLBACKS?.trim())
|
|
26
|
+
return;
|
|
27
|
+
try {
|
|
28
|
+
return fallbacksFromEnv({ JADE_FALLBACKS: env.JADE_FALLBACKS });
|
|
29
|
+
} catch {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function fallbacksHint(env, baseURL) {
|
|
34
|
+
const v = fallbacksSetting(env);
|
|
35
|
+
return v === undefined ? `${isOfficialAnthropic(baseURL) ? "on" : "off"} (default)` : v ? "on" : "off";
|
|
36
|
+
}
|
|
24
37
|
const serviceKeys = (kind) => ["JADE_PROVIDER", URL_KEY[kind], KEY_KEY[kind]];
|
|
25
38
|
const pick = (env, keys) => {
|
|
26
39
|
const out = {};
|
|
@@ -229,7 +242,7 @@ export function configurator(opts) {
|
|
|
229
242
|
return applyConfig(updates, rekeyed ? currentId : undefined);
|
|
230
243
|
}
|
|
231
244
|
async function configureSettings(target) {
|
|
232
|
-
const { title, kind, model } = target;
|
|
245
|
+
const { title, kind, model, baseURL } = target;
|
|
233
246
|
const efforts = isBuiltinKind(kind) ? EFFORTS[kind] : undefined;
|
|
234
247
|
while (true) {
|
|
235
248
|
const env = await target.read();
|
|
@@ -241,6 +254,7 @@ export function configurator(opts) {
|
|
|
241
254
|
{ label: "Context window", value: "window", hint: `${contextWindow(model, env)} tokens${env.JADE_CONTEXT_WINDOW ? "" : " (default)"}` },
|
|
242
255
|
{ label: "Requests per minute", value: "rpm", hint: env.JADE_RPM ? `${env.JADE_RPM}/min` : "no limit (slows down after being rate limited)" },
|
|
243
256
|
{ label: "Can see images", value: "vision", hint: visionHint(env, kind) },
|
|
257
|
+
...kind === "anthropic" ? [{ label: "Server-side fallback", value: "fallbacks", hint: fallbacksHint(env, baseURL) }] : [],
|
|
244
258
|
...kind === "openai-compat" ? [{ label: "Extra request body", value: "extra", hint: env.OPENAI_COMPAT_EXTRA_BODY ? shorten(env.OPENAI_COMPAT_EXTRA_BODY) : "none" }] : [],
|
|
245
259
|
{ label: "Back", value: "back" }
|
|
246
260
|
]
|
|
@@ -287,6 +301,19 @@ export function configurator(opts) {
|
|
|
287
301
|
const on = choice === DEFAULT ? isBuiltinKind(kind) && kind !== "openai-compat" : choice === "on";
|
|
288
302
|
report(on ? "Images will be sent to the model." : "Images will be replaced with a note.");
|
|
289
303
|
}
|
|
304
|
+
} else if (action === "fallbacks" && kind === "anthropic") {
|
|
305
|
+
const DEFAULT = "\x00default";
|
|
306
|
+
const current = fallbacksSetting(env);
|
|
307
|
+
const choice = await ui.select({
|
|
308
|
+
title: "Retry with another model on the service side when Claude refuses for safety reasons?",
|
|
309
|
+
options: [
|
|
310
|
+
{ label: "On", value: "on", hint: current === true ? "current" : "official API only; most relays reject it" },
|
|
311
|
+
{ label: "Off", value: "off", hint: current === false ? "current" : "the field is not sent" },
|
|
312
|
+
{ label: "Default", value: DEFAULT, hint: isOfficialAnthropic(baseURL) ? "on (official API)" : "off (not the official API)" }
|
|
313
|
+
]
|
|
314
|
+
}, opts.signal);
|
|
315
|
+
if (choice !== undefined)
|
|
316
|
+
await target.update({ JADE_FALLBACKS: choice === DEFAULT ? undefined : choice });
|
|
290
317
|
} else if (action === "window") {
|
|
291
318
|
const n = await ui.input({ title: "Context window in tokens, e.g. 128000, 512K, 1M (empty to infer it from the model name, or 256K if unknown)", initial: env.JADE_CONTEXT_WINDOW ?? "" }, opts.signal);
|
|
292
319
|
if (n !== undefined && tokensInput("Context window", n))
|
|
@@ -351,6 +378,7 @@ export function configurator(opts) {
|
|
|
351
378
|
title: o.model.name,
|
|
352
379
|
kind,
|
|
353
380
|
model: o.model.name,
|
|
381
|
+
baseURL: providerInfo(o.service.env).baseURL,
|
|
354
382
|
read,
|
|
355
383
|
update: (updates) => isCurrent ? applyConfig(updates) : writeSavedModel(o.service, o.model, updates)
|
|
356
384
|
});
|
|
@@ -170,6 +170,25 @@ export function visionFromEnv(env = process.env) {
|
|
|
170
170
|
return false;
|
|
171
171
|
throw new Error(`JADE_VISION must be on or off, got ${JSON.stringify(env.JADE_VISION)}`);
|
|
172
172
|
}
|
|
173
|
+
export function isOfficialAnthropic(baseURL) {
|
|
174
|
+
if (!baseURL?.trim())
|
|
175
|
+
return true;
|
|
176
|
+
try {
|
|
177
|
+
return new URL(baseURL).host === "api.anthropic.com";
|
|
178
|
+
} catch {
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
export function fallbacksFromEnv(env = process.env) {
|
|
183
|
+
const text = env.JADE_FALLBACKS?.trim().toLowerCase();
|
|
184
|
+
if (!text)
|
|
185
|
+
return isOfficialAnthropic(env.ANTHROPIC_BASE_URL);
|
|
186
|
+
if (["1", "true", "on", "yes"].includes(text))
|
|
187
|
+
return true;
|
|
188
|
+
if (["0", "false", "off", "no"].includes(text))
|
|
189
|
+
return false;
|
|
190
|
+
throw new Error(`JADE_FALLBACKS must be on or off, got ${JSON.stringify(env.JADE_FALLBACKS)}`);
|
|
191
|
+
}
|
|
173
192
|
export function effortFromEnv(env = process.env) {
|
|
174
193
|
const effort = env.JADE_EFFORT;
|
|
175
194
|
if (!effort)
|
|
@@ -247,7 +266,8 @@ export async function providerFromEnv(env = process.env) {
|
|
|
247
266
|
baseURL: env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com",
|
|
248
267
|
model: env.ANTHROPIC_MODEL,
|
|
249
268
|
effort: effort ?? "high",
|
|
250
|
-
maxTokens
|
|
269
|
+
maxTokens,
|
|
270
|
+
fallbacks: fallbacksFromEnv(env)
|
|
251
271
|
});
|
|
252
272
|
}
|
|
253
273
|
export async function listModels(env = process.env, fetchImpl = fetch) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
export const MODEL_SETTINGS = ["JADE_MAX_TOKENS", "JADE_EFFORT", "JADE_CONTEXT_WINDOW", "JADE_RPM", "JADE_VISION", "OPENAI_COMPAT_EXTRA_BODY"];
|
|
3
|
+
export const MODEL_SETTINGS = ["JADE_MAX_TOKENS", "JADE_EFFORT", "JADE_CONTEXT_WINDOW", "JADE_RPM", "JADE_VISION", "JADE_FALLBACKS", "OPENAI_COMPAT_EXTRA_BODY"];
|
|
4
4
|
const strings = (v) => typeof v === "object" && v !== null ? Object.fromEntries(Object.entries(v).filter(([, x]) => typeof x === "string")) : {};
|
|
5
5
|
export async function readSavedServices(file) {
|
|
6
6
|
try {
|
|
@@ -8,6 +8,7 @@ const ID = "jade/prompts";
|
|
|
8
8
|
const sections = [];
|
|
9
9
|
const loaded = new Map;
|
|
10
10
|
const notes = new Notes;
|
|
11
|
+
const gathered = new Map;
|
|
11
12
|
function segment(text, trust = "trusted", stability = "stable", by = ID, source) {
|
|
12
13
|
return { text, stability, origin: { by: "plugin", id: by, ...source ? { source } : {} }, trust };
|
|
13
14
|
}
|
|
@@ -44,7 +45,11 @@ export default definePlugin({
|
|
|
44
45
|
},
|
|
45
46
|
async session(ctx) {
|
|
46
47
|
const models = ctx.service("models@1");
|
|
47
|
-
const
|
|
48
|
+
const parent = ctx.session.parent?.sessionId;
|
|
49
|
+
const mine = (parent !== undefined ? gathered.get(parent) : undefined) ?? Promise.all([environment(ctx.cwd), allInstructions(ctx.home, ctx.cwd, ctx.config.claudeInstructions === false ? null : os.homedir())]);
|
|
50
|
+
gathered.set(ctx.session.id, mine);
|
|
51
|
+
await ctx.effect(() => () => void gathered.delete(ctx.session.id));
|
|
52
|
+
const [env, instructions] = await mine;
|
|
48
53
|
loaded.set(ctx.session.id, instructions.map(({ text, trust, source }) => ({ text, trust, source })));
|
|
49
54
|
await ctx.effect(() => () => void loaded.delete(ctx.session.id));
|
|
50
55
|
const fixed = [segment(env), ...instructions.map((i) => segment(i.text, i.trust, "stable", ID, i.source))];
|
|
@@ -255,6 +255,7 @@ ${describe(t, ctx.cwd)}`;
|
|
|
255
255
|
ctx.session.send(delivery(t)).catch((e) => ctx.signal.aborted || ui.notify(`scheduled task ${t.id} failed: ${err(e)}`, "error")).finally(() => running.delete(t.id));
|
|
256
256
|
}
|
|
257
257
|
};
|
|
258
|
+
ctx.session.afterTurn(() => void check());
|
|
258
259
|
await ctx.effect(() => {
|
|
259
260
|
const timer = setInterval(() => void check(), every);
|
|
260
261
|
return () => clearInterval(timer);
|
|
@@ -36,16 +36,19 @@ export default definePlugin({
|
|
|
36
36
|
let live = "";
|
|
37
37
|
let r;
|
|
38
38
|
let stopped = false;
|
|
39
|
+
const session = manager.current;
|
|
40
|
+
const exec = () => shell.run(command, {
|
|
41
|
+
cwd: ctx.cwd,
|
|
42
|
+
timeoutMs: SH_TIMEOUT_MS,
|
|
43
|
+
signal,
|
|
44
|
+
onOutput(text) {
|
|
45
|
+
live = (live + text).slice(-SH_LIVE_CHARS);
|
|
46
|
+
progress?.(live);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
const undo = ctx.service("undo@1");
|
|
39
50
|
try {
|
|
40
|
-
r = await
|
|
41
|
-
cwd: ctx.cwd,
|
|
42
|
-
timeoutMs: SH_TIMEOUT_MS,
|
|
43
|
-
signal,
|
|
44
|
-
onOutput(text) {
|
|
45
|
-
live = (live + text).slice(-SH_LIVE_CHARS);
|
|
46
|
-
progress?.(live);
|
|
47
|
-
}
|
|
48
|
-
});
|
|
51
|
+
r = session && undo ? await undo.track(session.id, `$ ${firstLine(command)}`, exec) : await exec();
|
|
49
52
|
} catch (e) {
|
|
50
53
|
if (!signal.aborted)
|
|
51
54
|
throw e;
|
|
@@ -60,7 +63,6 @@ export default definePlugin({
|
|
|
60
63
|
const more = lines.length > 1 ? ` (+${lines.length - 1} lines)` : "";
|
|
61
64
|
const folded = lines.length > 1 || first.length > SH_SUMMARY;
|
|
62
65
|
print(shade(failed, `⎿ ${first.length > SH_SUMMARY ? `${first.slice(0, SH_SUMMARY)}…` : first}${more}`), folded ? { details: r.output.replace(/^/gm, " ") } : undefined);
|
|
63
|
-
const session = manager.current;
|
|
64
66
|
if (!stopped && session && session.state.messages.length > 0)
|
|
65
67
|
return { prompt: `I ran this shell command myself (${status}):
|
|
66
68
|
$ ${command}
|