@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
@@ -11,7 +11,7 @@
11
11
  import { spawn, type ChildProcess } from "node:child_process";
12
12
  import { createHash } from "node:crypto";
13
13
  import { readFileSync, statSync } from "node:fs";
14
- import { readFile } from "node:fs/promises";
14
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
15
15
  import path from "node:path";
16
16
  import type { Block, Tool } from "uncarved";
17
17
  import { projectDirs } from "./project.ts";
@@ -193,6 +193,66 @@ export function mcpTrustHash(root: string, entry: McpServerEntry): string {
193
193
  return createHash("sha256").update(`jade-mcp\0${root}\0${entry.name}\0${spec}`).digest("hex");
194
194
  }
195
195
 
196
+ // ---------- 上次连上时的工具 ----------
197
+
198
+ /** 缓存里这么久没连上过的服务删掉(配置改了、服务删了,旧的那条就再也用不到了) */
199
+ const KNOWN_MAX_AGE_MS = 90 * 24 * 3600_000;
200
+
201
+ /** 同一个配置文件里同名、同样启动方式的服务算同一个;配置改了(包括展开后的环境变量)就不认了 */
202
+ export function mcpCacheKey(entry: McpServerEntry): string {
203
+ const { command, args, env, cwd, url, headers, type } = entry.config;
204
+ const spec = JSON.stringify({ type, command, args, env, cwd, url, headers: headers ? Object.keys(headers).sort() : undefined });
205
+ return createHash("sha256").update(`jade-mcp-tools\0${entry.file}\0${entry.name}\0${spec}`).digest("hex");
206
+ }
207
+
208
+ /**
209
+ * 每个服务上次连上时的工具和说明,存在 $JADE_HOME/state/mcp-tools.json。
210
+ * 会话的工具列表在会话开始时就定了(改了提示缓存就失效,内核也只在开始时收工具):
211
+ * 还没连上的服务先按上次的工具给会话,调用时再等连上,就不用等它启动,也不用开新会话才能用
212
+ */
213
+ export class McpToolCache {
214
+ readonly file: string;
215
+ #entries: Record<string, McpKnown & { at: number }> = {};
216
+ #writing: Promise<void> = Promise.resolve();
217
+
218
+ constructor(home: string) {
219
+ this.file = path.join(home, "state", "mcp-tools.json");
220
+ }
221
+
222
+ async load(): Promise<void> {
223
+ try {
224
+ const raw = JSON.parse(await readFile(this.file, "utf8")) as { version?: number; servers?: Record<string, McpKnown & { at: number }> };
225
+ if (raw?.version === 1 && raw.servers && typeof raw.servers === "object") this.#entries = raw.servers;
226
+ } catch {
227
+ // 没有或坏了:当作没连上过
228
+ }
229
+ }
230
+
231
+ get(entry: McpServerEntry): McpKnown | undefined {
232
+ const e = this.#entries[mcpCacheKey(entry)];
233
+ return e && Array.isArray(e.tools) ? { tools: e.tools, ...(e.instructions ? { instructions: e.instructions } : {}) } : undefined;
234
+ }
235
+
236
+ /** 记下这次连上时的;写盘在后台排队,失败不影响使用 */
237
+ put(entry: McpServerEntry, known: McpKnown): Promise<void> {
238
+ const now = Date.now();
239
+ this.#entries[mcpCacheKey(entry)] = { tools: known.tools, ...(known.instructions ? { instructions: known.instructions } : {}), at: now };
240
+ for (const [k, e] of Object.entries(this.#entries)) if (!(now - e.at < KNOWN_MAX_AGE_MS)) delete this.#entries[k];
241
+ const body = `${JSON.stringify({ version: 1, servers: this.#entries })}\n`;
242
+ this.#writing = this.#writing.then(async () => {
243
+ try {
244
+ await mkdir(path.dirname(this.file), { recursive: true });
245
+ const tmp = `${this.file}.${process.pid}.tmp`;
246
+ await writeFile(tmp, body);
247
+ await rename(tmp, this.file);
248
+ } catch {
249
+ // 下次连上再写
250
+ }
251
+ });
252
+ return this.#writing;
253
+ }
254
+ }
255
+
196
256
  /** 给用户看的启动方式 */
