@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
@@ -1,36 +1,32 @@
1
- // jade/keys:快捷键的注册表。前端在输入框有焦点时按下自己不用的键,查这里找到插件的处理函数。
2
1
  import { definePlugin } from "@uncarved/jade-api";
3
- /** "ctrl+<字母>"、"alt+<字母或数字>" 或 "shift+tab" */
4
2
  export const KEY_SPEC = /^(ctrl\+[a-z]|alt\+[a-z0-9]|shift\+tab)$/;
5
- /**
6
- * 前端自己用的键,插件不能用:编辑(ctrl+a/e/d/w/u/k,按词移动的 alt+f/b)、搜索历史(ctrl+r)、重画(ctrl+l)、展开(ctrl+o)、
7
- * 中断和退出(ctrl+c),以及终端里等同于退格、Tab、回车的 ctrl+h/i/j/m
8
- */
9
3
  export const RESERVED_KEYS = new Set([..."acdehijklmoruw"].map((c) => `ctrl+${c}`).concat("alt+f", "alt+b"));
10
- const registry = new Map();
4
+ const registry = new Map;
11
5
  export default definePlugin({
12
- process(ctx) {
13
- ctx.provide("keys@1", (caller) => ({
14
- register(key) {
15
- const spec = String(key?.key ?? "").toLowerCase();
16
- if (!KEY_SPEC.test(spec))
17
- throw new Error(`invalid key ${JSON.stringify(key?.key)}: use ctrl+<letter>, alt+<letter or digit> or shift+tab`);
18
- if (RESERVED_KEYS.has(spec))
19
- throw new Error(`key ${spec} is reserved by the frontend`);
20
- const taken = registry.get(spec);
21
- if (taken)
22
- throw new Error(`key ${spec} is already registered by ${taken.plugin}`);
23
- const entry = { key, plugin: caller.plugin };
24
- registry.set(spec, entry);
25
- const revoke = () => {
26
- if (registry.get(spec) === entry)
27
- registry.delete(spec);
28
- };
29
- caller.onDispose(revoke);
30
- return revoke;
31
- },
32
- get: (spec) => registry.get(spec.toLowerCase()),
33
- list: () => [...registry.entries()].map(([k, { key, plugin }]) => ({ key: k, ...(key.description ? { description: key.description } : {}), plugin })).sort((a, b) => a.key.localeCompare(b.key)),
34
- }));
35
- },
6
+ process(ctx) {
7
+ ctx.provide("keys@1", (caller) => ({
8
+ register(key) {
9
+ const spec = String(key?.key ?? "").toLowerCase();
10
+ if (!KEY_SPEC.test(spec))
11
+ throw new Error(`invalid key ${JSON.stringify(key?.key)}: use ctrl+<letter>, alt+<letter or digit> or shift+tab`);
12
+ if (RESERVED_KEYS.has(spec))
13
+ throw new Error(`key ${spec} is reserved by the frontend`);
14
+ const taken = registry.get(spec);
15
+ if (taken) {
16
+ ctx.report(`key ${spec} from ${caller.plugin} was skipped: ${taken.plugin} already registered it`);
17
+ return () => {};
18
+ }
19
+ const entry = { key, plugin: caller.plugin };
20
+ registry.set(spec, entry);
21
+ const revoke = () => {
22
+ if (registry.get(spec) === entry)
23
+ registry.delete(spec);
24
+ };
25
+ caller.onDispose(revoke);
26
+ return revoke;
27
+ },
28
+ get: (spec) => registry.get(spec.toLowerCase()),
29
+ list: () => [...registry.entries()].map(([k, { key, plugin }]) => ({ key: k, ...key.description ? { description: key.description } : {}, plugin })).sort((a, b) => a.key.localeCompare(b.key))
30
+ }));
31
+ }
36
32
  });
