@uncarved/jade 0.3.0 → 0.4.0

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 (207) 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/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +482 -27
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +49 -24
  14. package/plugins/approval/policy.ts +48 -25
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +55 -12
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +10 -9
  50. package/plugins/models/index.ts +31 -4
  51. package/plugins/models/provider.ts +12 -1
  52. package/plugins/modes/index.ts +13 -2
  53. package/plugins/print/index.ts +7 -4
  54. package/plugins/prompts/index.ts +0 -0
  55. package/plugins/renderers/index.ts +10 -5
  56. package/plugins/repeats/index.ts +39 -9
  57. package/plugins/schedule/index.ts +2 -0
  58. package/plugins/screenshot/browser.ts +231 -0
  59. package/plugins/screenshot/index.ts +3 -2
  60. package/plugins/screenshot/tool.ts +27 -51
  61. package/plugins/sessions/index.ts +48 -2
  62. package/plugins/shell/index.ts +75 -22
  63. package/plugins/shell/plugin.json +1 -2
  64. package/plugins/shell/renderers.ts +9 -7
  65. package/plugins/shell/shell.ts +93 -34
  66. package/plugins/skills/index.ts +28 -19
  67. package/plugins/skills/project.ts +12 -7
  68. package/plugins/steer/index.ts +5 -4
  69. package/plugins/task/index.ts +81 -81
  70. package/plugins/task/plugin.json +5 -2
  71. package/plugins/task/style.ts +13 -14
  72. package/plugins/task/subagent.ts +67 -184
  73. package/plugins/todo/index.ts +39 -9
  74. package/plugins/tools/index.ts +57 -0
  75. package/plugins/tools/plugin.json +7 -0
  76. package/plugins/tui/frontend.ts +161 -87
  77. package/plugins/tui/index.ts +2 -3
  78. package/plugins/tui/mascot.ts +8 -7
  79. package/plugins/tui/mentions.ts +11 -80
  80. package/plugins/tui/plugin.json +1 -1
  81. package/plugins/tui/screen.ts +55 -5
  82. package/plugins/tui/transcript.ts +17 -7
  83. package/plugins/tui/tui.ts +356 -104
  84. package/plugins/tui/vendor.ts +1 -1
  85. package/plugins/undo/checkpoint.ts +5 -3
  86. package/plugins/undo/index.ts +43 -14
  87. package/plugins/undo/style.ts +13 -14
  88. package/plugins/web/index.ts +7 -18
  89. package/plugins/web/plugin.json +1 -1
  90. package/plugins-dist/approval/index.js +363 -414
  91. package/plugins-dist/approval/policy.js +395 -497
  92. package/plugins-dist/approval/review.js +132 -158
  93. package/plugins-dist/approval/schema.js +50 -55
  94. package/plugins-dist/ask/index.js +115 -129
  95. package/plugins-dist/budget/index.js +27 -31
  96. package/plugins-dist/checks/checks.js +293 -329
  97. package/plugins-dist/checks/index.js +119 -139
  98. package/plugins-dist/checks/plugin.json +2 -1
  99. package/plugins-dist/checks/project.js +57 -65
  100. package/plugins-dist/commands/index.js +47 -29
  101. package/plugins-dist/compact/compact.js +233 -249
  102. package/plugins-dist/compact/index.js +98 -95
  103. package/plugins-dist/compact/style.js +9 -14
  104. package/plugins-dist/completions/index.js +30 -0
  105. package/plugins-dist/completions/plugin.json +9 -0
  106. package/plugins-dist/continue/index.js +40 -52
  107. package/plugins-dist/copy/index.js +40 -0
  108. package/plugins-dist/copy/plugin.json +9 -0
  109. package/plugins-dist/cost/index.js +98 -115
  110. package/plugins-dist/custom-commands/index.js +55 -72
  111. package/plugins-dist/editor/index.js +64 -72
  112. package/plugins-dist/fs/diff.js +111 -124
  113. package/plugins-dist/fs/fs.js +426 -469
  114. package/plugins-dist/fs/grep.js +262 -244
  115. package/plugins-dist/fs/index.js +20 -34
  116. package/plugins-dist/fs/plugin.json +1 -2
  117. package/plugins-dist/fs/renderers.js +100 -112
  118. package/plugins-dist/fs/style.js +11 -15
  119. package/plugins-dist/fs/sys.js +31 -43
  120. package/plugins-dist/hooks/index.js +107 -127
  121. package/plugins-dist/keys/index.js +27 -31
  122. package/plugins-dist/mcp/index.js +271 -199
  123. package/plugins-dist/mcp/install.js +123 -137
  124. package/plugins-dist/mcp/mcp.js +638 -577
  125. package/plugins-dist/mcp/plugin.json +3 -1
  126. package/plugins-dist/mcp/project.js +98 -115
  127. package/plugins-dist/memory/index.js +83 -88
  128. package/plugins-dist/memory/memory.js +111 -128
  129. package/plugins-dist/memory/style.js +9 -14
  130. package/plugins-dist/mentions/attach.js +91 -99
  131. package/plugins-dist/mentions/candidates.js +49 -0
  132. package/plugins-dist/mentions/index.js +71 -81
  133. package/plugins-dist/mentions/plugin.json +2 -1
  134. package/plugins-dist/mentions/style.js +9 -14
  135. package/plugins-dist/models/config.js +29 -43
  136. package/plugins-dist/models/configure.js +392 -473
  137. package/plugins-dist/models/context.js +14 -22
  138. package/plugins-dist/models/index.js +182 -188
  139. package/plugins-dist/models/provider.js +243 -295
  140. package/plugins-dist/models/saved.js +59 -71
  141. package/plugins-dist/modes/index.js +138 -165
  142. package/plugins-dist/plugins/index.js +34 -34
  143. package/plugins-dist/print/index.js +192 -175
  144. package/plugins-dist/prompts/index.js +81 -89
  145. package/plugins-dist/prompts/notes.js +31 -37
  146. package/plugins-dist/prompts/prompts.js +155 -193
  147. package/plugins-dist/prompts/results.js +40 -53
  148. package/plugins-dist/prompts/sys.js +39 -50
  149. package/plugins-dist/renderers/index.js +32 -32
  150. package/plugins-dist/repeats/index.js +134 -151
  151. package/plugins-dist/schedule/cron.js +49 -56
  152. package/plugins-dist/schedule/index.js +229 -247
  153. package/plugins-dist/schedule/store.js +93 -109
  154. package/plugins-dist/scratch/index.js +12 -18
  155. package/plugins-dist/screenshot/browser.js +169 -0
  156. package/plugins-dist/screenshot/index.js +37 -45
  157. package/plugins-dist/screenshot/sys.js +53 -65
  158. package/plugins-dist/screenshot/tool.js +101 -151
  159. package/plugins-dist/sessions/index.js +149 -117
  160. package/plugins-dist/shell/index.js +117 -74
  161. package/plugins-dist/shell/plugin.json +1 -2
  162. package/plugins-dist/shell/renderers.js +28 -33
  163. package/plugins-dist/shell/service.js +17 -23
  164. package/plugins-dist/shell/shell.js +317 -320
  165. package/plugins-dist/shell/sys.js +64 -79
  166. package/plugins-dist/skills/index.js +193 -211
  167. package/plugins-dist/skills/install.js +122 -149
  168. package/plugins-dist/skills/project.js +65 -73
  169. package/plugins-dist/skills/skills.js +135 -171
  170. package/plugins-dist/steer/index.js +108 -125
  171. package/plugins-dist/suggest/index.js +235 -259
  172. package/plugins-dist/task/index.js +130 -148
  173. package/plugins-dist/task/plugin.json +5 -4
  174. package/plugins-dist/task/style.js +9 -14
  175. package/plugins-dist/task/subagent.js +156 -279
  176. package/plugins-dist/todo/index.js +79 -63
  177. package/plugins-dist/tools/index.js +43 -0
  178. package/plugins-dist/tools/plugin.json +9 -0
  179. package/plugins-dist/tui/editor.js +145 -160
  180. package/plugins-dist/tui/frontend.js +641 -655
  181. package/plugins-dist/tui/history.js +34 -37
  182. package/plugins-dist/tui/index.js +16 -18
  183. package/plugins-dist/tui/markdown.js +203 -247
  184. package/plugins-dist/tui/mascot.js +266 -353
  185. package/plugins-dist/tui/mentions.js +67 -144
  186. package/plugins-dist/tui/plugin.json +1 -2
  187. package/plugins-dist/tui/render.js +35 -45
  188. package/plugins-dist/tui/screen.js +197 -180
  189. package/plugins-dist/tui/transcript.js +436 -468
  190. package/plugins-dist/tui/tui.js +1554 -1645
  191. package/plugins-dist/tui/vendor.js +1388 -1088
  192. package/plugins-dist/undo/checkpoint.js +95 -118
  193. package/plugins-dist/undo/index.js +185 -192
  194. package/plugins-dist/undo/snapshot.js +83 -99
  195. package/plugins-dist/undo/style.js +9 -14
  196. package/plugins-dist/update/index.js +26 -28
  197. package/plugins-dist/web/env.js +55 -68
  198. package/plugins-dist/web/index.js +80 -110
  199. package/plugins-dist/web/plugin.json +1 -2
  200. package/plugins-dist/web/renderers.js +4 -5
  201. package/plugins-dist/web/web.js +514 -593
  202. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  203. package/sdk/python/jade_plugin.py +9 -2
  204. package/src/api.ts +1 -1
  205. package/src/host.ts +39 -4
  206. package/src/remote.ts +6 -1
  207. package/src/session.ts +489 -34
