@uncarved/jade 0.0.0-stage → 0.1.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.
Files changed (168) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +191 -2
  3. package/bin/jade.js +20 -0
  4. package/dist/commands.d.ts +30 -0
  5. package/dist/commands.js +106 -0
  6. package/dist/commands.js.map +1 -0
  7. package/dist/config.d.ts +34 -0
  8. package/dist/config.js +130 -0
  9. package/dist/config.js.map +1 -0
  10. package/dist/context.d.ts +17 -0
  11. package/dist/context.js +53 -0
  12. package/dist/context.js.map +1 -0
  13. package/dist/distro.d.ts +97 -0
  14. package/dist/distro.js +311 -0
  15. package/dist/distro.js.map +1 -0
  16. package/dist/history.d.ts +10 -0
  17. package/dist/history.js +47 -0
  18. package/dist/history.js.map +1 -0
  19. package/dist/index.d.ts +27 -0
  20. package/dist/index.js +28 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/main.d.ts +2 -0
  23. package/dist/main.js +1214 -0
  24. package/dist/main.js.map +1 -0
  25. package/dist/mcp.d.ts +114 -0
  26. package/dist/mcp.js +640 -0
  27. package/dist/mcp.js.map +1 -0
  28. package/dist/memory.d.ts +19 -0
  29. package/dist/memory.js +129 -0
  30. package/dist/memory.js.map +1 -0
  31. package/dist/mentions.d.ts +35 -0
  32. package/dist/mentions.js +130 -0
  33. package/dist/mentions.js.map +1 -0
  34. package/dist/plugin-cli.d.ts +16 -0
  35. package/dist/plugin-cli.js +251 -0
  36. package/dist/plugin-cli.js.map +1 -0
  37. package/dist/plugins/budget.d.ts +9 -0
  38. package/dist/plugins/budget.js +30 -0
  39. package/dist/plugins/budget.js.map +1 -0
  40. package/dist/plugins/builtins.d.ts +10 -0
  41. package/dist/plugins/builtins.js +22 -0
  42. package/dist/plugins/builtins.js.map +1 -0
  43. package/dist/plugins/checks.d.ts +70 -0
  44. package/dist/plugins/checks.js +335 -0
  45. package/dist/plugins/checks.js.map +1 -0
  46. package/dist/plugins/compact.d.ts +26 -0
  47. package/dist/plugins/compact.js +216 -0
  48. package/dist/plugins/compact.js.map +1 -0
  49. package/dist/plugins/core.d.ts +42 -0
  50. package/dist/plugins/core.js +190 -0
  51. package/dist/plugins/core.js.map +1 -0
  52. package/dist/plugins/install.d.ts +68 -0
  53. package/dist/plugins/install.js +377 -0
  54. package/dist/plugins/install.js.map +1 -0
  55. package/dist/plugins/loader.d.ts +182 -0
  56. package/dist/plugins/loader.js +253 -0
  57. package/dist/plugins/loader.js.map +1 -0
  58. package/dist/plugins/policy.d.ts +80 -0
  59. package/dist/plugins/policy.js +541 -0
  60. package/dist/plugins/policy.js.map +1 -0
  61. package/dist/plugins/prompts.d.ts +30 -0
  62. package/dist/plugins/prompts.js +182 -0
  63. package/dist/plugins/prompts.js.map +1 -0
  64. package/dist/plugins/repeats.d.ts +9 -0
  65. package/dist/plugins/repeats.js +90 -0
  66. package/dist/plugins/repeats.js.map +1 -0
  67. package/dist/plugins/schema.d.ts +2 -0
  68. package/dist/plugins/schema.js +64 -0
  69. package/dist/plugins/schema.js.map +1 -0
  70. package/dist/provider.d.ts +111 -0
  71. package/dist/provider.js +326 -0
  72. package/dist/provider.js.map +1 -0
  73. package/dist/sessions.d.ts +22 -0
  74. package/dist/sessions.js +53 -0
  75. package/dist/sessions.js.map +1 -0
  76. package/dist/skills.d.ts +37 -0
  77. package/dist/skills.js +179 -0
  78. package/dist/skills.js.map +1 -0
  79. package/dist/sys.d.ts +48 -0
  80. package/dist/sys.js +116 -0
  81. package/dist/sys.js.map +1 -0
  82. package/dist/tools/checkpoint.d.ts +43 -0
  83. package/dist/tools/checkpoint.js +144 -0
  84. package/dist/tools/checkpoint.js.map +1 -0
  85. package/dist/tools/fs.d.ts +35 -0
  86. package/dist/tools/fs.js +417 -0
  87. package/dist/tools/fs.js.map +1 -0
  88. package/dist/tools/grep.d.ts +6 -0
  89. package/dist/tools/grep.js +243 -0
  90. package/dist/tools/grep.js.map +1 -0
  91. package/dist/tools/screenshot.d.ts +15 -0
  92. package/dist/tools/screenshot.js +162 -0
  93. package/dist/tools/screenshot.js.map +1 -0
  94. package/dist/tools/shell.d.ts +55 -0
  95. package/dist/tools/shell.js +314 -0
  96. package/dist/tools/shell.js.map +1 -0
  97. package/dist/tools/task.d.ts +31 -0
  98. package/dist/tools/task.js +86 -0
  99. package/dist/tools/task.js.map +1 -0
  100. package/dist/tools/todo.d.ts +10 -0
  101. package/dist/tools/todo.js +55 -0
  102. package/dist/tools/todo.js.map +1 -0
  103. package/dist/tools/web.d.ts +23 -0
  104. package/dist/tools/web.js +426 -0
  105. package/dist/tools/web.js.map +1 -0
  106. package/dist/ui/configure.d.ts +20 -0
  107. package/dist/ui/configure.js +369 -0
  108. package/dist/ui/configure.js.map +1 -0
  109. package/dist/ui/diff.d.ts +20 -0
  110. package/dist/ui/diff.js +142 -0
  111. package/dist/ui/diff.js.map +1 -0
  112. package/dist/ui/editor.d.ts +33 -0
  113. package/dist/ui/editor.js +128 -0
  114. package/dist/ui/editor.js.map +1 -0
  115. package/dist/ui/render.d.ts +13 -0
  116. package/dist/ui/render.js +84 -0
  117. package/dist/ui/render.js.map +1 -0
  118. package/dist/ui/screen.d.ts +95 -0
  119. package/dist/ui/screen.js +105 -0
  120. package/dist/ui/screen.js.map +1 -0
  121. package/dist/ui/transcript.d.ts +33 -0
  122. package/dist/ui/transcript.js +372 -0
  123. package/dist/ui/transcript.js.map +1 -0
  124. package/dist/ui/tui.d.ts +45 -0
  125. package/dist/ui/tui.js +1107 -0
  126. package/dist/ui/tui.js.map +1 -0
  127. package/package.json +59 -4
  128. package/src/commands.ts +120 -0
  129. package/src/config.ts +146 -0
  130. package/src/context.ts +64 -0
  131. package/src/distro.ts +395 -0
  132. package/src/history.ts +55 -0
  133. package/src/index.ts +27 -0
  134. package/src/main.ts +1267 -0
  135. package/src/mcp.ts +693 -0
  136. package/src/memory.ts +135 -0
  137. package/src/mentions.ts +135 -0
  138. package/src/plugin-cli.ts +239 -0
  139. package/src/plugins/budget.ts +37 -0
  140. package/src/plugins/builtins.ts +31 -0
  141. package/src/plugins/checks.ts +390 -0
  142. package/src/plugins/compact.ts +257 -0
  143. package/src/plugins/core.ts +217 -0
  144. package/src/plugins/install.ts +429 -0
  145. package/src/plugins/loader.ts +386 -0
  146. package/src/plugins/policy.ts +578 -0
  147. package/src/plugins/prompts.ts +215 -0
  148. package/src/plugins/repeats.ts +96 -0
  149. package/src/plugins/schema.ts +67 -0
  150. package/src/provider.ts +363 -0
  151. package/src/sessions.ts +61 -0
  152. package/src/skills.ts +197 -0
  153. package/src/sys.ts +136 -0
  154. package/src/tools/checkpoint.ts +164 -0
  155. package/src/tools/fs.ts +432 -0
  156. package/src/tools/grep.ts +268 -0
  157. package/src/tools/screenshot.ts +171 -0
  158. package/src/tools/shell.ts +357 -0
  159. package/src/tools/task.ts +105 -0
  160. package/src/tools/todo.ts +67 -0
  161. package/src/tools/web.ts +451 -0
  162. package/src/ui/configure.ts +397 -0
  163. package/src/ui/diff.ts +136 -0
  164. package/src/ui/editor.ts +136 -0
  165. package/src/ui/render.ts +74 -0
  166. package/src/ui/screen.ts +166 -0
  167. package/src/ui/transcript.ts +377 -0
  168. package/src/ui/tui.tsx +1662 -0
