@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
package/plugins/fs/fs.ts CHANGED
@@ -10,6 +10,7 @@ import type { Stats } from "node:fs";
10
10
  import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
11
11
  import path from "node:path";
12
12
  import type { Block, Message, Tool } from "uncarved";
13
+ import type { ToolMeta } from "@uncarved/jade-api";
13
14
  import { grepTool } from "./grep.ts";
14
15
  import { globMatcher, run } from "./sys.ts";
15
16
 
@@ -94,7 +95,7 @@ export class SeenFiles {
94
95
  }
95
96
  }
96
97
 
97
- export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
98
+ export function fsTools(cwd: string, opts: FsOptions = {}): (Tool & { meta?: ToolMeta })[] {
98
99
  const at = (p: unknown) => resolveIn(cwd, p as string);
99
100
  const tracked = opts.seen ?? new SeenFiles();
100
101
  const seen = tracked.files;
@@ -201,8 +202,9 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
201
202
  },
202
203
  };
203
204
 
204
- const writeFileTool: Tool = {
205
+ const writeFileTool: Tool & { meta: ToolMeta } = {
205
206
  name: "write_file",
207
+ meta: { writes: "path" },
206
208
  description:
207
209
  "Create a file or overwrite it with the complete new content. Missing parent directories are created. " +
208
210
  "An existing file must have been read with read_file first. Prefer edit_file for changing part of an existing file.",
@@ -262,8 +264,9 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
262
264
  return { content: `Edited ${shown} (${total} replacement${total === 1 ? "" : "s"})` };
263
265
  };
264
266
 
265
- const editFileTool: Tool = {
267
+ const editFileTool: Tool & { meta: ToolMeta } = {
266
268
  name: "edit_file",
269
+ meta: { writes: "path" },
267
270
  description:
268
271
  "Replace exact text in a file. old_string must match the file exactly (including whitespace and indentation) " +
269
272
  "and must be unique unless replace_all is true. The file must have been read with read_file first, " +
@@ -284,8 +287,9 @@ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
284
287
  },
285
288
  };
286
289
 
287
- const multiEditTool: Tool = {
290
+ const multiEditTool: Tool & { meta: ToolMeta } = {
288
291
  name: "multi_edit",
292
+ meta: { writes: "path" },
289
293
  description:
290
294
  "Make several exact-text replacements in one file at once. The edits are applied in order, each to the result of the previous one, " +
291
295
  "with the same rules as edit_file. Either all edits succeed or the file is left unchanged.",
@@ -64,7 +64,8 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
64
64
  `optionally only files matching the glob include (e.g. "*.ts" matches at any depth; "src/**/*.ts" limits it to src). Skips files ignored by git, binary files and .git/node_modules. ` +
65
65
  `output_mode: "content" (default) returns "file:line:text" for matches and "file-line-text" for context lines, at most ${MAX_MATCHES} matches; ` +
66
66
  `"files" returns only the paths of matching files; "count" returns "file:count". ` +
67
- `context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode.`,
67
+ `context (0-${MAX_CONTEXT}) adds that many lines before and after each match in content mode. ` +
68
+ "head_limit keeps only the first that many lines of the output.",
68
69
  inputSchema: {
69
70
  type: "object",
70
71
  properties: {
@@ -75,6 +76,10 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
75
76
  // files_with_matches 是 ripgrep / Claude Code 的叫法,很多模型会这样传,当作 files
76
77
  output_mode: { type: "string", enum: ["content", "files", "count", "files_with_matches"] },
77
78
  context: { type: "integer" },
79
+ // head_limit、glob 也是 ripgrep / Claude Code 的叫法;不接受的话模型要多花一轮去掉它们重发。
80
+ // 有的模型把数字写成字符串("30"),也接受
81
+ head_limit: { type: ["integer", "string"] },
82
+ glob: { type: "string" },
78
83
  },
79
84
  required: ["pattern"],
80
85
  additionalProperties: false,
@@ -83,10 +88,12 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
83
88
  concurrency: "safe",
84
89
  idempotent: true,
85
90
  async execute(input, { signal }) {
86
- const { pattern, path: p = ".", include, ignore_case = false, output_mode = "content", context = 0 } = input as {
91
+ const { pattern, path: p = ".", glob, include = glob, ignore_case = false, output_mode = "content", context = 0, head_limit } = input as {
87
92
  pattern: string;
88
93
  path?: string;
89
94
  include?: string;
95
+ glob?: string;
96
+ head_limit?: number | string;
90
97
  ignore_case?: boolean;
91
98
  output_mode?: Mode | "files_with_matches";
92
99
  context?: number;
@@ -115,7 +122,10 @@ export function grepTool(cwd: string, opts: GrepOptions = {}): Tool {
115
122
  else found = result;
116
123
  }
117
124
  found ??= await jsGrep(search);
118
- return { content: format(cwd, found, search) };
125
+ const lines = format(cwd, found, search).split("\n");
126
+ const limit = Number(head_limit);
127
+ if (limit > 0 && lines.length > limit) lines.splice(limit, Infinity, `(showing the first ${limit} of ${lines.length} lines)`);
128
+ return { content: lines.join("\n") };
119
129
  },
120
130
  };
121
131
  }
@@ -163,9 +173,23 @@ const enough = (s: Search, files: FileHits[], matches: number) =>
163
173
 
164
174
  // ---------- ripgrep ----------
165
175
 
166
- /** ripgrep 不存在时返回 "missing";正则语法 ripgrep 不支持时返回 undefined,由调用方改用 JS 搜索 */
176
+ /**
177
+ * ripgrep 不存在时返回 "missing";正则语法 ripgrep 不支持时返回 undefined,由调用方改用 JS 搜索。
178
+ * 先不用 --sort path:它让 ripgrep 只用一个线程(几万个文件的仓库慢好几倍),文件的先后在收完之后自己排。
179
+ * 结果多到提前停下时,先搜到的是哪些文件每次不同:按路径顺序再搜一次,同样的调用总是留下路径最靠前的那些。
180
+ * 这时命中很密,按顺序搜很快就够数了
181
+ */
167
182
  async function ripgrep(rg: string, s: Search): Promise<Found | undefined | "missing"> {
168
- const args = ["--json", "--sort", "path", "--hidden", "--glob", "!.git", "--glob", "!node_modules", "--max-filesize", `${MAX_FILE_BYTES}`];
183
+ const first = await ripgrepOnce(rg, s, false);
184
+ return typeof first === "object" && first.truncated ? ripgrepOnce(rg, s, true) : first;
185
+ }
186
+
187
+ async function ripgrepOnce(rg: string, s: Search, sorted: boolean): Promise<Found | undefined | "missing"> {
188
+ const args = [...(sorted ? ["--sort", "path"] : []), "--hidden", "--glob", "!.git", "--glob", "!node_modules", "--max-filesize", `${MAX_FILE_BYTES}`];
189
+ // files、count 模式用不到每一行的内容:让 ripgrep 只报文件名(和行数),不用逐条解析 JSON
190
+ if (s.mode === "content") args.push("--json");
191
+ else if (s.mode === "files") args.push("--files-with-matches", "--null");
192
+ else args.push("--count", "--with-filename", "--null");
169
193
  if (s.ignoreCase) args.push("--ignore-case");
170
194
  if (s.context > 0) args.push("--context", String(s.context));
171
195
  if (s.include) args.push("--glob", s.include);
@@ -204,15 +228,32 @@ async function ripgrep(rg: string, s: Search): Promise<Found | undefined | "miss
204
228
  hits.count++;
205
229
  matches++;
206
230
  }
207
- if (s.mode === "content") hits.lines.push({ n: ev.data.line_number, text: text.replace(/\r?\n$/, ""), match });
231
+ hits.lines.push({ n: ev.data.line_number, text: text.replace(/\r?\n$/, ""), match });
232
+ };
233
+ /** files、count 模式的一个文件;不是合法 UTF-8 的路径跳过(同上) */
234
+ const add = (file: string, count: number) => {
235
+ if (!file.includes("�")) files.push({ file: path.resolve(file), count, lines: [] });
236
+ };
237
+ /** 取走 buf 里已经完整的记录。content:一行一个 JSON;files:路径后面一个 NUL;count:路径、NUL、行数、换行 */
238
+ const drain = () => {
239
+ for (;;) {
240
+ const end = buf.indexOf(s.mode === "content" ? "\n" : "\0");
241
+ if (end < 0) return;
242
+ let next = end + 1;
243
+ if (s.mode === "content") handle(buf.slice(0, end));
244
+ else if (s.mode === "files") add(buf.slice(0, end), 1);
245
+ else {
246
+ const nl = buf.indexOf("\n", end);
247
+ if (nl < 0) return;
248
+ add(buf.slice(0, end), Number(buf.slice(end + 1, nl)));
249
+ next = nl + 1;
250
+ }
251
+ buf = buf.slice(next);
252
+ }
208
253
  };
209
254
  for await (const chunk of proc.stdout) {
210
255
  buf += decoder.decode(chunk, { stream: true });
211
- let nl: number;
212
- while ((nl = buf.indexOf("\n")) >= 0) {
213
- handle(buf.slice(0, nl));
214
- buf = buf.slice(nl + 1);
215
- }
256
+ drain();
216
257
  // count 模式要数完每个文件,只有文件数超了才停
217
258
  if (enough(s, files, matches)) {
218
259
  stopped = true;
@@ -220,11 +261,13 @@ async function ripgrep(rg: string, s: Search): Promise<Found | undefined | "miss
220
261
  break;
221
262
  }
222
263
  }
223
- if (!stopped) handle(buf);
264
+ if (!stopped && s.mode === "content") handle(buf);
224
265
  const [code, err] = await Promise.all([proc.exited, stderr]);
225
266
  s.signal.throwIfAborted();
226
267
  // 1:没有命中;2:出错,但部分文件出错(例如没有权限)时其余结果仍然有效
227
268
  if (!stopped && code === 2 && /regex parse error|error parsing regex|look-?around|backreference/i.test(err)) return undefined;
269
+ // 和 JS 搜索一样按路径排
270
+ files.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));
228
271
  return { files, truncated: stopped };
229
272
  } finally {
230
273
  s.signal.removeEventListener("abort", kill);
@@ -1,7 +1,7 @@
1
1
  // jade/fs:文件工具 read_file、write_file、edit_file、multi_edit、list_dir、glob、grep。
2
2
 
3
3
  import { definePlugin } from "@uncarved/jade-api";
4
- import type { Renderers, Task } from "@uncarved/jade-api/services";
4
+ import type { Renderers } from "@uncarved/jade-api/services";
5
5
  import { fsTools, SeenFiles } from "./fs.ts";
6
6
  import { fsRenderers } from "./renderers.ts";
7
7
 
@@ -25,12 +25,7 @@ export default definePlugin({
25
25
  seen.prune(request.messages);
26
26
  },
27
27
  });
