@uncarved/jade 0.3.0 → 0.3.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 (59) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/package.json +2 -2
  5. package/plugins/approval/index.ts +14 -11
  6. package/plugins/approval/policy.ts +34 -16
  7. package/plugins/fs/grep.ts +13 -3
  8. package/plugins/fs/index.ts +5 -5
  9. package/plugins/fs/plugin.json +1 -1
  10. package/plugins/mcp/index.ts +5 -5
  11. package/plugins/mcp/plugin.json +1 -1
  12. package/plugins/models/index.ts +4 -3
  13. package/plugins/models/provider.ts +12 -1
  14. package/plugins/repeats/index.ts +31 -1
  15. package/plugins/screenshot/browser.ts +221 -0
  16. package/plugins/screenshot/index.ts +3 -2
  17. package/plugins/screenshot/tool.ts +27 -51
  18. package/plugins/shell/index.ts +64 -6
  19. package/plugins/shell/plugin.json +1 -1
  20. package/plugins/shell/shell.ts +90 -33
  21. package/plugins/task/index.ts +12 -42
  22. package/plugins/task/plugin.json +1 -2
  23. package/plugins/task/subagent.ts +2 -2
  24. package/plugins/tools/index.ts +50 -0
  25. package/plugins/tools/plugin.json +7 -0
  26. package/plugins/tui/frontend.ts +27 -3
  27. package/plugins/tui/mascot.ts +8 -7
  28. package/plugins/tui/tui.ts +23 -7
  29. package/plugins/web/index.ts +7 -7
  30. package/plugins/web/plugin.json +1 -1
  31. package/plugins-dist/approval/index.js +16 -12
  32. package/plugins-dist/approval/policy.js +30 -15
  33. package/plugins-dist/fs/grep.js +12 -3
  34. package/plugins-dist/fs/index.js +5 -5
  35. package/plugins-dist/fs/plugin.json +1 -1
  36. package/plugins-dist/mcp/index.js +5 -5
  37. package/plugins-dist/mcp/plugin.json +1 -1
  38. package/plugins-dist/models/index.js +4 -3
  39. package/plugins-dist/models/provider.js +13 -1
  40. package/plugins-dist/repeats/index.js +27 -1
  41. package/plugins-dist/screenshot/browser.js +187 -0
  42. package/plugins-dist/screenshot/index.js +3 -2
  43. package/plugins-dist/screenshot/tool.js +27 -49
  44. package/plugins-dist/shell/index.js +68 -5
  45. package/plugins-dist/shell/plugin.json +1 -1
  46. package/plugins-dist/shell/shell.js +82 -30
  47. package/plugins-dist/task/index.js +11 -42
  48. package/plugins-dist/task/plugin.json +1 -3
  49. package/plugins-dist/task/subagent.js +1 -1
  50. package/plugins-dist/tools/index.js +49 -0
  51. package/plugins-dist/tools/plugin.json +9 -0
  52. package/plugins-dist/tui/frontend.js +28 -3
  53. package/plugins-dist/tui/mascot.js +8 -6
  54. package/plugins-dist/tui/tui.js +18 -7
  55. package/plugins-dist/tui/vendor.js +1388 -1088
  56. package/plugins-dist/web/index.js +6 -6
  57. package/plugins-dist/web/plugin.json +1 -1
  58. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  59. package/src/api.ts +1 -1
@@ -50,7 +50,7 @@ export function shellTool(opts: ShellOptions): Tool {
50
50
  interface Background {
51
51
  id: string;
52
52
  command: string;
53
- proc: Proc;
53
+ proc: Tagged;
54
54
  /** 还没被 bash_output 读走的输出 */
55
55
  unread: string;
56
56
  /** 因超出缓存而丢弃的字符数,下次读取时告诉模型 */
@@ -73,13 +73,7 @@ export function shellTools(opts: ShellOptions): ShellTools {
73
73
  const background = new Map<string, Background>();
74
74
  let nextId = 1;
75
75
 
76
- const spawn = (command: string, cwd = opts.cwd) =>
77
- spawnProc([executable, "-c", command], {
78
- cwd,
79
- env,
80
- // 自成进程组,超时/中断时能连同子进程一起杀掉
81
- detached: process.platform !== "win32",
82
- });
76
+ const spawn = (command: string, cwd = opts.cwd) => launch(executable, env, command, cwd);
83
77
 
84
78
  async function startBackground(command: string): Promise<string> {
85
79
  const id = `bg${nextId++}`;
@@ -106,7 +100,7 @@ export function shellTools(opts: ShellOptions): ShellTools {
106
100
  const stop = async (bg: Background) => {
107
101
  if (bg.exitCode !== undefined) return;
108
102
  bg.killed = true;
109
- killTree(executable, env, bg.proc.pid);
103
+ killTree(executable, env, bg.proc);
110
104
  await bg.proc.exited;
111
105
  };
112
106
 
@@ -137,17 +131,22 @@ export function shellTools(opts: ShellOptions): ShellTools {
137
131
  const timeout = Math.min(Math.max(timeout_ms ?? DEFAULT_TIMEOUT_MS, 1000), MAX_TIMEOUT_MS);
138
132
  const proc = await spawn(command);
139
133
  let timedOut = false;
134
+ const killed = giveUp();
140
135
  const timer = setTimeout(() => {
141
136
  timedOut = true;
142
- killTree(executable, env, proc.pid);
137
+ killTree(executable, env, proc);
138
+ killed.start();
143
139
  }, timeout);
144
- const kill = () => killTree(executable, env, proc.pid);
140
+ const kill = () => {
141
+ killTree(executable, env, proc);
142
+ killed.start();
143
+ };
145
144
  signal.addEventListener("abort", kill, { once: true });
146
145
  try {
147
146
  const [stdout, stderr, code] = await Promise.all([
148
- collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text })),
149
- collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text })),
150
- proc.exited,
147
+ collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text }), true, killed.done),
148
+ collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text }), true, killed.done),
149
+ Promise.race([proc.exited, killed.done.then(() => null)]),
151
150
  ]);