@@ -0,0 +1,357 @@
1
+ // bash 工具:在工作目录里执行一条 shell 命令。输出边读边通过 ctx.progress 推给宿主。
2
+ //
3
+ // run_in_background 的命令立即返回一个编号,进程留在后台(开发服务器、watch 等);
4
+ // 用 bash_output 读取它的新输出,kill_shell 停止它。后台进程只属于本进程,宿主退出时调用 shutdown 全部杀掉。
5
+
6
+ import { existsSync } from "node:fs";
7
+ import path from "node:path";
8
+ import type { Tool } from "uncarved";
9
+ import { runSync, spawn as spawnProc, which, type Proc } from "../sys.ts";
10
+
11
+ const DEFAULT_TIMEOUT_MS = 120_000;
12
+ const MAX_TIMEOUT_MS = 600_000;
13
+ const MAX_OUTPUT_CHARS = 30_000;
14
+ /** 后台进程最多缓存这么多还没读取的输出,超出的丢弃最早的部分 */
15
+ const MAX_BUFFER_CHARS = 1_000_000;
16
+
17
+ export interface ShellOptions {
18
+ cwd: string;
19
+ /** 默认 JADE_SHELL 环境变量,否则 bash(Windows 上是 Git Bash) */
20
+ shell?: string;
21
+ }
22
+
23
+ export interface ShellTools {
24
+ /** bash、bash_output、kill_shell;找不到 shell 时为空 */
25
+ tools: Tool[];
26
+ /** 实际执行的 shell 程序;找不到时为 undefined */
27
+ executable?: string;
28
+ /** 找不到 shell 时的说明,宿主显示给用户 */
29
+ unavailable?: string;
30
+ /** 杀掉所有还在运行的后台进程 */
31
+ shutdown(): void;
32
+ /** 宿主和插件自己执行一条命令(不经过模型和审批),找不到 shell 时为 undefined */
33
+ run?: RunCommand;
34
+ }
35
+
36
+ export interface RunResult {
37
+ /** 超时被杀掉时为 null */
38
+ code: number | null;
39
+ /** stdout 和 stderr 合在一起,超长时保留首尾 */
40
+ output: string;
41
+ timedOut: boolean;
42
+ }
43
+
44
+ export type RunCommand = (command: string, opts: { cwd?: string; timeoutMs: number; signal?: AbortSignal }) => Promise<RunResult>;
45
+
46
+ /** 只要 bash 工具时用(测试) */
47
+ export function shellTool(opts: ShellOptions): Tool {
48
+ const { tools, unavailable } = shellTools(opts);
49
+ if (!tools[0]) throw new Error(unavailable);
50
+ return tools[0];
51
+ }
52
+
53
+ interface Background {
54
+ id: string;
55
+ command: string;
56
+ proc: Proc;
57
+ /** 还没被 bash_output 读走的输出 */
58
+ unread: string;
59
+ /** 因超出缓存而丢弃的字符数,下次读取时告诉模型 */
60
+ dropped: number;
61
+ exitCode?: number | null;
62
+ }
63
+
64
+ export function shellTools(opts: ShellOptions): ShellTools {
65
+ const shell = opts.shell ?? process.env.JADE_SHELL ?? "bash";
66
+ const found = findShell(shell);
67
+ // 找不到 shell 时不提供这几个工具:否则模型每次调用都要用户先批准,执行时才失败,模型还会反复重试
68
+ if (!found) {
69
+ const hint = process.platform === "win32" ? "install Git for Windows, or set JADE_SHELL to the path of a bash executable" : "set JADE_SHELL to the path of a shell";
70
+ return { tools: [], unavailable: `${shell} was not found, so the bash tool is disabled; ${hint}`, shutdown() {} };
71
+ }
72
+ const executable = found;
73
+ const env = shellEnv(executable);
74
+ const background = new Map<string, Background>();
75
+ let nextId = 1;
76
+
77
+ const spawn = (command: string, cwd = opts.cwd) =>
78
+ spawnProc([executable, "-c", command], {
79
+ cwd,
80
+ env,
81
+ // 自成进程组,超时/中断时能连同子进程一起杀掉
82
+ detached: process.platform !== "win32",
83
+ });
84
+
85
+ async function startBackground(command: string): Promise<string> {
86
+ const id = `bg${nextId++}`;
87
+ const bg: Background = { id, command, proc: await spawn(command), unread: "", dropped: 0 };
88
+ const append = (text: string) => {
89
+ bg.unread += text;
90
+ if (bg.unread.length > MAX_BUFFER_CHARS) {
91
+ bg.dropped += bg.unread.length - MAX_BUFFER_CHARS;
92
+ bg.unread = bg.unread.slice(-MAX_BUFFER_CHARS);
93
+ }
94
+ };
95
+ // 输出只进 unread,不另外累积:后台进程可能一直运行
96
+ void Promise.all([collect(bg.proc.stdout, append, false), collect(bg.proc.stderr, append, false)]).catch(() => {});
97
+ void bg.proc.exited.then((code) => {
98
+ bg.exitCode = code;
99
+ });
100
+ background.set(id, bg);
101
+ return id;
102
+ }
103
+
104
+ const status = (bg: Background) => (bg.exitCode === undefined ? "running" : `exited with code ${bg.exitCode}`);
105
+
106
+ const bash: Tool = {
107
+ name: "bash",
108
+ description:
109
+ `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` +
110
+ `Each call starts a fresh shell: cd and environment variables do not persist. ` +
111
+ `Default timeout ${DEFAULT_TIMEOUT_MS / 1000}s (timeout_ms, max ${MAX_TIMEOUT_MS / 1000}s). ` +
112
+ "Set run_in_background for servers, watchers and other long-running commands: it returns an id at once, " +
113
+ "then read new output with bash_output and stop it with kill_shell. " +
114
+ "Never start interactive programs. Prefer read_file/grep/glob over cat/grep/find.",
115
+ inputSchema: {
116
+ type: "object",
117
+ properties: { command: { type: "string" }, timeout_ms: { type: "integer" }, run_in_background: { type: "boolean" } },
118
+ required: ["command"],
119
+ additionalProperties: false,
120
+ },
121
+ effect: "external",
122
+ concurrency: "exclusive",
123
+ idempotent: false,
124
+ async execute(input, { signal, progress }) {
125
+ const { command, timeout_ms, run_in_background } = input as { command: string; timeout_ms?: number; run_in_background?: boolean };
126
+ if (run_in_background) {
127
+ const id = await startBackground(command);
128
+ return { content: `Started background shell ${id}. Read its output with bash_output, stop it with kill_shell.` };
129
+ }
130
+ const timeout = Math.min(Math.max(timeout_ms ?? DEFAULT_TIMEOUT_MS, 1000), MAX_TIMEOUT_MS);
131
+ const proc = await spawn(command);
132
+ let timedOut = false;
133
+ const timer = setTimeout(() => {
134
+ timedOut = true;
135
+ killTree(executable, env, proc.pid);
136
+ }, timeout);
137
+ const kill = () => killTree(executable, env, proc.pid);
138
+ signal.addEventListener("abort", kill, { once: true });
139
+ try {
140
+ const [stdout, stderr, code] = await Promise.all([
141
+ collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text })),
142
+ collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text })),
143
+ proc.exited,
144
+ ]);
145
+ signal.throwIfAborted();
146
+ const parts = [timedOut ? `Timed out after ${timeout}ms (killed)` : `Exit code ${code}`];
147
+ if (stdout) parts.push(`<stdout>\n${stdout}\n</stdout>`);
148
+ if (stderr) parts.push(`<stderr>\n${stderr}\n</stderr>`);
149
+ return { content: parts.join("\n"), isError: timedOut || code !== 0 };
150
+ } finally {
151
+ clearTimeout(timer);
152
+ signal.removeEventListener("abort", kill);
153
+ }
154
+ },
155
+ };
156
+
157
+ const idSchema = {
158
+ type: "object",
159
+ properties: { id: { type: "string", description: "id returned by bash with run_in_background" } },
160
+ required: ["id"],
161
+ additionalProperties: false,
162
+ };
163
+ const find = (id: string) => background.get(id);
164
+ const unknown = (id: string) => ({
165
+ content: `No background shell ${id}${background.size ? `; known: ${[...background.keys()].join(", ")}` : ""}`,
166
+ isError: true,
167
+ });
168
+
169
+ const bashOutput: Tool = {
170
+ name: "bash_output",
171
+ description:
172
+ "Return the output a background shell (started with bash run_in_background) has produced since the last bash_output call, " +
173
+ "and whether it is still running. stdout and stderr are interleaved.",
174
+ inputSchema: idSchema,
175
+ effect: "read",
176
+ concurrency: "safe",
177
+ // 读走的输出不会再出现
178
+ idempotent: false,
179
+ async execute(input) {
180
+ const { id } = input as { id: string };
181
+ const bg = find(id);
182
+ if (!bg) return unknown(id);
183
+ const { unread, dropped } = bg;
184
+ bg.unread = "";
185
+ bg.dropped = 0;
186
+ const title = bg.command.split("\n")[0]!;
187
+ const head = `${id} (${title.length > 100 ? title.slice(0, 100) + "…" : title}): ${status(bg)}`;
188
+ const note = dropped > 0 ? `\n(${dropped} earlier characters were dropped)` : "";
189
+ return { content: unread ? `${head}${note}\n<output>\n${clip(unread)}\n</output>` : `${head}${note}\n(no new output)` };
190
+ },
191
+ };
192
+
193
+ const killShell: Tool = {
194
+ name: "kill_shell",
195
+ description: "Stop a background shell started with bash run_in_background, together with the processes it started.",
196
+ inputSchema: idSchema,
197
+ // 只能停掉本会话自己启动、已经批准过的进程
198
+ effect: "read",
199
+ concurrency: "exclusive",
200
+ idempotent: true,
201
+ async execute(input) {
202
+ const { id } = input as { id: string };
203
+ const bg = find(id);
204
+ if (!bg) return unknown(id);
205
+ if (bg.exitCode === undefined) {
206
+ killTree(executable, env, bg.proc.pid);
207
+ await bg.proc.exited;
208
+ }
209
+ return { content: `${id} stopped (${status(bg)})` };
210
+ },
211
+ };
212
+
213
+ const run: RunCommand = async (command, { cwd, timeoutMs, signal }) => {
214
+ signal?.throwIfAborted();
215
+ const proc = await spawn(command, cwd);
216
+ let timedOut = false;
217
+ const kill = () => killTree(executable, env, proc.pid);
218
+ const timer = setTimeout(() => {
219
+ timedOut = true;
220
+ kill();
221
+ }, timeoutMs);
222
+ signal?.addEventListener("abort", kill, { once: true });
223
+ try {
224
+ const [stdout, stderr, code] = await Promise.all([collect(proc.stdout, () => {}), collect(proc.stderr, () => {}), proc.exited]);
225
+ signal?.throwIfAborted();
226
+ return { code: timedOut ? null : code, output: [stdout, stderr].filter(Boolean).join("\n"), timedOut };
227
+ } finally {
228
+ clearTimeout(timer);
229
+ signal?.removeEventListener("abort", kill);
230
+ }
231
+ };
232
+
233
+ return {
234
+ tools: [bash, bashOutput, killShell],
235
+ executable,
236
+ run,
237
+ shutdown() {
238
+ for (const bg of background.values()) if (bg.exitCode === undefined) killTree(executable, env, bg.proc.pid);
239
+ },
240
+ };
241
+ }
242
+
243
+ /** ctx.progress 推送的内容 */
244
+ export interface ShellProgress {
245
+ kind: "output";
246
+ stream: "stdout" | "stderr";
247
+ text: string;
248
+ }
249
+
250
+ /**
251
+ * 找到要执行的 shell 程序,找不到返回 undefined。
252
+ *
253
+ * Windows 上 Git for Windows 安装时默认只把 Git\cmd 加进 PATH,PATH 里通常找不到 bash,
254
+ * 所以 bash、sh 还要从 git.exe 的位置和常见安装目录找 Git 的安装目录。
255
+ * Git 的 bin\bash.exe、bin\sh.exe 只是启动器,真正的 shell 是它启动的 usr\bin 下的同名程序;
256
+ * killTree 按 WINPID 找 msys 进程,用启动器的 pid 找不到,所以直接用 usr\bin 下的。
257
+ * Git Bash 优先于 PATH 里别的 bash(例如 System32\bash.exe 是 WSL 的启动器,看不到 Windows 路径)
258
+ */
259
+ export function findShell(shell: string): string | undefined {
260
+ const found = which(shell);
261
+ if (process.platform !== "win32") return found;
262
+ const name = /^(bash|sh)(\.exe)?$/i.exec(shell)?.[1]?.toLowerCase();
263
+ if (!name) return found;
264
+ const inGit = (root: string) => {
265
+ const real = path.join(root, "usr", "bin", `${name}.exe`);
266
+ return existsSync(real) ? real : undefined;
267
+ };
268
+ const m = /^(.*\\Git)\\(usr\\)?bin\\(bash|sh)\.exe$/i.exec(found ?? "");
269
+ if (m) return inGit(m[1]!) ?? found;
270
+ // git.exe 在 Git\cmd、Git\bin 或 Git\mingw64\bin 下
271
+ const git = which("git");
272
+ const roots = git ? [path.dirname(path.dirname(git)), path.dirname(path.dirname(path.dirname(git)))] : [];
273
+ for (const base of [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, "Programs")]) {
274
+ if (base) roots.push(path.join(base, "Git"));
275
+ }
276
+ for (const root of roots) {
277
+ const real = inGit(root);
278
+ if (real) return real;
279
+ }
280
+ return found;
281
+ }
282
+
283
+ /**
284
+ * 直接执行 Git 的 usr\bin\bash.exe 时没有经过 bin\bash.exe 启动器,启动器会把 /usr/bin、/mingw64/bin 加进 PATH;
285
+ * 不补上的话 PATH 里只有 Windows 的目录,cat、grep、head、sed 都找不到,find 还会变成 Windows 的 find.exe。
286
+ * 不是 Git Bash 时返回 undefined,继承当前环境
287
+ */
288
+ export function shellEnv(executable: string, env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv | undefined {
289
+ if (process.platform !== "win32") return undefined;
290
+ const m = /^(.*\\Git)\\usr\\bin\\(bash|sh)\.exe$/i.exec(executable);
291
+ if (!m) return undefined;
292
+ const root = m[1]!;
293
+ // Windows 的环境变量名不分大小写,展开成普通对象后要沿用原来的键名(通常是 Path),否则会同时出现 Path 和 PATH
294
+ const key = Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
295
+ const dirs = [path.join(root, "usr", "bin"), path.join(root, "mingw64", "bin")];
296
+ return { ...env, [key]: [...dirs, env[key]].filter(Boolean).join(path.delimiter) };
297
+ }
298
+
299
+ /**
300
+ * 只杀 shell 本身不够:它启动的子进程还占着 stdout/stderr 管道,读取会一直等到它们退出。
301
+ * POSIX 上杀整个进程组。Windows 上 Git Bash(msys)模拟 fork,Windows 进程树里看不到父子关系,
302
+ * 要先在 msys 里按 WINPID 找到 shell 的 msys PID(它也是进程组号)杀掉整组;taskkill /T 兜底非 msys 的 shell
303
+ */
304
+ function killTree(shell: string, env: NodeJS.ProcessEnv | undefined, pid: number) {
305
+ try {
306
+ if (process.platform !== "win32") return process.kill(-pid, "SIGKILL");
307
+ const script = `for d in /proc/[0-9]*; do [ "$(cat "$d/winpid" 2>/dev/null)" = "${pid}" ] && kill -9 -- "-\${d#/proc/}"; done`;
308
+ try {
309
+ runSync([shell, "-c", script], { env });
310
+ } catch {
311
+ // 不是 msys/cygwin 的 shell
312
+ }
313
+ runSync(["taskkill", "/T", "/F", "/PID", String(pid)]);
314
+ } catch {
315
+ // 已经退出
316
+ }
317
+ }
318
+
319
+ /**
320
+ * 返回截好的输出:超过 MAX_OUTPUT_CHARS 时保留开头和结尾各一半,中间截掉。
321
+ * 边读边截,输出再多也只占几倍 MAX_OUTPUT_CHARS 的内存。keep 为 false 时只推给 onChunk,不累积,返回空串
322
+ */
323
+ async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string) => void, keep = true): Promise<string> {
324
+ const half = MAX_OUTPUT_CHARS / 2;
325
+ const decoder = new TextDecoder();
326
+ let head = "";
327
+ let tail = "";
328
+ let total = 0;
329
+ const add = (text: string) => {
330
+ onChunk(text);
331
+ if (!keep) return;
332
+ total += text.length;
333
+ if (head.length < half) {
334
+ const n = half - head.length;
335
+ head += text.slice(0, n);
336
+ text = text.slice(n);
337
+ }
338
+ tail += text;
339
+ // 攒到两倍再截,不用每块都复制
340
+ if (tail.length > 2 * half) tail = tail.slice(-half);
341
+ };
342
+ for await (const chunk of stream) {
343
+ const text = decoder.decode(chunk, { stream: true });
344
+ if (text) add(text);
345
+ }
346
+ const rest = decoder.decode();
347
+ if (rest) add(rest);
348
+ if (total <= MAX_OUTPUT_CHARS) return (head + tail).trimEnd();
349
+ return `${head}\n… (${total - MAX_OUTPUT_CHARS} characters omitted) …\n${tail.slice(-half)}`.trimEnd();
350
+ }
351
+
352
+ /** 保留开头和结尾,中间截掉 */
353
+ function clip(s: string): string {
354
+ if (s.length <= MAX_OUTPUT_CHARS) return s.trimEnd();
355
+ const half = MAX_OUTPUT_CHARS / 2;
356
+ return `${s.slice(0, half)}\n… (${s.length - MAX_OUTPUT_CHARS} characters omitted) …\n${s.slice(-half)}`.trimEnd();
357
+ }
@@ -0,0 +1,105 @@
1
+ // task 工具:启动一个只读的子 Agent。子 Agent 是一个普通会话,用日志引用和父会话关联(3.4、第六章)。
2
+ // 子 Agent 调用的工具通过 ctx.progress 推给宿主显示;需要用户批准的调用(例如 web_fetch)交给宿主的 approve。
3
+
4
+ import { Runtime, type EventDataMap, type LogStore, type Plugin, type Provider, type Tool } from "uncarved";
5
+
6
+ /** ctx.progress 推送的内容 */
7
+ export type TaskProgress =
8
+ | { kind: "task-start"; sessionId: string; description: string }
9
+ | { kind: "task-tool"; name: string; input: unknown; decision: string };
10
+
11
+ /** 子 Agent 的调用要用户批准时,宿主给出的回答 */
12
+ export interface SubagentApproval {
13
+ approved: boolean;
14
+ reason?: string;
15
+ }
16
+
17
+ export type ApproveSubagent = (call: { toolUseId: string; name: string; input: unknown }, signal: AbortSignal) => Promise<SubagentApproval>;
18
+
19
+ export interface TaskOptions {
20
+ store: LogStore;
21
+ provider: Provider;
22
+ /** 每个子会话一套新的插件实例 */
23
+ plugins: () => Plugin[];
24
+ /** 不给时一律拒绝 */
25
+ approve?: ApproveSubagent;
26
+ }
27
+
28
+ const NOBODY: SubagentApproval = { approved: false, reason: "Nobody can approve this action for a sub-agent. Report what you need instead." };
29
+
30
+ export function taskTool(opts: TaskOptions): Tool {
31
+ return {
32
+ name: "task",
33
+ description:
34
+ "Delegate a self-contained research task to a sub-agent with read-only tools (read_file, list_dir, glob, grep, and web_fetch / web_search when available). " +
35
+ "Use it for broad searches across many files, or web research across several pages, so that only the conclusion comes back. " +
36
+ "The sub-agent sees nothing of this conversation: the prompt must contain everything it needs. " +
37
+ "Several task calls in one response run in parallel.",
38
+ inputSchema: {
39
+ type: "object",
40
+ properties: {
41
+ description: { type: "string", description: "3-6 word label" },
42
+ prompt: { type: "string", description: "Complete instructions, including what to report back" },
43
+ },
44
+ required: ["description", "prompt"],
45
+ additionalProperties: false,
46
+ },
47
+ effect: "read",
48
+ concurrency: "safe",
49
+ // 子 Agent 只读,重跑只是多花 token
50
+ idempotent: true,
51
+ async execute(input, ctx) {
52
+ const { description, prompt } = input as { description: string; prompt: string };
53
+ const child = await Runtime.create({
54
+ store: opts.store,
55
+ provider: opts.provider,
56
+ plugins: opts.plugins(),
57
+ parent: ctx.parent,
58
+ });
59
+ const sessionId = child.state.sessionId;
60
+ const progress = (p: TaskProgress) => ctx.progress(p);
61
+ progress({ kind: "task-start", sessionId, description });
62
+ const names = new Map<string, string>();
63
+ child.subscribe((n) => {
64
+ if (n.type !== "event") return;
65
+ if (n.event.type === "model.responded") {
66
+ for (const b of (n.event.data as EventDataMap["model.responded"]).content) if (b.kind === "tool_use") names.set(b.id, b.name);
67
+ } else if (n.event.type === "tool.decided") {
68
+ const d = n.event.data as EventDataMap["tool.decided"];
69
+ progress({ kind: "task-tool", name: names.get(d.toolUseId) ?? "?", input: d.input, decision: d.decision });
70
+ }
71
+ });
72
+ const forward = () => child.abort(ctx.signal.reason);
73
+ ctx.signal.addEventListener("abort", forward, { once: true });
74
+ let failure: unknown;
75
+ try {
76
+ await child.send({
77
+ kind: "message",
78
+ content: [{ kind: "text", text: prompt, origin: { by: "runtime" }, trust: "trusted" }],
79
+ });
80
+ while (child.state.phase === "awaiting") {
81
+ for (const c of child.state.batch.filter((x) => x.decision === "ask")) {
82
+ const answer = opts.approve ? await opts.approve(c, ctx.signal) : NOBODY;
83
+ await child.send({ kind: "approval", toolUseId: c.toolUseId, approved: answer.approved, reason: answer.reason });
84
+ }
85
+ }
86
+ } catch (err) {
87
+ failure = err;
88
+ } finally {
89
+ ctx.signal.removeEventListener("abort", forward);
90
+ // 中断时也结束子会话,不留下没有结尾的日志
91
+ await child.close().catch(() => {});
92
+ }
93
+ if (ctx.signal.aborted) throw failure ?? ctx.signal.reason;
94
+
95
+ const ref = { sessionId, seq: child.state.lastSeq };
96
+ const last = child.state.messages.findLast((m) => m.role === "assistant");
97
+ const text = (last?.content ?? []).flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n").trim();
98
+ if (failure) {
99
+ const msg = failure instanceof Error ? failure.message : String(failure);
100
+ return { content: `Sub-agent failed: ${msg}${text ? `\nLast output:\n${text}` : ""}`, isError: true, child: ref };
101
+ }
102
+ return { content: text || "(sub-agent returned no text)", isError: !text, child: ref };
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,67 @@
1
+ // todo_write 工具:模型维护本轮任务的清单。每次调用给出完整清单,替换之前的。
2
+ //
3
+ // 清单本身就是工具调用的参数,已经在日志里,不另外保存:宿主从 tool.decided 读取并显示,
4
+ // 压缩插件把被压缩部分里最后一份清单写进摘要。
5
+
6
+ import type { Message, Tool } from "uncarved";
7
+
8
+ export type TodoStatus = "pending" | "in_progress" | "completed";
9
+
10
+ export interface Todo {
11
+ content: string;
12
+ status: TodoStatus;
13
+ }
14
+
15
+ const MARK: Record<TodoStatus, string> = { pending: "[ ]", in_progress: "[~]", completed: "[x]" };
16
+
17
+ export function renderTodos(todos: Todo[]): string {
18
+ return todos.length ? todos.map((t) => `${MARK[t.status]} ${t.content}`).join("\n") : "(empty)";
19
+ }
20
+
21
+ export function todoTool(): Tool {
22
+ return {
23
+ name: "todo_write",
24
+ description:
25
+ "Maintain a task list for multi-step work. Each call replaces the whole list. " +
26
+ "Use it when a task has three or more steps: write the plan, mark one item in_progress while working on it, " +
27
+ "and mark items completed as soon as they are done. Skip it for simple tasks.",
28
+ inputSchema: {
29
+ type: "object",
30
+ properties: {
31
+ todos: {
32
+ type: "array",
33
+ items: {
34
+ type: "object",
35
+ properties: {
36
+ content: { type: "string" },
37
+ status: { type: "string", enum: ["pending", "in_progress", "completed"] },
38
+ },
39
+ required: ["content", "status"],
40
+ additionalProperties: false,
41
+ },
42
+ },
43
+ },
44
+ required: ["todos"],
45
+ additionalProperties: false,
46
+ },
47
+ // 不碰文件和进程
48
+ effect: "read",
49
+ concurrency: "exclusive",
50
+ idempotent: true,
51
+ async execute(input) {
52
+ const { todos } = input as { todos: Todo[] };
53
+ const active = todos.filter((t) => t.status === "in_progress").length;
54
+ const note = active > 1 ? "\nNote: keep only one item in_progress at a time." : "";
55
+ return { content: `Todo list updated:\n${renderTodos(todos)}${note}` };
56
+ },
57
+ };
58
+ }
59
+
60
+ /** messages 里最后一次 todo_write 的清单 */
61
+ export function latestTodos(messages: Message[]): Todo[] | undefined {
62
+ for (let i = messages.length - 1; i >= 0; i--) {
63
+ const use = messages[i]!.content.findLast((b) => b.kind === "tool_use" && b.name === "todo_write");
64
+ if (use?.kind === "tool_use") return (use.input as { todos?: Todo[] }).todos;
65
+ }
66
+ return undefined;
67
+ }