@@ -5,10 +5,10 @@
5
5
  // 它只是给模型看的文字,不执行代码;和旧 jade 一样,列表里有项目层的 skill 时整段标为不可信。
6
6
 
7
7
  import path from "node:path";
8
- import { definePlugin, type Cli, type Sources, type UI } from "@uncarved/jade-api";
8
+ import { definePlugin, type Cli, type Sources, type Text, type UI } from "@uncarved/jade-api";
9
9
  import type { Approval, Commands, Prompts } from "@uncarved/jade-api/services";
10
10
  import { addSkill, removeSkill, skillsRoot, updateSkills } from "./install.ts";
11
- import { bold, clip, dim, display, estimateTokens, realPath, red, repoRoot, splitArgs } from "./project.ts";
11
+ import { bold, clip, dim, display, error, estimateTokens, lines as joinLines, plain, realPath, repoRoot, splitArgs } from "./project.ts";
12
12
  import { loadSkills, skillLine, skillsPrompt, skillTool, type Skill } from "./skills.ts";
13
13
 
14
14
  const ID = "jade/skills";
@@ -36,7 +36,7 @@ export const manageUsage = (cmd: string) => `usage: ${cmd} [list]
36
36
  export async function manageSkills(
37
37
  argv: readonly string[],
38
38
  env: { home: string; cwd: string; cmd: string; sources: Sources; log?: (text: string) => void; skills?: Skill[] },
39
- ): Promise<string> {
39
+ ): Promise<Text> {
40
40
  const usage = manageUsage(env.cmd);
41
41
  const [sub, ...tail] = argv;
42
42
  if (sub === "-h" || sub === "--help" || tail.includes("-h") || tail.includes("--help")) return usage;
@@ -50,10 +50,10 @@ export async function manageSkills(
50
50
  return dim(`(no skills) install one with ${env.cmd} add <source>, or put it in ${display(env.cwd, path.join(env.home, "skills"))}/<name>/SKILL.md or .jade/skills/<name>/SKILL.md\nthe skill tool itself takes ≈${toolTokens} tokens in every request`);
51
51
  }
52
52
  const total = toolTokens + estimateTokens(skillsPrompt(skills)!);
53
- return [
54
- ...skills.map((sk) => `${bold(sk.name)} ${dim(`${sk.layer} · ${display(env.cwd, sk.dir)} · ≈${estimateTokens(skillLine(sk))} tokens`)}\n ${clip(sk.description.replace(/\s+/g, " "), 300)}`),
53
+ return joinLines([
54
+ ...skills.map((sk): Text => [bold(sk.name), " ", dim(`${sk.layer} · ${display(env.cwd, sk.dir)} · ≈${estimateTokens(skillLine(sk))} tokens`), `\n ${clip(sk.description.replace(/\s+/g, " "), 300)}`]),
55
55
  dim(`≈${total} tokens in every request (the skill list and the skill tool); a skill's instructions are read only when it is used`),
