@uncarved/jade 0.3.1 → 0.4.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 (206) 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 +490 -29
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +36 -14
  14. package/plugins/approval/policy.ts +15 -10
  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 +42 -9
  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 +47 -12
  50. package/plugins/models/index.ts +27 -1
  51. package/plugins/models/provider.ts +24 -0
  52. package/plugins/models/saved.ts +1 -1
  53. package/plugins/modes/index.ts +13 -2
  54. package/plugins/print/index.ts +7 -4
  55. package/plugins/prompts/index.ts +0 -0
  56. package/plugins/renderers/index.ts +10 -5
  57. package/plugins/repeats/index.ts +8 -8
  58. package/plugins/schedule/index.ts +5 -1
  59. package/plugins/screenshot/browser.ts +10 -0
  60. package/plugins/sessions/index.ts +48 -2
  61. package/plugins/shell/index.ts +27 -28
  62. package/plugins/shell/plugin.json +1 -1
  63. package/plugins/shell/renderers.ts +9 -7
  64. package/plugins/shell/shell.ts +3 -1
  65. package/plugins/skills/index.ts +28 -19
  66. package/plugins/skills/project.ts +12 -7
  67. package/plugins/steer/index.ts +5 -4
  68. package/plugins/task/index.ts +80 -50
  69. package/plugins/task/plugin.json +6 -2
  70. package/plugins/task/style.ts +13 -14
  71. package/plugins/task/subagent.ts +67 -184
  72. package/plugins/todo/index.ts +39 -9
  73. package/plugins/tools/index.ts +9 -2
  74. package/plugins/tui/frontend.ts +139 -89
  75. package/plugins/tui/index.ts +2 -3
  76. package/plugins/tui/mentions.ts +11 -80
  77. package/plugins/tui/plugin.json +1 -1
  78. package/plugins/tui/screen.ts +55 -5
  79. package/plugins/tui/transcript.ts +17 -7
  80. package/plugins/tui/tui.ts +337 -101
  81. package/plugins/tui/vendor.ts +1 -1
  82. package/plugins/undo/checkpoint.ts +8 -4
  83. package/plugins/undo/index.ts +170 -31
  84. package/plugins/undo/plugin.json +1 -0
  85. package/plugins/undo/snapshot.ts +87 -14
  86. package/plugins/undo/style.ts +13 -14
  87. package/plugins/web/index.ts +7 -18
  88. package/plugins/web/plugin.json +1 -1
  89. package/plugins-dist/approval/index.js +363 -418
  90. package/plugins-dist/approval/policy.js +391 -508
  91. package/plugins-dist/approval/review.js +132 -158
  92. package/plugins-dist/approval/schema.js +50 -55
  93. package/plugins-dist/ask/index.js +115 -129
  94. package/plugins-dist/budget/index.js +27 -31
  95. package/plugins-dist/checks/checks.js +293 -329
  96. package/plugins-dist/checks/index.js +119 -139
  97. package/plugins-dist/checks/plugin.json +2 -1
  98. package/plugins-dist/checks/project.js +57 -65
  99. package/plugins-dist/commands/index.js +47 -29
  100. package/plugins-dist/compact/compact.js +233 -249
  101. package/plugins-dist/compact/index.js +98 -95
  102. package/plugins-dist/compact/style.js +9 -14
  103. package/plugins-dist/completions/index.js +30 -0
  104. package/plugins-dist/completions/plugin.json +9 -0
  105. package/plugins-dist/continue/index.js +40 -52
  106. package/plugins-dist/copy/index.js +40 -0
  107. package/plugins-dist/copy/plugin.json +9 -0
  108. package/plugins-dist/cost/index.js +98 -115
  109. package/plugins-dist/custom-commands/index.js +55 -72
  110. package/plugins-dist/editor/index.js +64 -72
  111. package/plugins-dist/fs/diff.js +111 -124
  112. package/plugins-dist/fs/fs.js +426 -469
  113. package/plugins-dist/fs/grep.js +262 -253
  114. package/plugins-dist/fs/index.js +20 -34
  115. package/plugins-dist/fs/plugin.json +1 -2
  116. package/plugins-dist/fs/renderers.js +100 -112
  117. package/plugins-dist/fs/style.js +11 -15
  118. package/plugins-dist/fs/sys.js +31 -43
  119. package/plugins-dist/hooks/index.js +107 -127
  120. package/plugins-dist/keys/index.js +27 -31
  121. package/plugins-dist/mcp/index.js +271 -199
  122. package/plugins-dist/mcp/install.js +123 -137
  123. package/plugins-dist/mcp/mcp.js +638 -577
  124. package/plugins-dist/mcp/plugin.json +3 -1
  125. package/plugins-dist/mcp/project.js +98 -115
  126. package/plugins-dist/memory/index.js +83 -88
  127. package/plugins-dist/memory/memory.js +111 -128
  128. package/plugins-dist/memory/style.js +9 -14
  129. package/plugins-dist/mentions/attach.js +91 -99
  130. package/plugins-dist/mentions/candidates.js +49 -0
  131. package/plugins-dist/mentions/index.js +71 -81
  132. package/plugins-dist/mentions/plugin.json +2 -1
  133. package/plugins-dist/mentions/style.js +9 -14
  134. package/plugins-dist/models/config.js +29 -43
  135. package/plugins-dist/models/configure.js +421 -474
  136. package/plugins-dist/models/context.js +14 -22
  137. package/plugins-dist/models/index.js +182 -189
  138. package/plugins-dist/models/provider.js +263 -307
  139. package/plugins-dist/models/saved.js +60 -72
  140. package/plugins-dist/modes/index.js +138 -165
  141. package/plugins-dist/plugins/index.js +34 -34
  142. package/plugins-dist/print/index.js +192 -175
  143. package/plugins-dist/prompts/index.js +86 -89
  144. package/plugins-dist/prompts/notes.js +31 -37
  145. package/plugins-dist/prompts/prompts.js +155 -193
  146. package/plugins-dist/prompts/results.js +40 -53
  147. package/plugins-dist/prompts/sys.js +39 -50
  148. package/plugins-dist/renderers/index.js +32 -32
  149. package/plugins-dist/repeats/index.js +131 -174
  150. package/plugins-dist/schedule/cron.js +49 -56
  151. package/plugins-dist/schedule/index.js +230 -247
  152. package/plugins-dist/schedule/store.js +93 -109
  153. package/plugins-dist/scratch/index.js +12 -18
  154. package/plugins-dist/screenshot/browser.js +136 -154
  155. package/plugins-dist/screenshot/index.js +37 -46
  156. package/plugins-dist/screenshot/sys.js +53 -65
  157. package/plugins-dist/screenshot/tool.js +98 -126
  158. package/plugins-dist/sessions/index.js +149 -117
  159. package/plugins-dist/shell/index.js +117 -135
  160. package/plugins-dist/shell/plugin.json +1 -1
  161. package/plugins-dist/shell/renderers.js +28 -33
  162. package/plugins-dist/shell/service.js +17 -23
  163. package/plugins-dist/shell/shell.js +307 -362
  164. package/plugins-dist/shell/sys.js +64 -79
  165. package/plugins-dist/skills/index.js +193 -211
  166. package/plugins-dist/skills/install.js +122 -149
  167. package/plugins-dist/skills/project.js +65 -73
  168. package/plugins-dist/skills/skills.js +135 -171
  169. package/plugins-dist/steer/index.js +108 -125
  170. package/plugins-dist/suggest/index.js +235 -259
  171. package/plugins-dist/task/index.js +130 -117
  172. package/plugins-dist/task/plugin.json +5 -2
  173. package/plugins-dist/task/style.js +9 -14
  174. package/plugins-dist/task/subagent.js +156 -279
  175. package/plugins-dist/todo/index.js +79 -63
  176. package/plugins-dist/tools/index.js +36 -42
  177. package/plugins-dist/tui/editor.js +145 -160
  178. package/plugins-dist/tui/frontend.js +639 -678
  179. package/plugins-dist/tui/history.js +34 -37
  180. package/plugins-dist/tui/index.js +16 -18
  181. package/plugins-dist/tui/markdown.js +203 -247
  182. package/plugins-dist/tui/mascot.js +266 -355
  183. package/plugins-dist/tui/mentions.js +67 -144
  184. package/plugins-dist/tui/plugin.json +1 -2
  185. package/plugins-dist/tui/render.js +35 -45
  186. package/plugins-dist/tui/screen.js +197 -180
  187. package/plugins-dist/tui/transcript.js +436 -468
  188. package/plugins-dist/tui/tui.js +1554 -1656
  189. package/plugins-dist/tui/vendor.js +1088 -1388
  190. package/plugins-dist/undo/checkpoint.js +97 -118
  191. package/plugins-dist/undo/index.js +281 -192
  192. package/plugins-dist/undo/plugin.json +3 -0
  193. package/plugins-dist/undo/snapshot.js +134 -99
  194. package/plugins-dist/undo/style.js +9 -14
  195. package/plugins-dist/update/index.js +26 -28
  196. package/plugins-dist/web/env.js +55 -68
  197. package/plugins-dist/web/index.js +80 -110
  198. package/plugins-dist/web/plugin.json +1 -2
  199. package/plugins-dist/web/renderers.js +4 -5
  200. package/plugins-dist/web/web.js +514 -593
  201. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  202. package/sdk/python/jade_plugin.py +9 -2
  203. package/src/api.ts +1 -1
  204. package/src/host.ts +39 -4
  205. package/src/remote.ts +6 -1
  206. package/src/session.ts +496 -36