197
257
  export function describeServer(c: McpServerConfig): string {
198
258
  return c.command !== undefined ? [c.command, ...(c.args ?? [])].join(" ") : `${c.url}`;
@@ -206,6 +266,8 @@ interface Transport {
206
266
  close(): Promise<void>;
207
267
  /** 连接断开时 resolve */
208
268
  readonly closed: Promise<string>;
269
+ /** 服务端发来的通知(例如 notifications/tools/list_changed)。HTTP 只收得到夹在回复流里的 */
270
+ onNotification?: (method: string) => void;
209
271
  }
210
272
 
211
273
  export class McpError extends Error {
@@ -224,9 +286,19 @@ export interface McpClientOptions {
224
286
  cwd: string;
225
287
  /** 连接断开(进程退出等),不包括主动关闭 */
226
288
  onDisconnect?(client: McpClient, why: string): void;
289
+ /** 列出了工具:连上时(包括重连),以及服务通知工具列表变了、重新列出之后 */
290
+ onTools?(client: McpClient): void;
291
+ /** 连接失败(第一次连、或断开后调用工具时重连):offered() 不再给工具 */
292
+ onFailed?(client: McpClient): void;
227
293
  fetch?: typeof fetch;
228
294
  }
229
295
 
296
+ /** 上次连上时服务给的工具和说明(见 McpToolCache) */
297
+ export interface McpKnown {
298
+ tools: McpToolInfo[];
299
+ instructions?: string;
300
+ }
301
+
230
302
  /** 一个 MCP 服务的连接 */
231
303
  export class McpClient {
232
304
  readonly entry: McpServerEntry;
@@ -236,11 +308,15 @@ export class McpClient {
236
308
  instructions?: string;
237
309
  tools: McpToolInfo[] = [];
238
310
  readonly stderr: string[] = [];
311
+ /** 上次连上时的工具和说明:还在连接时先拿它们给会话,调用时再等连上 */
312
+ known?: McpKnown;
239
313
 
240
314
  #opts: McpClientOptions;
241
315
  #transport?: Transport;
242
316
  #connecting?: Promise<void>;
243
317
  #closing = false;
318
+ /** 连上之后连接断了(不是连接失败):工具照常提供,调用时重连 */
319
+ #dropped = false;
244
320
 
245
321
  constructor(entry: McpServerEntry, opts: McpClientOptions) {
246
322
  this.entry = entry;
@@ -261,17 +337,22 @@ export class McpClient {
261
337
  this.status = "connecting";
262
338
  this.error = undefined;
263
339
  this.#closing = false;
340
+ this.#dropped = false;
264
341
  const c = this.entry.config;
265
342
  const signal = AbortSignal.timeout(c.startupTimeoutMs ?? 30_000);
266
343
  try {
267
344
  const t = c.command !== undefined ? stdioTransport(c, this.#opts.cwd, this.stderr) : httpTransport(c, this.#opts.fetch ?? fetch);
268
345
  this.#transport = t;
346
+ t.onNotification = (method) => {
347
+ if (method === "notifications/tools/list_changed" && this.#transport === t && this.status === "connected") void this.#relist(t);
348
+ };
269
349
  void t.closed.then((why) => {
270
350
  if (this.#transport !== t) return;
271
351
  this.#transport = undefined;
272
352
  if (this.#closing) return;
273
353
  this.status = "failed";
274
354
  this.error = why;
355
+ this.#dropped = this.tools.length > 0;
275
356
  this.#opts.onDisconnect?.(this, why);
276
357
  });
277
358
  const init = (await t.request(
@@ -290,8 +371,62 @@ export class McpClient {
290
371
  this.error = why;
291
372
  await this.close().catch(() => {});
292
373
  this.status = "failed";
374
+ try {
375
+ this.#opts.onFailed?.(this);
376
+ } catch {
377
+ // 通知会话出错不影响连接的结果
378
+ }
293
379
  throw new McpError(why);
294
380
  }
381
+ this.#listed();
382
+ }
383
+
384
+ #listed(): void {
385
+ try {
386
+ this.#opts.onTools?.(this);
387
+ } catch {
388
+ // 记缓存之类的事出错不影响连接
389
+ }
390
+ }
391
+
392
+ /** 正在重新列出工具;列的时候又收到通知,列完再列一次 */
393
+ #relisting?: Promise<void>;
394
+ #relistAgain = false;
395
+
396
+ /** 服务说工具列表变了:重新列出。失败(例如连接正好断了)就留着原来的,下次连上时会重新列出 */
397
+ #relist(t: Transport): Promise<void> {
398
+ if (this.#relisting) {
399
+ this.#relistAgain = true;
400
+ return this.#relisting;
401
+ }
402
+ this.#relisting = (async () => {
403
+ do {
404
+ this.#relistAgain = false;
405
+ try {
406
+ const tools = await this.#listTools(t, AbortSignal.timeout(this.entry.config.startupTimeoutMs ?? 30_000));
407
+ if (this.#transport !== t) return;
408
+ this.tools = tools;
409
+ this.#listed();
410
+ } catch {
411
+ return;
412
+ }
413
+ } while (this.#relistAgain);
414
+ })().finally(() => (this.#relisting = undefined));
415
+ return this.#relisting;
416
+ }
417
+
418
+ /** 现在给会话的工具:连上了用服务列出的;还在连接(或没开始连)时用上次连上时的;连接断了照旧(调用时重连);连不上没有 */
419
+ offered(): McpToolInfo[] {
420
+ if (this.status === "connected" || this.#dropped) return this.tools;
421
+ if (this.status === "failed") return [];
422
+ return this.known?.tools ?? [];
423
+ }
424
+
425
+ /** 同 offered,服务的使用说明 */
426
+ offeredInstructions(): string | undefined {
427
+ if (this.status === "connected" || this.#dropped) return this.instructions;
428
+ if (this.status === "failed") return undefined;
429
+ return this.known?.instructions;
295
430
  }
296
431
 
297
432
  async #listTools(t: Transport, signal: AbortSignal): Promise<McpToolInfo[]> {
@@ -309,6 +444,8 @@ export class McpClient {
309
444
  /** 调用工具。连接断了先重连一次 */
310
445
  async callTool(name: string, args: unknown, signal: AbortSignal): Promise<{ content?: unknown[]; isError?: boolean; structuredContent?: unknown }> {
311
446
  if (this.status !== "connected" || !this.#transport) await this.connect();
447
+ // 会话的工具可能来自上次连上时(known),这次连上后服务已经不提供了
448
+ if (!this.tools.some((x) => x.name === name)) throw new McpError(`the server no longer offers the tool "${name}"; /mcp lists its current tools`);
312
449
  const t = this.#transport!;
313
450
  const limit = AbortSignal.timeout(this.entry.config.toolTimeoutMs ?? 600_000);
314
451
  const both = AbortSignal.any([signal, limit]);
@@ -374,7 +511,7 @@ function stdioTransport(c: McpServerConfig, cwd: string, stderr: string[]): Tran
374
511
  child.on("close", (code, sig) => resolve(`exited (${sig ?? `code ${code}`})${stderr.length ? `: ${stderr.at(-1)}` : ""}`));
375
512
  });
376
513
  void closed.then((why) => rpc.fail(new McpError(`server ${why}`)));
377
- return {
514
+ const t: Transport = {
378
515
  request: (method, params, signal) => rpc.request(method, params, signal),
379
516
  notify: async (method, params) => rpc.send({ jsonrpc: "2.0", method, ...(params ? { params } : {}) }),
380
517
  closed,
@@ -384,6 +521,8 @@ function stdioTransport(c: McpServerConfig, cwd: string, stderr: string[]): Tran
384
521
  if (!done) killTree(child);
385
522
  },
386
523
  };
524
+ rpc.onNotify = (method) => t.onNotification?.(method);
525
+ return t;
387
526
  }
388
527
 
389
528
  /**
@@ -466,7 +605,7 @@ function httpTransport(c: McpServerConfig, doFetch: typeof fetch): Transport {
466
605
  return res;
467
606
  }
468
607
 
469
- return {
608
+ const t: Transport = {
470
609
  async request(method, params, signal) {
471
610
  const id = nextId++;
472
611
  const res = await post({ jsonrpc: "2.0", id, method, ...(params ? { params } : {}) }, signal);
@@ -475,7 +614,7 @@ function httpTransport(c: McpServerConfig, doFetch: typeof fetch): Transport {
475
614
  throw new McpError(`HTTP ${res.status}${res.status === 401 ? " (unauthorized: check the headers in the MCP config)" : ""}${text ? `: ${text}` : ""}`);
476
615
  }
477
616
  const type = res.headers.get("content-type") ?? "";
478
- const reply = type.includes("text/event-stream") ? await fromSse(res, id, signal) : ((await res.json()) as RpcMessage);
617
+ const reply = type.includes("text/event-stream") ? await fromSse(res, id, signal, (m) => t.onNotification?.(m)) : ((await res.json()) as RpcMessage);
479
618
  const result = unwrap(reply);
480
619
  if (method === "initialize") protocol = (result as { protocolVersion?: string })?.protocolVersion ?? PROTOCOL_VERSION;
481
620
  return result;
@@ -493,10 +632,11 @@ function httpTransport(c: McpServerConfig, doFetch: typeof fetch): Transport {
493
632
  markClosed("closed");
494
633
  },
495
634
  };
635
+ return t;
496
636
  }
497
637
 
498
- /** 从 SSE 流里找到 id 对应的回复;流里其他的消息(通知、服务端的请求)忽略 */
499
- async function fromSse(res: Response, id: number, signal: AbortSignal): Promise<RpcMessage> {
638
+ /** 从 SSE 流里找到 id 对应的回复;流里的通知交给 onNotify,服务端的请求忽略 */
639
+ async function fromSse(res: Response, id: number, signal: AbortSignal, onNotify: (method: string) => void): Promise<RpcMessage> {
500
640
  const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
501
641
  let buf = "";
502
642
  try {
@@ -517,6 +657,7 @@ async function fromSse(res: Response, id: number, signal: AbortSignal): Promise<
517
657
  try {
518
658
  const msg = JSON.parse(data) as RpcMessage;
519
659
  if (msg.id === id && (msg.result !== undefined || msg.error !== undefined)) return msg;
660
+ if (msg.id === undefined && typeof msg.method === "string") onNotify(msg.method);
520
661
  } catch {
521
662
  // 不是 JSON 的事件忽略
522
663
  }
@@ -549,6 +690,8 @@ class Rpc {
549
690
  #nextId = 1;
550
691
  #pending = new Map<number | string, { resolve: (v: unknown) => void; reject: (e: unknown) => void }>();
551
692
  #dead?: Error;
693
+ /** 服务端发来的通知 */
694
+ onNotify?: (method: string) => void;
552
695
 
553
696
  constructor(send: (msg: RpcMessage) => void) {
554
697
  this.#send = send;
@@ -579,8 +722,15 @@ class Rpc {
579
722
 
580
723
  receive(msg: RpcMessage): void {
581
724
  if (msg.method !== undefined) {
582
- // 服务端发来的请求:只支持 ping,其他的回复"不支持",免得服务端一直等
583
- if (msg.id === undefined) return;
725
+ // 通知交给连接;服务端发来的请求只支持 ping,其他的回复"不支持",免得服务端一直等
726
+ if (msg.id === undefined) {
727
+ try {
728
+ this.onNotify?.(msg.method);
729
+ } catch {
730
+ // 处理通知出错不影响连接
731
+ }
732
+ return;
733
+ }
584
734
  if (msg.method === "ping") this.#send({ jsonrpc: "2.0", id: msg.id, result: {} });
585
735
  else this.#send({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: `jade does not support ${msg.method}` } });
586
736
  return;
@@ -611,13 +761,15 @@ export function mcpToolName(server: string, tool: string): string {
611
761
  return `${full.slice(0, MAX_TOOL_NAME - 9)}_${hash}`;
612
762
  }
613
763
 
614
- /** 把已连接的服务的工具变成 jade 的工具;readOnly 为 true 时只要声明了只读的工具(给子 Agent) */
764
+ /**
765
+ * 把服务的工具变成 jade 的工具:已连接的用服务列出的,还在连接的用上次连上时的(调用时等连上,见 McpClient.offered)。
766
+ * readOnly 为 true 时只要声明了只读的工具(给子 Agent)
767
+ */
615
768
  export function mcpTools(clients: McpClient[], opts: { readOnly?: boolean } = {}): Tool[] {
616
769
  const out: Tool[] = [];
617
770
  const names = new Set<string>();
618
771
  for (const client of clients) {
619
- if (client.status !== "connected") continue;
620
- for (const info of client.tools) {
772
+ for (const info of client.offered()) {
621
773
  const readOnly = info.annotations?.readOnlyHint === true;
622
774
  if (opts.readOnly && !readOnly) continue;
623
775
  const name = mcpToolName(client.name, info.name);
@@ -3,5 +3,6 @@
3
3
  "version": "0.2.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "optional": ["ui@1", "commands@1", "prompts@1", "task@1", "cli@1"]
6
+ "requires": ["trust@1"],
7
+ "optional": ["ui@1", "commands@1", "prompts@1", "cli@1"]
7
8
  }
@@ -1,7 +1,8 @@
1
1
  // 仓库目录、确认记录、显示用的小工具、斜杠命令参数的切分、token 估算。插件之间不共享代码(只能共享类型),jade/skills、jade/checks 各有一份。
2
2
 
3
+ import type { Span, Text, TextStyle, Trust } from "@uncarved/jade-api";
3
4
  import { existsSync, realpathSync } from "node:fs";
4
- import { appendFile, mkdir, readFile } from "node:fs/promises";
5
+ import { readFile } from "node:fs/promises";
5
6
  import path from "node:path";
6
7
 
7
8
  export function realPath(p: string): string {
@@ -40,57 +41,17 @@ export function display(cwd: string, full: string): string {
40
41
  return shown.split(path.sep).join("/");
41
42
  }
42
43
 
43
- /**
44
- * 用户确认过的东西(项目层的 MCP 服务),每行一条 { hash, path, at }。
45
- * 和旧 jade 的 $JADE_HOME/trust.jsonl 同一个文件、同一种格式,旧 jade 里确认过的不用再确认
46
- */
47
- export class TrustFile {
48
- readonly file: string;
49
- #known = new Set<string>();
50
-
51
- constructor(file: string) {
52
- this.file = file;
53
- }
54
-
55
- async has(hash: string): Promise<boolean> {
56
- if (this.#known.has(hash)) return true;
57
- let text = "";
58
- try {
59
- text = await readFile(this.file, "utf8");
60
- } catch {
61
- return false;
62
- }
63
- for (const line of text.split("\n")) {
64
- try {
65
- if ((JSON.parse(line) as { hash?: unknown }).hash === hash) {
66
- this.#known.add(hash);
67
- return true;
68
- }
69
- } catch {
70
- // 写到一半的行
71
- }
72
- }
73
- return false;
74
- }
75
-
76
- async add(hash: string, where: string): Promise<void> {
77
- await mkdir(path.dirname(this.file), { recursive: true });
78
- await appendFile(this.file, `${JSON.stringify({ hash, path: where, at: new Date().toISOString() })}\n`);
79
- this.#known.add(hash);
80
- }
81
- }
82
-
83
44
  export const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
84
45
 
85
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色,见 https://no-color.org
86
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
87
- const paint = (open: string, close: string) => (s: string) =>
88
- colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
89
- export const dim = paint("2", "22");
90
- export const red = paint("31", "39");
91
- export const green = paint("32", "39");
92
- export const yellow = paint("33", "39");
93
- export const bold = paint("1", "22");
46
+ // 带语义样式的文字(jade-api 的 Text):插件只说这段是次要的、成功、警告……,怎么画由前端决定
47
+ const styled = (style: TextStyle) => (text: string): Span => ({ text, style });
48
+ export const dim = styled("dim");
49
+ export const bold = styled("bold");
50
+ export const ok = styled("ok");
51
+ export const warn = styled("warn");
52
+ export const error = styled("error");
53
+ /** 几行接成一段,行之间换行 */
54
+ export const lines = (rows: readonly Text[]): Text => rows.flatMap((r, i) => (i ? ["\n", r] : [r]));
94
55
 
95
56
  /** 斜杠命令的参数按空白切开;"…" 或 '…' 里的空白不切(不处理反斜杠,Windows 路径照写) */
96
57
  export function splitArgs(text: string): string[] {
@@ -127,3 +88,39 @@ export function estimateTokens(text: string): number {
127
88
  const wide = text.match(WIDE)?.length ?? 0;
128
89
  return Math.ceil((text.length - wide) / 4 + wide);
129
90
  }
91
+
92
+ /**
93
+ * 0.3.1 及以前,本插件自己把确认记在 $JADE_HOME/trust.jsonl(每行 { hash, path, at })。升级后照认,不用再确认一遍:
94
+ * trust@1 里没有时查这份旧文件,查到了顺手记进 trust@1。这是本插件自己的旧数据,核心不认识它
95
+ */
96
+ export function withLegacyTrust(trust: Trust, home: string): Trust {
97
+ let legacy: Promise<Map<string, string>> | undefined;
98
+ const read = async () => {
99
+ const hashes = new Map<string, string>();
100
+ let text = "";
101
+ try {
102
+ text = await readFile(path.join(home, "trust.jsonl"), "utf8");
103
+ } catch {
104
+ return hashes;
105
+ }
106
+ for (const line of text.split("\n")) {
107
+ try {
108
+ const r = JSON.parse(line) as { hash?: unknown; path?: unknown };
109
+ if (typeof r.hash === "string") hashes.set(r.hash, typeof r.path === "string" ? r.path : "");
110
+ } catch {
111
+ // 空行、写到一半的行
112
+ }
113
+ }
114
+ return hashes;
115
+ };
116
+ return {
117
+ has: async (hash) => {
118
+ if (await trust.has(hash)) return true;
119
+ const where = (await (legacy ??= read())).get(hash);
120
+ if (where === undefined) return false;
121
+ await trust.add(hash, where).catch(() => {});
122
+ return true;
123
+ },
124
+ add: (hash, where) => trust.add(hash, where),
125
+ };
126
+ }
@@ -5,7 +5,7 @@
5
5
  import { definePlugin } from "@uncarved/jade-api";
6
6
  import type { Commands, Prompts, Renderers } from "@uncarved/jade-api/services";
7
7
  import { Memory, MEMORY_SCOPES, memoryTool, projectRoot, type MemoryScope } from "./memory.ts";
8
- import { clip, dim, green, red } from "./style.ts";
8
+ import { clip, dim, error, ok as success } from "./style.ts";
9
9
 
10
10
  const args = (input: unknown) => (input ?? {}) as { action?: string; scope?: string; text?: string };
11
11
 
@@ -21,7 +21,7 @@ export default definePlugin({
21
21
  },
22
22
  preview: (input) => {
23
23
  const i = args(input);
24
- return `${i.action === "remove" ? red("- ") : green("+ ")}${String(i.text ?? "")}`;
24
+ return [i.action === "remove" ? error("- ") : success("+ "), String(i.text ?? "")];
25
25
  },
26
26
  });
27
27
 
@@ -65,7 +65,7 @@ export default definePlugin({
65
65
  if (ok !== "yes") return;
66
66
  await memory.remove(entry.scope, entry.text);
67
67
  note(`The user removed this ${entry.scope} memory, so stop following it: ${entry.text}`);
68
- return green(`Removed from ${entry.scope} memory: ${entry.text}`);
68
+ return success(`Removed from ${entry.scope} memory: ${entry.text}`);
69
69
  }
70
70
  text = (await ui.input({ title: "What should jade remember?", placeholder: "e.g. Reply in Chinese; run tests with bun test" }, signal)) ?? "";
71
71
  if (!text.trim()) return;
@@ -85,7 +85,7 @@ export default definePlugin({
85
85
  if (!scope) return;
86
86
  const added = await memory.add(scope, text);
87
87
  if (added) note(`The user saved a ${scope} memory; follow it from now on: ${text.replace(/\s+/g, " ").trim()}`);
88
- return added ? green(`Saved to ${scope} memory.`) : dim(`The ${scope} memory already has this.`);
88
+ return added ? success(`Saved to ${scope} memory.`) : dim(`The ${scope} memory already has this.`);
89
89
  },
90
90
  });
91
91
  },
@@ -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]));
@@ -0,0 +1,67 @@
1
+ // 输入框里 @ 补全的候选:工作目录里的文件(git 仓库里只看版本控制的,和 glob 一样)和它们所在的目录。
2
+ // 经 completions@1 交给前端,前端只管排序和插入。原来在 jade/tui 里,搬到这里:@ 的意思归 jade/mentions。
3
+
4
+ import { execFile } from "node:child_process";
5
+ import { readdir } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { display } from "./attach.ts";
8
+
9
+ /** 候选(文件加目录)最多这么多,再多也只是拖慢补全 */
10
+ const MAX_CANDIDATES = 20_000;
11
+
12
+ /**
13
+ * 工作目录里的文件和它们所在的目录,目录以 / 结尾。
14
+ * 5 秒还没列完就先给已经找到的(大仓库第一次列得慢,不该让输入框卡住)
15
+ */
16
+ export async function mentionCandidates(cwd: string, signal: AbortSignal = AbortSignal.timeout(5000)): Promise<string[]> {
17
+ const files: string[] = [];
18
+ const dirs = new Set<string>();
19
+ try {
20
+ for await (const full of await listFiles(cwd, signal)) {
21
+ const rel = display(cwd, full);
22
+ files.push(rel);
23
+ for (let i = rel.lastIndexOf("/"); i > 0; i = rel.lastIndexOf("/", i - 1)) {
24
+ const dir = rel.slice(0, i + 1);
25
+ if (dirs.has(dir)) break;
26
+ dirs.add(dir);
27
+ }
28
+ if (files.length + dirs.size >= MAX_CANDIDATES) break;
29
+ }
30
+ } catch {
31
+ // 列到一半被中止(超时):用已经找到的
32
+ }
33
+ return [...dirs, ...files];
34
+ }
35
+
36
+ // 以下和 jade/fs 的 listFiles 相同:插件之间不共享代码(只能共享类型),所以这里留一份
37
+
38
+ const SKIP_DIRS = new Set([".git", "node_modules"]);
39
+
40
+ /** git 仓库里的文件(版本控制的和没忽略的新文件);不是仓库、没有 git 时 undefined */
41
+ function gitFiles(root: string): Promise<string[] | undefined> {
42
+ return new Promise((resolve) => {
43
+ execFile("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: root, maxBuffer: 256 * 1024 * 1024, windowsHide: true }, (err, out) =>
44
+ // 合并冲突中的文件会出现多次
45
+ resolve(err ? undefined : [...new Set(out.split("\0").filter(Boolean))]),
46
+ );
47
+ });
48
+ }
49
+
50
+ async function listFiles(root: string, signal: AbortSignal): Promise<Iterable<string> | AsyncIterable<string>> {
51
+ const tracked = await gitFiles(root);
52
+ if (!tracked) return walk(root, signal);
53
+ return tracked.filter((rel) => !rel.split("/").some((seg) => SKIP_DIRS.has(seg))).map((rel) => path.join(root, rel));
54
+ }
55
+
56
+ async function* walk(dir: string, signal: AbortSignal): AsyncIterable<string> {
57
+ signal.throwIfAborted();
58
+ const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
59
+ for (const e of entries) {
60
+ const full = path.join(dir, e.name);
61
+ if (e.isDirectory()) {
62
+ if (!SKIP_DIRS.has(e.name)) yield* walk(full, signal);
63
+ } else if (e.isFile()) {
64
+ yield full;
65
+ }
66
+ }
67
+ }
@@ -5,13 +5,14 @@
5
5
  // 文件之后变了也不影响已经发出的消息(提示缓存不失效),恢复会话后也一样。
6
6
  // 每条消息的附件单独记一个 key(attachedKey):derived.recorded 是整值替换,记成一张表的话,
7
7
  // 每次有新的 @ 都要把之前附过的全部内容再写一遍,日志按平方增长。
8
- // 输入框里 @ 的补全不在这里,在 jade/tui。
8
+ // 输入框里 @ 的补全:经 completions@1 交给前端候选(candidates.ts),前端只管排序和插入。
9
9
 
10
10
  import type { Block, Message } from "uncarved";
11
11
  import { definePlugin } from "@uncarved/jade-api";
12
- import type { Renderers } from "@uncarved/jade-api/services";
12
+ import type { Completions, Renderers } from "@uncarved/jade-api/services";
13
13
  import { attachMentions } from "./attach.ts";
14
- import { clip, dim, yellow } from "./style.ts";
14
+ import { mentionCandidates } from "./candidates.ts";
15
+ import { clip, dim, lines as joinLines, warn } from "./style.ts";
15
16
 
16
17
  export interface MentionsState {
17
18
  /** state.messages 的前 upTo 条已经处理过 */
@@ -31,16 +32,22 @@ const userText = (m: Message) => (m.role === "user" ? m.content.flatMap((b) => (
31
32
 
32
33
  export default definePlugin({
33
34
  process(ctx) {
35
+ ctx.service<Completions>("completions@1")?.register({
36
+ trigger: "@",
37
+ label: "files",
38
+ hint: "the file's content is sent with the message",
39
+ candidates: () => mentionCandidates(ctx.cwd),
40
+ });
34
41
  const renderers = ctx.service<Renderers>("renderers@1");
35
42
  renderers?.event({
36
43
  event: "attached",
37
44
  render: (data) => {
38
45
  const d = data as { attached: string[]; failed: { path: string; reason: string }[] };
39
46
  const lines = [
40
- ...d.failed.map((f) => yellow(`[@${f.path} not attached: ${clip(f.reason, 200)}]`)),
47
+ ...d.failed.map((f) => warn(`[@${f.path} not attached: ${clip(f.reason, 200)}]`)),
41
48
  ...(d.attached.length ? [dim(`[attached ${d.attached.map((p) => `@${p}`).join(", ")}]`)] : []),
42
49
  ];
43
- return lines.length ? { line: lines.join("\n") } : undefined;
50
+ return lines.length ? { line: joinLines(lines) } : undefined;
44
51
  },
45
52
  });
46
53
  },
@@ -3,5 +3,5 @@
3
3
  "version": "0.2.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "optional": ["renderers@1"]
6
+ "optional": ["renderers@1", "completions@1"]
7
7
  }
@@ -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]));