56
- ].join("\n");
56
+ ]);
57
57
  }
58
58
  const positionals: string[] = [];
59
59
  let project = false;
@@ -124,19 +124,20 @@ export default definePlugin({
124
124
  try {
125
125
  argv = splitArgs(args);
126
126
  } catch (e) {
127
- return red(errorText(e));
127
+ return error(errorText(e));
128
128
  }
129
129
  try {
130
130
  return await manageSkills(argv, { home: ctx.home, cwd: ctx.cwd, cmd: "/skills", sources, log: (t) => cctx.print(dim(t)), ...(latest ? { skills: latest } : {}) });
131
131
  } catch (e) {
132
- return red(errorText(e));
132
+ return error(errorText(e));
133
133
  }
134
134
  },
135
135
  });
136
136
  // 同样的事也能在终端里做:jade skills add <source> [--project](cli@1,核心提供)
137
137
  ctx.service<Cli>("cli@1")?.register({
138
138
  name: "skills",
139
- run: (argv, cli) => manageSkills(argv, { home: ctx.home, cwd: ctx.cwd, cmd: "jade skills", sources, log: cli.log }),
139
+ // 终端里的命令输出到 stdout,常常被管道接走:只要文字
140
+ run: async (argv, cli) => plain(await manageSkills(argv, { home: ctx.home, cwd: ctx.cwd, cmd: "jade skills", sources, log: cli.log })),
140
141
  });