28
+ // 子 Agent 是核心开的子会话,本插件在里面另有一份(读过的文件各算各的),不用再经 tools@1 另登记
28
29
  for (const tool of fsTools(ctx.cwd, { responses, seen })) ctx.kernel.tool(tool);
29
- // 子 Agent(jade/task)的只读工具:另一套实例,子 Agent 读过的文件不算主会话读过
30
- // jade/task 被隔离时它的服务已失效:子 Agent 没有文件工具,文件工具本身照常
31
- try {
32
- const task = ctx.service<Task>("task@1");
33
- if (task) for (const tool of fsTools(ctx.cwd)) if (tool.effect === "read") task.tool(tool);
34
- } catch {}
35
30
  },
36
31
  });
@@ -3,5 +3,5 @@
3
3
  "version": "0.2.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "optional": ["renderers@1", "task@1"]
6
+ "optional": ["renderers@1"]
7
7
  }
@@ -6,10 +6,11 @@
6
6
  import { readFileSync } from "node:fs";
7
7
  import { readFile } from "node:fs/promises";
8
8
  import path from "node:path";
9
+ import type { Span, Text } from "@uncarved/jade-api";
9
10
  import type { ToolRenderer } from "@uncarved/jade-api/services";
10
11
  import { diffLines, diffStats, renderDiff } from "./diff.ts";
