@uncarved/jade 0.2.0 → 0.2.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 +215 -0
- package/bin/jade.js +11 -0
- package/dist/main.js +2 -1
- package/dist/main.js.map +1 -1
- package/package.json +4 -4
- package/plugins/approval/index.ts +16 -2
- package/plugins/approval/plugin.json +4 -0
- package/plugins/approval/policy.ts +25 -5
- package/plugins/compact/compact.ts +7 -1
- package/plugins/fs/fs.ts +78 -12
- package/plugins/fs/grep.ts +35 -7
- package/plugins/fs/index.ts +7 -4
- package/plugins/mentions/index.ts +31 -11
- package/plugins/models/index.ts +17 -2
- package/plugins/print/index.ts +26 -8
- package/plugins/prompts/index.ts +29 -1
- package/plugins/prompts/prompts.ts +9 -4
- package/plugins/prompts/results.ts +63 -0
- package/plugins/prompts/sys.ts +16 -4
- package/plugins/task/index.ts +1 -0
- package/plugins/task/subagent.ts +96 -10
- package/plugins/todo/index.ts +2 -2
- package/plugins/tui/frontend.ts +27 -4
- package/plugins/tui/mentions.ts +48 -8
- package/plugins/tui/transcript.ts +5 -1
- package/plugins/tui/tui.ts +2 -5
- package/plugins/tui/vendor.ts +16 -0
- package/plugins/undo/checkpoint.ts +24 -0
- package/plugins/undo/index.ts +8 -4
- package/plugins/web/web.ts +6 -5
- package/plugins-dist/approval/index.js +18 -2
- package/plugins-dist/approval/plugin.json +4 -0
- package/plugins-dist/approval/policy.js +27 -5
- package/plugins-dist/compact/compact.js +7 -1
- package/plugins-dist/fs/fs.js +73 -12
- package/plugins-dist/fs/grep.js +35 -9
- package/plugins-dist/fs/index.js +7 -4
- package/plugins-dist/mentions/index.js +28 -10
- package/plugins-dist/models/index.js +16 -2
- package/plugins-dist/print/index.js +25 -6
- package/plugins-dist/prompts/index.js +28 -0
- package/plugins-dist/prompts/prompts.js +8 -4
- package/plugins-dist/prompts/results.js +60 -0
- package/plugins-dist/prompts/sys.js +15 -3
- package/plugins-dist/task/index.js +1 -0
- package/plugins-dist/task/subagent.js +86 -10
- package/plugins-dist/todo/index.js +2 -2
- package/plugins-dist/tui/frontend.js +28 -5
- package/plugins-dist/tui/mentions.js +44 -6
- package/plugins-dist/tui/transcript.js +3 -1
- package/plugins-dist/tui/tui.js +1 -2
- package/plugins-dist/tui/vendor.js +13822 -0
- package/plugins-dist/undo/checkpoint.js +27 -0
- package/plugins-dist/undo/index.js +7 -4
- package/plugins-dist/web/web.js +6 -5
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/src/main.ts +2 -1
package/plugins-dist/fs/grep.js
CHANGED
|
@@ -196,6 +196,32 @@ async function ripgrep(rg, s) {
|
|
|
196
196
|
}
|
|
197
197
|
}
|
|
198
198
|
// ---------- JS ----------
|
|
199
|
+
/** 同时读几个文件。逐个等 stat、readFile 时,几万个文件的仓库要好几秒(多数时间花在等 IO 上) */
|
|
200
|
+
const READ_AHEAD = 16;
|
|
201
|
+
/** 读出可以搜的文本;不存在(git 列出的文件可能已在工作区删除)、太大、二进制的返回 undefined */
|
|
202
|
+
async function readSearchable(file) {
|
|
203
|
+
const info = await statOrUndefined(file);
|
|
204
|
+
if (!info?.isFile() || info.size > MAX_FILE_BYTES)
|
|
205
|
+
return undefined;
|
|
206
|
+
const buf = await readFile(file).catch(() => undefined);
|
|
207
|
+
return buf && !buf.includes(0) ? buf : undefined;
|
|
208
|
+
}
|
|
209
|
+
/** 按 items 的顺序产出 fn 的结果,最多 n 个同时进行;调用方提前停止时,已经开始的读取随它结束 */
|
|
210
|
+
async function* ordered(items, n, fn) {
|
|
211
|
+
const pending = [];
|
|
212
|
+
for await (const item of items) {
|
|
213
|
+
const result = fn(item);
|
|
214
|
+
// 先挂上处理,免得提前停止时没人等的 Promise 报 unhandled rejection
|
|
215
|
+
result.catch(() => { });
|
|
216
|
+
pending.push({ item, result });
|
|
217
|
+
if (pending.length >= n) {
|
|
218
|
+
const head = pending.shift();
|
|
219
|
+
yield [head.item, await head.result];
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
for (const p of pending)
|
|
223
|
+
yield [p.item, await p.result];
|
|
224
|
+
}
|
|
199
225
|
async function jsGrep(s) {
|
|
200
226
|
// 和 ripgrep 的 --glob 一致:不含 / 的模式("*.ts")匹配任意深度的文件名
|
|
201
227
|
const filter = s.include ? globMatcher(s.include.includes("/") ? s.include : `**/${s.include}`) : undefined;
|
|
@@ -204,17 +230,17 @@ async function jsGrep(s) {
|
|
|
204
230
|
const single = (await stat(s.root)).isFile();
|
|
205
231
|
const candidates = single ? [s.root] : await listFiles(s.root, s.signal);
|
|
206
232
|
const sorted = Array.isArray(candidates) ? [...candidates].sort() : candidates;
|
|
207
|
-
|
|
233
|
+
const wanted = async function* () {
|
|
234
|
+
for await (const file of sorted) {
|
|
235
|
+
if (filter && !single && !filter(path.relative(s.root, file).split(path.sep).join("/")))
|
|
236
|
+
continue;
|
|
237
|
+
yield file;
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
for await (const [file, buf] of ordered(wanted(), READ_AHEAD, readSearchable)) {
|
|
208
241
|
s.signal.throwIfAborted();
|
|
209
|
-
if (
|
|
210
|
-
continue;
|
|
211
|
-
// git 列出的文件可能已在工作区删除
|
|
212
|
-
const info = await statOrUndefined(file);
|
|
213
|
-
if (!info?.isFile() || info.size > MAX_FILE_BYTES)
|
|
242
|
+
if (!buf)
|
|
214
243
|
continue;
|
|
215
|
-
const buf = await readFile(file);
|
|
216
|
-
if (buf.includes(0))
|
|
217
|
-
continue; // 二进制文件
|
|
218
244
|
const all = buf.toString("utf8").split(/\r?\n/);
|
|
219
245
|
if (all.at(-1) === "")
|
|
220
246
|
all.pop();
|
package/plugins-dist/fs/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// jade/fs:文件工具 read_file、write_file、edit_file、multi_edit、list_dir、glob、grep。
|
|
2
2
|
import { definePlugin } from "../../dist/api.js";
|
|
3
|
-
import { fsTools } from "./fs.js";
|
|
3
|
+
import { fsTools, SeenFiles } from "./fs.js";
|
|
4
4
|
import { fsRenderers } from "./renderers.js";
|
|
5
5
|
export default definePlugin({
|
|
6
6
|
process(ctx) {
|
|
@@ -11,16 +11,19 @@ export default definePlugin({
|
|
|
11
11
|
renderers.tool(r);
|
|
12
12
|
},
|
|
13
13
|
session(ctx) {
|
|
14
|
-
//
|
|
14
|
+
// 数模型调用的次数:同一次回复里先读后改的,改的内容是看到读取结果之前写好的。
|
|
15
|
+
// 同时按最终发给模型的消息让被压缩(jade/compact 总结或清理)掉的读取失效:那些文件要重新读才能改
|
|
15
16
|
const responses = { calls: 0 };
|
|
17
|
+
const seen = new SeenFiles();
|
|
16
18
|
ctx.kernel.hook({
|
|
17
19
|
kind: "transform",
|
|
18
20
|
point: "model.before",
|
|
19
|
-
fn: () => {
|
|
21
|
+
fn: (request) => {
|
|
20
22
|
responses.calls++;
|
|
23
|
+
seen.prune(request.messages);
|
|
21
24
|
},
|
|
22
25
|
});
|
|
23
|
-
for (const tool of fsTools(ctx.cwd, { responses }))
|
|
26
|
+
for (const tool of fsTools(ctx.cwd, { responses, seen }))
|
|
24
27
|
ctx.kernel.tool(tool);
|
|
25
28
|
// 子 Agent(jade/task)的只读工具:另一套实例,子 Agent 读过的文件不算主会话读过
|
|
26
29
|
// jade/task 被隔离时它的服务已失效:子 Agent 没有文件工具,文件工具本身照常
|
|
@@ -3,10 +3,14 @@
|
|
|
3
3
|
// 内核没有改写用户输入的扩展点:input.received 原样进日志。所以在 context.project 里把附件加到引用它的那条用户消息后面。
|
|
4
4
|
// 附件在消息之后第一次投影时读取,先用 ctx.record 写进日志(derived)再使用(I-5):之后每次投影都从 derived 里取,
|
|
5
5
|
// 文件之后变了也不影响已经发出的消息(提示缓存不失效),恢复会话后也一样。
|
|
6
|
+
// 每条消息的附件单独记一个 key(attachedKey):derived.recorded 是整值替换,记成一张表的话,
|
|
7
|
+
// 每次有新的 @ 都要把之前附过的全部内容再写一遍,日志按平方增长。
|
|
6
8
|
// 输入框里 @ 的补全不在这里,在 jade/tui。
|
|
7
9
|
import { definePlugin } from "../../dist/api.js";
|
|
8
10
|
import { attachMentions } from "./attach.js";
|
|
9
11
|
import { clip, dim, yellow } from "./style.js";
|
|
12
|
+
/** 附在第 i 条消息后面的内容记在这个 key 下 */
|
|
13
|
+
export const attachedKey = (plugin, i) => `${plugin}/${i}`;
|
|
10
14
|
/** 读文件的时限 */
|
|
11
15
|
const READ_TIMEOUT_MS = 30_000;
|
|
12
16
|
/** 用户自己写的文字;工具结果、插件加的说明不算 */
|
|
@@ -39,11 +43,20 @@ export default definePlugin({
|
|
|
39
43
|
optional: true,
|
|
40
44
|
timeoutMs: READ_TIMEOUT_MS + 5_000,
|
|
41
45
|
fn: async (messages, hook) => {
|
|
42
|
-
|
|
43
|
-
const start = Math.max(state
|
|
44
|
-
|
|
46
|
+
const state = hook.derived[key];
|
|
47
|
+
const start = Math.max(state?.upTo ?? 0, scanned);
|
|
48
|
+
/** 这次记下的;hook.derived 是调用时的快照,刚记下的不在里面 */
|
|
49
|
+
const fresh = new Map();
|
|
50
|
+
if (state?.attached) {
|
|
51
|
+
// 旧格式的会话:先拆成每条消息一个 key,进度里去掉整表,之后不再随新的 @ 重写
|
|
52
|
+
for (const [i, blocks] of Object.entries(state.attached)) {
|
|
53
|
+
await hook.record(attachedKey(key, Number(i)), blocks);
|
|
54
|
+
fresh.set(Number(i), blocks);
|
|
55
|
+
}
|
|
56
|
+
await hook.record(key, { upTo: state.upTo });
|
|
57
|
+
}
|
|
45
58
|
if (messages.length > start) {
|
|
46
|
-
|
|
59
|
+
let changed = false;
|
|
47
60
|
const signal = AbortSignal.any([hook.signal, AbortSignal.timeout(READ_TIMEOUT_MS)]);
|
|
48
61
|
for (let i = start; i < messages.length; i++) {
|
|
49
62
|
const text = userText(messages[i]);
|
|
@@ -51,18 +64,23 @@ export default definePlugin({
|
|
|
51
64
|
continue;
|
|
52
65
|
changed = true;
|
|
53
66
|
const refs = await attachMentions(text, { cwd: ctx.cwd, plugin: ctx.plugin, signal });
|
|
54
|
-
if (refs.blocks.length)
|
|
55
|
-
|
|
67
|
+
if (refs.blocks.length) {
|
|
68
|
+
await hook.record(attachedKey(key, i), refs.blocks);
|
|
69
|
+
fresh.set(i, refs.blocks);
|
|
70
|
+
}
|
|
56
71
|
if (refs.attached.length || refs.failed.length)
|
|
57
72
|
await hook.emit("attached", { attached: refs.attached, failed: refs.failed });
|
|
58
73
|
}
|
|
59
|
-
|
|
60
|
-
//
|
|
74
|
+
// 处理过带 @ 的消息才记:恢复的会话不再重新读这些消息引用的文件(文件可能已经变了)
|
|
75
|
+
// 附件先于进度记下:两次记录之间崩溃时请求还没发出,恢复后重新处理这条消息即可
|
|
61
76
|
if (changed)
|
|
62
|
-
await hook.record(key,
|
|
77
|
+
await hook.record(key, { upTo: messages.length });
|
|
63
78
|
scanned = messages.length;
|
|
64
79
|
}
|
|
65
|
-
return messages.map((m, i) =>
|
|
80
|
+
return messages.map((m, i) => {
|
|
81
|
+
const extra = fresh.get(i) ?? hook.derived[attachedKey(key, i)];
|
|
82
|
+
return extra ? { ...m, content: [...m.content, ...extra] } : m;
|
|
83
|
+
});
|
|
66
84
|
},
|
|
67
85
|
});
|
|
68
86
|
},
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { definePlugin } from "../../dist/api.js";
|
|
8
8
|
import { contextWindow } from "./context.js";
|
|
9
|
-
import { envWithFile, hasProvider } from "./config.js";
|
|
9
|
+
import { envWithFile, hasProvider, parseTokens } from "./config.js";
|
|
10
10
|
import { configurator } from "./configure.js";
|
|
11
11
|
import { isBuiltinKind, listModels, MODEL_KEY, providerFromEnv, providerInfo, providerKind, RateGate, rpmFromEnv, visionFromEnv, withRetry } from "./provider.js";
|
|
12
12
|
import { readSavedServices } from "./saved.js";
|
|
@@ -99,7 +99,21 @@ export default definePlugin({
|
|
|
99
99
|
// 写错的 JADE_VISION 在创建 provider 时报错,这里当作不能看
|
|
100
100
|
vision = false;
|
|
101
101
|
}
|
|
102
|
-
|
|
102
|
+
let maxTokens;
|
|
103
|
+
try {
|
|
104
|
+
maxTokens = env.JADE_MAX_TOKENS ? parseTokens("JADE_MAX_TOKENS", env.JADE_MAX_TOKENS) : undefined;
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
// 写错的在创建 provider 时报错
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
kind: info.kind,
|
|
111
|
+
model: info.model,
|
|
112
|
+
via: via(info.kind, info.baseURL),
|
|
113
|
+
contextWindow: contextWindow(info.model, env),
|
|
114
|
+
vision,
|
|
115
|
+
...(maxTokens === undefined ? {} : { maxTokens }),
|
|
116
|
+
};
|
|
103
117
|
},
|
|
104
118
|
complete,
|
|
105
119
|
list: () => listModels(env),
|
|
@@ -3,9 +3,13 @@
|
|
|
3
3
|
import { definePlugin } from "../../dist/api.js";
|
|
4
4
|
const USAGE = `usage: jade -p <prompt> [--resume <session id>]
|
|
5
5
|
echo <prompt> | jade -p
|
|
6
|
+
cat <file> | jade -p - <prompt>
|
|
7
|
+
|
|
8
|
+
With "-", what comes in on stdin is added after the prompt (without a prompt, stdin is the prompt).
|
|
6
9
|
|
|
7
10
|
Runs one prompt and exits. The reply goes to stdout; tool calls and notices go to stderr.
|
|
8
|
-
Exit code: 0 when the turn ends normally, 1 on an error, 130 when interrupted
|
|
11
|
+
Exit code: 0 when the turn ends normally, 1 on an error, 130 when interrupted.
|
|
12
|
+
jade's own commands (plugins, update, --safe): jade help`;
|
|
9
13
|
const ui = {
|
|
10
14
|
interactive: false,
|
|
11
15
|
notify(message, level = "info") {
|
|
@@ -25,12 +29,22 @@ const frontend = {
|
|
|
25
29
|
process.stdout.write(`${USAGE}\n`);
|
|
26
30
|
return 0;
|
|
27
31
|
}
|
|
28
|
-
|
|
32
|
+
// 有 prompt 参数时只在写了 "-" 时读 stdin:脚本启动 jade -p 时 stdin 常是没人关的管道,默认去读会一直等下去
|
|
33
|
+
const piped = args.stdin || (args.prompt === undefined && !process.stdin.isTTY) ? (await readStdin()).trim() : "";
|
|
34
|
+
const prompt = [args.prompt, piped].filter(Boolean).join("\n\n");
|
|
29
35
|
if (!prompt) {
|
|
30
36
|
process.stderr.write(`no prompt given\n\n${USAGE}\n`);
|
|
31
37
|
return 2;
|
|
32
38
|
}
|
|
33
|
-
|
|
39
|
+
let session;
|
|
40
|
+
try {
|
|
41
|
+
session = await sessions.open(args.resume ? { resume: args.resume } : {});
|
|
42
|
+
}
|
|
43
|
+
catch (e) {
|
|
44
|
+
// 例如 --resume 的会话不存在:只说原因,不带插件名的包装
|
|
45
|
+
process.stderr.write(`jade: ${args.resume ? `could not resume ${args.resume}` : "could not start a session"}: ${errorText(e)}\n`);
|
|
46
|
+
return args.resume ? 2 : 1;
|
|
47
|
+
}
|
|
34
48
|
let ended;
|
|
35
49
|
let midLine = false;
|
|
36
50
|
const out = (text) => {
|
|
@@ -96,9 +110,7 @@ const frontend = {
|
|
|
96
110
|
if (end?.reason === "aborted")
|
|
97
111
|
return 130;
|
|
98
112
|
if (failure !== undefined || end?.reason === "error") {
|
|
99
|
-
|
|
100
|
-
const cause = failure instanceof Error && failure.cause instanceof Error ? failure.cause : failure;
|
|
101
|
-
process.stderr.write(`error: ${cause instanceof Error ? cause.message : (end?.error ?? String(cause ?? "the turn failed"))}\n`);
|
|
113
|
+
process.stderr.write(`error: ${failure !== undefined ? errorText(failure) : (end?.error ?? "the turn failed")}\n`);
|
|
102
114
|
return 1;
|
|
103
115
|
}
|
|
104
116
|
return 0;
|
|
@@ -119,6 +131,8 @@ function parse(argv) {
|
|
|
119
131
|
continue;
|
|
120
132
|
if (a === "-h" || a === "--help")
|
|
121
133
|
out.help = true;
|
|
134
|
+
else if (a === "-")
|
|
135
|
+
out.stdin = true;
|
|
122
136
|
else if (a === "--resume") {
|
|
123
137
|
const id = argv[++i];
|
|
124
138
|
if (!id)
|
|
@@ -147,6 +161,11 @@ function summary(input) {
|
|
|
147
161
|
const line = (s ?? "").split("\n")[0];
|
|
148
162
|
return line.length > 120 ? `${line.slice(0, 120)}…` : line;
|
|
149
163
|
}
|
|
164
|
+
/** 经过膜的错误包成了 PluginError,带着插件名;用户要看的是原因 */
|
|
165
|
+
function errorText(e) {
|
|
166
|
+
const cause = e instanceof Error && e.cause instanceof Error ? e.cause : e;
|
|
167
|
+
return cause instanceof Error ? cause.message : String(cause);
|
|
168
|
+
}
|
|
150
169
|
function firstLine(content) {
|
|
151
170
|
const text = content.find((b) => b.kind === "text");
|
|
152
171
|
return text && "text" in text ? text.text.split("\n")[0] : "(no message)";
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// jade/prompts:在 context.build 里生成系统提示词。其他插件经 prompts@1 往里加段落。
|
|
2
|
+
// 也负责内核不写的、给模型看的说明:内容为空的错误工具结果在投影里补一句原因(results.ts)。
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import { definePlugin } from "../../dist/api.js";
|
|
4
5
|
import { allInstructions, environment, mainPrompt, realPath } from "./prompts.js";
|
|
6
|
+
import { explainEmptyResults, whyEmpty } from "./results.js";
|
|
5
7
|
const ID = "jade/prompts";
|
|
6
8
|
/** 其他插件加的段落。模块每个进程只加载一次,进程级和会话级共用 */
|
|
7
9
|
const sections = [];
|
|
@@ -39,6 +41,32 @@ export default definePlugin({
|
|
|
39
41
|
// 告诉用户读了哪些指令文件,否则看不出它们生效了
|
|
40
42
|
if (instructions.length > 0)
|
|
41
43
|
ctx.service("ui@1")?.notify(`loaded instructions: ${instructions.map((i) => display(realPath(ctx.cwd), i.file)).join(", ")}`);
|
|
44
|
+
// 内容为空的错误工具结果补上说明(results.ts)。原因记在 derived 里;同一批里可能有几个,
|
|
45
|
+
// observe 并发执行、拿到的 derived 快照可能是旧的,所以在这里累积,每次记完整的一份。
|
|
46
|
+
// 运行时不等 observe:紧接着的模型调用投影时记录可能还没落盘,所以投影也看这份累积的。
|
|
47
|
+
// observe 在事件写入时就(以微任务)开始执行,早于之后的投影;下一轮之前记录一定已落盘,恢复会话时从 derived 读,
|
|
48
|
+
// 所以投影只取决于日志,每次相同
|
|
49
|
+
const reasonsKey = `${ID}/empty-results`;
|
|
50
|
+
let reasons;
|
|
51
|
+
ctx.kernel.hook({
|
|
52
|
+
kind: "observe",
|
|
53
|
+
point: "event",
|
|
54
|
+
fn: async (e, hook) => {
|
|
55
|
+
const found = whyEmpty(e);
|
|
56
|
+
if (!found)
|
|
57
|
+
return;
|
|
58
|
+
reasons ??= { ...(hook.derived[reasonsKey] ?? {}) };
|
|
59
|
+
reasons[found.toolUseId] = found.why;
|
|
60
|
+
await hook.record(reasonsKey, { ...reasons });
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
ctx.kernel.hook({
|
|
64
|
+
kind: "transform",
|
|
65
|
+
point: "context.project",
|
|
66
|
+
// 出错时跳过(不补说明),不让这一轮失败
|
|
67
|
+
optional: true,
|
|
68
|
+
fn: (messages, hook) => explainEmptyResults(messages, { ...hook.derived[reasonsKey], ...reasons }, ID),
|
|
69
|
+
});
|
|
42
70
|
ctx.kernel.hook({
|
|
43
71
|
kind: "transform",
|
|
44
72
|
point: "context.build",
|
|
@@ -71,7 +71,8 @@ export async function environment(cwd, today = localDate()) {
|
|
|
71
71
|
const [branch, status, entries] = await gitSnapshot(cwd);
|
|
72
72
|
if (branch) {
|
|
73
73
|
lines.push(`- Git branch: ${branch}`);
|
|
74
|
-
|
|
74
|
+
const shown = status === undefined ? "unknown (git status did not finish)" : status ? `\n${status.split("\n").slice(0, 30).join("\n")}` : "clean";
|
|
75
|
+
lines.push(`- Git status at session start: ${shown}`);
|
|
75
76
|
}
|
|
76
77
|
else {
|
|
77
78
|
lines.push("- Not a git repository");
|
|
@@ -153,7 +154,8 @@ function gitSnapshot(cwd) {
|
|
|
153
154
|
// 三个 git 命令同时跑:Windows 上每启动一次 git 要几十毫秒,启动时会串起来等
|
|
154
155
|
p = Promise.all([
|
|
155
156
|
git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]),
|
|
156
|
-
git
|
|
157
|
+
// 巨型仓库里 git status 可能要很久,会话打开要等它:超时就不给
|
|
158
|
+
git(cwd, ["status", "--short"], STATUS_TIMEOUT_MS),
|
|
157
159
|
// 让模型一开始就知道仓库的大致样子,不用先盲猜语言、到处 ls
|
|
158
160
|
topLevel(cwd),
|
|
159
161
|
]);
|
|
@@ -212,9 +214,11 @@ export function repoRoot(cwd) {
|
|
|
212
214
|
}
|
|
213
215
|
return p;
|
|
214
216
|
}
|
|
215
|
-
|
|
217
|
+
/** 会话开始时 git status 最多等这么久 */
|
|
218
|
+
const STATUS_TIMEOUT_MS = 3000;
|
|
219
|
+
async function git(cwd, args, timeoutMs) {
|
|
216
220
|
try {
|
|
217
|
-
const { code, stdout } = await run(["git", ...args], { cwd });
|
|
221
|
+
const { code, stdout } = await run(["git", ...args], timeoutMs === undefined ? { cwd } : { cwd, timeoutMs });
|
|
218
222
|
return code === 0 ? stdout.trim() : undefined;
|
|
219
223
|
}
|
|
220
224
|
catch {
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// 内容为空的错误工具结果:内核不写说明文字(I-1),模型只看到 is_error,分不清是工具名写错、没执行还是被拒绝,
|
|
2
|
+
// 容易原样重试。这里在投影里按原因补一句说明(I-4:只改投影,不改日志)。
|
|
3
|
+
//
|
|
4
|
+
// 空结果有四种来源,块本身只能分出最后一种(origin 不是 runtime):
|
|
5
|
+
// - 调用了不存在的工具:运行时直接拒绝(tool.decided 没有 reason,也没有 decidedBy)
|
|
6
|
+
// - 崩溃恢复时,执行到一半的非幂等工具记为 tool.interrupted
|
|
7
|
+
// - 这一轮先结束了(用户中断、出错、输出被截断),没有结果的调用由内核补成空的错误结果
|
|
8
|
+
// - 关卡拒绝但没给原因(例如关卡 hook 出错或超时,按拒绝处理;tool.decided 有 decidedBy)
|
|
9
|
+
// tool.decided 的 origin 一律是 runtime,分不出前一种和最后一种,要看 decidedBy(与内核 step.ts 的判断相同)。
|
|
10
|
+
// 前两种只有日志事件分得出来,由 observe 记进 derived,投影时按它说明;恢复会话后同样成立,
|
|
11
|
+
// 投影也只取决于日志,每次算出的结果相同,不破坏提示缓存。
|
|
12
|
+
/** 从事件判断空结果的原因;不是这两种返回 undefined */
|
|
13
|
+
export function whyEmpty(e) {
|
|
14
|
+
if (e.type === "tool.decided") {
|
|
15
|
+
const d = e.data;
|
|
16
|
+
if (d.decision === "deny" && !d.reason && d.decidedBy === undefined)
|
|
17
|
+
return { toolUseId: d.toolUseId, why: "unknown-tool" };
|
|
18
|
+
}
|
|
19
|
+
if (e.type === "tool.interrupted")
|
|
20
|
+
return { toolUseId: e.data.toolUseId, why: "interrupted" };
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
function explanation(why, origin, name) {
|
|
24
|
+
if (why === "unknown-tool") {
|
|
25
|
+
return `There is no tool named ${JSON.stringify(name ?? "")}; the call was not run. Use only the tools you were given.`;
|
|
26
|
+
}
|
|
27
|
+
if (why === "interrupted") {
|
|
28
|
+
return "This call was interrupted while it was running (jade stopped before it finished), so it may have partly taken effect. Check its effects before running it again.";
|
|
29
|
+
}
|
|
30
|
+
if (origin.by === "runtime") {
|
|
31
|
+
return "This call has no result: the turn ended before it finished (the user interrupted, an error occurred, or the response was cut off). It may not have run, or may have stopped partway; check its effects before relying on them or running it again.";
|
|
32
|
+
}
|
|
33
|
+
if (origin.by === "user")
|
|
34
|
+
return "The user declined this call.";
|
|
35
|
+
return "This call was blocked by a check in jade, which gave no reason. Do not retry it unchanged.";
|
|
36
|
+
}
|
|
37
|
+
/** 给内容为空的错误工具结果补上说明;没有要补的时候原样返回 */
|
|
38
|
+
export function explainEmptyResults(messages, reasons, plugin) {
|
|
39
|
+
let names;
|
|
40
|
+
const nameOf = (id) => {
|
|
41
|
+
names ??= new Map(messages.flatMap((m) => m.content.flatMap((b) => (b.kind === "tool_use" ? [[b.id, b.name]] : []))));
|
|
42
|
+
return names.get(id);
|
|
43
|
+
};
|
|
44
|
+
let changed = false;
|
|
45
|
+
const out = messages.map((m) => {
|
|
46
|
+
if (m.role !== "user" || !m.content.some((b) => b.kind === "tool_result" && b.isError && b.content.length === 0))
|
|
47
|
+
return m;
|
|
48
|
+
changed = true;
|
|
49
|
+
return {
|
|
50
|
+
...m,
|
|
51
|
+
content: m.content.map((b) => {
|
|
52
|
+
if (b.kind !== "tool_result" || !b.isError || b.content.length > 0)
|
|
53
|
+
return b;
|
|
54
|
+
const text = explanation(reasons[b.toolUseId], b.origin, nameOf(b.toolUseId));
|
|
55
|
+
return { ...b, content: [{ kind: "text", text, origin: { by: "plugin", id: plugin }, trust: "trusted" }] };
|
|
56
|
+
}),
|
|
57
|
+
};
|
|
58
|
+
});
|
|
59
|
+
return changed ? out : messages;
|
|
60
|
+
}
|
|
@@ -31,11 +31,23 @@ export function spawn(cmd, opts = {}) {
|
|
|
31
31
|
});
|
|
32
32
|
});
|
|
33
33
|
}
|
|
34
|
-
/** 运行一条命令,返回 stdout 文本和退出码;启动失败时 reject */
|
|
34
|
+
/** 运行一条命令,返回 stdout 文本和退出码;启动失败时 reject。超过 timeoutMs 时杀掉,退出码为 null */
|
|
35
35
|
export async function run(cmd, opts = {}) {
|
|
36
36
|
const proc = await spawn(cmd, { cwd: opts.cwd, stderr: "ignore" });
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
let timedOut = false;
|
|
38
|
+
const timer = opts.timeoutMs === undefined
|
|
39
|
+
? undefined
|
|
40
|
+
: setTimeout(() => {
|
|
41
|
+
timedOut = true;
|
|
42
|
+
proc.kill();
|
|
43
|
+
}, opts.timeoutMs);
|
|
44
|
+
try {
|
|
45
|
+
const [stdout, code] = await Promise.all([text(proc.stdout), proc.exited]);
|
|
46
|
+
return { code: timedOut ? null : code, stdout };
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
clearTimeout(timer);
|
|
50
|
+
}
|
|
39
51
|
}
|
|
40
52
|
export async function text(stream) {
|
|
41
53
|
const decoder = new TextDecoder();
|
|
@@ -131,6 +131,7 @@ export default definePlugin({
|
|
|
131
131
|
allowed: (call) => ctx.service("approval@1")?.allows(ctx.session.id, call) ?? false,
|
|
132
132
|
id: ctx.plugin,
|
|
133
133
|
usage: (toolUseId, u) => void usage.set(toolUseId, u),
|
|
134
|
+
contextWindow: () => models.current()?.contextWindow,
|
|
134
135
|
}));
|
|
135
136
|
// 子 Agent 的用量记成本插件的事件(和压缩、审查的用量一样),界面据此计入会话用量;只能在 hook 里记
|
|
136
137
|
ctx.kernel.hook({
|
|
@@ -6,7 +6,17 @@
|
|
|
6
6
|
import { realpathSync } from "node:fs";
|
|
7
7
|
import os from "node:os";
|
|
8
8
|
import path from "node:path";
|
|
9
|
-
import { definePlugin as kernelPlugin, MemoryLogStore, Runtime, } from "uncarved";
|
|
9
|
+
import { definePlugin as kernelPlugin, MemoryLogStore, Runtime, ProviderError, } from "uncarved";
|
|
10
|
+
/** 历史到了上下文窗口的这个比例就停下来写报告:子 Agent 没有压缩,再读几个大文件就会超出窗口 */
|
|
11
|
+
const WRAP_UP_AT = 0.7;
|
|
12
|
+
/** 写报告时工具输出最多占窗口的这个比例,更早的不放进去,保证报告这次请求放得下 */
|
|
13
|
+
const REPORT_TOOL_SHARE = 0.5;
|
|
14
|
+
/** 不知道窗口时按这个算 */
|
|
15
|
+
const FALLBACK_WINDOW = 128_000;
|
|
16
|
+
/** 粗略估算:英文和代码约 4 个字符 1 个 token */
|
|
17
|
+
const CHARS_PER_TOKEN = 4;
|
|
18
|
+
/** 不放进报告请求的工具输出换成这句 */
|
|
19
|
+
export const OMITTED = "[Output omitted to fit the context window. Use what you noted from it in your later messages.]";
|
|
10
20
|
const NOBODY = { approved: false, reason: "Nobody can approve this action for a sub-agent. Report what you need instead." };
|
|
11
21
|
/** 用完步数还没写报告时追加的消息 */
|
|
12
22
|
export const WRAP_UP = "You have reached your step limit. Do not call any more tools: write your report now from what you have found so far, " +
|
|
@@ -66,8 +76,33 @@ function needsApproval(cwd, input) {
|
|
|
66
76
|
return `read ${i.pattern}, outside the working directory`;
|
|
67
77
|
return undefined;
|
|
68
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* 从最新的往前保留工具输出,合计不超过 maxChars;更早的换成 OMITTED。只改投影(I-4),工具结果不是模型块(I-6)。
|
|
81
|
+
* 没有超出时原样返回
|
|
82
|
+
*/
|
|
83
|
+
export function fitToolResults(messages, maxChars, plugin) {
|
|
84
|
+
const size = (b) => JSON.stringify(b.kind === "tool_result" ? b.content : "").length;
|
|
85
|
+
let used = 0;
|
|
86
|
+
let cut = -1;
|
|
87
|
+
for (let i = messages.length - 1; i >= 0 && cut < 0; i--) {
|
|
88
|
+
for (const b of messages[i].content) {
|
|
89
|
+
if (b.kind !== "tool_result")
|
|
90
|
+
continue;
|
|
91
|
+
used += size(b);
|
|
92
|
+
if (used > maxChars)
|
|
93
|
+
cut = i;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (cut < 0)
|
|
97
|
+
return messages;
|
|
98
|
+
const note = { kind: "text", text: OMITTED, origin: { by: "plugin", id: plugin }, trust: "trusted" };
|
|
99
|
+
return messages.map((m, i) => i > cut || !m.content.some((b) => b.kind === "tool_result")
|
|
100
|
+
? m
|
|
101
|
+
: { ...m, content: m.content.map((b) => (b.kind === "tool_result" && b.content.length > 0 ? { ...b, content: [note] } : b)) });
|
|
102
|
+
}
|
|
69
103
|
/** 子 Agent 的插件:只读工具、提示词、关卡、步数上限。每个子会话一套新的 */
|
|
70
104
|
function plugins(opts, tools, control, signal) {
|
|
105
|
+
const window = () => opts.contextWindow?.() ?? FALLBACK_WINDOW;
|
|
71
106
|
const names = tools.map((t) => t.name);
|
|
72
107
|
const system = subagentPrompt(names, opts.maxSteps);
|
|
73
108
|
const env = ["# Environment", `- Working directory: ${opts.cwd}`, `- Platform: ${process.platform} (${os.release()})`, `- Today: ${opts.today ?? localDate()}`].join("\n");
|
|
@@ -93,8 +128,20 @@ function plugins(opts, tools, control, signal) {
|
|
|
93
128
|
return answer.approved ? { decision: "allow" } : { decision: "deny", reason: answer.reason ?? NOBODY.reason };
|
|
94
129
|
},
|
|
95
130
|
},
|
|
96
|
-
// 步数上限;wrapUp
|
|
97
|
-
{
|
|
131
|
+
// 步数上限;wrapUp 时只再要一次回复(报告)。历史接近上下文窗口时也停下,之后要报告
|
|
132
|
+
{
|
|
133
|
+
kind: "gate",
|
|
134
|
+
point: "turn.continue",
|
|
135
|
+
fn: (s) => stepsThisTurn(s) >= (control.wrapUp ? 1 : opts.maxSteps) || (control.lastTokens ?? 0) >= window() * WRAP_UP_AT
|
|
136
|
+
? { decision: "deny" }
|
|
137
|
+
: { decision: "abstain" },
|
|
138
|
+
},
|
|
139
|
+
// 要报告时工具输出可能已经很多(上面停下时、或者已经超出窗口):只放进最近的一部分
|
|
140
|
+
{
|
|
141
|
+
kind: "transform",
|
|
142
|
+
point: "context.project",
|
|
143
|
+
fn: (messages) => (control.wrapUp ? fitToolResults(messages, window() * REPORT_TOOL_SHARE * CHARS_PER_TOKEN, `${opts.id}/subagent`) : messages),
|
|
144
|
+
},
|
|
98
145
|
],
|
|
99
146
|
}),
|
|
100
147
|
];
|
|
@@ -145,6 +192,9 @@ export function taskTool(opts) {
|
|
|
145
192
|
names.set(b.id, b.name);
|
|
146
193
|
for (const k of Object.keys(used))
|
|
147
194
|
used[k] += data.usage?.[k] ?? 0;
|
|
195
|
+
// 输入 token 已含缓存部分(各 provider 的 Usage 约定);这次的输出也会进下一次请求
|
|
196
|
+
if (data.usage)
|
|
197
|
+
control.lastTokens = (data.usage.inputTokens ?? 0) + (data.usage.outputTokens ?? 0);
|
|
148
198
|
}
|
|
149
199
|
else if (n.event.type === "tool.decided") {
|
|
150
200
|
const d = n.event.data;
|
|
@@ -158,17 +208,31 @@ export function taskTool(opts) {
|
|
|
158
208
|
ctx.signal.addEventListener("abort", forward, { once: true });
|
|
159
209
|
let failure;
|
|
160
210
|
const turn = (text) => child.send({ kind: "message", content: [{ kind: "text", text, origin: { by: "runtime" }, trust: "trusted" }] });
|
|
211
|
+
let recovered;
|
|
161
212
|
try {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
213
|
+
try {
|
|
214
|
+
await turn(prompt);
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
failure = err;
|
|
218
|
+
}
|
|
219
|
+
// 步数用完或历史接近窗口时,最后一条回复通常只有工具调用;出错(例如超出上下文窗口)时也没有报告。
|
|
220
|
+
// 再要一次报告,否则前面的调研全白做了。重试已经用完的错误(限流、服务不可用)不再要:再试一次也一样,还要再等很久
|
|
221
|
+
const cause = unwrap(failure);
|
|
222
|
+
const exhausted = cause instanceof ProviderError && cause.retryable;
|
|
223
|
+
if (!ctx.signal.aborted && !exhausted && !lastText(child.state.messages)) {
|
|
165
224
|
control.wrapUp = true;
|
|
166
|
-
|
|
225
|
+
try {
|
|
226
|
+
await turn(WRAP_UP);
|
|
227
|
+
if (failure !== undefined)
|
|
228
|
+
recovered = cause instanceof Error ? cause.message : String(cause);
|
|
229
|
+
failure = undefined;
|
|
230
|
+
}
|
|
231
|
+
catch (err) {
|
|
232
|
+
failure ??= err;
|
|
233
|
+
}
|
|
167
234
|
}
|
|
168
235
|
}
|
|
169
|
-
catch (err) {
|
|
170
|
-
failure = err;
|
|
171
|
-
}
|
|
172
236
|
finally {
|
|
173
237
|
ctx.signal.removeEventListener("abort", forward);
|
|
174
238
|
await child.close().catch(() => { });
|
|
@@ -182,10 +246,22 @@ export function taskTool(opts) {
|
|
|
182
246
|
const msg = failure instanceof Error ? failure.message : String(failure);
|
|
183
247
|
return { content: `Sub-agent failed: ${msg}${text ? `\nLast output:\n${text}` : ""}`, isError: true };
|
|
184
248
|
}
|
|
249
|
+
if (recovered && text)
|
|
250
|
+
return { content: `(The sub-agent stopped on an error: ${recovered}. This report was written afterwards from what it had found.)\n\n${text}` };
|
|
185
251
|
return { content: text || "(sub-agent returned no text)", isError: !text };
|
|
186
252
|
},
|
|
187
253
|
};
|
|
188
254
|
}
|
|
255
|
+
/**
|
|
256
|
+
* 模型调用经 models@1 跨插件,错误被宿主的膜包成 PluginError(原来的错误在 cause 里)。
|
|
257
|
+
* 插件不从宿主 import 值,按 name 认
|
|
258
|
+
*/
|
|
259
|
+
function unwrap(err) {
|
|
260
|
+
let e = err;
|
|
261
|
+
for (let i = 0; i < 5 && e instanceof Error && e.name === "PluginError" && e.cause !== undefined; i++)
|
|
262
|
+
e = e.cause;
|
|
263
|
+
return e;
|
|
264
|
+
}
|
|
189
265
|
const textOf = (m) => m.content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n").trim();
|
|
190
266
|
/** 最后一条回复的正文 */
|
|
191
267
|
function lastText(messages) {
|
|
@@ -32,9 +32,9 @@ export function todoTool() {
|
|
|
32
32
|
required: ["todos"],
|
|
33
33
|
additionalProperties: false,
|
|
34
34
|
},
|
|
35
|
-
//
|
|
35
|
+
// 不碰文件和进程;可以和同一批的读并发(用到清单的地方按模型给出的顺序取最后一次调用,与执行顺序无关)
|
|
36
36
|
effect: "read",
|
|
37
|
-
concurrency: "
|
|
37
|
+
concurrency: "safe",
|
|
38
38
|
idempotent: true,
|
|
39
39
|
async execute(input) {
|
|
40
40
|
const todos = input.todos;
|