@@ -4,12 +4,14 @@
4
4
  // 正是想要的;自己写 progress 反而只能把一次推送(可能是好几行、半行)显示成一行。
5
5
 
6
6
  import type { ToolRenderer } from "@uncarved/jade-api/services";
7
+ import type { Span, Text } from "@uncarved/jade-api";
7
8
 
8
9
  // 截断和颜色从旧 jade 的 ui/render.ts、ui/screen.ts 复制:插件之间不共享代码,fs 插件也有一份
9
10
  const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
10
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色,见 https://no-color.org
11
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
12
- const dim = (s: string) => (colors ? `\x1b[2m${s.replaceAll("\x1b[22m", "\x1b[22m\x1b[2m")}\x1b[22m` : s);
11
+ // 带语义样式的文字(jade-api 的 Text):怎么画由前端决定
12
+ const dim = (text: string): Span => ({ text, style: "dim" });
13
+ /** 几行接成一段,行之间换行 */
14
+ const joinLines = (rows: readonly Text[]): Text => rows.flatMap((r, i) => (i ? ["\n", r] : [r]));
13
15
 
14
16
  type Args = Record<string, unknown>;
15
17
  const args = (input: unknown) => (input !== null && typeof input === "object" ? input : {}) as Args;
@@ -19,11 +21,11 @@ const command = (input: unknown) => String(args(input).command ?? "");
19
21
  const MAX_SUMMARY = 120;