11
12
  import { applyEditsToText, display, type Edit } from "./fs.ts";
12
- import { clip, dim, green, red, yellow } from "./style.ts";
13
+ import { added, clip, dim, lines as joinLines, removed, warn } from "./style.ts";
13
14
 
14
15
  type Args = Record<string, unknown>;
15
16
  const args = (input: unknown) => (input !== null && typeof input === "object" ? input : {}) as Args;
@@ -21,18 +22,18 @@ function pathOf(cwd: string, i: Args): string {
21
22
  }
22
23
 
23
24
  /** 预览里的多行文字:每行前面加上标记,最多 max 行 */
24
- function marked(s: string, mark: string, color: (s: string) => string, max = 30): string {
25
+ function marked(s: string, mark: string, color: (s: string) => Span, max = 30): Text {
25
26
  const all = s.split("\n");
26
27
  const shown = all.slice(0, max).map((l) => color(`${mark} ${l}`));
27
28
  if (all.length > max) shown.push(dim(` … ${all.length - max} more lines`));
28
- return shown.join("\n");
29
+ return joinLines(shown);
29
30
  }
30
31
 
31
32
  /** 折叠内容里的多行文字(缩进由前端加),最多 max 行 */
32
- function capped(lines: string[], color: (s: string) => string, max: number): string {
33
- const shown = lines.slice(0, max).map(color);
33
+ function capped(lines: string[], max: number): Text {
34
+ const shown: Text[] = lines.slice(0, max);
34
35
  if (lines.length > max) shown.push(dim(`… ${lines.length - max} more lines`));
35
- return shown.join("\n");
36
+ return joinLines(shown);
36
37
  }
37
38
 
38
39
  type FileTool = "edit_file" | "multi_edit" | "write_file";
@@ -42,29 +43,29 @@ const editsOf = (tool: FileTool, i: Args) => (tool === "edit_file" ? [i] : Array
42
43
  * 审批时的预览:带行号和上下文的 diff(读出文件、按工具的规则算出修改后的内容)。
43
44
  * 文件读不了、替换不成立时退回到只显示参数里的新旧文本
44
45
  */
45
- async function filePreview(cwd: string, tool: FileTool, input: unknown): Promise<string> {
46
+ async function filePreview(cwd: string, tool: FileTool, input: unknown): Promise<Text> {
46
47
  const i = args(input);
47
48
  const file = typeof i.path === "string" ? path.resolve(cwd, i.path) : undefined;
48
49
  const current = file ? await readFile(file, "utf8").catch(() => undefined) : undefined;
49
50
  if (tool === "write_file") {
50
51
  const content = String(i.content ?? "");
51
- if (current !== undefined) return `${dim(" overwrites the existing file:")}\n${renderDiff(current, content)}`;
52
- return marked(content, "+", green, 20);
52
+ if (current !== undefined) return [dim(" overwrites the existing file:"), "\n", renderDiff(current, content)];
53
+ return marked(content, "+", added, 20);
53
54
  }
54
55
  if (tool === "multi_edit" && !Array.isArray(i.edits)) return dim(clip(JSON.stringify(input, null, 2), 2000));
55
56
  const edits = editsOf(tool, i);
56
- const raw = (e: Args) => `${marked(String(e.old_string ?? ""), "-", red)}\n${marked(String(e.new_string ?? ""), "+", green)}`;
57
- const fallback = () => edits.map((e) => raw(e as unknown as Args)).join(dim("\n ⋯\n"));
57
+ const raw = (e: Args): Text => [marked(String(e.old_string ?? ""), "-", removed), "\n", marked(String(e.new_string ?? ""), "+", added)];
58
+ const fallback = (): Text => edits.map((e) => raw(e as unknown as Args)).flatMap((t, k) => (k ? [dim("\n ⋯\n"), t] : [t]));
58
59
  if (current === undefined) return fallback();
59
60
  const r = applyEditsToText(current, edits, display(cwd, file!));
60
- if (typeof r === "string") return `${fallback()}\n${yellow(` (this edit will fail: ${clip(r, 200)})`)}`;
61
+ if (typeof r === "string") return [fallback(), "\n", warn(` (this edit will fail: ${clip(r, 200)})`)];
61
62
  return renderDiff(current, r.text);
62
63
  }
63
64
 
64
65
  interface FileDiff {
65
66
  added: number;
66
67
  removed: number;
67
- text: string;
68
+ text: Text;
68
69
  }
69
70
 
70
71
  /** 对话里折叠的 diff 最多显示这么多行 */
@@ -109,8 +110,8 @@ function fileRenderer(cwd: string, tool: FileTool, summary: (input: unknown) =>
109
110
  const diff = before as FileDiff | undefined;
110
111
  if (!diff || isError) return undefined;
111
112
  const [first = "", ...rest] = text.split("\n");
112
- const extra = rest.length ? [capped(rest, (s) => s, MAX_RESULT_LINES)] : [];
113
- return { line: dim(`${clip(first, 150)} `) + `${green(`+${diff.added}`)} ${red(`-${diff.removed}`)}`, details: [...extra, diff.text].join("\n") };
113
+ const extra = rest.length ? [capped(rest, MAX_RESULT_LINES)] : [];
114
+ return { line: [dim(`${clip(first, 150)} `), added(`+${diff.added}`), " ", removed(`-${diff.removed}`)], details: joinLines([...extra, diff.text]) };
114
115
  },
115
116
  };
116
117
  }
@@ -1,18 +1,19 @@
1
- // 显示用的小工具:截断和 ANSI 颜色。从旧 jade 的 ui/render.ts、ui/screen.ts 复制过来:
2
- // 插件之间不共享代码(只能共享类型),所以 shell 插件也有一份。
1
+ // 显示用的小工具:截断,和带语义样式的文字(jade-api 的 Text)。插件只说这段是次要的、成功、警告……,
2
+ // 怎么画由前端决定(终端界面画成颜色,-p 只取文字)。插件之间不共享代码(只能共享类型),所以每个插件有一份。
3
+
4
+ import type { Span, Text, TextStyle } from "@uncarved/jade-api";
3
5
 
4
6
  export const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
5
7
 
6
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色,见 https://no-color.org
7
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
8
- /**
9
- * 每种样式用自己的关闭码,不用 \x1b[0m 全部重置:外面套着别的样式时,后面的文字仍保持外层样式。
10
- * 里面出现同一个关闭码(例如 dim 里套 bold,两者都用 22 关闭)时紧接着重新打开外层的样式
11
- */
12
- const paint = (open: string, close: string) => (s: string) =>
13
- colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
14
- export const dim = paint("2", "22");
15
- export const red = paint("31", "39");
16
- export const green = paint("32", "39");
17
- export const yellow = paint("33", "39");
18
- 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
+ export const added = styled("added");
16
+ export const removed = styled("removed");
17
+
18
+ /** 几行接成一段,行之间换行 */
19
+ export const lines = (rows: readonly Text[]): Text => rows.flatMap((r, i) => (i ? ["\n", r] : [r]));
@@ -10,7 +10,7 @@
10
10
  //
11
11
  // - before:工具执行前(审批的关卡里)运行。退出码不是 0 时这次调用被拒绝,命令的输出作为理由告诉模型;是 0 时不表态。
12
12
  // - after:工具成功执行后运行。退出码不是 0 时把输出留给模型看(下一次请求时附上),不改工具的结果。
13
- // - turn:一轮结束后运行,结果不影响会话。
13
+ // - turn:一轮结束后运行,结果不影响会话。子 Agent 的轮次不触发。
14
14
  // tool 是工具名,不写或写 "*" 表示所有工具。命令经 shell@1 在工作目录里运行(和 bash 工具同一个 shell),环境变量:
15
15
  // JADE_TOOL(工具名)、JADE_TOOL_INPUT(参数的 JSON 文件的路径)、JADE_TOOL_PATH(参数里有 path 时)。
16
16
 
@@ -132,7 +132,8 @@ export default definePlugin({
132
132
  },
133
133
  });
134
134
  }