@@ -1,219 +1,291 @@
1
- // jade/mcp:配置的 MCP 服务的工具交给模型(声明只读的也经 tools@1 交给嵌套 Agent);/mcp 查看状态、重连,
2
- // /mcp add、/mcp remove 改配置文件(见 install.ts;终端里是 jade mcp add|remove)。
3
- //
4
- // 服务是进程级的资源:第一个会话打开时读配置、确认项目层的服务、连接,之后各会话共用;进程退出时(进程作用域关闭)全部关掉。
5
- // 一个会话里的工具列表不变(否则提示缓存失效):第一个会话最多等 STARTUP_WAIT_MS,没连上的在后台接着连,
6
- // 它们的工具从下一个会话(/clear)开始提供。不能交互时(-p)只有这一个会话,照常等到每个服务连上或超时。
7
- // 服务进程退出后,下一次调用它的工具时重新连接一次。
8
1
  import path from "node:path";
9
2
  import { definePlugin } from "@uncarved/jade-api";
10
- import { describeServer, loadMcpConfig, McpClient, mcpTools, mcpTrustHash } from "./mcp.js";
3
+ import { describeServer, loadMcpConfig, McpClient, mcpCacheKey, McpToolCache, mcpTools, mcpTrustHash } from "./mcp.js";
11
4
  import { manageMcp, manageUsage } from "./install.js";
12
- import { bold, clip, dim, display, estimateTokens, green, realPath, red, repoRoot, splitArgs, TrustFile, yellow } from "./project.js";
5
+ import { bold, clip, dim, display, error, estimateTokens, lines as joinLines, ok, realPath, repoRoot, splitArgs, warn, withLegacyTrust } from "./project.js";
13
6
  const ID = "jade/mcp";
14
- /** 第一个会话最多等 MCP 服务连接这么久(能交互时),没连上的在后台接着连 */
15
7
  const STARTUP_WAIT_MS = 5000;