141
142
  },
142
143
 
@@ -154,17 +155,11 @@ export default definePlugin({
154
155
  /** 这个会话注册过的 /<skill> 命令 */
155
156
  const mine = new Set<string>();
156
157
 
157
- /** 用新找到的 skill 更新提示词里的列表、可读目录和 /<skill> 命令;没变时什么也不做(不让提示缓存失效) */
158
- const apply = (skills: Skill[], warnings: string[]) => {
159
- for (const w of warnings) {
160
- if (warned.has(w)) continue;
161
- warned.add(w);
162
- ui?.notify(`${ID}: ${w}`, "warning");
163
- }
164
- current = skills;
165
- latest = skills;
158
+ const child = ctx.session.parent !== undefined;
159
+ /** 更新提示词里的列表和可读目录;没变时什么也不做(不让提示缓存失效),返回 false */
160
+ const applyPrompt = (skills: Skill[]): boolean => {
166
161
  const key = JSON.stringify(skills.map((s) => [s.name, s.description, s.dir, s.layer]));
167
- if (key === shown) return;
162
+ if (key === shown) return false;
168
163
  shown = key;
169
164
 
170
165
  // 有随仓库分发的 skill 时整段不可信
@@ -175,6 +170,20 @@ export default definePlugin({
175
170
  const dirs = new Set(skills.map((s) => s.dir));
176
171
  for (const [dir, revoke] of readable) if (!dirs.has(dir)) (revoke(), readable.delete(dir));
177
172
  for (const dir of dirs) if (!readable.has(dir) && approval) readable.set(dir, approval.allowRead(dir));
173
+ return true;
174
+ };
175
+ /** 用新找到的 skill 更新提示词里的列表、可读目录和 /<skill> 命令;没变时什么也不做(不让提示缓存失效) */
176
+ const apply = (skills: Skill[], warnings: string[]) => {
177
+ for (const w of warnings) {
178
+ if (warned.has(w)) continue;
179
+ warned.add(w);
180
+ ui?.notify(`${ID}: ${w}`, "warning");
181
+ }
182
+ current = skills;
183
+ // 子会话(子 Agent)的 skill 和用户的会话一样,/skills、/<skill> 命令归用户的会话管:子会话关闭时不能把它们带走
184
+ if (child) return applyPrompt(skills);
185
+ latest = skills;
186
+ if (!applyPrompt(skills)) return;
178
187
 
179
188
  // skill 也可以当命令用:/<skill 名> [要做的事]。
180
189
  // 新会话在旧会话关闭之前打开:旧会话注册的同名命令先撤销,换成这个会话的。
@@ -1,5 +1,6 @@
1
1
  // 仓库目录、显示用的小工具、斜杠命令参数的切分、token 估算。插件之间不共享代码(只能共享类型),jade/mcp、jade/checks 各有一份。
2
2
 
3
+ import type { Span, Text, TextStyle } from "@uncarved/jade-api";
3
4
  import { existsSync, realpathSync } from "node:fs";
4
5
  import path from "node:path";
5
6
 
@@ -41,13 +42,17 @@ export function display(cwd: string, full: string): string {
41
42
 
42
43
  export const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
43
44
 
44
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色,见 https://no-color.org
45
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
46
- const paint = (open: string, close: string) => (s: string) =>
47
- colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
48
- export const dim = paint("2", "22");
49
- export const red = paint("31", "39");
50
- export const bold = paint("1", "22");
45
+ // 带语义样式的文字(jade-api 的 Text):插件只说这段是次要的、成功、警告……,怎么画由前端决定
46
+ const styled = (style: TextStyle) => (text: string): Span => ({ text, style });
47
+ export const dim = styled("dim");
48
+ export const bold = styled("bold");
49
+ export const ok = styled("ok");
50
+ export const warn = styled("warn");
51
+ export const error = styled("error");
52
+ /** 几行接成一段,行之间换行 */
53
+ export const lines = (rows: readonly Text[]): Text => rows.flatMap((r, i) => (i ? ["\n", r] : [r]));
54
+ /** 只取文字(输出到 stdout 的终端命令用) */
55
+ export const plain = (t: Text): string => (typeof t === "string" ? t : Array.isArray(t) ? (t as readonly Text[]).map(plain).join("") : (t as Span).text);
51
56
 
52
57
  /** 斜杠命令的参数按空白切开;"…" 或 '…' 里的空白不切(不处理反斜杠,Windows 路径照写) */
53
58
  export function splitArgs(text: string): string[] {
@@ -7,7 +7,7 @@
7
7
  // 当作普通消息发出去。
8
8
 
9
9
  import type { Block, Message } from "uncarved";
10
- import { definePlugin } from "@uncarved/jade-api";
10
+ import { definePlugin, type Span } from "@uncarved/jade-api";
11
11
  import type { Renderers, Steer } from "@uncarved/jade-api/services";
12
12
 
13
13
  const ID = "jade/steer";
@@ -39,8 +39,9 @@ function changed(): void {
39
39
  }
40
40
  }
41
41
 
42
- const bold = (s: string) => `\x1b[1m${s}\x1b[22m`;
43
- const dim = (s: string) => `\x1b[2m${s}\x1b[22m`;
42
+ // 带语义样式的文字(jade-api 的 Text):怎么画由前端决定
43
+ const bold = (text: string): Span => ({ text, style: "bold" });
44
+ const dim = (text: string): Span => ({ text, style: "dim" });
44
45
 
45
46
  export default definePlugin({
46
47
  process(ctx) {
@@ -81,7 +82,7 @@ export default definePlugin({
81
82
  render(data) {
82
83
  const text = (data as { text?: unknown } | null)?.text;
83
84
  if (typeof text !== "string") return undefined;
84
- return { line: `\n${bold(`› ${text.replace(/\n/g, "\n ")}`)} ${dim("(sent while working)")}` };
85
+ return { line: ["\n", bold(`› ${text.replace(/\n/g, "\n ")}`), " ", dim("(sent while working)")] };
85
86
  },
86
87
  });
87
88
  },
@@ -1,59 +1,22 @@
1
- // jade/task:task 工具,把调研交给只读的子 Agent(见 subagent.ts)。
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 是核心开的子会话(ctx.session.spawn):工具就是会话里的工具,默认只留只读的(加上只放行只读命令的 bash),
4
+ // 配置 write 为 true 时全部保留,写操作和主会话一样经过审批。子会话的日志存盘,父会话的工具结果带着它的引用。
5
5
 
6
- import type { Tool, Usage } from "uncarved";
7
- import { definePlugin, type UI } from "@uncarved/jade-api";
8
- import type { Approval, Models, Prompts, Renderers, Task } from "@uncarved/jade-api/services";
9
- import { taskTool, type ApproveSubagent, type TaskProgress } from "./subagent.ts";
10
- import { clip, dim, red } from "./style.ts";
6
+ import type { Usage } from "uncarved";
7
+ import { definePlugin, type SessionContext } from "@uncarved/jade-api";
8
+ import type { Approval, Models, Renderers } from "@uncarved/jade-api/services";
9
+ import { CHARS_PER_TOKEN, FALLBACK_WINDOW, fitToolResults, READ_ONLY_REASON, REPORT_TOOL_SHARE, stepsThisTurn, subagentPrompt, taskTool, WRAP_UP_AT, type Control, type TaskProgress } from "./subagent.ts";
10
+ import { clip, dim, error, lines as joinLines } 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
- /** 子 Agent 的审批一次问一个:并行的几个子 Agent 不同时弹对话框 */
35
- let asking: Promise<unknown> = Promise.resolve();
15
+ /** task 开的、还在跑的子会话 → 它的运行状态(子会话里本插件的 hook 用) */
16
+ const controls = new Map<string, Control>();
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
  // 运行中每个只有一行进度(标签、调用过几个工具、正在做什么),并行的几个靠标签分清;结束时把它调用过的工具放进结果的折叠内容里
@@ -87,11 +50,11 @@ export default definePlugin({
87
50
  // 没调用过工具时用默认的显示
88
51
  if (!sub.length) return undefined;
89
52
  const lines = text.split("\n");
90
- const shown = lines.slice(0, MAX_DETAIL_LINES).map((l) => (isError ? red(l) : l));
53
+ const shown = lines.slice(0, MAX_DETAIL_LINES).map((l) => (isError ? error(l) : l));
91
54
  if (lines.length > MAX_DETAIL_LINES) shown.push(dim(`… (${lines.length - MAX_DETAIL_LINES} more lines)`));
92
55
  return {
93
- line: isError ? red(clip(lines[0] ?? "", 200)) : dim(`${clip(lines[0] ?? "", 160)}${lines.length > 1 ? ` (+${lines.length - 1} lines)` : ""}`),
94
- details: [dim(`sub-agent ran ${sub.length} tool call${sub.length > 1 ? "s" : ""}:`), ...sub.map((l) => dim(` ${l}`)), ...shown].join("\n"),
56
+ line: isError ? error(clip(lines[0] ?? "", 200)) : dim(`${clip(lines[0] ?? "", 160)}${lines.length > 1 ? ` (+${lines.length - 1} lines)` : ""}`),
57
+ details: joinLines([dim(`sub-agent ran ${sub.length} tool call${sub.length > 1 ? "s" : ""}:`), ...sub.map((l) => dim(` ${l}`)), ...shown]),
95
58
  };
96
59
  },
97
60
  });
@@ -100,45 +63,42 @@ export default definePlugin({
100
63
 
101
64
  session(ctx) {
102
65
  const models = ctx.require<Models>("models@1");
103
- /** 跑完、还没记进日志的子 Agent 用量,按 task 调用的 toolUseId */
104
- const usage = new Map<string, Usage>();
105
66
  const configured = ctx.config.maxSteps;
106
67
  const maxSteps = typeof configured === "number" && Number.isInteger(configured) && configured > 0 ? configured : DEFAULT_MAX_STEPS;
68
+ const write = ctx.config.write === true;
69
+ const window = () => models.current()?.contextWindow ?? FALLBACK_WINDOW;
70
+
71
+ // 本插件在子会话里的那份:task 开的子会话的步数上限、写报告、只读的限制。别的插件开的子会话(controls 里没有)不管
72
+ if (ctx.session.parent) childHooks(ctx, () => controls.get(ctx.session.id), window);
73
+
74
+ // 层数到了上限的会话(默认子 Agent 不能再开子 Agent)不给 task 工具
75
+ if (!ctx.session.canSpawn) return;
76
+ /** 跑完、还没记进日志的子 Agent 用量,按 task 调用的 toolUseId */
77
+ const usage = new Map<string, Usage>();
107
78
  // 子 Agent 用的模型:/model 保存过的名字,或当前服务上的另一个模型;不设时用会话的模型
108
79
  const model = typeof ctx.config.model === "string" && ctx.config.model ? ctx.config.model : undefined;
109
- const approve: ApproveSubagent = (call, signal) => {
110
- const ui = ctx.service<UI>("ui@1");
111
- if (!ui?.interactive) return Promise.resolve({ approved: false, reason: "Nobody can approve this action for a sub-agent. Report what you need instead." });
112
- const ask = asking.then(async () => {
113
- const choice = await ui.select(
114
- {
115
- title: `A sub-agent wants to ${call.why}. Allow it?`,
116
- detail: `${call.name} ${clip(JSON.stringify(call.input), 2000)}`,
117
- options: [
118
- { label: "Yes", value: "yes" },
119
- { label: "No", value: "no" },
120
- ],
121
- },
122
- signal,
123
- );
124
- return choice === "yes" ? { approved: true } : { approved: false, reason: "The user denied this action." };
125
- });
126
- asking = ask.catch(() => {});
127
- return ask;
128
- };
80
+ const provider = model ? { id: ctx.plugin, complete: (req: Parameters<Models["complete"]>[0], o: Parameters<Models["complete"]>[1]) => models.complete(req, { ...o, model }) } : undefined;
81
+ const system = subagentPrompt(maxSteps, write);
129
82
  ctx.kernel.tool(
130
83
  taskTool({
131
- cwd: ctx.cwd,
132
- provider: { id: ctx.plugin, complete: (req, o) => models.complete(req, model ? { ...o, model } : o) },
133
- tools: available,
134
84
  maxSteps,
135
- approve,
136
- allowed: (call) => ctx.service<Approval>("approval@1")?.allows(ctx.session.id, call) ?? false,
137
- // 用到的时候再取:prompts@1 的提供者在自己的 session() 里才读指令文件,可能排在本插件后面
138
- ...(ctx.config.instructions === false ? {} : { instructions: () => ctx.service<Prompts>("prompts@1")?.instructions?.(ctx.session.id) ?? [] }),
139
- id: ctx.plugin,
85
+ write,
86
+ spawn: (parent, description, signal) =>
87
+ ctx.session.spawn({
88
+ parent,
89
+ signal,
90
+ label: description,
91
+ system,
92
+ ...(provider ? { provider } : {}),
93
+ // 只读时:只读的工具,加上 bash 这类按命令判断的(只放行审批规则认定为只读的命令,见 childHooks)。
94
+ // 子 Agent 不能问用户问题(ask_user):它的过程用户看不到,问了也没有上下文
95
+ tools: (t) => t.name !== "ask_user" && (write || t.effect === "read" || t.meta?.shell !== undefined),
96
+ }),
97
+ register: (child, control) => {
98
+ controls.set(child, control);
99
+ return () => void controls.delete(child);
100
+ },
140
101
  usage: (toolUseId, u) => void usage.set(toolUseId, u),
141
- contextWindow: () => models.current()?.contextWindow,
142
102
  }),
143
103
  );
144
104
  // 子 Agent 的用量记成本插件的事件(和压缩、审查的用量一样),界面据此计入会话用量;只能在 hook 里记
@@ -157,3 +117,43 @@ export default definePlugin({
157
117
  ctx.kernel.hook({ kind: "observe", point: "event", fn: (e) => void (e.type === "turn.ended" && usage.clear()) });
158
118
  },
159
119
  });
120
+
121
+ /** task 开的子会话里,本插件加的 hook。control 在子会话开好之后才登记,hook 执行时再取 */
122
+ function childHooks(ctx: SessionContext, control: () => Control | undefined, window: () => number): void {
123
+ // 步数上限;wrapUp 时只再要一次回复(报告)。历史接近上下文窗口时也停下,之后要报告
124
+ ctx.kernel.hook({
125
+ kind: "gate",
126
+ point: "turn.continue",
127
+ fn: (s) => {
128
+ const c = control();
129
+ if (!c) return { decision: "abstain" };
130
+ return stepsThisTurn(s) >= (c.wrapUp ? 1 : c.maxSteps) || (c.lastTokens ?? 0) >= window() * WRAP_UP_AT ? { decision: "deny" } : { decision: "abstain" };
131
+ },
132
+ });
133
+ // 要报告时工具输出可能已经很多(上面停下时、或者已经超出窗口):只放进最近的一部分
134
+ ctx.kernel.hook({
135
+ kind: "transform",
136
+ point: "context.project",
137
+ fn: (messages) => (control()?.wrapUp ? fitToolResults(messages, window() * REPORT_TOOL_SHARE * CHARS_PER_TOKEN, ctx.plugin) : messages),
138
+ });
139
+ // 只读的子 Agent:不是只读的工具(bash)只放行主会话的审批规则认定为只读的调用(git log、ls、rg……),其余的不问用户,直接拒绝
140
+ ctx.kernel.hook({
141
+ kind: "gate",
142
+ point: "tool.gate",
143
+ fn: (call) => {
144
+ const c = control();
145
+ if (!c || c.write || call.tool.effect === "read") return { decision: "abstain" };
146
+ if (ctx.service<Approval>("approval@1")?.allows(ctx.session.id, call)) return { decision: "abstain" };
147
+ return { decision: "deny", reason: READ_ONLY_REASON(call.name) };
148
+ },
149
+ });
150
+ // instructions: false:不给子 Agent 指令文件(jade/prompts 放进来的、带来源的那几段)
151
+ if (ctx.config.instructions === false) {
152
+ ctx.kernel.hook({
153
+ kind: "transform",
154
+ point: "context.build",
155
+ order: 100,
156
+ fn: (req) => (control() ? { ...req, system: req.system.filter((seg) => !(seg.origin.by === "plugin" && seg.origin.id === "jade/prompts" && seg.origin.source)) } : req),
157
+ });
158
+ }
159
+ }
@@ -1,9 +1,8 @@
1
1
  {
2
2
  "id": "jade/task",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "provides": ["task@1"],
7
6
  "requires": ["models@1"],
8
7
  "optional": ["ui@1", "renderers@1", "approval@1", "prompts@1"],
9
8
  "config": {
@@ -17,6 +16,10 @@
17
16
  },
18
17
  "model": {
19
18
  "description": "the model sub-agents use: a model saved by /model, or another model of the current service (for example a cheaper, faster one); default: the session's model"
19
+ },
20
+ "write": {
21
+ "default": false,
22
+ "description": "let sub-agents use every tool of the session, including ones that change files; their changes go through the same approval as the main agent's"
20
23
  }
21
24
  }
22
25
  }
@@ -1,17 +1,16 @@
1
- // 显示用的小工具:截断和 ANSI 颜色。插件之间不共享代码(只能共享类型),所以这里也有一份(同 jade/fs 的 style.ts)。
1
+ // 显示用的小工具:截断,和带语义样式的文字(jade-api 的 Text)。插件只说这段是次要的、成功、警告……,
2
+ // 怎么画由前端决定(终端界面画成颜色,-p 只取文字)。插件之间不共享代码(只能共享类型),所以每个插件有一份。
3
+
4
+ import type { Span, Text, TextStyle } from "@uncarved/jade-api";
2
5
 
3
6
  export const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
4
7
 
5
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色,见 https://no-color.org
6
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
7
- /**
8
- * 每种样式用自己的关闭码,不用 \x1b[0m 全部重置:外面套着别的样式时,后面的文字仍保持外层样式。
9
- * 里面出现同一个关闭码(例如 dim 里套 bold,两者都用 22 关闭)时紧接着重新打开外层的样式
10
- */
11
- const paint = (open: string, close: string) => (s: string) =>
12
- colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
13
- export const dim = paint("2", "22");
14
- export const red = paint("31", "39");
15
- export const green = paint("32", "39");
16
- export const yellow = paint("33", "39");
17
- export const bold = paint("1", "22");
8
+ const styled = (style: TextStyle) => (text: string): Span => ({ text, style });
9
+ export const dim = styled("dim");
10
+ export const bold = styled("bold");
11
+ export const ok = styled("ok");
12
+ export const warn = styled("warn");
13
+ export const error = styled("error");
14
+
15
+ /** 几行接成一段,行之间换行 */
16
+ export const lines = (rows: readonly Text[]): Text => rows.flatMap((r, i) => (i ? ["\n", r] : [r]));