@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
@@ -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 = () => {
@@ -1,30 +1,43 @@
1
- // jade/mcp:配置的 MCP 服务的工具交给模型(声明只读的也经 tools@1 交给嵌套 Agent);/mcp 查看状态、重连,
2
- // /mcp add、/mcp remove 改配置文件(见 install.ts;终端里是 jade mcp add|remove)。
1
+ // jade/mcp:配置的 MCP 服务的工具交给模型(子 Agent 是核心开的子会话,本插件在里面另有一份);/mcp 查看状态、重连,
2
+ // /mcp add、/mcp remove 改配置文件(见 install.ts;终端里是 jade mcp add|remove),jade 运行时马上启动、停掉服务。
3
3
  //
4
4
  // 服务是进程级的资源:第一个会话打开时读配置、确认项目层的服务、连接,之后各会话共用;进程退出时(进程作用域关闭)全部关掉。
5
- // 一个会话里的工具列表不变(否则提示缓存失效):第一个会话最多等 STARTUP_WAIT_MS,没连上的在后台接着连,
6
- // 它们的工具从下一个会话(/clear)开始提供。不能交互时(-p)只有这一个会话,照常等到每个服务连上或超时。
5
+ // 会话里的工具跟着服务变:连上、服务通知工具列表变了(notifications/tools/list_changed)、/mcp add|remove|reconnect 之后,
6
+ // 从下一轮起生效(核心在两轮之间按新的工具表重挂会话,不用 /clear;代价是下一次请求的提示缓存失效)。
7
+ // 能交互时会话不等连上过的服务:每个服务上次连上时的工具记在 $JADE_HOME/state/mcp-tools.json(McpToolCache),还在连接时
8
+ // 先按它们提供,调用时再等连上;第一次用的服务最多等 STARTUP_WAIT_MS,等不到的连上后工具从下一轮起有。不能交互时(-p)通常只有一轮,照常等到每个服务连上或超时。
7
9
  // 服务进程退出后,下一次调用它的工具时重新连接一次。
8
10
 
9
11
  import path from "node:path";
10
- import { definePlugin, type Cli, type ProcessContext, type UI } from "@uncarved/jade-api";
11
- import type { Commands, Prompts, Tools } from "@uncarved/jade-api/services";
12
- import { describeServer, loadMcpConfig, McpClient, mcpTools, mcpTrustHash } from "./mcp.ts";
12
+ import { definePlugin, type Cli, type ProcessContext, type Text, type Tool, type Trust, type UI } from "@uncarved/jade-api";
13
+ import type { Commands, Prompts } from "@uncarved/jade-api/services";
14
+ import { describeServer, loadMcpConfig, McpClient, mcpCacheKey, McpToolCache, mcpTools, mcpTrustHash, type McpServerEntry } from "./mcp.ts";
13
15
  import { manageMcp, manageUsage } from "./install.ts";
14
- import { bold, clip, dim, display, estimateTokens, green, realPath, red, repoRoot, splitArgs, TrustFile, yellow } from "./project.ts";
16
+ import { bold, clip, dim, display, error, estimateTokens, lines as joinLines, ok, realPath, repoRoot, splitArgs, warn, withLegacyTrust } from "./project.ts";
15
17
 
16
18
  const ID = "jade/mcp";
17
- /** 第一个会话最多等 MCP 服务连接这么久(能交互时),没连上的在后台接着连 */
19
+ /** 能交互时,第一次用(没有记下工具)的服务最多等这么久;没连上的连上后从下一轮起有工具 */
18
20
  const STARTUP_WAIT_MS = 5000;
19
21
 
20
22
  const errorText = (err: unknown) => (err instanceof Error ? err.message : String(err));
21
23
 
24
+ /** 启动时算好的东西,加服务(/mcp add)时还要用 */
25
+ interface Setup {
26
+ cwd: string;
27
+ root: string;
28
+ trust: Trust;
29
+ cache: McpToolCache;
30
+ }
31
+
22
32
  /** 本进程的 MCP 服务 */
23
33
  class Servers {
24
34
  clients: McpClient[] = [];
25
35
  readonly #ctx: ProcessContext;
26
36
  #started?: Promise<void>;
37
+ #setup?: Setup;
27
38
  #closing = false;
39
+ /** 服务给的工具或说明变了时通知的会话 */
40
+ #watchers = new Set<() => void>();
28
41
 
29
42
  constructor(ctx: ProcessContext) {
30
43
  this.#ctx = ctx;
@@ -48,6 +61,23 @@ class Servers {
48
61
  }
49
62
  }
50
63
 
64
+ /** 工具或说明变了时调用 fn,返回取消 */
65
+ watch(fn: () => void): () => void {
66
+ this.#watchers.add(fn);
67
+ return () => void this.#watchers.delete(fn);
68
+ }
69
+
70
+ #changed(): void {
71
+ if (this.#closing) return;
72
+ for (const fn of [...this.#watchers]) {
73
+ try {
74
+ fn();
75
+ } catch {
76
+ // 一个会话同步失败不影响别的
77
+ }
78
+ }
79
+ }
80
+
51
81
  /** 第一次调用时读配置、确认、连接;之后等同一次。失败时关掉已经建的连接,下次调用重来,免得一次失败让 MCP 一直用不了 */
52
82
  start(): Promise<void> {
53
83
  this.#started ??= this.#start().catch(async (e: unknown) => {
@@ -62,57 +92,97 @@ class Servers {
62
92
  const ctx = this.#ctx;
63
93
  const cwd = realPath(ctx.cwd);
64
94
  const root = realPath(repoRoot(cwd));
65
- const trust = new TrustFile(path.join(ctx.home, "trust.jsonl"));
66
- const { servers, warnings } = await loadMcpConfig({ home: ctx.home, root, cwd });
95
+ const setup: Setup = { cwd, root, trust: withLegacyTrust(ctx.require<Trust>("trust@1"), ctx.home), cache: new McpToolCache(ctx.home) };
96
+ const [{ servers, warnings }] = await Promise.all([loadMcpConfig({ home: ctx.home, root, cwd }), setup.cache.load()]);
97
+ this.#setup = setup;
67
98
  for (const w of warnings) this.notify(`${ID}: ${w}`, "warning");
68
- const ui = this.ui();
69
99
  const connecting: Promise<unknown>[] = [];
70
100
  for (const entry of servers) {
71
- if (entry.config.disabled) continue;
72
- if (entry.layer === "project") {
73
- // 项目层的服务随仓库分发,启动它就是执行仓库指定的命令:第一次启动前(配置变了也算)请用户确认
74
- const hash = mcpTrustHash(root, entry);
75
- if (!(await trust.has(hash))) {
76
- const ok = ui?.interactive
77
- ? (await ui.select(
78
- {
79
- title: `MCP server "${entry.name}" from ${display(cwd, entry.file)} is new or changed. Start it?`,
80
- detail: `${entry.config.command !== undefined ? "runs" : "connects to"}: ${describeServer(entry.config)}`,
81
- options: [
82
- { label: "No", value: "no" },
83
- { label: "Yes, start it", value: "yes" },
84
- ],
85
- },
86
- ctx.signal,
87
- )) === "yes"
88
- : false;
89
- if (!ok) {
90
- this.notify(`[skipped] MCP server ${entry.name}: not confirmed${ui?.interactive ? "" : " (run jade interactively in this directory once to confirm it)"}`, "warning");
91
- continue;
92
- }
93
- await trust.add(hash, entry.file);
94
- }
95
- }
96
- const client = new McpClient(entry, {
97
- cwd,
98
- onDisconnect: (c, why) => this.notify(`MCP server ${c.name} disconnected: ${why}. jade reconnects on its next tool call; /mcp shows details`, "warning"),
99
- });
100
- this.clients.push(client);
101
- connecting.push(client.connect().catch((err) => this.notify(`MCP server ${client.name} is unavailable: ${errorText(err)}`, "warning")));
101
+ const added = await this.#add(entry, setup);
102
+ // 能交互时,记下过工具的服务不等:先按上次的工具提供
103
+ if (added && !(this.ui()?.interactive && added.client.known)) connecting.push(added.done);
102
104
  }
103
- if (this.clients.length === 0) return;
104
- const all = Promise.all(connecting);
105
+ // 不能交互时通常只有一轮,等到每个服务连上或超时。能交互时第一次用的服务最多等 STARTUP_WAIT_MS:
106
+ // 等不到就先开始,它连上后工具从下一轮起有(pi 在第一条消息前等最多 10 秒,dsh 一直等)
107
+ if (!this.ui()?.interactive) return void (await Promise.all(connecting));
105
108
  let timer: ReturnType<typeof setTimeout> | undefined;
106
- if (ui?.interactive) await Promise.race([all, new Promise<void>((resolve) => (timer = setTimeout(resolve, STARTUP_WAIT_MS)))]);
107
- else await all;
109
+ await Promise.race([Promise.all(connecting), new Promise<void>((resolve) => (timer = setTimeout(resolve, STARTUP_WAIT_MS)))]);
108
110
  clearTimeout(timer);
109
- for (const c of this.clients.filter((x) => x.status === "connecting")) {
110
- this.notify(`MCP server ${c.name} is still starting; its tools are available from the next session (/clear) once it is connected`);
111
- void c.connect().then(
112
- () => this.notify(`MCP server ${c.name} connected; its tools are available from the next session (/clear)`),
113
- () => {},
114
- );
111
+ }
112
+
113
+ /** 确认(项目层)、建连接、在后台连接;done 是连接的结果(不会 reject)。跳过时返回 undefined */
114
+ async #add(entry: McpServerEntry, setup: Setup): Promise<{ client: McpClient; done: Promise<void> } | undefined> {
115
+ if (entry.config.disabled) return undefined;
116
+ const ui = this.ui();
117
+ if (entry.layer === "project") {
118
+ // 项目层的服务随仓库分发,启动它就是执行仓库指定的命令:第一次启动前(配置变了也算)请用户确认
119
+ const hash = mcpTrustHash(setup.root, entry);
120
+ if (!(await setup.trust.has(hash))) {
121
+ const ok = ui?.interactive
122
+ ? (await ui.select(
123
+ {
124
+ title: `MCP server "${entry.name}" from ${display(setup.cwd, entry.file)} is new or changed. Start it?`,
125
+ detail: `${entry.config.command !== undefined ? "runs" : "connects to"}: ${describeServer(entry.config)}`,
126
+ options: [
127
+ { label: "No", value: "no" },
128
+ { label: "Yes, start it", value: "yes" },
129
+ ],
130
+ },
131
+ this.#ctx.signal,
132
+ )) === "yes"
133
+ : false;
134
+ if (!ok) {
135
+ this.notify(`[skipped] MCP server ${entry.name}: not confirmed${ui?.interactive ? "" : " (run jade interactively in this directory once to confirm it)"}`, "warning");
136
+ return undefined;
137
+ }
138
+ await setup.trust.add(hash, entry.file);
139
+ }
115
140
  }
141
+ const client = new McpClient(entry, {
142
+ cwd: setup.cwd,
143
+ onDisconnect: (c, why) => this.notify(`MCP server ${c.name} disconnected: ${why}. jade reconnects on its next tool call; /mcp shows details`, "warning"),
144
+ // 连上、重新列出工具之后:记进缓存,会话跟着增减工具
145
+ // 工具没变也记:刷新时间,常用的服务不会因为工具一直没变被当作久没连上而清掉
146
+ onTools: (c) => {
147
+ const now = { tools: c.tools, ...(c.instructions ? { instructions: c.instructions } : {}) };
148
+ void setup.cache.put(entry, now);
149
+ c.known = now;
150
+ this.#changed();
151
+ },
152
+ // 连不上(包括调用工具时的重连):上次的工具不再提供
153
+ onFailed: () => this.#changed(),
154
+ });
155
+ client.known = setup.cache.get(entry);
156
+ this.clients.push(client);
157
+ const done = client.connect().catch((err) => {
158
+ this.notify(`MCP server ${client.name} is unavailable: ${errorText(err)}`, "warning");
159
+ });
160
+ // 包一层:async 函数直接返回 Promise 会被等到它完成
161
+ return { client, done };
162
+ }
163
+
164
+ /**
165
+ * 配置改了(/mcp add、/mcp remove):去掉的服务关掉,新的(或改了的)启动。还没启动过时什么都不做,第一次启动会读新配置
166
+ */
167
+ async reload(): Promise<void> {
168
+ if (!this.#started) return;
169
+ await this.#started.catch(() => {});
170
+ const setup = this.#setup;
171
+ if (!setup) return;
172
+ const { servers, warnings } = await loadMcpConfig({ home: this.#ctx.home, root: setup.root, cwd: setup.cwd });
173
+ for (const w of warnings) this.notify(`${ID}: ${w}`, "warning");
174
+ const wanted = new Set(servers.filter((e) => !e.config.disabled).map(mcpCacheKey));
175
+ const gone = this.clients.filter((c) => !wanted.has(mcpCacheKey(c.entry)));
176
+ this.clients = this.clients.filter((c) => !gone.includes(c));
177
+ await Promise.all(gone.map((c) => c.close().catch(() => {})));
178
+ const have = new Set(this.clients.map((c) => mcpCacheKey(c.entry)));
179
+ for (const entry of servers) if (!have.has(mcpCacheKey(entry))) await this.#add(entry, setup);
180
+ this.#changed();
181
+ }
182
+
183
+ /** 服务的工具变了(例如重连之后):会话跟着增减 */
184
+ touch(): void {
185
+ this.#changed();
116
186
  }
117
187
 
118
188
  async close(): Promise<void> {
@@ -122,20 +192,29 @@ class Servers {
122
192
  }
123
193
 
124
194
  /** 服务在初始化时给出的使用说明,放进系统提示词。来自外部,标为不可信 */
125
- function instructions(clients: McpClient[]): string[] {
126
- return clients
127
- .filter((c) => c.status === "connected" && c.instructions)
128
- .map((c) => `# Instructions from the MCP server "${c.name}" (about its mcp__${c.name}__* tools)
195
+ function instructions(c: McpClient): string | undefined {
196
+ const text = c.offeredInstructions();
197
+ return text
198
+ ? `# Instructions from the MCP server "${c.name}" (about its mcp__${c.name}__* tools)
129
199
 
130
- ${c.instructions}`);
200
+ ${text}`
201
+ : undefined;
131
202
  }
132
203
 
133
204
  /** 一个服务每次请求都带着的大约多少 token:发给模型的工具定义,加上它的使用说明。没连上时为 0 */
134
205
  function serverTokens(c: McpClient): number {
135
206
  const tools = mcpTools([c]).reduce((n, t) => n + estimateTokens(JSON.stringify({ name: t.name, description: t.description, input_schema: t.inputSchema })), 0);
136
- return tools + instructions([c]).reduce((n, text) => n + estimateTokens(text), 0);
207
+ return tools + estimateTokens(instructions(c) ?? "");
137
208
  }
138
209
 
210
+ /** 连接对象的编号:服务重新加进来(/mcp add --force)后是新的连接,旧工具要换掉 */
211
+ const serial = new WeakMap<McpClient, number>();
212
+ let nextSerial = 1;
213
+ const serialOf = (c: McpClient) => serial.get(c) ?? (serial.set(c, nextSerial), nextSerial++);
214
+
215
+ /** 工具交给模型的样子;变了就要重新注册 */
216
+ const toolKey = (c: McpClient, t: Tool) => JSON.stringify([serialOf(c), t.description, t.inputSchema, t.effect, t.concurrency, t.idempotent]);
217
+
139
218
  /** 当前进程的服务;process() 里创建,session() 里用 */
140
219
  let current: Servers | undefined;
141
220
 
@@ -156,47 +235,56 @@ export default definePlugin({
156
235
  try {
157
236
  words = splitArgs(args);
158
237
  } catch (e) {
159
- return red(errorText(e));
238
+ return error(errorText(e));
160
239
  }
161
- // 只改配置文件,不用先连接
162
240
  if (words[0] === "add" || words[0] === "remove" || words[0] === "rm") {
241
+ let done: string;
163
242
  try {
164
- return await manageMcp(words, { home: ctx.home, cwd: ctx.cwd, cmd: "/mcp" });
243
+ done = await manageMcp(words, { home: ctx.home, cwd: ctx.cwd, cmd: "/mcp", live: true });
165
244
  } catch (e) {
166
- return red(errorText(e));
245
+ return error(errorText(e));
167
246
  }
247
+ try {
248
+ await servers.reload();
249
+ } catch (e) {
250
+ return [done, "\n", error(`could not apply the change now: ${errorText(e)}; restart jade to apply it`)];
251
+ }
252
+ return done;
168
253
  }
169
254
  await servers.start();
170
255
  const clients = servers.clients;
171
256
  if (words[0] === "reconnect") {
172
257
  const c = clients.find((x) => x.name === words[1]);
173
- if (!c) return red(`usage: /mcp reconnect <name>; servers: ${clients.map((x) => x.name).join(", ") || "(none)"}`);
258
+ if (!c) return error(`usage: /mcp reconnect <name>; servers: ${clients.map((x) => x.name).join(", ") || "(none)"}`);
174
259
  await c.close();
175
260
  try {
176
261
  await c.connect();
177
- return green(`${c.name} connected, ${c.tools.length} tools; new tools are available from the next session (/clear)`);
262
+ return ok(`${c.name} connected, ${c.tools.length} tools; changes to its tools apply from the next turn`);
178
263
  } catch (err) {
179
- return red(`${c.name}: ${errorText(err)}`);
264
+ servers.touch();
265
+ return error(`${c.name}: ${errorText(err)}`);
180
266
  }
181
267
  }
182
- if (words.length > 0) return red(`usage: /mcp [reconnect <name>]\n${manageUsage("/mcp")}`);
268
+ if (words.length > 0) return error(`usage: /mcp [reconnect <name>]\n${manageUsage("/mcp")}`);
183
269
  if (clients.length === 0) {
184
270
  return dim(`(no MCP servers) add one with /mcp add, or configure them in ${display(ctx.cwd, path.join(ctx.home, "mcp.json"))}, .mcp.json or .jade/mcp.json`);
185
271
  }
186
- const lines: string[] = [];
272
+ const lines: Text[] = [];
187
273
  let total = 0;
188
274
  for (const c of clients) {
189
- const state = c.status === "connected" ? green("connected") : c.status === "failed" ? red("failed") : yellow(c.status);
275
+ const state = c.status === "connected" ? ok("connected") : c.status === "failed" ? error("failed") : warn(c.status);
190
276
  const info = c.serverInfo?.name ? ` · ${c.serverInfo.name}${c.serverInfo.version ? ` ${c.serverInfo.version}` : ""}` : "";
191
277
  const tokens = serverTokens(c);
192
278
  total += tokens;
193
- lines.push(`${bold(c.name)} ${state} ${dim(`${c.entry.layer} · ${display(ctx.cwd, c.entry.file)} · ${describeServer(c.entry.config)}${info}${tokens ? ` · ≈${tokens} tokens` : ""}`)}`);
194
- if (c.error) lines.push(red(` ${c.error}`));
195
- if (c.tools.length) lines.push(` tools ${c.tools.map((t) => `${t.name}${t.annotations?.readOnlyHint ? dim(" (read)") : ""}`).join(", ")}`);
279
+ lines.push([bold(c.name), " ", state, " ", dim(`${c.entry.layer} · ${display(ctx.cwd, c.entry.file)} · ${describeServer(c.entry.config)}${info}${tokens ? ` · ≈${tokens} tokens` : ""}`)]);
280
+ if (c.error) lines.push(error(` ${c.error}`));
281
+ const tools = c.offered();
282
+ if (c.status === "connecting" && tools.length) lines.push(dim(" (tools from the last time jade connected; calls wait for the server)"));
283
+ if (tools.length) lines.push([" tools ", tools.flatMap((t, k) => [...(k ? [", "] : []), t.name, ...(t.annotations?.readOnlyHint ? [dim(" (read)")] : [])])]);
196
284
  if (c.status === "failed" && c.stderr.length) lines.push(dim(c.stderr.map((l) => ` │ ${clip(l, 200)}`).join("\n")));
197
285
  }
198
286
  if (total) lines.push(dim(`≈${total} tokens in every request (tool definitions and server instructions); remove or disable servers you do not use to save them`));
199
- return lines.join("\n");
287
+ return joinLines(lines);
200
288
  },
201
289
  });
202
290
  // 终端里加、删服务:jade mcp add|remove …(cli@1,核心提供)。查看状态要连接服务,只在 /mcp 里有
@@ -210,11 +298,42 @@ export default definePlugin({
210
298
  const servers = current;
211
299
  if (!servers) return;
212
300
  await servers.start();
213
- for (const tool of mcpTools(servers.clients)) ctx.kernel.tool(tool);
214
- // 嵌套 Agent(例如 jade/task 的子 Agent)只拿声明了只读(readOnlyHint)的工具:另一套实例,和 jade/fs 一样
215
- const shared = ctx.service<Tools>("tools@1");
216
- if (shared) for (const tool of mcpTools(servers.clients, { readOnly: true })) shared.register(tool);
217
301
  const prompts = ctx.service<Prompts>("prompts@1");
218
- for (const text of instructions(servers.clients)) prompts?.add({ text, untrusted: true });
302
+ // 这个会话里注册了的工具、加了的说明;服务变了就按现在的增减(session() 之后注册的从下一轮起生效)
303
+ const tools = new Map<string, { key: string; off: () => void }>();
304
+ const notes = new Map<McpClient, { text: string; off: () => void }>();
305
+ const refused = new Set<string>();
306
+ const sync = () => {
307
+ const want = new Map<string, { key: string; tool: Tool }>();
308
+ for (const c of servers.clients) for (const t of mcpTools([c])) if (!want.has(t.name)) want.set(t.name, { key: toolKey(c, t), tool: t });
309
+ for (const [name, r] of tools) {
310
+ if (want.get(name)?.key === r.key) continue;
311
+ r.off();
312
+ tools.delete(name);
313
+ }
314
+ for (const [name, w] of want) {
315
+ if (tools.has(name)) continue;
316
+ try {
317
+ tools.set(name, { key: w.key, off: ctx.kernel.tool(w.tool) });
318
+ } catch (e) {
319
+ // 和别的插件的工具重名之类:说一次
320
+ if (!refused.has(name)) ctx.report(`tool ${name}: ${errorText(e)}`);
321
+ refused.add(name);
322
+ }
323
+ }
324
+ if (!prompts) return;
325
+ for (const [c, n] of notes) {
326
+ if (servers.clients.includes(c) && instructions(c) === n.text) continue;
327
+ n.off();
328
+ notes.delete(c);
329
+ }
330
+ for (const c of servers.clients) {
331
+ const text = instructions(c);
332
+ if (text && !notes.has(c)) notes.set(c, { text, off: prompts.add({ text, untrusted: true }) });
333
+ }
334
+ };
335
+ sync();
336
+ const unwatch = servers.watch(sync);
337
+ await ctx.effect(() => unwatch);
219
338
  },
220
339
  });
@@ -25,7 +25,7 @@ export const manageUsage = (cmd: string) => `usage: ${cmd} add <name> [--project
25
25
  export const mcpConfigFile = (home: string, cwd: string, project: boolean) => (project ? path.join(cwd, ".jade", "mcp.json") : path.join(home, "mcp.json"));
26
26
 
27
27
  /** add / remove,参数已经切好;返回给用户看的结果,用法错误或失败时抛错。cmd 用在提示里 */
28
- export async function manageMcp(argv: readonly string[], env: { home: string; cwd: string; cmd: string }): Promise<string> {
28
+ export async function manageMcp(argv: readonly string[], env: { home: string; cwd: string; cmd: string; /** jade 正在运行,改完配置马上生效(/mcp) */ live?: boolean }): Promise<string> {
29
29
  const usage = manageUsage(env.cmd);
30
30
  const [sub, ...tail] = argv;
31
31
  if (sub === "-h" || sub === "--help") return usage;
@@ -38,7 +38,9 @@ export async function manageMcp(argv: readonly string[], env: { home: string; cw
38
38
  });
39
39
  return [
40
40
  `added MCP server ${name} to ${display(env.cwd, file)}: ${describeServer(config)}`,
41
- `restart jade to start it${project ? "; jade asks you to confirm it the first time" : ""}`,
41
+ env.live
42
+ ? `jade starts it now${project ? " (after you confirm it)" : ""}; its tools are available from the next turn`
43
+ : `restart jade to start it${project ? "; jade asks you to confirm it the first time" : ""}`,
42
44
  ].join("\n");
43
45
  }
44
46
  if (sub === "remove" || sub === "rm") {
@@ -51,7 +53,7 @@ export async function manageMcp(argv: readonly string[], env: { home: string; cw
51
53
  if (servers[name] === undefined) throw new Error(`${display(env.cwd, file)} has no MCP server named ${name}`);
52
54
  delete servers[name];
53
55
  });
54
- return `removed MCP server ${name} from ${display(env.cwd, file)}; restart jade to stop it`;
56
+ return `removed MCP server ${name} from ${display(env.cwd, file)}; ${env.live ? "jade stops it and its tools go away from the next turn" : "restart jade to stop it"}`;
55
57
  }
56
58
  throw new Error(usage);
57
59
  }