16
- const errorText = (err) => (err instanceof Error ? err.message : String(err));
17
- /** 本进程的 MCP 服务 */
8
+ const errorText = (err) => err instanceof Error ? err.message : String(err);
9
+
18
10
  class Servers {
19
- clients = [];
20
- #ctx;
21
- #started;
22
- #closing = false;
23
- constructor(ctx) {
24
- this.#ctx = ctx;
11
+ clients = [];
12
+ #ctx;
13
+ #started;
14
+ #setup;
15
+ #closing = false;
16
+ #watchers = new Set;
17
+ constructor(ctx) {
18
+ this.#ctx = ctx;
19
+ }
20
+ ui() {
21
+ try {
22
+ return this.#ctx.service("ui@1");
23
+ } catch {
24
+ return;
25
25
  }
26
- /** 用到时才取:ui@1 的提供者可能排在后面激活(3.3) */
27
- ui() {
28
- try {
29
- return this.#ctx.service("ui@1");
30
- }
31
- catch {
32
- return undefined;
33
- }
26
+ }
27
+ notify(text, level = "info") {
28
+ if (this.#closing)
29
+ return;
30
+ try {
31
+ this.ui()?.notify(text, level);
32
+ } catch {}
33
+ }
34
+ watch(fn) {
35
+ this.#watchers.add(fn);
36
+ return () => void this.#watchers.delete(fn);
37
+ }
38
+ #changed() {
39
+ if (this.#closing)
40
+ return;
41
+ for (const fn of [...this.#watchers]) {
42
+ try {
43
+ fn();
44
+ } catch {}
34
45
  }
35
- notify(text, level = "info") {
36
- if (this.#closing)
37
- return;
38
- try {
39
- this.ui()?.notify(text, level);
40
- }
41
- catch {
42
- // 前端已经关了
43
- }
46
+ }
47
+ start() {
48
+ this.#started ??= this.#start().catch(async (e) => {
49
+ await Promise.all(this.clients.splice(0).map((c) => c.close().catch(() => {})));
50
+ this.#started = undefined;
51
+ throw e;
52
+ });
53
+ return this.#started;
54
+ }
55
+ async#start() {
56
+ const ctx = this.#ctx;
57
+ const cwd = realPath(ctx.cwd);
58
+ const root = realPath(repoRoot(cwd));
59
+ const setup = { cwd, root, trust: withLegacyTrust(ctx.require("trust@1"), ctx.home), cache: new McpToolCache(ctx.home) };
60
+ const [{ servers, warnings }] = await Promise.all([loadMcpConfig({ home: ctx.home, root, cwd }), setup.cache.load()]);
61
+ this.#setup = setup;
62
+ for (const w of warnings)
63
+ this.notify(`${ID}: ${w}`, "warning");
64
+ const connecting = [];
65
+ for (const entry of servers) {
66
+ const added = await this.#add(entry, setup);
67
+ if (added && !(this.ui()?.interactive && added.client.known))
68
+ connecting.push(added.done);
44
69
  }
45
- /** 第一次调用时读配置、确认、连接;之后等同一次。失败时关掉已经建的连接,下次调用重来,免得一次失败让 MCP 一直用不了 */
46
- start() {
47
- this.#started ??= this.#start().catch(async (e) => {
48
- await Promise.all(this.clients.splice(0).map((c) => c.close().catch(() => { })));
49
- this.#started = undefined;
50
- throw e;
51
- });
52
- return this.#started;
53
- }
54
- async #start() {
55
- const ctx = this.#ctx;
56
- const cwd = realPath(ctx.cwd);
57
- const root = realPath(repoRoot(cwd));
58
- const trust = new TrustFile(path.join(ctx.home, "trust.jsonl"));
59
- const { servers, warnings } = await loadMcpConfig({ home: ctx.home, root, cwd });
60
- for (const w of warnings)
61
- this.notify(`${ID}: ${w}`, "warning");
62
- const ui = this.ui();
63
- const connecting = [];
64
- for (const entry of servers) {
65
- if (entry.config.disabled)
66
- continue;
67
- if (entry.layer === "project") {
68
- // 项目层的服务随仓库分发,启动它就是执行仓库指定的命令:第一次启动前(配置变了也算)请用户确认
69
- const hash = mcpTrustHash(root, entry);
70
- if (!(await trust.has(hash))) {
71
- const ok = ui?.interactive
72
- ? (await ui.select({
73
- title: `MCP server "${entry.name}" from ${display(cwd, entry.file)} is new or changed. Start it?`,
74
- detail: `${entry.config.command !== undefined ? "runs" : "connects to"}: ${describeServer(entry.config)}`,
75
- options: [
76
- { label: "No", value: "no" },
77
- { label: "Yes, start it", value: "yes" },
78
- ],
79
- }, ctx.signal)) === "yes"
80
- : false;
81
- if (!ok) {
82
- this.notify(`[skipped] MCP server ${entry.name}: not confirmed${ui?.interactive ? "" : " (run jade interactively in this directory once to confirm it)"}`, "warning");
83
- continue;
84
- }
85
- await trust.add(hash, entry.file);
86
- }
87
- }
88
- const client = new McpClient(entry, {
89
- cwd,
90
- onDisconnect: (c, why) => this.notify(`MCP server ${c.name} disconnected: ${why}. jade reconnects on its next tool call; /mcp shows details`, "warning"),
91
- });
92
- this.clients.push(client);
93
- connecting.push(client.connect().catch((err) => this.notify(`MCP server ${client.name} is unavailable: ${errorText(err)}`, "warning")));
94
- }
95
- if (this.clients.length === 0)
96
- return;
97
- const all = Promise.all(connecting);
98
- let timer;
99
- if (ui?.interactive)
100
- await Promise.race([all, new Promise((resolve) => (timer = setTimeout(resolve, STARTUP_WAIT_MS)))]);
101
- else
102
- await all;
103
- clearTimeout(timer);
104
- for (const c of this.clients.filter((x) => x.status === "connecting")) {
105
- this.notify(`MCP server ${c.name} is still starting; its tools are available from the next session (/clear) once it is connected`);
106
- void c.connect().then(() => this.notify(`MCP server ${c.name} connected; its tools are available from the next session (/clear)`), () => { });
70
+ if (!this.ui()?.interactive)
71
+ return void await Promise.all(connecting);
72
+ let timer;
73
+ await Promise.race([Promise.all(connecting), new Promise((resolve) => timer = setTimeout(resolve, STARTUP_WAIT_MS))]);
74
+ clearTimeout(timer);
75
+ }
76
+ async#add(entry, setup) {
77
+ if (entry.config.disabled)
78
+ return;
79
+ const ui = this.ui();
80
+ if (entry.layer === "project") {
81
+ const hash = mcpTrustHash(setup.root, entry);
82
+ if (!await setup.trust.has(hash)) {
83
+ const ok = ui?.interactive ? await ui.select({
84
+ title: `MCP server "${entry.name}" from ${display(setup.cwd, entry.file)} is new or changed. Start it?`,
85
+ detail: `${entry.config.command !== undefined ? "runs" : "connects to"}: ${describeServer(entry.config)}`,
86
+ options: [
87
+ { label: "No", value: "no" },
88
+ { label: "Yes, start it", value: "yes" }
89
+ ]
90
+ }, this.#ctx.signal) === "yes" : false;
91
+ if (!ok) {
92
+ this.notify(`[skipped] MCP server ${entry.name}: not confirmed${ui?.interactive ? "" : " (run jade interactively in this directory once to confirm it)"}`, "warning");
93
+ return;
107
94
  }
95
+ await setup.trust.add(hash, entry.file);
96
+ }
108
97
  }
109
- async close() {
110
- this.#closing = true;
111
- await Promise.all(this.clients.map((c) => c.close().catch(() => { })));
112
- }
98
+ const client = new McpClient(entry, {
99
+ cwd: setup.cwd,
100
+ onDisconnect: (c, why) => this.notify(`MCP server ${c.name} disconnected: ${why}. jade reconnects on its next tool call; /mcp shows details`, "warning"),
101
+ onTools: (c) => {
102
+ const now = { tools: c.tools, ...c.instructions ? { instructions: c.instructions } : {} };
103
+ setup.cache.put(entry, now);
104
+ c.known = now;
105
+ this.#changed();
106
+ },
107
+ onFailed: () => this.#changed()
108
+ });
109
+ client.known = setup.cache.get(entry);
110
+ this.clients.push(client);
111
+ const done = client.connect().catch((err) => {
112
+ this.notify(`MCP server ${client.name} is unavailable: ${errorText(err)}`, "warning");
113
+ });
114
+ return { client, done };
115
+ }
116
+ async reload() {
117
+ if (!this.#started)
118
+ return;
119
+ await this.#started.catch(() => {});
120
+ const setup = this.#setup;
121
+ if (!setup)
122
+ return;
123
+ const { servers, warnings } = await loadMcpConfig({ home: this.#ctx.home, root: setup.root, cwd: setup.cwd });
124
+ for (const w of warnings)
125
+ this.notify(`${ID}: ${w}`, "warning");
126
+ const wanted = new Set(servers.filter((e) => !e.config.disabled).map(mcpCacheKey));
127
+ const gone = this.clients.filter((c) => !wanted.has(mcpCacheKey(c.entry)));
128
+ this.clients = this.clients.filter((c) => !gone.includes(c));
129
+ await Promise.all(gone.map((c) => c.close().catch(() => {})));
130
+ const have = new Set(this.clients.map((c) => mcpCacheKey(c.entry)));
131
+ for (const entry of servers)
132
+ if (!have.has(mcpCacheKey(entry)))
133
+ await this.#add(entry, setup);
134
+ this.#changed();
135
+ }
136
+ touch() {
137
+ this.#changed();
138
+ }
139
+ async close() {
140
+ this.#closing = true;
141
+ await Promise.all(this.clients.map((c) => c.close().catch(() => {})));
142
+ }
113
143
  }
114
- /** 服务在初始化时给出的使用说明,放进系统提示词。来自外部,标为不可信 */
115
- function instructions(clients) {
116
- return clients
117
- .filter((c) => c.status === "connected" && c.instructions)
118
- .map((c) => `# Instructions from the MCP server "${c.name}" (about its mcp__${c.name}__* tools)
144
+ function instructions(c) {
145
+ const text = c.offeredInstructions();
146
+ return text ? `# Instructions from the MCP server "${c.name}" (about its mcp__${c.name}__* tools)
119
147
 
120
- ${c.instructions}`);
148
+ ${text}` : undefined;
121
149
  }
122
- /** 一个服务每次请求都带着的大约多少 token:发给模型的工具定义,加上它的使用说明。没连上时为 0 */
123
150
  function serverTokens(c) {
124
- const tools = mcpTools([c]).reduce((n, t) => n + estimateTokens(JSON.stringify({ name: t.name, description: t.description, input_schema: t.inputSchema })), 0);
125
- return tools + instructions([c]).reduce((n, text) => n + estimateTokens(text), 0);
151
+ const tools = mcpTools([c]).reduce((n, t) => n + estimateTokens(JSON.stringify({ name: t.name, description: t.description, input_schema: t.inputSchema })), 0);
152
+ return tools + estimateTokens(instructions(c) ?? "");
126
153
  }
127
- /** 当前进程的服务;process() 里创建,session() 里用 */
154
+ const serial = new WeakMap;
155
+ let nextSerial = 1;
156
+ const serialOf = (c) => serial.get(c) ?? (serial.set(c, nextSerial), nextSerial++);
157
+ const toolKey = (c, t) => JSON.stringify([serialOf(c), t.description, t.inputSchema, t.effect, t.concurrency, t.idempotent]);
128
158
  let current;
129
159
  export default definePlugin({
130
- async process(ctx) {
131
- const servers = new Servers(ctx);
132
- current = servers;
133
- // 后台资源:进程作用域关闭时关掉所有服务(服务本身到第一个会话打开时才启动)
134
- await ctx.effect(() => () => servers.close());
135
- ctx.service("commands@1")?.register({
136
- name: "mcp",
137
- args: "[reconnect <name> | add <name> … | remove <name>] [--project]",
138
- description: "MCP servers: status and tools; add or remove one",
139
- instant: true,
140
- async run(args) {
141
- let words;
142
- try {
143
- words = splitArgs(args);
144
- }
145
- catch (e) {
146
- return red(errorText(e));
147
- }
148
- // 只改配置文件,不用先连接
149
- if (words[0] === "add" || words[0] === "remove" || words[0] === "rm") {
150
- try {
151
- return await manageMcp(words, { home: ctx.home, cwd: ctx.cwd, cmd: "/mcp" });
152
- }
153
- catch (e) {
154
- return red(errorText(e));
155
- }
156
- }
157
- await servers.start();
158
- const clients = servers.clients;
159
- if (words[0] === "reconnect") {
160
- const c = clients.find((x) => x.name === words[1]);
161
- if (!c)
162
- return red(`usage: /mcp reconnect <name>; servers: ${clients.map((x) => x.name).join(", ") || "(none)"}`);
163
- await c.close();
164
- try {
165
- await c.connect();
166
- return green(`${c.name} connected, ${c.tools.length} tools; new tools are available from the next session (/clear)`);
167
- }
168
- catch (err) {
169
- return red(`${c.name}: ${errorText(err)}`);
170
- }
171
- }
172
- if (words.length > 0)
173
- return red(`usage: /mcp [reconnect <name>]\n${manageUsage("/mcp")}`);
174
- if (clients.length === 0) {
175
- 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`);
176
- }
177
- const lines = [];
178
- let total = 0;
179
- for (const c of clients) {
180
- const state = c.status === "connected" ? green("connected") : c.status === "failed" ? red("failed") : yellow(c.status);
181
- const info = c.serverInfo?.name ? ` · ${c.serverInfo.name}${c.serverInfo.version ? ` ${c.serverInfo.version}` : ""}` : "";
182
- const tokens = serverTokens(c);
183
- total += tokens;
184
- lines.push(`${bold(c.name)} ${state} ${dim(`${c.entry.layer} · ${display(ctx.cwd, c.entry.file)} · ${describeServer(c.entry.config)}${info}${tokens ? ` · ≈${tokens} tokens` : ""}`)}`);
185
- if (c.error)
186
- lines.push(red(` ${c.error}`));
187
- if (c.tools.length)
188
- lines.push(` tools ${c.tools.map((t) => `${t.name}${t.annotations?.readOnlyHint ? dim(" (read)") : ""}`).join(", ")}`);
189
- if (c.status === "failed" && c.stderr.length)
190
- lines.push(dim(c.stderr.map((l) => ` │ ${clip(l, 200)}`).join("\n")));
191
- }
192
- if (total)
193
- lines.push(dim(`≈${total} tokens in every request (tool definitions and server instructions); remove or disable servers you do not use to save them`));
194
- return lines.join("\n");
195
- },
196
- });
197
- // 终端里加、删服务:jade mcp add|remove …(cli@1,核心提供)。查看状态要连接服务,只在 /mcp 里有
198
- ctx.service("cli@1")?.register({
199
- name: "mcp",
200
- run: (argv) => manageMcp(argv, { home: ctx.home, cwd: ctx.cwd, cmd: "jade mcp" }),
201
- });
202
- },
203
- async session(ctx) {
204
- const servers = current;
205
- if (!servers)
206
- return;
160
+ async process(ctx) {
161
+ const servers = new Servers(ctx);
162
+ current = servers;
163
+ await ctx.effect(() => () => servers.close());
164
+ ctx.service("commands@1")?.register({
165
+ name: "mcp",
166
+ args: "[reconnect <name> | add <name> … | remove <name>] [--project]",
167
+ description: "MCP servers: status and tools; add or remove one",
168
+ instant: true,
169
+ async run(args) {
170
+ let words;
171
+ try {
172
+ words = splitArgs(args);
173
+ } catch (e) {
174
+ return error(errorText(e));
175
+ }
176
+ if (words[0] === "add" || words[0] === "remove" || words[0] === "rm") {
177
+ let done;
178
+ try {
179
+ done = await manageMcp(words, { home: ctx.home, cwd: ctx.cwd, cmd: "/mcp", live: true });
180
+ } catch (e) {
181
+ return error(errorText(e));
182
+ }
183
+ try {
184
+ await servers.reload();
185
+ } catch (e) {
186
+ return [done, `
187
+ `, error(`could not apply the change now: ${errorText(e)}; restart jade to apply it`)];
188
+ }
189
+ return done;
190
+ }
207
191
  await servers.start();
208
- for (const tool of mcpTools(servers.clients))
209
- ctx.kernel.tool(tool);
210
- // 嵌套 Agent(例如 jade/task 的子 Agent)只拿声明了只读(readOnlyHint)的工具:另一套实例,和 jade/fs 一样
211
- const shared = ctx.service("tools@1");
212
- if (shared)
213
- for (const tool of mcpTools(servers.clients, { readOnly: true }))
214
- shared.register(tool);
215
- const prompts = ctx.service("prompts@1");
216
- for (const text of instructions(servers.clients))
217
- prompts?.add({ text, untrusted: true });
218
- },
192
+ const clients = servers.clients;
193
+ if (words[0] === "reconnect") {
194
+ const c = clients.find((x) => x.name === words[1]);
195
+ if (!c)
196
+ return error(`usage: /mcp reconnect <name>; servers: ${clients.map((x) => x.name).join(", ") || "(none)"}`);
197
+ await c.close();
198
+ try {
199
+ await c.connect();
200
+ return ok(`${c.name} connected, ${c.tools.length} tools; changes to its tools apply from the next turn`);
201
+ } catch (err) {
202
+ servers.touch();
203
+ return error(`${c.name}: ${errorText(err)}`);
204
+ }
205
+ }
206
+ if (words.length > 0)
207
+ return error(`usage: /mcp [reconnect <name>]
208
+ ${manageUsage("/mcp")}`);
209
+ if (clients.length === 0) {
210
+ 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`);
211
+ }
212
+ const lines = [];
213
+ let total = 0;
214
+ for (const c of clients) {
215
+ const state = c.status === "connected" ? ok("connected") : c.status === "failed" ? error("failed") : warn(c.status);
216
+ const info = c.serverInfo?.name ? ` · ${c.serverInfo.name}${c.serverInfo.version ? ` ${c.serverInfo.version}` : ""}` : "";
217
+ const tokens = serverTokens(c);
218
+ total += tokens;
219
+ lines.push([bold(c.name), " ", state, " ", dim(`${c.entry.layer} · ${display(ctx.cwd, c.entry.file)} · ${describeServer(c.entry.config)}${info}${tokens ? ` · ≈${tokens} tokens` : ""}`)]);
220
+ if (c.error)
221
+ lines.push(error(` ${c.error}`));
222
+ const tools = c.offered();
223
+ if (c.status === "connecting" && tools.length)
224
+ lines.push(dim(" (tools from the last time jade connected; calls wait for the server)"));
225
+ if (tools.length)
226
+ lines.push([" tools ", tools.flatMap((t, k) => [...k ? [", "] : [], t.name, ...t.annotations?.readOnlyHint ? [dim(" (read)")] : []])]);
227
+ if (c.status === "failed" && c.stderr.length)
228
+ lines.push(dim(c.stderr.map((l) => ` │ ${clip(l, 200)}`).join(`
229
+ `)));
230
+ }
231
+ if (total)
232
+ lines.push(dim(`≈${total} tokens in every request (tool definitions and server instructions); remove or disable servers you do not use to save them`));
233
+ return joinLines(lines);
234
+ }
235
+ });
236
+ ctx.service("cli@1")?.register({
237
+ name: "mcp",
238
+ run: (argv) => manageMcp(argv, { home: ctx.home, cwd: ctx.cwd, cmd: "jade mcp" })
239
+ });
240
+ },
241
+ async session(ctx) {
242
+ const servers = current;
243
+ if (!servers)
244
+ return;
245
+ await servers.start();
246
+ const prompts = ctx.service("prompts@1");
247
+ const tools = new Map;
248
+ const notes = new Map;
249
+ const refused = new Set;
250
+ const sync = () => {
251
+ const want = new Map;
252
+ for (const c of servers.clients)
253
+ for (const t of mcpTools([c]))
254
+ if (!want.has(t.name))
255
+ want.set(t.name, { key: toolKey(c, t), tool: t });
256
+ for (const [name, r] of tools) {
257
+ if (want.get(name)?.key === r.key)
258
+ continue;
259
+ r.off();
260
+ tools.delete(name);
261
+ }
262
+ for (const [name, w] of want) {
263
+ if (tools.has(name))
264
+ continue;
265
+ try {
266
+ tools.set(name, { key: w.key, off: ctx.kernel.tool(w.tool) });
267
+ } catch (e) {
268
+ if (!refused.has(name))
269
+ ctx.report(`tool ${name}: ${errorText(e)}`);
270
+ refused.add(name);
271
+ }
272
+ }
273
+ if (!prompts)
274
+ return;
275
+ for (const [c, n] of notes) {
276
+ if (servers.clients.includes(c) && instructions(c) === n.text)
277
+ continue;
278
+ n.off();
279
+ notes.delete(c);
280
+ }
281
+ for (const c of servers.clients) {
282
+ const text = instructions(c);
283
+ if (text && !notes.has(c))
284
+ notes.set(c, { text, off: prompts.add({ text, untrusted: true }) });
285
+ }
286
+ };
287
+ sync();
288
+ const unwatch = servers.watch(sync);
289
+ await ctx.effect(() => unwatch);
290
+ }
219
291
  });