@uncarved/jade 0.1.2 → 0.1.3
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 +204 -198
- package/bin/jade.js +23 -0
- package/dist/commands.d.ts +20 -0
- package/dist/commands.js +20 -0
- package/dist/commands.js.map +1 -1
- package/dist/distro.d.ts +43 -6
- package/dist/distro.js +198 -48
- package/dist/distro.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/main.js +436 -300
- package/dist/main.js.map +1 -1
- package/dist/plugin-cli.d.ts +1 -1
- package/dist/plugin-cli.js +79 -36
- package/dist/plugin-cli.js.map +1 -1
- package/dist/plugins/budget.d.ts +2 -2
- package/dist/plugins/budget.js +2 -2
- package/dist/plugins/budget.js.map +1 -1
- package/dist/plugins/builtins.js +6 -3
- package/dist/plugins/builtins.js.map +1 -1
- package/dist/plugins/checks.d.ts +2 -1
- package/dist/plugins/checks.js +25 -5
- package/dist/plugins/checks.js.map +1 -1
- package/dist/plugins/compact.js +45 -1
- package/dist/plugins/compact.js.map +1 -1
- package/dist/plugins/core.d.ts +5 -0
- package/dist/plugins/core.js +39 -0
- package/dist/plugins/core.js.map +1 -1
- package/dist/plugins/host.d.ts +52 -0
- package/dist/plugins/host.js +115 -0
- package/dist/plugins/host.js.map +1 -0
- package/dist/plugins/install.d.ts +1 -1
- package/dist/plugins/loader.d.ts +238 -10
- package/dist/plugins/loader.js +175 -21
- package/dist/plugins/loader.js.map +1 -1
- package/dist/plugins/policy.d.ts +2 -0
- package/dist/plugins/policy.js +17 -1
- package/dist/plugins/policy.js.map +1 -1
- package/dist/plugins/prompts.d.ts +6 -1
- package/dist/plugins/prompts.js +103 -15
- package/dist/plugins/prompts.js.map +1 -1
- package/dist/plugins/repeats.d.ts +7 -0
- package/dist/plugins/repeats.js +74 -13
- package/dist/plugins/repeats.js.map +1 -1
- package/dist/plugins/review.d.ts +2 -0
- package/dist/plugins/review.js +41 -3
- package/dist/plugins/review.js.map +1 -1
- package/dist/plugins/sessions.d.ts +7 -0
- package/dist/plugins/sessions.js +110 -0
- package/dist/plugins/sessions.js.map +1 -0
- package/dist/provider.d.ts +56 -2
- package/dist/provider.js +73 -7
- package/dist/provider.js.map +1 -1
- package/dist/session-lifecycle.d.ts +61 -0
- package/dist/session-lifecycle.js +167 -0
- package/dist/session-lifecycle.js.map +1 -0
- package/dist/session-scope.d.ts +53 -0
- package/dist/session-scope.js +116 -0
- package/dist/session-scope.js.map +1 -0
- package/dist/sessions.d.ts +6 -0
- package/dist/sessions.js +20 -0
- package/dist/sessions.js.map +1 -1
- package/dist/sys.d.ts +4 -1
- package/dist/sys.js +18 -1
- package/dist/sys.js.map +1 -1
- package/dist/tools/ask.d.ts +11 -0
- package/dist/tools/ask.js +62 -0
- package/dist/tools/ask.js.map +1 -0
- package/dist/tools/fs.d.ts +4 -0
- package/dist/tools/fs.js +53 -12
- package/dist/tools/fs.js.map +1 -1
- package/dist/tools/grep.js +3 -2
- package/dist/tools/grep.js.map +1 -1
- package/dist/tools/shell.js +5 -1
- package/dist/tools/shell.js.map +1 -1
- package/dist/tools/task.d.ts +6 -2
- package/dist/tools/task.js +36 -8
- package/dist/tools/task.js.map +1 -1
- package/dist/tools/web.d.ts +33 -3
- package/dist/tools/web.js +351 -143
- package/dist/tools/web.js.map +1 -1
- package/dist/ui/configure.js +91 -22
- package/dist/ui/configure.js.map +1 -1
- package/dist/ui/diff.d.ts +1 -1
- package/dist/ui/diff.js +1 -2
- package/dist/ui/diff.js.map +1 -1
- package/dist/ui/editor.d.ts +8 -0
- package/dist/ui/editor.js +50 -1
- package/dist/ui/editor.js.map +1 -1
- package/dist/ui/markdown.d.ts +6 -1
- package/dist/ui/markdown.js +57 -19
- package/dist/ui/markdown.js.map +1 -1
- package/dist/ui/render.d.ts +9 -10
- package/dist/ui/render.js +35 -72
- package/dist/ui/render.js.map +1 -1
- package/dist/ui/renderers.d.ts +8 -0
- package/dist/ui/renderers.js +169 -0
- package/dist/ui/renderers.js.map +1 -0
- package/dist/ui/screen.d.ts +22 -2
- package/dist/ui/screen.js +104 -15
- package/dist/ui/screen.js.map +1 -1
- package/dist/ui/transcript.d.ts +13 -0
- package/dist/ui/transcript.js +105 -15
- package/dist/ui/transcript.js.map +1 -1
- package/dist/ui/tui.d.ts +2 -0
- package/dist/ui/tui.js +309 -58
- package/dist/ui/tui.js.map +1 -1
- package/dist/update.d.ts +53 -0
- package/dist/update.js +255 -0
- package/dist/update.js.map +1 -0
- package/package.json +6 -5
- package/src/commands.ts +24 -0
- package/src/distro.ts +228 -51
- package/src/index.ts +2 -0
- package/src/main.ts +413 -292
- package/src/plugin-cli.ts +73 -34
- package/src/plugins/budget.ts +4 -4
- package/src/plugins/builtins.ts +6 -3
- package/src/plugins/checks.ts +25 -6
- package/src/plugins/compact.ts +40 -1
- package/src/plugins/core.ts +40 -0
- package/src/plugins/host.ts +146 -0
- package/src/plugins/install.ts +1 -1
- package/src/plugins/loader.ts +379 -23
- package/src/plugins/policy.ts +17 -1
- package/src/plugins/prompts.ts +108 -15
- package/src/plugins/repeats.ts +75 -14
- package/src/plugins/review.ts +40 -3
- package/src/plugins/sessions.ts +109 -0
- package/src/provider.ts +109 -10
- package/src/session-lifecycle.ts +194 -0
- package/src/session-scope.ts +135 -0
- package/src/sessions.ts +17 -0
- package/src/sys.ts +18 -1
- package/src/tools/ask.ts +72 -0
- package/src/tools/fs.ts +53 -12
- package/src/tools/grep.ts +3 -2
- package/src/tools/shell.ts +5 -1
- package/src/tools/task.ts +51 -11
- package/src/tools/web.ts +370 -140
- package/src/ui/configure.ts +90 -27
- package/src/ui/diff.ts +1 -2
- package/src/ui/editor.ts +50 -1
- package/src/ui/markdown.ts +258 -219
- package/src/ui/render.ts +35 -57
- package/src/ui/renderers.ts +183 -0
- package/src/ui/screen.ts +113 -19
- package/src/ui/transcript.ts +109 -16
- package/src/ui/tui.tsx +353 -58
- package/src/update.ts +262 -0
package/src/tools/fs.ts
CHANGED
|
@@ -17,6 +17,8 @@ import { globMatcher, run } from "../sys.ts";
|
|
|
17
17
|
|
|
18
18
|
const MAX_LINES = 2000;
|
|
19
19
|
const MAX_LINE_CHARS = 2000;
|
|
20
|
+
/** 一次 read_file 返回的文本上限(约 25k token) */
|
|
21
|
+
const MAX_READ_CHARS = 100_000;
|
|
20
22
|
const MAX_GLOB = 500;
|
|
21
23
|
const MAX_IMAGE_BYTES = 5_000_000;
|
|
22
24
|
const MAX_PDF_BYTES = 10_000_000;
|
|
@@ -51,6 +53,8 @@ export interface FsOptions {
|
|
|
51
53
|
responses?: { readonly calls: number };
|
|
52
54
|
/** grep 用的 ripgrep,默认 "rg";null 表示不用(测试) */
|
|
53
55
|
rg?: string | null;
|
|
56
|
+
/** 会话的临时目录:里面的文件只有模型自己会写(包括它跑的命令生成的),修改前不用先读 */
|
|
57
|
+
scratch?: string;
|
|
54
58
|
}
|
|
55
59
|
|
|
56
60
|
/** 读过或写过的文件当时的样子;只在本进程内有效,恢复的会话靠 checkpoints 里记的 sha256 */
|
|
@@ -64,6 +68,11 @@ interface Seen {
|
|
|
64
68
|
export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
|
|
65
69
|
const at = (p: unknown) => resolveIn(cwd, p as string);
|
|
66
70
|
const seen = new Map<string, Seen>();
|
|
71
|
+
const inScratch = (full: string) => {
|
|
72
|
+
if (opts.scratch === undefined) return false;
|
|
73
|
+
const rel = path.relative(opts.scratch, full);
|
|
74
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
|
|
75
|
+
};
|
|
67
76
|
/** 文件没变时保留更早的 call:之前的回复里读过,这次回复里又读一遍,不影响修改 */
|
|
68
77
|
const remember = async (ctx: { sessionId: string }, full: string, info: Stats, text: string, call: number) => {
|
|
69
78
|
const s = seen.get(full);
|
|
@@ -73,6 +82,7 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
|
|
|
73
82
|
};
|
|
74
83
|
/** 不能修改已有文件的原因;可以修改时返回 undefined。text 是文件现在的内容 */
|
|
75
84
|
const staleness = async (ctx: { sessionId: string }, full: string, info: Stats, text: string): Promise<string | undefined> => {
|
|
85
|
+
if (inScratch(full)) return undefined;
|
|
76
86
|
const shown = display(cwd, full);
|
|
77
87
|
const modified = `${shown} has been modified since it was last read (by the user or a command). Read it again before changing it.`;
|
|
78
88
|
const s = seen.get(full);
|
|
@@ -98,7 +108,8 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
|
|
|
98
108
|
name: "read_file",
|
|
99
109
|
description:
|
|
100
110
|
"Read a UTF-8 text file, an image (png, jpg, gif, webp) or a PDF. Text is returned as lines prefixed with their 1-based line number and a tab. " +
|
|
101
|
-
`At most ${MAX_LINES} lines are returned per call; use offset (1-based start line) and limit to page through larger files
|
|
111
|
+
`At most ${MAX_LINES} lines (about ${MAX_READ_CHARS / 1000}k characters) are returned per call; use offset (1-based start line) and limit to page through larger files. ` +
|
|
112
|
+
`Lines longer than ${MAX_LINE_CHARS} characters are cut and marked "[line truncated]"; do not copy a cut line into edit_file.`,
|
|
102
113
|
inputSchema: {
|
|
103
114
|
type: "object",
|
|
104
115
|
properties: { path: str, offset: int, limit: int },
|
|
@@ -147,10 +158,20 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
|
|
|
147
158
|
const start = Math.max(1, offset);
|
|
148
159
|
const slice = lines.slice(start - 1, start - 1 + Math.min(limit, MAX_LINES));
|
|
149
160
|
if (slice.length === 0) return { content: `(file has ${lines.length} lines; offset ${start} is past the end)`, isError: true };
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
const
|
|
161
|
+
// 按整行截断到 MAX_READ_CHARS:压缩过的代码、lock 文件一次就能占掉大半个上下文
|
|
162
|
+
const out: string[] = [];
|
|
163
|
+
let size = 0;
|
|
164
|
+
for (const [i, l] of slice.entries()) {
|
|
165
|
+
const row = `${start + i}\t${l.length > MAX_LINE_CHARS ? `${l.slice(0, MAX_LINE_CHARS)}… [line truncated: ${l.length} characters]` : l}`;
|
|
166
|
+
if (out.length > 0 && size + row.length + 1 > MAX_READ_CHARS) break;
|
|
167
|
+
out.push(row);
|
|
168
|
+
size += row.length + 1;
|
|
169
|
+
}
|
|
170
|
+
const body = out.join("\n");
|
|
171
|
+
const end = start + out.length - 1;
|
|
172
|
+
if (out.length < slice.length) {
|
|
173
|
+
return { content: `${body}\n(output capped at about ${MAX_READ_CHARS} characters: showing lines ${start}-${end} of ${lines.length}; continue with offset ${end + 1})` };
|
|
174
|
+
}
|
|
154
175
|
return { content: end < lines.length ? `${body}\n(showing lines ${start}-${end} of ${lines.length})` : body };
|
|
155
176
|
},
|
|
156
177
|
};
|
|
@@ -171,12 +192,14 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
|
|
|
171
192
|
// 写入完整内容,重复执行结果相同
|
|
172
193
|
idempotent: true,
|
|
173
194
|
async execute(input, ctx) {
|
|
174
|
-
const { path: p, content } = input as { path: string; content: string };
|
|
195
|
+
const { path: p, content: given } = input as { path: string; content: string };
|
|
175
196
|
const full = at(p);
|
|
176
197
|
const info = await statOrUndefined(full);
|
|
177
198
|
if (info?.isDirectory()) return { content: `${display(cwd, full)} is a directory`, isError: true };
|
|
178
199
|
// 同样内容重复写入(崩溃后重跑)不算覆盖别人的修改
|
|
179
200
|
const before = info ? await readFile(full, "utf8") : null;
|
|
201
|
+
// read_file 不显示换行风格和 BOM:覆盖已有文件时沿用原来的,否则整个文件每一行都算改了
|
|
202
|
+
const content = before === null ? given : keepStyle(before, given);
|
|
180
203
|
const problem = info && before !== null && before !== content ? await staleness(ctx, full, info, before) : undefined;
|
|
181
204
|
if (problem) return { content: problem, isError: true };
|
|
182
205
|
await mkdir(path.dirname(full), { recursive: true });
|
|
@@ -341,19 +364,37 @@ export function applyEditsToText(text: string, edits: Edit[], shown: string): st
|
|
|
341
364
|
return { text: next };
|
|
342
365
|
}
|
|
343
366
|
|
|
367
|
+
/** text 里多数换行是 CRLF 时返回 "\r\n",多数是 LF 时返回 "\n",一样多或没有换行时返回 fallback */
|
|
368
|
+
function eolOf(text: string, fallback: string): string {
|
|
369
|
+
const crlf = text.split("\r\n").length - 1;
|
|
370
|
+
const lf = text.split("\n").length - 1 - crlf;
|
|
371
|
+
return crlf > lf ? "\r\n" : lf > crlf ? "\n" : fallback;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** 原文件主要用 CRLF、新内容只有 LF 时换成 CRLF;原文件有 BOM、新内容没有时补上 */
|
|
375
|
+
export function keepStyle(before: string, content: string): string {
|
|
376
|
+
let out = content;
|
|
377
|
+
if (eolOf(before, "\n") === "\r\n" && !out.includes("\r\n")) out = out.replaceAll("\n", "\r\n");
|
|
378
|
+
if (before.startsWith("") && !out.startsWith("")) out = `${out}`;
|
|
379
|
+
return out;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
383
|
+
|
|
344
384
|
/** 在 text 上做一次替换;失败时返回原因 */
|
|
345
385
|
function replaceIn(text: string, { old_string, new_string, replace_all }: Edit, shown: string): { text: string; count: number } | string {
|
|
346
386
|
if (old_string === new_string) return "old_string and new_string are identical";
|
|
347
387
|
if (old_string === "") return "old_string must not be empty; use write_file to create a file";
|
|
348
|
-
//
|
|
349
|
-
const
|
|
350
|
-
const
|
|
351
|
-
const to = crlf ? new_string.replaceAll("\n", "\r\n") : new_string;
|
|
352
|
-
const count = text.split(from).length - 1;
|
|
388
|
+
// read_file 不显示换行风格:old_string 里的换行匹配 LF 和 CRLF,CRLF 文件、换行混用的文件都能对上
|
|
389
|
+
const pattern = new RegExp(old_string.split(/\r?\n/).map(escapeRegExp).join("\\r?\\n"), "g");
|
|
390
|
+
const count = text.match(pattern)?.length ?? 0;
|
|
353
391
|
if (count === 0) return `old_string not found in ${shown}${nearMiss(text, old_string)}`;
|
|
354
392
|
if (count > 1 && !replace_all) return `old_string occurs ${count} times in ${shown}; add context to make it unique or set replace_all`;
|
|
393
|
+
// new_string 的换行沿用被替换那段的;那段只有一行时沿用整个文件的,单行改成多行也不会混进 LF
|
|
394
|
+
const fileEol = eolOf(text, "\n");
|
|
395
|
+
const to = (matched: string) => (new_string.includes("\r\n") ? new_string : new_string.replaceAll("\n", eolOf(matched, fileEol)));
|
|
355
396
|
// 用函数作替换值,new_string 里的 $& $1 等不会被当成替换模式
|
|
356
|
-
return { text:
|
|
397
|
+
return { text: text.replace(replace_all ? pattern : new RegExp(pattern.source), to), count: replace_all ? count : 1 };
|
|
357
398
|
}
|
|
358
399
|
|
|
359
400
|
/**
|
package/src/tools/grep.ts
CHANGED
|
@@ -61,7 +61,7 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
|
|
|
61
61
|
name: "grep",
|
|
62
62
|
description:
|
|
63
63
|
"Search file contents with a regular expression (JavaScript syntax). Searches path (a file or directory, default: the working directory), " +
|
|
64
|
-
`optionally only files matching the glob include (e.g. "
|
|
64
|
+
`optionally only files matching the glob include (e.g. "*.ts" matches at any depth; "src/**/*.ts" limits it to src). Skips files ignored by git, binary files and .git/node_modules. ` +
|
|
65
65
|
`output_mode: "content" (default) returns "file:line:text" for matches and "file-line-text" for context lines, at most ${MAX_MATCHES} matches; ` +
|
|
66
66
|
`"files" returns only the paths of matching files; "count" returns "file:count". ` +
|
|
67
67
|
`context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode.`,
|
|
@@ -232,7 +232,8 @@ async function ripgrep(rg: string, s: Search): Promise<Found | undefined | "miss
|
|
|
232
232
|
// ---------- JS ----------
|
|
233
233
|
|
|
234
234
|
async function jsGrep(s: Search): Promise<Found> {
|
|
235
|
-
|
|
235
|
+
// 和 ripgrep 的 --glob 一致:不含 / 的模式("*.ts")匹配任意深度的文件名
|
|
236
|
+
const filter = s.include ? globMatcher(s.include.includes("/") ? s.include : `**/${s.include}`) : undefined;
|
|
236
237
|
const files: FileHits[] = [];
|
|
237
238
|
let matches = 0;
|
|
238
239
|
const single = (await stat(s.root)).isFile();
|
package/src/tools/shell.ts
CHANGED
|
@@ -143,7 +143,11 @@ export function shellTools(opts: ShellOptions): ShellTools {
|
|
|
143
143
|
proc.exited,
|
|
144
144
|
]);
|
|
145
145
|
signal.throwIfAborted();
|
|
146
|
-
const parts = [
|
|
146
|
+
const parts = [
|
|
147
|
+
timedOut
|
|
148
|
+
? `Timed out after ${timeout}ms (killed). If it needs longer, raise timeout_ms (max ${MAX_TIMEOUT_MS / 1000}s); for servers and watchers use run_in_background.`
|
|
149
|
+
: `Exit code ${code}`,
|
|
150
|
+
];
|
|
147
151
|
if (stdout) parts.push(`<stdout>\n${stdout}\n</stdout>`);
|
|
148
152
|
if (stderr) parts.push(`<stderr>\n${stderr}\n</stderr>`);
|
|
149
153
|
return { content: parts.join("\n"), isError: timedOut || code !== 0 };
|
package/src/tools/task.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// task 工具:启动一个只读的子 Agent。子 Agent 是一个普通会话,用日志引用和父会话关联(3.4、第六章)。
|
|
2
2
|
// 子 Agent 调用的工具通过 ctx.progress 推给宿主显示;需要用户批准的调用(例如 web_fetch)交给宿主的 approve。
|
|
3
3
|
|
|
4
|
-
import { Runtime, type EventDataMap, type LogStore, type Plugin, type Provider, type Tool } from "uncarved";
|
|
4
|
+
import { Runtime, type EventDataMap, type LogStore, type Message, type Plugin, type Provider, type Tool } from "uncarved";
|
|
5
5
|
|
|
6
6
|
/** ctx.progress 推送的内容 */
|
|
7
7
|
export type TaskProgress =
|
|
@@ -18,17 +18,30 @@ export interface SubagentApproval {
|
|
|
18
18
|
|
|
19
19
|
export type ApproveSubagent = (call: { toolUseId: string; name: string; input: unknown }, signal: AbortSignal) => Promise<SubagentApproval>;
|
|
20
20
|
|
|
21
|
+
/** 一个子会话的控制:wrapUp 为 true 时步数上限收紧到一步,只让它写报告 */
|
|
22
|
+
export interface SubagentControl {
|
|
23
|
+
wrapUp: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
21
26
|
export interface TaskOptions {
|
|
22
27
|
store: LogStore;
|
|
23
28
|
provider: Provider;
|
|
24
|
-
/**
|
|
25
|
-
plugins: () => Plugin[];
|
|
29
|
+
/** 每个子会话一套新的插件实例;步数插件读取 control */
|
|
30
|
+
plugins: (control: SubagentControl) => Plugin[];
|
|
26
31
|
/** 不给时一律拒绝 */
|
|
27
32
|
approve?: ApproveSubagent;
|
|
28
33
|
}
|
|
29
34
|
|
|
30
35
|
const NOBODY: SubagentApproval = { approved: false, reason: "Nobody can approve this action for a sub-agent. Report what you need instead." };
|
|
31
36
|
|
|
37
|
+
/** 用完步数还没写报告时追加的消息 */
|
|
38
|
+
const WRAP_UP =
|
|
39
|
+
"You have reached your step limit. Do not call any more tools: write your report now from what you have found so far, " +
|
|
40
|
+
"and say what you could not check.";
|
|
41
|
+
|
|
42
|
+
/** 返回给主会话的报告上限,免得一个子 Agent 撑满主会话的上下文 */
|
|
43
|
+
const MAX_REPORT_CHARS = 20_000;
|
|
44
|
+
|
|
32
45
|
export function taskTool(opts: TaskOptions): Tool {
|
|
33
46
|
return {
|
|
34
47
|
name: "task",
|
|
@@ -52,10 +65,11 @@ export function taskTool(opts: TaskOptions): Tool {
|
|
|
52
65
|
idempotent: true,
|
|
53
66
|
async execute(input, ctx) {
|
|
54
67
|
const { description, prompt } = input as { description: string; prompt: string };
|
|
68
|
+
const control: SubagentControl = { wrapUp: false };
|
|
55
69
|
const child = await Runtime.create({
|
|
56
70
|
store: opts.store,
|
|
57
71
|
provider: opts.provider,
|
|
58
|
-
plugins: opts.plugins(),
|
|
72
|
+
plugins: opts.plugins(control),
|
|
59
73
|
parent: ctx.parent,
|
|
60
74
|
});
|
|
61
75
|
const sessionId = child.state.sessionId;
|
|
@@ -76,17 +90,22 @@ export function taskTool(opts: TaskOptions): Tool {
|
|
|
76
90
|
const forward = () => child.abort(ctx.signal.reason);
|
|
77
91
|
ctx.signal.addEventListener("abort", forward, { once: true });
|
|
78
92
|
let failure: unknown;
|
|
79
|
-
|
|
80
|
-
await child.send({
|
|
81
|
-
kind: "message",
|
|
82
|
-
content: [{ kind: "text", text: prompt, origin: { by: "runtime" }, trust: "trusted" }],
|
|
83
|
-
});
|
|
93
|
+
const turn = async (text: string) => {
|
|
94
|
+
await child.send({ kind: "message", content: [{ kind: "text", text, origin: { by: "runtime" }, trust: "trusted" }] });
|
|
84
95
|
while (child.state.phase === "awaiting") {
|
|
85
96
|
for (const c of child.state.batch.filter((x) => x.decision === "ask")) {
|
|
86
97
|
const answer = opts.approve ? await opts.approve(c, ctx.signal) : NOBODY;
|
|
87
98
|
await child.send({ kind: "approval", toolUseId: c.toolUseId, approved: answer.approved, reason: answer.reason });
|
|
88
99
|
}
|
|
89
100
|
}
|
|
101
|
+
};
|
|
102
|
+
try {
|
|
103
|
+
await turn(prompt);
|
|
104
|
+
// 步数用完时最后一条回复通常只有工具调用:再要一次报告,否则前面的调研全白做了
|
|
105
|
+
if (!lastText(child.state.messages)) {
|
|
106
|
+
control.wrapUp = true;
|
|
107
|
+
await turn(WRAP_UP);
|
|
108
|
+
}
|
|
90
109
|
} catch (err) {
|
|
91
110
|
failure = err;
|
|
92
111
|
} finally {
|
|
@@ -97,8 +116,8 @@ export function taskTool(opts: TaskOptions): Tool {
|
|
|
97
116
|
if (ctx.signal.aborted) throw failure ?? ctx.signal.reason;
|
|
98
117
|
|
|
99
118
|
const ref = { sessionId, seq: child.state.lastSeq };
|
|
100
|
-
|
|
101
|
-
const text = (
|
|
119
|
+
// 还是没有报告时,把它一路上说过的话都带回去
|
|
120
|
+
const text = clip(lastText(child.state.messages) || allText(child.state.messages));
|
|
102
121
|
if (failure) {
|
|
103
122
|
const msg = failure instanceof Error ? failure.message : String(failure);
|
|
104
123
|
return { content: `Sub-agent failed: ${msg}${text ? `\nLast output:\n${text}` : ""}`, isError: true, child: ref };
|
|
@@ -107,3 +126,24 @@ export function taskTool(opts: TaskOptions): Tool {
|
|
|
107
126
|
},
|
|
108
127
|
};
|
|
109
128
|
}
|
|
129
|
+
|
|
130
|
+
const textOf = (m: Message) => m.content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n").trim();
|
|
131
|
+
|
|
132
|
+
/** 最后一条回复的正文 */
|
|
133
|
+
function lastText(messages: Message[]): string {
|
|
134
|
+
const last = messages.findLast((m) => m.role === "assistant");
|
|
135
|
+
return last ? textOf(last) : "";
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** 所有回复的正文 */
|
|
139
|
+
function allText(messages: Message[]): string {
|
|
140
|
+
return messages
|
|
141
|
+
.filter((m) => m.role === "assistant")
|
|
142
|
+
.map(textOf)
|
|
143
|
+
.filter(Boolean)
|
|
144
|
+
.join("\n\n");
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function clip(s: string): string {
|
|
148
|
+
return s.length > MAX_REPORT_CHARS ? `${s.slice(0, MAX_REPORT_CHARS)}\n… (report truncated: ${s.length - MAX_REPORT_CHARS} more characters)` : s;
|
|
149
|
+
}
|