20
22
 
21
23
  /** 预览里的多行文字:每行前面加上标记,最多 max 行 */
22
- function marked(s: string, mark: string, max = 30): string {
24
+ function marked(s: string, mark: string, max = 30): Text {
23
25
  const all = s.split("\n");
24
- const shown = all.slice(0, max).map((l) => `${mark} ${l}`);
26
+ const shown: Text[] = all.slice(0, max).map((l) => `${mark} ${l}`);
25
27
  if (all.length > max) shown.push(dim(` … ${all.length - max} more lines`));
26
- return shown.join("\n");
28
+ return joinLines(shown);
27
29
  }
28
30
 
29
31
  export const shellRenderers: ToolRenderer[] = [
@@ -36,7 +38,7 @@ export const shellRenderers: ToolRenderer[] = [
36
38
  if (lines.length === 1 && lines[0]!.length <= MAX_SUMMARY) return undefined;
37
39
  const shown = lines.slice(0, 200).map((l, i) => dim(`${i === 0 ? "$" : " "} ${l}`));
38
40
  if (lines.length > 200) shown.push(dim(`… ${lines.length - 200} more lines`));
39
- return shown.join("\n");
41
+ return joinLines(shown);
40
42
  },
41
43
  preview: (input) => marked(command(input), "$"),
42
44
  },
@@ -6,6 +6,7 @@
6
6
  import { existsSync } from "node:fs";
7
7
  import path from "node:path";
8
8
  import type { Tool } from "uncarved";
9
+ import type { ToolMeta } from "@uncarved/jade-api";
9
10
  import { runSync, spawn as spawnProc, which, type Proc } from "./sys.ts";
10
11
  import type { RunCommand, RunResult } from "@uncarved/jade-api/services";
11
12
 
@@ -104,8 +105,9 @@ export function shellTools(opts: ShellOptions): ShellTools {
104
105
  await bg.proc.exited;
105
106
  };
106
107
 
107
- const bash: Tool = {
108
+ const bash: Tool & { meta: ToolMeta } = {
108
109
  name: "bash",
110
+ meta: { shell: "command" },
109
111
  description:
110
112
  `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` +
111
113
  `Each call starts a fresh shell: cd and environment variables do not persist. ` +
@@ -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,19 +1,19 @@
1
- // jade/task:task 工具,把调研交给只读的子 Agent(见 subagent.ts)。
1
+ // jade/task:task 工具,把一件事交给子 Agent(见 subagent.ts)。
2
2
  //
3
- // 子 Agent 用哪些工具:其他插件登记在 tools@1(jade/tools)里的那些(jade/fs 登记 read_file、list_dir、glob、grep),
4
- // 每次启动子 Agent 时取。主会话里的工具对象是各插件私有的,子 Agent 拿到的是登记者另给的一份。
3
+ // 子 Agent 是核心开的子会话(ctx.session.spawn):工具就是会话里的工具,默认只留只读的(加上只放行只读命令的 bash),
4
+ // 配置 write 为 true 时全部保留,写操作和主会话一样经过审批。子会话的日志存盘,父会话的工具结果带着它的引用。
5
5
 
6
6
  import type { Usage } from "uncarved";
7
- import { definePlugin, type UI } from "@uncarved/jade-api";
8
- import type { Approval, Models, Prompts, Renderers, Tools } from "@uncarved/jade-api/services";
9
- import { taskTool, type ApproveSubagent, type TaskProgress } from "./subagent.ts";
10
- import { clip, dim, red } from "./style.ts";
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
- /** 子 Agent 的审批一次问一个:并行的几个子 Agent 不同时弹对话框 */
16
- let asking: Promise<unknown> = Promise.resolve();
15
+ /** task 开的、还在跑的子会话 → 它的运行状态(子会话里本插件的 hook 用) */
16
+ const controls = new Map<string, Control>();
17
17
 
18
18
  export default definePlugin({
19
19
  process(ctx) {
@@ -50,11 +50,11 @@ export default definePlugin({
50
50
  // 没调用过工具时用默认的显示
51
51
  if (!sub.length) return undefined;
52
52
  const lines = text.split("\n");
53
- 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));
54
54
  if (lines.length > MAX_DETAIL_LINES) shown.push(dim(`… (${lines.length - MAX_DETAIL_LINES} more lines)`));
55
55
  return {
56
- line: isError ? red(clip(lines[0] ?? "", 200)) : dim(`${clip(lines[0] ?? "", 160)}${lines.length > 1 ? ` (+${lines.length - 1} lines)` : ""}`),
57
- 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]),
58
58
  };
59
59
  },
60
60
  });
@@ -63,52 +63,42 @@ export default definePlugin({
63
63
 
64
64
  session(ctx) {
65
65
  const models = ctx.require<Models>("models@1");
66
- /** 跑完、还没记进日志的子 Agent 用量,按 task 调用的 toolUseId */
67
- const usage = new Map<string, Usage>();
68
66
  const configured = ctx.config.maxSteps;
69
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>();
70
78
  // 子 Agent 用的模型:/model 保存过的名字,或当前服务上的另一个模型;不设时用会话的模型
71
79
  const model = typeof ctx.config.model === "string" && ctx.config.model ? ctx.config.model : undefined;
72
- const approve: ApproveSubagent = (call, signal) => {
73
- const ui = ctx.service<UI>("ui@1");
74
- if (!ui?.interactive) return Promise.resolve({ approved: false, reason: "Nobody can approve this action for a sub-agent. Report what you need instead." });
75
- const ask = asking.then(async () => {
76
- const choice = await ui.select(
77
- {
78
- title: `A sub-agent wants to ${call.why}. Allow it?`,
79
- detail: `${call.name} ${clip(JSON.stringify(call.input), 2000)}`,
80
- options: [
81
- { label: "Yes", value: "yes" },
82
- { label: "No", value: "no" },
83
- ],
84
- },
85
- signal,
86
- );
87
- return choice === "yes" ? { approved: true } : { approved: false, reason: "The user denied this action." };
88
- });
89
- asking = ask.catch(() => {});
90
- return ask;
91
- };
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);
92
82
  ctx.kernel.tool(
93
83
  taskTool({
94
- cwd: ctx.cwd,
95
- provider: { id: ctx.plugin, complete: (req, o) => models.complete(req, model ? { ...o, model } : o) },
96
- // 没有 jade/tools、或者它被隔离了(服务已失效,调用会抛错):子 Agent 没有工具
97
- tools: () => {
98
- try {
99
- return ctx.service<Tools>("tools@1")?.list() ?? [];
100
- } catch {
101
- return [];
102
- }
103
- },
104
84
  maxSteps,
105
- approve,
106
- allowed: (call) => ctx.service<Approval>("approval@1")?.allows(ctx.session.id, call) ?? false,
107
- // 用到的时候再取:prompts@1 的提供者在自己的 session() 里才读指令文件,可能排在本插件后面
108
- ...(ctx.config.instructions === false ? {} : { instructions: () => ctx.service<Prompts>("prompts@1")?.instructions?.(ctx.session.id) ?? [] }),
109
- 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
+ },
110
101
  usage: (toolUseId, u) => void usage.set(toolUseId, u),
111
- contextWindow: () => models.current()?.contextWindow,
112
102
  }),
113
103
  );
114
104
  // 子 Agent 的用量记成本插件的事件(和压缩、审查的用量一样),界面据此计入会话用量;只能在 hook 里记
@@ -127,3 +117,43 @@ export default definePlugin({
127
117
  ctx.kernel.hook({ kind: "observe", point: "event", fn: (e) => void (e.type === "turn.ended" && usage.clear()) });
128
118
  },
129
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,10 +1,10 @@
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
6
  "requires": ["models@1"],
7
- "optional": ["tools@1", "ui@1", "renderers@1", "approval@1", "prompts@1"],
7
+ "optional": ["ui@1", "renderers@1", "approval@1", "prompts@1"],
8
8
  "config": {
9
9
  "maxSteps": {
10
10
  "default": 40,
@@ -16,6 +16,10 @@
16
16
  },
17
17
  "model": {
18
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"
19
23
  }
20
24
  }
21
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]));