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