@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
@@ -1,30 +1,43 @@
1
- // jade/mcp:配置的 MCP 服务的工具交给模型(声明只读的也经 task@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, Task } 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)只拿声明了只读(readOnlyHint)的工具:另一套实例,和 jade/fs 一样
215
- const task = ctx.service<Task>("task@1");
216
- if (task) for (const tool of mcpTools(servers.clients, { readOnly: true })) task.tool(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
  }