135
- if (hooks.some((h) => h.on === "turn")) {
135
+ // turn 是用户等着的那一轮结束了(例如弹通知):子会话(子 Agent)的轮次不算,before、after 照常
136
+ if (hooks.some((h) => h.on === "turn") && !ctx.session.parent) {
136
137
  ctx.kernel.hook({
137
138
  kind: "observe",
138
139
  point: "event",
@@ -20,8 +20,12 @@ export default definePlugin({
20
20
  const spec = String(key?.key ?? "").toLowerCase();
21
21
  if (!KEY_SPEC.test(spec)) throw new Error(`invalid key ${JSON.stringify(key?.key)}: use ctrl+<letter>, alt+<letter or digit> or shift+tab`);
22
22
  if (RESERVED_KEYS.has(spec)) throw new Error(`key ${spec} is reserved by the frontend`);
23
+ // 重名时先注册的留下,后来的跳过并报告(同 commands@1)
23
24
  const taken = registry.get(spec);
24
- if (taken) throw new Error(`key ${spec} is already registered by ${taken.plugin}`);
25
+ if (taken) {
26
+ ctx.report(`key ${spec} from ${caller.plugin} was skipped: ${taken.plugin} already registered it`);
27
+ return () => {};
28
+ }
25
29
  const entry = { key, plugin: caller.plugin };
26
30
  registry.set(spec, entry);
27
31
  const revoke = () => {