152
151
  signal.throwIfAborted();
153
152
  const parts = [
@@ -228,7 +227,7 @@ export function shellTools(opts: ShellOptions): ShellTools {
228
227
  for (const bg of background.values()) {
229
228
  if (bg.exitCode !== undefined) continue;
230
229
  bg.killed = true;
231
- killTree(executable, env, bg.proc.pid);
230
+ killTree(executable, env, bg.proc);
232
231
  }
233
232
  },
234
233
  list: () => [...background.values()].map((bg) => ({ id: bg.id, command: bg.command, status: status(bg) })),
@@ -245,23 +244,34 @@ export function shellTools(opts: ShellOptions): ShellTools {
245
244
  * 执行一条命令并把输出收下来(不经过模型、不推进度);超时或中止时连同子进程一起杀掉。
246
245
  * 后台命令和别的插件(`shell@1`,例如 jade/checks)都用它
247
246
  */
248
- export async function capture(executable: string, env: NodeJS.ProcessEnv | undefined, command: string, opts: { cwd?: string; timeoutMs: number; signal?: AbortSignal }): Promise<RunResult> {
247
+ export async function capture(executable: string, env: NodeJS.ProcessEnv | undefined, command: string, opts: { cwd?: string; timeoutMs: number; signal?: AbortSignal; onOutput?: (text: string) => void }): Promise<RunResult> {
249
248
  opts.signal?.throwIfAborted();
250
- const proc = await spawnProc([executable, "-c", command], {
251
- cwd: opts.cwd,
252
- env,
253
- // 自成进程组,超时/中断时能连同子进程一起杀掉
254
- detached: process.platform !== "win32",
255
- });
249
+ const proc = await launch(executable, env, command, opts.cwd);
250
+ // 输出一到就推给调用方(用户自己执行的命令要边跑边看);它出错不影响命令
251
+ const onOutput = (text: string) => {
252
+ try {
253
+ opts.onOutput?.(text);
254
+ } catch {
255
+ // 调用方的错
256
+ }
257
+ };
256
258
  let timedOut = false;
257
- const kill = () => killTree(executable, env, proc.pid);
259
+ const killed = giveUp();
260
+ const kill = () => {
261
+ killTree(executable, env, proc);
262
+ killed.start();
263
+ };
258
264
  const timer = setTimeout(() => {
259
265
  timedOut = true;
260
266
  kill();
261
267
  }, opts.timeoutMs);
262
268
  opts.signal?.addEventListener("abort", kill, { once: true });
263
269
  try {
264
- const [stdout, stderr, code] = await Promise.all([collect(proc.stdout, () => {}), collect(proc.stderr, () => {}), proc.exited]);
270
+ const [stdout, stderr, code] = await Promise.all([
271
+ collect(proc.stdout, onOutput, true, killed.done),
272
+ collect(proc.stderr, onOutput, true, killed.done),
273
+ Promise.race([proc.exited, killed.done.then(() => null)]),
274
+ ]);
265
275
  opts.signal?.throwIfAborted();
266
276
  return { code: timedOut ? null : code, output: [stdout, stderr].filter(Boolean).join("\n"), timedOut };
267
277
  } finally {
@@ -326,31 +336,69 @@ export function shellEnv(executable: string, env: NodeJS.ProcessEnv = process.en
326
336
  return { ...env, [key]: [...dirs, env[key]].filter(Boolean).join(path.delimiter) };
327
337
  }
328
338
 
339
+ /** 启动的命令和它的标记(killTree 用) */
340
+ type Tagged = Proc & { tag: string };
341
+
342
+ /** 标记用的环境变量:命令启动的进程都继承它,killTree 在 Windows 上靠它把它们找出来 */
343
+ const TAG = "JADE_SHELL_TAG";
344
+ let launched = 0;
345
+
346
+ /** 启动 shell 执行一条命令 */
347
+ async function launch(executable: string, env: NodeJS.ProcessEnv | undefined, command: string, cwd: string | undefined): Promise<Tagged> {
348
+ const tag = `${process.pid}-${Date.now().toString(36)}-${++launched}`;
349
+ const proc = await spawnProc([executable, "-c", command], {
350
+ cwd,
351
+ env: process.platform === "win32" ? { ...(env ?? process.env), [TAG]: tag } : env,
352
+ // 自成进程组,超时/中断时能连同子进程一起杀掉
353
+ detached: process.platform !== "win32",
354
+ });
355
+ return Object.assign(proc, { tag });
356
+ }
357
+
329
358
  /**
330
359
  * 只杀 shell 本身不够:它启动的子进程还占着 stdout/stderr 管道,读取会一直等到它们退出。
331
- * POSIX 上杀整个进程组。Windows 上 Git Bash(msys)模拟 fork,Windows 进程树里看不到父子关系,
332
- * 要先在 msys 里按 WINPID 找到 shell 的 msys PID(它也是进程组号)杀掉整组;taskkill /T 兜底非 msys 的 shell
360
+ * POSIX 上杀整个进程组。Windows 上 Git Bash(msys)模拟 fork,Windows 进程树里看不到父子关系;
361
+ * 按 WINPID 找也不行:msys 的 exec(bash -c "npm login" 直接换成 npm 那个脚本)会换一个 Windows 进程,
362
+ * 我们手里的 pid 只剩一个空壳。所以启动时在环境变量里放一个标记,这里在 msys 的 /proc 里把带标记的进程
363
+ * 找出来,连同它们的进程组(里面有 node 这类不是 msys 的子进程)一起杀掉
333
364
  */
334
- function killTree(shell: string, env: NodeJS.ProcessEnv | undefined, pid: number) {
365
+ function killTree(shell: string, env: NodeJS.ProcessEnv | undefined, proc: Tagged) {
335
366
  try {
336
- if (process.platform !== "win32") return process.kill(-pid, "SIGKILL");
337
- const script = `for d in /proc/[0-9]*; do [ "$(cat "$d/winpid" 2>/dev/null)" = "${pid}" ] && kill -9 -- "-\${d#/proc/}"; done`;
367
+ if (process.platform !== "win32") return process.kill(-proc.pid, "SIGKILL");
368
+ const script =
369
+ `for d in /proc/[0-9]*; do ` +
370
+ `if grep -qa "${TAG}=${proc.tag}" "$d/environ" 2>/dev/null || [ "$(cat "$d/winpid" 2>/dev/null)" = "${proc.pid}" ]; then ` +
371
+ `kill -9 -- "-$(cat "$d/pgid")" "\${d#/proc/}" 2>/dev/null; fi; done`;
372
+ // 先按 Windows 的进程树杀:cmd、node 这类不是 msys 的进程启动的子进程只有这里找得到,先杀掉它们的父进程就找不到了
373
+ runSync(["taskkill", "/T", "/F", "/PID", String(proc.pid)]);
338
374
  try {
375
+ // 用没有标记的环境变量跑,免得它把自己也算进去
339
376
  runSync([shell, "-c", script], { env });
340
377
  } catch {
341
378
  // 不是 msys/cygwin 的 shell
342
379
  }
343
- runSync(["taskkill", "/T", "/F", "/PID", String(pid)]);
344
380
  } catch {
345
381
  // 已经退出
346
382
  }
347
383
  }
348
384
 
385
+ /** 杀掉之后最多再等这么久就不等了:没杀干净的进程还占着输出管道时,读取永远等不到结束,这一轮(和整个界面)就卡在那里 */
386
+ const KILL_GRACE_MS = 2000;
387
+
388
+ /** start 之后过 KILL_GRACE_MS,done 就 resolve;不 start 永远不 resolve */
389
+ function giveUp(): { start(): void; done: Promise<void> } {
390
+ let start = () => {};
391
+ const done = new Promise<void>((resolve) => {
392
+ start = () => void setTimeout(resolve, KILL_GRACE_MS);
393
+ });
394
+ return { start, done };
395
+ }
396
+
349
397
  /**
350
398
  * 返回截好的输出:超过 MAX_OUTPUT_CHARS 时保留开头和结尾各一半,中间截掉。
351
399
  * 边读边截,输出再多也只占几倍 MAX_OUTPUT_CHARS 的内存。keep 为 false 时只推给 onChunk,不累积,返回空串
352
400
  */
353
- async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string) => void, keep = true): Promise<string> {
401
+ async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string) => void, keep = true, stop?: Promise<void>): Promise<string> {
354
402
  const half = MAX_OUTPUT_CHARS / 2;
355
403
  const decoder = new TextDecoder();
356
404
  let head = "";
@@ -369,8 +417,17 @@ async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string
369
417
  // 攒到两倍再截,不用每块都复制
370
418
  if (tail.length > 2 * half) tail = tail.slice(-half);
371
419
  };
372
- for await (const chunk of stream) {
373
- const text = decoder.decode(chunk, { stream: true });
420
+ // stop:不再等(进程杀掉之后管道还被别的进程占着),返回已经读到的
421
+ const it = stream[Symbol.asyncIterator]();
422
+ const stopped = stop?.then(() => undefined);
423
+ for (;;) {
424
+ const r = await (stopped ? Promise.race([it.next(), stopped]) : it.next());
425
+ if (!r) {
426
+ void Promise.resolve(it.return?.()).catch(() => {});
427
+ break;
428
+ }
429
+ if (r.done) break;
430
+ const text = decoder.decode(r.value, { stream: true });
374
431
  if (text) add(text);
375
432
  }
376
433
  const rest = decoder.decode();
@@ -1,59 +1,22 @@
1
1
  // jade/task:task 工具,把调研交给只读的子 Agent(见 subagent.ts)。
2
2
  //
3
- // 子 Agent 用哪些工具:插件经 task@1 登记只读工具(jade/fs 登记 read_file、list_dir、glob、grep),
4
- // 登记随登记者的作用域撤销。主会话里的工具对象是各插件私有的,子 Agent 拿到的是登记者另给的一份。
3
+ // 子 Agent 用哪些工具:其他插件登记在 tools@1(jade/tools)里的那些(jade/fs 登记 read_file、list_dir、glob、grep),
4
+ // 每次启动子 Agent 时取。主会话里的工具对象是各插件私有的,子 Agent 拿到的是登记者另给的一份。
5
5
 
6
- import type { Tool, Usage } from "uncarved";
6
+ import type { Usage } from "uncarved";
7
7
  import { definePlugin, type UI } from "@uncarved/jade-api";
8
- import type { Approval, Models, Prompts, Renderers, Task } from "@uncarved/jade-api/services";
8
+ import type { Approval, Models, Prompts, Renderers, Tools } from "@uncarved/jade-api/services";
9
9
  import { taskTool, type ApproveSubagent, type TaskProgress } from "./subagent.ts";
10
10
  import { clip, dim, red } from "./style.ts";
11
11
 
12
12
  const DEFAULT_MAX_STEPS = 40;
13
13
  const MAX_DETAIL_LINES = 40;
14
14
 
15
- /** 登记的只读工具,按登记顺序 */
16
- const registry: { tool: Tool; plugin: string; when?: () => boolean }[] = [];
17
-
18
- /** 这次启动子 Agent 时给它的工具:同名的取最后登记的那个,when 返回 false 或出错的不给 */
19
- function available(): Tool[] {
20
- const latest = new Map<string, (typeof registry)[number]>();
21
- for (const r of registry) {
22
- latest.delete(r.tool.name);
23
- latest.set(r.tool.name, r);
24
- }
25
- return [...latest.values()].flatMap((r) => {
26
- try {
27
- return !r.when || r.when() ? [r.tool] : [];
28
- } catch {
29
- return [];
30
- }
31
- });
32
- }
33
-
34
15
  /** 子 Agent 的审批一次问一个:并行的几个子 Agent 不同时弹对话框 */
35
16
  let asking: Promise<unknown> = Promise.resolve();
36
17
 
37
18
  export default definePlugin({
38
19
  process(ctx) {
39
- ctx.provide("task@1", (caller): Task => ({
40
- tool(tool, opts) {
41
- if (typeof tool?.name !== "string" || typeof tool.execute !== "function") throw new Error("task.tool: a tool needs a name and execute");
42
- // 同一个插件重复登记是正常的:换会话时新会话先登记,旧会话随后撤销它的那份;取最后登记的
43
- const taken = registry.find((r) => r.tool.name === tool.name && r.plugin !== caller.plugin);
44
- if (taken) throw new Error(`task.tool: ${tool.name} is already registered by ${taken.plugin}`);
45
- if (opts?.when !== undefined && typeof opts.when !== "function") throw new Error("task.tool: when must be a function");
46
- const entry = { tool, plugin: caller.plugin, ...(opts?.when ? { when: opts.when } : {}) };
47
- registry.push(entry);
48
- const revoke = () => {
49
- const i = registry.indexOf(entry);
50
- if (i !== -1) registry.splice(i, 1);
51
- };
52
- caller.onDispose(revoke);
53
- return revoke;
54
- },
55
- }));
56
-
57
20
  const renderers = ctx.service<Renderers>("renderers@1");
58
21
  if (renderers) {
59
22
  // 运行中每个只有一行进度(标签、调用过几个工具、正在做什么),并行的几个靠标签分清;结束时把它调用过的工具放进结果的折叠内容里
@@ -130,7 +93,14 @@ export default definePlugin({
130
93
  taskTool({
131
94
  cwd: ctx.cwd,
132
95
  provider: { id: ctx.plugin, complete: (req, o) => models.complete(req, model ? { ...o, model } : o) },
133
- tools: available,
96
+ // 没有 jade/tools、或者它被隔离了(服务已失效,调用会抛错):子 Agent 没有工具
97
+ tools: () => {
98
+ try {
99
+ return ctx.service<Tools>("tools@1")?.list() ?? [];
100
+ } catch {
101
+ return [];
102
+ }
103
+ },
134
104
  maxSteps,
135
105
  approve,
136
106
  allowed: (call) => ctx.service<Approval>("approval@1")?.allows(ctx.session.id, call) ?? false,
@@ -3,9 +3,8 @@
3
3
  "version": "0.3.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "provides": ["task@1"],
7
6
  "requires": ["models@1"],
8
- "optional": ["ui@1", "renderers@1", "approval@1", "prompts@1"],
7
+ "optional": ["tools@1", "ui@1", "renderers@1", "approval@1", "prompts@1"],
9
8
  "config": {
10
9
  "maxSteps": {
11
10
  "default": 40,
@@ -1,6 +1,6 @@
1
1
  // task 工具:启动一个只读的子 Agent。从旧 jade 的 tools/task.ts 移植。
2
2
  //
3
- // 子 Agent 是一个嵌套的 uncarved Runtime:工具是其他插件经 task@1 登记的只读工具,模型经 models@1 调用。
3
+ // 子 Agent 是一个嵌套的 uncarved Runtime:工具是其他插件登记在 tools@1 里的工具,模型经 models@1 调用。
4
4
  // 它的日志放在内存里:会话日志存储归 jade 核心,插件拿不到,所以子会话不和父会话的日志关联(不返回 child 引用)。
5
5
  // 子 Agent 调用的工具通过 ctx.progress 推给前端显示;要用户批准的调用(工作目录之外的路径、带 URL 的工具)经 ui@1 问。
6
6
 
@@ -45,7 +45,7 @@ export interface TaskOptions {
45
45
  cwd: string;
46
46
  /** 调用模型(models@1) */
47
47
  provider: Provider;
48
- /** 每次调用时取:其他插件登记的只读工具 */
48
+ /** 每次调用时取:其他插件登记给嵌套 Agent 的工具(tools@1) */
49
49
  tools(): Tool[];
50
50
  /** 子 Agent 一次最多回复几次 */
51
51
  maxSteps: number;
@@ -0,0 +1,50 @@
1
+ // jade/tools:给嵌套 Agent(子 Agent 之类)用的工具的注册表。
2
+ //
3
+ // 主会话里的工具对象是各插件私有的,另起一个 Agent 的插件拿不到。提供工具的插件在这里另登记一套实例,
4
+ // 要用的插件(jade/task,或任何第三方插件)自己来取、自己筛选、自己把关:登记的一方不用知道谁在用。
5
+
6
+ import type { Tool } from "uncarved";
7
+ import { definePlugin } from "@uncarved/jade-api";
8
+ import type { Tools } from "@uncarved/jade-api/services";
9
+
10
+ /** 登记的工具,按登记顺序 */
11
+ const registry: { tool: Tool; plugin: string; when?: () => boolean }[] = [];
12
+
13
+ /** 同名的取最后登记的那个,when 返回 false 或出错的不给 */
14
+ function available(): Tool[] {
15
+ const latest = new Map<string, (typeof registry)[number]>();
16
+ for (const r of registry) {
17
+ latest.delete(r.tool.name);
18
+ latest.set(r.tool.name, r);
19
+ }
20
+ return [...latest.values()].flatMap((r) => {
21
+ try {
22
+ return !r.when || r.when() ? [r.tool] : [];
23
+ } catch {
24
+ return [];
25
+ }
26
+ });
27
+ }
28
+
29
+ export default definePlugin({
30
+ process(ctx) {
31
+ ctx.provide("tools@1", (caller): Tools => ({
32
+ register(tool, opts) {
33
+ if (typeof tool?.name !== "string" || typeof tool.execute !== "function") throw new Error("tools.register: a tool needs a name and execute");
34
+ // 同一个插件重复登记是正常的:换会话时新会话先登记,旧会话随后撤销它的那份;取最后登记的
35
+ const taken = registry.find((r) => r.tool.name === tool.name && r.plugin !== caller.plugin);
36
+ if (taken) throw new Error(`tools.register: ${tool.name} is already registered by ${taken.plugin}`);
37
+ if (opts?.when !== undefined && typeof opts.when !== "function") throw new Error("tools.register: when must be a function");
38
+ const entry = { tool, plugin: caller.plugin, ...(opts?.when ? { when: opts.when } : {}) };
39
+ registry.push(entry);
40
+ const revoke = () => {
41
+ const i = registry.indexOf(entry);
42
+ if (i !== -1) registry.splice(i, 1);
43
+ };
44
+ caller.onDispose(revoke);
45
+ return revoke;
46
+ },
47
+ list: available,
48
+ }));
49
+ },
50
+ });
@@ -0,0 +1,7 @@
1
+ {
2
+ "id": "jade/tools",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.ts",
6
+ "provides": ["tools@1"]
7
+ }
@@ -50,7 +50,13 @@ const OWN: CommandInfo[] = [
50
50
  ];
51
51
 
52
52
  const KEYS =
53
- "Keys: enter send · ctrl+j, alt+enter or \\ then enter: new line · ↑↓ history · esc interrupt (twice to also move queued messages back to the input) · ↑ on the first line edits queued messages · ctrl+o expand · ctrl+c twice to exit";
53
+ "Keys: enter send · !<command> runs a shell command yourself · ctrl+j, alt+enter or \\ then enter: new line · ↑↓ history · esc interrupt (twice to also move queued messages back to the input) · ↑ on the first line edits queued messages · ctrl+o expand · ctrl+c twice to exit";
54
+
55
+ /** 退出时最多等正在做的事这么久 */
56
+ const QUIT_WAIT_MS = 3000;
57
+
58
+ /** 命令运行中的临时显示(CommandContext.progress)最多占几行 */
59
+ const LIVE_ROWS = 8;
54
60
 
55
61
  /** 第二次 esc 算作"再按一次"的时间窗口 */
56
62
  const SECOND_ESC_MS = 3000;
@@ -508,7 +514,9 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
508
514
  if (quitting) return;
509
515
  quitting = true;
510
516
  if (running) current?.abort(new Error("exiting"));
511
- await work?.catch(() => {});
517
+ // 正在做的事停不下来时(例如命令杀不掉)不一直等:退出不能被它卡住
518
+ for (const ac of commandAborts) ac.abort(new Error("exiting"));
519
+ await Promise.race([work?.catch(() => {}), new Promise((r) => setTimeout(r, QUIT_WAIT_MS))]);
512
520
  keyAbort.abort(new Error("exiting"));
513
521
  offMode?.();
514
522
  offModel?.();
@@ -571,7 +579,18 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
571
579
  }
572
580
  const ac = new AbortController();
573
581
  commandAborts.add(ac);
574
- const ctx: CommandContext = { signal: ac.signal, ui: bridge.ui, sessions: manager, print: (t) => screen.log(t) };
582
+ // 命令的临时显示:末尾几行,每行占进度区的一行
583
+ const showLive = (text: string | undefined) => {
584
+ const lines = text?.replace(/\r\n?/g, "\n").trimEnd().split("\n").slice(-LIVE_ROWS) ?? [];
585
+ for (let i = 0; i < LIVE_ROWS; i++) screen.progress(`command:${i}`, text !== undefined && i < lines.length ? dim(` │ ${lines[i]}`) : undefined);
586
+ };
587
+ const ctx: CommandContext = {
588
+ signal: ac.signal,
589
+ ui: bridge.ui,
590
+ sessions: manager,
591
+ print: (t, o) => screen.log(t, o?.details ? { details: o.details } : undefined),
592
+ progress: showLive,
593
+ };
575
594
  try {
576
595
  const result = await found.command.run(rest, ctx);
577
596
  if (typeof result === "string") screen.log(result);
@@ -582,6 +601,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
582
601
  } catch (e) {
583
602
  if (!ac.signal.aborted) screen.log(red(`[error] /${name}: ${errorText(e)}`));
584
603
  } finally {
604
+ showLive(undefined);
585
605
  commandAborts.delete(ac);
586
606
  }
587
607
  return true;
@@ -589,6 +609,8 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
589
609
 
590
610
  function onSubmit(text: string) {
591
611
  if (quitting) return;
612
+ // !<命令> 是 /sh <命令> 的简写(jade/shell 提供):用户自己执行,不经过模型
613
+ if (/^!\s*\S/.test(text)) text = `/sh ${text.slice(1).trim()}`;
592
614
  const name = commandName(text);
593
615
  if (name !== undefined && instant(name)) {
594
616
  // 不碰会话的命令运行中也直接执行
@@ -625,6 +647,8 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
625
647
  showQueued();
626
648
  view.echo(text);
627
649
  if (commandName(text) !== undefined) {
650
+ // 命令可能要跑一阵(/sh 跑测试):让用户看到它在跑
651
+ screen.busy("Running");
628
652
  if (!(await command(text))) {
629
653
  exit = true;
630
654
  return;
@@ -19,7 +19,7 @@ export type Mood =
19
19
  | "writing" // 输出正文或工具参数:低头,眼睛随打字左右移,旁边打字的点
20
20
  | "tool" // 运行工具:看向右边转着的圈,身上扫过一道光
21
21
  | "asking" // 弹出对话框等用户:睁大眼,头上一个闪烁的感叹号
22
- | "stopping" // 正在中断:眯眼,变成琥珀色,冒一滴汗
22
+ | "stopping" // 正在中断:眯眼,变成琥珀色,汗一滴滴往下滑
23
23
  | "happy"; // 刚做完:^ ^ 地原地蹦一下,落地一亮,转头看右边画出一个 ✓,再回过头冲你眨一只眼
24
24
 
25
25
  /** 做完后笑多久 */
@@ -386,12 +386,13 @@ function side(mood: Mood, now: number, t: number): [number, number, RGB][] {
386
386
  const c = mix(BANG[0]!, BANG[1]!, 0.5 + 0.5 * Math.sin(now / 160));
387
387
  return [0, 1, 2, 4].map((y) => [1, y, c]);
388
388
  }
389
- case "stopping":
390
- // 汗珠挂在头的右上角,贴着身体
391
- return [
392
- [-1, 0, SWEAT],
393
- [-1, 1, mix(SWEAT, rgb("#ffffff"), 0.4)],
394
- ];
389
+ case "stopping": {
390
+ // 汗珠从头的右上角贴着身体一滴滴往下滑:亮的一头在下面,上面拖一格淡的;滑到底停一拍再冒下一滴
391
+ const row = Math.floor((now % 1000) / 200);
392
+ if (row > 3) return [];
393
+ const head: [number, number, RGB] = [-1, row, mix(SWEAT, rgb("#ffffff"), 0.4)];
394
+ return row > 0 ? [[-1, row - 1, SWEAT], head] : [head];
395
+ }
395
396
  default:
396
397
  return [];
397
398
  }
@@ -1516,7 +1516,7 @@ function Prompt({
1516
1516
  bridge: DraftBridge;
1517
1517
  /** 插件设置的灰色提示 */
1518
1518
  hint?: string;
1519
- /** 提示被接受了,或者用户开始打字了:去掉它 */
1519
+ /** 提示随消息发出去了:去掉它 */
1520
1520
  onHintDone(): void;
1521
1521
  busy: boolean;
1522
1522
  /** 有排队等待发送的消息 */
@@ -1641,8 +1641,7 @@ function Prompt({
1641
1641
  /** 提示只在空闲、输入框为空、没有在搜索历史时显示,也只有这时能接受 */
1642
1642
  const hinting = () => hint !== undefined && !busy && current().value === "" && !getSearch();
1643
1643
  const set = (s: EditState) => {
1644
- // 用户开始打字(或者插件改了输入框):提示作废
1645
- if (s.value && hint !== undefined) onHintDone();
1644
+ // 打字时提示只是不显示(hinting() 要求输入框为空),删回空的又出现;发出去才作废
1646
1645
  setState(s);
1647
1646
  setSelected(0);
1648
1647
  setNotice(undefined);
@@ -1657,6 +1656,7 @@ function Prompt({
1657
1656
  };
1658
1657
  const submit = (text: string) => {
1659
1658
  if (!text.trim()) return;
1659
+ if (hint !== undefined) onHintDone();
1660
1660
  remember(text);
1661
1661
  set(empty);
1662
1662
  // 发出去之后弹出的对话框是用户自己要的(/mode、/model),马上就能回答
@@ -1791,7 +1791,12 @@ function Prompt({
1791
1791
  ? setSearch({ query: "", index: 0 })
1792
1792
  : undefined;
1793
1793
  if (key.ctrl && input === "c") {
1794
- if (busy) return handlers.interrupt();
1794
+ if (busy) {
1795
+ // 第一下中断;停不下来时(卡在 Interrupting)再按一下也能退出
1796
+ if (Date.now() - lastCtrlC.current < 2000) return handlers.exit();
1797
+ lastCtrlC.current = Date.now();
1798
+ return handlers.interrupt();
1799
+ }
1795
1800
  if (state.value) return discard();
1796
1801
  if (Date.now() - lastCtrlC.current < 2000) return handlers.exit();
1797
1802
  lastCtrlC.current = Date.now();
@@ -1829,7 +1834,6 @@ function Prompt({
1829
1834
  }
1830
1835
  // Tab 或 →:把提示变成输入框里的文字,接着可以改
1831
1836
  if (((key.tab && !key.shift) || key.rightArrow) && hinting()) {
1832
- onHintDone();
1833
1837
  browsing.current = -1;
1834
1838
  return set({ value: hint!, cursor: hint!.length });
1835
1839
  }
@@ -1888,13 +1892,16 @@ function Prompt({
1888
1892
  ? [Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)]
1889
1893
  : undefined;
1890
1894
 
1895
+ // ! 开头:这一行是用户自己执行的 shell 命令(/sh),边框换个颜色、上边框的右边写一行说明
1896
+ const bang = !search && state.value.startsWith("!");
1897
+
1891
1898
  // 对话框打开时隐藏但不卸载,输入到一半的内容和历史都保留
1892
1899
  return h(
1893
1900
  Box,
1894
1901
  { flexDirection: "column", marginTop: 1, display: active ? "flex" : "none" },
1895
1902
  h(
1896
1903
  Box,
1897
- { borderStyle: "round", borderColor: busy ? "gray" : "cyan", paddingX: 1 },
1904
+ { borderStyle: "round", borderColor: bang ? "magenta" : busy ? "gray" : "cyan", paddingX: 1 },
1898
1905
  search
1899
1906
  ? h(EditableText, {
1900
1907
  state: { value: search.query, cursor: search.query.length },
@@ -1991,7 +1998,16 @@ function Prompt({
1991
1998
  ? h(Text, { color: "yellow" }, ` ${notice}`)
1992
1999
  : null,
1993
2000
  // 压在输入框上边框的右边,不占行,出现和消失时下面的内容不跳
1994
- flash ? h(Box, { position: "absolute", top: 0, right: 2 }, h(Text, { color: "green" }, ` ${flash} `)) : null,
2001
+ // ! 开头时同一个位置写这一行是什么(刚复制的提示优先)
2002
+ flash
2003
+ ? h(Box, { position: "absolute", top: 0, right: 2 }, h(Text, { color: "green" }, ` ${flash} `))
2004
+ : bang
2005
+ ? h(
2006
+ Box,
2007
+ { position: "absolute", top: 0, right: 2 },
2008
+ h(Text, { color: "magenta" }, columns >= 70 ? (busy ? " shell command · runs after this turn · esc stops it " : " shell command · you run it, not the agent · esc stops it ") : " shell command "),
2009
+ )
2010
+ : null,
1995
2011
  );
1996
2012
  }
1997
2013
 
@@ -6,7 +6,7 @@
6
6
 
7
7
  import path from "node:path";
8
8
  import { definePlugin, type ScopeContext, type UI } from "@uncarved/jade-api";
9
- import type { Commands, Prompts, Renderers, Task } from "@uncarved/jade-api/services";
9
+ import type { Commands, Prompts, Renderers, Tools } from "@uncarved/jade-api/services";
10
10
  import { envWithFile, updateEnvFile, type Env } from "./env.ts";
11
11
  import { webRenderers } from "./renderers.ts";
12
12
  import { parseOrder, parseResults, SEARCH_PROVIDERS, webTools } from "./web.ts";
@@ -98,14 +98,14 @@ export default definePlugin({
98
98
  const web = webTools({ ...opts, env: () => keys ?? env });
99
99
  for (const tool of web.tools) ctx.kernel.tool(tool);
100
100
 
101
- // 子 Agent(jade/task)也能查网页:另一套实例;web_search 只在配置了搜索服务时给它。
102
- // web_fetch 带 url 参数,子 Agent 每次都要问用户(URL 能把读到的内容带出去)。
103
- // jade/task 被隔离时它的服务已失效:子 Agent 没有 web 工具,web 工具本身照常
101
+ // 嵌套 Agent(例如 jade/task 的子 Agent)也能查网页:另一套实例;web_search 只在配置了搜索服务时给它。
102
+ // web_fetch 带 url 参数,jade/task 的子 Agent 每次都要问用户(URL 能把读到的内容带出去)。
103
+ // jade/tools 被隔离时它的服务已失效:嵌套 Agent 没有 web 工具,web 工具本身照常
104
104
  try {
105
- const task = ctx.service<Task>("task@1");
106
- if (task) {
105
+ const shared = ctx.service<Tools>("tools@1");
106
+ if (shared) {
107
107
  const sub = webTools({ ...opts, env: () => keys ?? env });
108
- for (const tool of sub.tools) task.tool(tool, tool.name === "web_search" ? { when: () => sub.search().length > 0 } : {});
108
+ for (const tool of sub.tools) shared.register(tool, tool.name === "web_search" ? { when: () => sub.search().length > 0 } : {});
109
109
  }
110
110
  } catch {}
111
111
 
@@ -3,7 +3,7 @@
3
3
  "version": "0.3.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "optional": ["ui@1", "commands@1", "prompts@1", "renderers@1", "task@1"],
6
+ "optional": ["ui@1", "commands@1", "prompts@1", "renderers@1", "tools@1"],
7
7
  "config": {
8
8
  "search": {
9
9
  "description": "search services to use, in order: a list or comma-separated names (tinyfish, anysearch, tavily, exa, firecrawl, jina); default: every service with an API key. Keys are read from the environment and $JADE_HOME/.env (/search sets them). $JADE_SEARCH still works"