@uncarved/jade 0.0.0-stage → 0.1.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 (164) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +187 -2
  3. package/bin/jade.js +20 -0
  4. package/dist/commands.d.ts +30 -0
  5. package/dist/commands.js +106 -0
  6. package/dist/commands.js.map +1 -0
  7. package/dist/config.d.ts +34 -0
  8. package/dist/config.js +130 -0
  9. package/dist/config.js.map +1 -0
  10. package/dist/context.d.ts +17 -0
  11. package/dist/context.js +53 -0
  12. package/dist/context.js.map +1 -0
  13. package/dist/distro.d.ts +93 -0
  14. package/dist/distro.js +277 -0
  15. package/dist/distro.js.map +1 -0
  16. package/dist/history.d.ts +10 -0
  17. package/dist/history.js +47 -0
  18. package/dist/history.js.map +1 -0
  19. package/dist/index.d.ts +26 -0
  20. package/dist/index.js +27 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/main.d.ts +2 -0
  23. package/dist/main.js +1124 -0
  24. package/dist/main.js.map +1 -0
  25. package/dist/mcp.d.ts +114 -0
  26. package/dist/mcp.js +640 -0
  27. package/dist/mcp.js.map +1 -0
  28. package/dist/memory.d.ts +19 -0
  29. package/dist/memory.js +129 -0
  30. package/dist/memory.js.map +1 -0
  31. package/dist/mentions.d.ts +35 -0
  32. package/dist/mentions.js +130 -0
  33. package/dist/mentions.js.map +1 -0
  34. package/dist/plugin-cli.d.ts +16 -0
  35. package/dist/plugin-cli.js +251 -0
  36. package/dist/plugin-cli.js.map +1 -0
  37. package/dist/plugins/budget.d.ts +9 -0
  38. package/dist/plugins/budget.js +30 -0
  39. package/dist/plugins/budget.js.map +1 -0
  40. package/dist/plugins/builtins.d.ts +10 -0
  41. package/dist/plugins/builtins.js +22 -0
  42. package/dist/plugins/builtins.js.map +1 -0
  43. package/dist/plugins/checks.d.ts +70 -0
  44. package/dist/plugins/checks.js +335 -0
  45. package/dist/plugins/checks.js.map +1 -0
  46. package/dist/plugins/compact.d.ts +26 -0
  47. package/dist/plugins/compact.js +216 -0
  48. package/dist/plugins/compact.js.map +1 -0
  49. package/dist/plugins/core.d.ts +42 -0
  50. package/dist/plugins/core.js +190 -0
  51. package/dist/plugins/core.js.map +1 -0
  52. package/dist/plugins/install.d.ts +68 -0
  53. package/dist/plugins/install.js +377 -0
  54. package/dist/plugins/install.js.map +1 -0
  55. package/dist/plugins/loader.d.ts +182 -0
  56. package/dist/plugins/loader.js +253 -0
  57. package/dist/plugins/loader.js.map +1 -0
  58. package/dist/plugins/policy.d.ts +64 -0
  59. package/dist/plugins/policy.js +269 -0
  60. package/dist/plugins/policy.js.map +1 -0
  61. package/dist/plugins/prompts.d.ts +28 -0
  62. package/dist/plugins/prompts.js +169 -0
  63. package/dist/plugins/prompts.js.map +1 -0
  64. package/dist/plugins/repeats.d.ts +9 -0
  65. package/dist/plugins/repeats.js +55 -0
  66. package/dist/plugins/repeats.js.map +1 -0
  67. package/dist/plugins/schema.d.ts +2 -0
  68. package/dist/plugins/schema.js +64 -0
  69. package/dist/plugins/schema.js.map +1 -0
  70. package/dist/provider.d.ts +52 -0
  71. package/dist/provider.js +187 -0
  72. package/dist/provider.js.map +1 -0
  73. package/dist/sessions.d.ts +13 -0
  74. package/dist/sessions.js +40 -0
  75. package/dist/sessions.js.map +1 -0
  76. package/dist/skills.d.ts +37 -0
  77. package/dist/skills.js +179 -0
  78. package/dist/skills.js.map +1 -0
  79. package/dist/sys.d.ts +44 -0
  80. package/dist/sys.js +115 -0
  81. package/dist/sys.js.map +1 -0
  82. package/dist/tools/checkpoint.d.ts +43 -0
  83. package/dist/tools/checkpoint.js +144 -0
  84. package/dist/tools/checkpoint.js.map +1 -0
  85. package/dist/tools/fs.d.ts +35 -0
  86. package/dist/tools/fs.js +417 -0
  87. package/dist/tools/fs.js.map +1 -0
  88. package/dist/tools/grep.d.ts +6 -0
  89. package/dist/tools/grep.js +243 -0
  90. package/dist/tools/grep.js.map +1 -0
  91. package/dist/tools/shell.d.ts +49 -0
  92. package/dist/tools/shell.js +295 -0
  93. package/dist/tools/shell.js.map +1 -0
  94. package/dist/tools/task.d.ts +31 -0
  95. package/dist/tools/task.js +86 -0
  96. package/dist/tools/task.js.map +1 -0
  97. package/dist/tools/todo.d.ts +10 -0
  98. package/dist/tools/todo.js +55 -0
  99. package/dist/tools/todo.js.map +1 -0
  100. package/dist/tools/web.d.ts +23 -0
  101. package/dist/tools/web.js +426 -0
  102. package/dist/tools/web.js.map +1 -0
  103. package/dist/ui/configure.d.ts +20 -0
  104. package/dist/ui/configure.js +285 -0
  105. package/dist/ui/configure.js.map +1 -0
  106. package/dist/ui/diff.d.ts +20 -0
  107. package/dist/ui/diff.js +142 -0
  108. package/dist/ui/diff.js.map +1 -0
  109. package/dist/ui/editor.d.ts +33 -0
  110. package/dist/ui/editor.js +128 -0
  111. package/dist/ui/editor.js.map +1 -0
  112. package/dist/ui/render.d.ts +13 -0
  113. package/dist/ui/render.js +84 -0
  114. package/dist/ui/render.js.map +1 -0
  115. package/dist/ui/screen.d.ts +90 -0
  116. package/dist/ui/screen.js +105 -0
  117. package/dist/ui/screen.js.map +1 -0
  118. package/dist/ui/transcript.d.ts +33 -0
  119. package/dist/ui/transcript.js +336 -0
  120. package/dist/ui/transcript.js.map +1 -0
  121. package/dist/ui/tui.d.ts +28 -0
  122. package/dist/ui/tui.js +884 -0
  123. package/dist/ui/tui.js.map +1 -0
  124. package/package.json +59 -4
  125. package/src/commands.ts +120 -0
  126. package/src/config.ts +146 -0
  127. package/src/context.ts +64 -0
  128. package/src/distro.ts +358 -0
  129. package/src/history.ts +55 -0
  130. package/src/index.ts +26 -0
  131. package/src/main.ts +1180 -0
  132. package/src/mcp.ts +693 -0
  133. package/src/memory.ts +135 -0
  134. package/src/mentions.ts +135 -0
  135. package/src/plugin-cli.ts +239 -0
  136. package/src/plugins/budget.ts +37 -0
  137. package/src/plugins/builtins.ts +31 -0
  138. package/src/plugins/checks.ts +390 -0
  139. package/src/plugins/compact.ts +257 -0
  140. package/src/plugins/core.ts +217 -0
  141. package/src/plugins/install.ts +429 -0
  142. package/src/plugins/loader.ts +386 -0
  143. package/src/plugins/policy.ts +304 -0
  144. package/src/plugins/prompts.ts +200 -0
  145. package/src/plugins/repeats.ts +62 -0
  146. package/src/plugins/schema.ts +67 -0
  147. package/src/provider.ts +208 -0
  148. package/src/sessions.ts +48 -0
  149. package/src/skills.ts +197 -0
  150. package/src/sys.ts +133 -0
  151. package/src/tools/checkpoint.ts +164 -0
  152. package/src/tools/fs.ts +432 -0
  153. package/src/tools/grep.ts +268 -0
  154. package/src/tools/shell.ts +339 -0
  155. package/src/tools/task.ts +105 -0
  156. package/src/tools/todo.ts +67 -0
  157. package/src/tools/web.ts +451 -0
  158. package/src/ui/configure.ts +310 -0
  159. package/src/ui/diff.ts +136 -0
  160. package/src/ui/editor.ts +136 -0
  161. package/src/ui/render.ts +74 -0
  162. package/src/ui/screen.ts +164 -0
  163. package/src/ui/transcript.ts +345 -0
  164. package/src/ui/tui.tsx +1374 -0
package/dist/mcp.js ADDED
@@ -0,0 +1,640 @@
1
+ // MCP(Model Context Protocol)客户端:连接 MCP 服务,把它们的工具变成 jade 的工具。
2
+ //
3
+ // 配置兼容 Claude Code 的 .mcp.json:{ "mcpServers": { "<name>": { command, args, env } | { type: "http", url, headers } } }。
4
+ // 读取顺序(同名时后面的覆盖前面的):
5
+ // $JADE_HOME/mcp.json(用户层)、<仓库根目录>/.mcp.json、仓库根目录到工作目录每一级的 .jade/mcp.json(项目层)。
6
+ // 项目层的服务随仓库分发,启动它就是执行仓库指定的命令,所以第一次启动前要用户确认(按配置内容记录)。
7
+ //
8
+ // 传输:stdio(一行一条 JSON-RPC 消息)和 Streamable HTTP(POST,回复是 JSON 或 SSE)。旧的 HTTP+SSE 传输不支持。
9
+ // 服务在 jade 启动时连接,各会话共用;进程退出后,下一次调用工具时重新连接一次。
10
+ import { spawn } from "node:child_process";
11
+ import { createHash } from "node:crypto";
12
+ import { statSync } from "node:fs";
13
+ import { readFile } from "node:fs/promises";
14
+ import path from "node:path";
15
+ import { projectDirs } from "./commands.js";
16
+ import { VERSION } from "./sys.js";
17
+ export const PROTOCOL_VERSION = "2025-06-18";
18
+ const CLIENT_INFO = { name: "jade", version: VERSION };
19
+ /** 一次工具调用结果里文本的上限,超过时保留开头 */
20
+ const MAX_RESULT_CHARS = 60_000;
21
+ const STDERR_LINES = 20;
22
+ /** 工具名的上限:OpenAI 的接口要求不超过 64 个字符 */
23
+ const MAX_TOOL_NAME = 64;
24
+ // ---------- 配置 ----------
25
+ /** 用户层在前,项目层从仓库根目录往下;同名的后面覆盖前面 */
26
+ export async function loadMcpConfig(opts) {
27
+ const base = opts.env ?? process.env;
28
+ const files = [
29
+ ...(opts.plugins ?? []),
30
+ { file: path.join(opts.home, "mcp.json"), layer: "user" },
31
+ { file: path.join(opts.root, ".mcp.json"), layer: "project" },
32
+ ...projectDirs(opts.root, opts.cwd).map((d) => ({ file: path.join(d, ".jade", "mcp.json"), layer: "project" })),
33
+ ];
34
+ const out = new Map();
35
+ const warnings = [];
36
+ for (const { file, layer, plugin, dir, servers: inline } of files) {
37
+ const env = dir ? { ...base, JADE_PLUGIN_DIR: dir, CLAUDE_PLUGIN_ROOT: dir } : base;
38
+ let servers = inline;
39
+ if (servers === undefined) {
40
+ let text;
41
+ try {
42
+ text = await readFile(file, "utf8");
43
+ }
44
+ catch {
45
+ continue;
46
+ }
47
+ let json;
48
+ try {
49
+ json = JSON.parse(text);
50
+ }
51
+ catch (err) {
52
+ warnings.push(`${file}: ${err instanceof Error ? err.message : String(err)}`);
53
+ continue;
54
+ }
55
+ servers = json?.mcpServers;
56
+ }
57
+ if (typeof servers !== "object" || servers === null || Array.isArray(servers)) {
58
+ warnings.push(`${file}: expected { "mcpServers": { ... } }`);
59
+ continue;
60
+ }
61
+ for (const [name, raw] of Object.entries(servers)) {
62
+ const problem = checkConfig(name, raw);
63
+ if (problem) {
64
+ warnings.push(`${file}: MCP server ${JSON.stringify(name)}: ${problem}`);
65
+ continue;
66
+ }
67
+ const missing = [];
68
+ const config = expandConfig(raw, env, missing);
69
+ if (missing.length) {
70
+ warnings.push(`${file}: MCP server ${name} is skipped: environment variable ${[...new Set(missing)].join(", ")} is not set`);
71
+ out.delete(name);
72
+ continue;
73
+ }
74
+ // 地址里可以有 ${VAR},展开之后再检查格式
75
+ if (config.command === undefined && !/^https?:\/\//.test(config.url)) {
76
+ warnings.push(`${file}: MCP server ${name}: "url" must start with http:// or https://`);
77
+ out.delete(name);
78
+ continue;
79
+ }
80
+ if (config.cwd && !path.isAbsolute(config.cwd))
81
+ config.cwd = path.resolve(path.dirname(file), config.cwd);
82
+ out.set(name, { name, layer, file, config, ...(plugin ? { plugin } : {}) });
83
+ }
84
+ }
85
+ return { servers: [...out.values()], warnings };
86
+ }
87
+ const SERVER_NAME = /^[A-Za-z0-9_.-]+$/;
88
+ function checkConfig(name, raw) {
89
+ if (!SERVER_NAME.test(name))
90
+ return "the name may only contain letters, digits, '.', '_' and '-'";
91
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
92
+ return "must be an object";
93
+ const c = raw;
94
+ const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
95
+ const stringMap = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string");
96
+ if (c.type === "sse")
97
+ return 'the legacy "sse" transport is not supported; use a streamable HTTP endpoint ("type": "http")';
98
+ if (c.type !== undefined && !["stdio", "http", "streamable-http"].includes(c.type))
99
+ return `unknown type ${JSON.stringify(c.type)}`;
100
+ const http = c.type === "http" || c.type === "streamable-http" || (c.type === undefined && c.command === undefined);
101
+ if (http) {
102
+ if (typeof c.url !== "string" || !c.url)
103
+ return 'needs "command" (stdio) or an http(s) "url"';
104
+ if (c.headers !== undefined && !stringMap(c.headers))
105
+ return '"headers" must map names to strings';
106
+ }
107
+ else {
108
+ if (typeof c.command !== "string" || !c.command)
109
+ return '"command" must be a non-empty string';
110
+ if (c.args !== undefined && !strings(c.args))
111
+ return '"args" must be an array of strings';
112
+ if (c.env !== undefined && !stringMap(c.env))
113
+ return '"env" must map names to strings';
114
+ if (c.cwd !== undefined && typeof c.cwd !== "string")
115
+ return '"cwd" must be a string';
116
+ }
117
+ for (const k of ["startupTimeoutMs", "toolTimeoutMs"]) {
118
+ if (c[k] !== undefined && !(typeof c[k] === "number" && c[k] > 0))
119
+ return `"${k}" must be a positive number`;
120
+ }
121
+ return undefined;
122
+ }
123
+ /** ${VAR} 和 ${VAR:-默认值},和 Claude Code 一样;没有设置又没有默认值的变量记进 missing */
124
+ export function expandEnv(text, env, missing) {
125
+ return text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_, name, fallback) => {
126
+ const v = env[name];
127
+ if (v !== undefined && v !== "")
128
+ return v;
129
+ if (fallback !== undefined)
130
+ return fallback;
131
+ missing.push(name);
132
+ return "";
133
+ });
134
+ }
135
+ function expandConfig(c, env, missing) {
136
+ const s = (v) => expandEnv(v, env, missing);
137
+ const map = (m) => (m ? Object.fromEntries(Object.entries(m).map(([k, v]) => [k, s(v)])) : undefined);
138
+ return {
139
+ ...c,
140
+ command: c.command === undefined ? undefined : s(c.command),
141
+ args: c.args?.map(s),
142
+ env: map(c.env),
143
+ cwd: c.cwd === undefined ? undefined : s(c.cwd),
144
+ url: c.url === undefined ? undefined : s(c.url),
145
+ headers: map(c.headers),
146
+ };
147
+ }
148
+ /** 项目层服务的确认记录:同一个仓库里同样的配置只问一次。配置变了(包括展开后的环境变量)就要重新确认 */
149
+ export function mcpTrustHash(root, entry) {
150
+ const { command, args, env, cwd, url, headers, type } = entry.config;
151
+ // 请求头里通常是密钥,只记名字
152
+ const spec = JSON.stringify({ type, command, args, env, cwd, url, headers: headers ? Object.keys(headers).sort() : undefined });
153
+ return createHash("sha256").update(`jade-mcp\0${root}\0${entry.name}\0${spec}`).digest("hex");
154
+ }
155
+ /** 给用户看的启动方式 */
156
+ export function describeServer(c) {
157
+ return c.command !== undefined ? [c.command, ...(c.args ?? [])].join(" ") : `${c.url}`;
158
+ }
159
+ export class McpError extends Error {
160
+ code;
161
+ constructor(message, code) {
162
+ super(message);
163
+ this.name = "McpError";
164
+ this.code = code;
165
+ }
166
+ }
167
+ /** 一个 MCP 服务的连接 */
168
+ export class McpClient {
169
+ entry;
170
+ status = "disconnected";
171
+ error;
172
+ serverInfo;
173
+ instructions;
174
+ tools = [];
175
+ stderr = [];
176
+ #opts;
177
+ #transport;
178
+ #connecting;
179
+ #closing = false;
180
+ constructor(entry, opts) {
181
+ this.entry = entry;
182
+ this.#opts = opts;
183
+ }
184
+ get name() {
185
+ return this.entry.name;
186
+ }
187
+ /** 启动、初始化并列出工具;已经在连接时等同一次连接 */
188
+ connect() {
189
+ this.#connecting ??= this.#connect().finally(() => (this.#connecting = undefined));
190
+ return this.#connecting;
191
+ }
192
+ async #connect() {
193
+ this.status = "connecting";
194
+ this.error = undefined;
195
+ this.#closing = false;
196
+ const c = this.entry.config;
197
+ const signal = AbortSignal.timeout(c.startupTimeoutMs ?? 30_000);
198
+ try {
199
+ const t = c.command !== undefined ? stdioTransport(c, this.#opts.cwd, this.stderr) : httpTransport(c, this.#opts.fetch ?? fetch);
200
+ this.#transport = t;
201
+ void t.closed.then((why) => {
202
+ if (this.#transport !== t)
203
+ return;
204
+ this.#transport = undefined;
205
+ if (this.#closing)
206
+ return;
207
+ this.status = "failed";
208
+ this.error = why;
209
+ this.#opts.onDisconnect?.(this, why);
210
+ });
211
+ const init = (await t.request("initialize", { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: CLIENT_INFO }, signal));
212
+ this.serverInfo = init?.serverInfo;
213
+ this.instructions = typeof init?.instructions === "string" && init.instructions.trim() ? init.instructions.trim() : undefined;
214
+ await t.notify("notifications/initialized");
215
+ this.tools = init?.capabilities?.tools === undefined ? [] : await this.#listTools(t, signal);
216
+ this.status = "connected";
217
+ }
218
+ catch (err) {
219
+ const why = signal.aborted ? `did not finish starting within ${(c.startupTimeoutMs ?? 30_000) / 1000}s` : errorText(err);
220
+ this.status = "failed";
221
+ this.error = why;
222
+ await this.close().catch(() => { });
223
+ this.status = "failed";
224
+ throw new McpError(why);
225
+ }
226
+ }
227
+ async #listTools(t, signal) {
228
+ const tools = [];
229
+ let cursor;
230
+ for (let page = 0; page < 100; page++) {
231
+ const r = (await t.request("tools/list", cursor ? { cursor } : undefined, signal));
232
+ for (const tool of r?.tools ?? [])
233
+ if (tool && typeof tool.name === "string")
234
+ tools.push(tool);
235
+ cursor = typeof r?.nextCursor === "string" && r.nextCursor ? r.nextCursor : undefined;
236
+ if (!cursor)
237
+ break;
238
+ }
239
+ return tools;
240
+ }
241
+ /** 调用工具。连接断了先重连一次 */
242
+ async callTool(name, args, signal) {
243
+ if (this.status !== "connected" || !this.#transport)
244
+ await this.connect();
245
+ const t = this.#transport;
246
+ const limit = AbortSignal.timeout(this.entry.config.toolTimeoutMs ?? 600_000);
247
+ const both = AbortSignal.any([signal, limit]);
248
+ try {
249
+ return (await t.request("tools/call", { name, arguments: args ?? {} }, both));
250
+ }
251
+ catch (err) {
252
+ if (limit.aborted && !signal.aborted)
253
+ throw new McpError(`timed out after ${(this.entry.config.toolTimeoutMs ?? 600_000) / 1000}s`);
254
+ throw err;
255
+ }
256
+ }
257
+ async close() {
258
+ this.#closing = true;
259
+ const t = this.#transport;
260
+ this.#transport = undefined;
261
+ if (this.status !== "failed")
262
+ this.status = "disconnected";
263
+ await t?.close();
264
+ }
265
+ }
266
+ // ---------- 传输:stdio ----------
267
+ function stdioTransport(c, cwd, stderr) {
268
+ const { file, args, verbatim } = resolveCommand(c.command, c.args ?? []);
269
+ const child = spawn(file, args, {
270
+ cwd: c.cwd ?? cwd,
271
+ env: mergeEnv(c.env),
272
+ stdio: ["pipe", "pipe", "pipe"],
273
+ windowsHide: true,
274
+ windowsVerbatimArguments: verbatim,
275
+ detached: process.platform !== "win32",
276
+ });
277
+ const rpc = new Rpc((msg) => {
278
+ if (child.stdin?.writable)
279
+ child.stdin.write(JSON.stringify(msg) + "\n");
280
+ });
281
+ let partialErr = "";
282
+ child.stderr.setEncoding("utf8");
283
+ child.stderr.on("data", (text) => {
284
+ const lines = (partialErr + text).split(/\r?\n/);
285
+ partialErr = lines.pop() ?? "";
286
+ stderr.push(...lines.filter((l) => l.trim()));
287
+ stderr.splice(0, Math.max(0, stderr.length - STDERR_LINES));
288
+ });
289
+ let buf = "";
290
+ child.stdout.setEncoding("utf8");
291
+ child.stdout.on("data", (text) => {
292
+ buf += text;
293
+ let i;
294
+ while ((i = buf.indexOf("\n")) >= 0) {
295
+ const line = buf.slice(0, i).trim();
296
+ buf = buf.slice(i + 1);
297
+ if (!line)
298
+ continue;
299
+ try {
300
+ rpc.receive(JSON.parse(line));
301
+ }
302
+ catch {
303
+ // 有的服务往 stdout 打日志;不是 JSON 的行忽略
304
+ }
305
+ }
306
+ });
307
+ child.stdin.on("error", () => { });
308
+ const closed = new Promise((resolve) => {
309
+ child.on("error", (err) => resolve(`could not start ${c.command}: ${err.message}`));
310
+ child.on("close", (code, sig) => resolve(`exited (${sig ?? `code ${code}`})${stderr.length ? `: ${stderr.at(-1)}` : ""}`));
311
+ });
312
+ void closed.then((why) => rpc.fail(new McpError(`server ${why}`)));
313
+ return {
314
+ request: (method, params, signal) => rpc.request(method, params, signal),
315
+ notify: async (method, params) => rpc.send({ jsonrpc: "2.0", method, ...(params ? { params } : {}) }),
316
+ closed,
317
+ async close() {
318
+ child.stdin?.end();
319
+ const done = await Promise.race([closed.then(() => true), new Promise((r) => setTimeout(() => r(false), 2_000).unref())]);
320
+ if (!done)
321
+ killTree(child);
322
+ },
323
+ };
324
+ }
325
+ /**
326
+ * Windows 上 npx、npm 这类命令是 .cmd 脚本,不经过 shell 无法启动:找到它时改用 cmd.exe /c 启动。
327
+ * MCP 的配置里大多写的是 "command": "npx"
328
+ */
329
+ function resolveCommand(command, args) {
330
+ if (process.platform !== "win32" || /[\\/]/.test(command) || /\.(exe|com)$/i.test(command))
331
+ return { file: command, args, verbatim: false };
332
+ const exts = /\.(cmd|bat)$/i.test(command) ? [""] : (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";");
333
+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
334
+ if (!dir)
335
+ continue;
336
+ for (const ext of exts) {
337
+ const full = path.join(dir, command + ext.toLowerCase());
338
+ let isFile = false;
339
+ try {
340
+ isFile = statSync(full).isFile();
341
+ }
342
+ catch {
343
+ continue;
344
+ }
345
+ if (!isFile)
346
+ continue;
347
+ if (/\.(exe|com)$/i.test(full))
348
+ return { file: full, args, verbatim: false };
349
+ if (/\.(cmd|bat)$/i.test(full)) {
350
+ const line = [full, ...args].map(cmdQuote).join(" ");
351
+ return { file: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
352
+ }
353
+ }
354
+ }
355
+ return { file: command, args, verbatim: false };
356
+ }
357
+ /** cmd.exe 的引号规则:含空格或特殊字符的参数用双引号括起来,里面的双引号写两次 */
358
+ function cmdQuote(arg) {
359
+ if (arg && !/[\s"&|<>^%!(),;=]/.test(arg))
360
+ return arg;
361
+ return `"${arg.replace(/"/g, '""')}"`;
362
+ }
363
+ function mergeEnv(extra = {}) {
364
+ const env = { ...process.env };
365
+ if (process.platform === "win32") {
366
+ const keys = new Set(Object.keys(extra).map((k) => k.toUpperCase()));
367
+ for (const k of Object.keys(env))
368
+ if (keys.has(k.toUpperCase()))
369
+ delete env[k];
370
+ }
371
+ return { ...env, ...extra };
372
+ }
373
+ function killTree(child) {
374
+ if (child.pid === undefined)
375
+ return;
376
+ if (process.platform === "win32") {
377
+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on("error", () => child.kill());
378
+ return;
379
+ }
380
+ try {
381
+ process.kill(-child.pid, "SIGKILL");
382
+ }
383
+ catch {
384
+ child.kill("SIGKILL");
385
+ }
386
+ }
387
+ // ---------- 传输:Streamable HTTP ----------
388
+ function httpTransport(c, doFetch) {
389
+ let session;
390
+ let protocol;
391
+ let nextId = 1;
392
+ const abort = new AbortController();
393
+ let markClosed;
394
+ const closed = new Promise((r) => (markClosed = r));
395
+ const headers = () => ({
396
+ ...c.headers,
397
+ "content-type": "application/json",
398
+ accept: "application/json, text/event-stream",
399
+ ...(session ? { "mcp-session-id": session } : {}),
400
+ ...(protocol ? { "mcp-protocol-version": protocol } : {}),
401
+ });
402
+ async function post(body, signal) {
403
+ const res = await doFetch(c.url, { method: "POST", headers: headers(), body: JSON.stringify(body), signal: AbortSignal.any([signal, abort.signal]) });
404
+ const sid = res.headers.get("mcp-session-id");
405
+ if (sid)
406
+ session = sid;
407
+ return res;
408
+ }
409
+ return {
410
+ async request(method, params, signal) {
411
+ const id = nextId++;
412
+ const res = await post({ jsonrpc: "2.0", id, method, ...(params ? { params } : {}) }, signal);
413
+ if (!res.ok) {
414
+ const text = (await res.text().catch(() => "")).slice(0, 500);
415
+ throw new McpError(`HTTP ${res.status}${res.status === 401 ? " (unauthorized: check the headers in the MCP config)" : ""}${text ? `: ${text}` : ""}`);
416
+ }
417
+ const type = res.headers.get("content-type") ?? "";
418
+ const reply = type.includes("text/event-stream") ? await fromSse(res, id, signal) : (await res.json());
419
+ const result = unwrap(reply);
420
+ if (method === "initialize")
421
+ protocol = result?.protocolVersion ?? PROTOCOL_VERSION;
422
+ return result;
423
+ },
424
+ async notify(method, params) {
425
+ const res = await post({ jsonrpc: "2.0", method, ...(params ? { params } : {}) }, AbortSignal.timeout(10_000));
426
+ await res.body?.cancel().catch(() => { });
427
+ },
428
+ closed,
429
+ async close() {
430
+ if (session) {
431
+ await doFetch(c.url, { method: "DELETE", headers: headers(), signal: AbortSignal.timeout(2_000) }).catch(() => { });
432
+ }
433
+ abort.abort();
434
+ markClosed("closed");
435
+ },
436
+ };
437
+ }
438
+ /** 从 SSE 流里找到 id 对应的回复;流里其他的消息(通知、服务端的请求)忽略 */
439
+ async function fromSse(res, id, signal) {
440
+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
441
+ let buf = "";
442
+ try {
443
+ while (!signal.aborted) {
444
+ const { value, done } = await reader.read();
445
+ if (done)
446
+ break;
447
+ buf += value;
448
+ let i;
449
+ while ((i = buf.search(/\r?\n\r?\n/)) >= 0) {
450
+ const event = buf.slice(0, i);
451
+ buf = buf.slice(i).replace(/^\r?\n\r?\n/, "");
452
+ const data = event
453
+ .split(/\r?\n/)
454
+ .filter((l) => l.startsWith("data:"))
455
+ .map((l) => l.slice(5).replace(/^ /, ""))
456
+ .join("\n");
457
+ if (!data)
458
+ continue;
459
+ try {
460
+ const msg = JSON.parse(data);
461
+ if (msg.id === id && (msg.result !== undefined || msg.error !== undefined))
462
+ return msg;
463
+ }
464
+ catch {
465
+ // 不是 JSON 的事件忽略
466
+ }
467
+ }
468
+ }
469
+ }
470
+ finally {
471
+ await reader.cancel().catch(() => { });
472
+ }
473
+ throw new McpError(signal.aborted ? "request aborted" : "the server closed the stream without replying");
474
+ }
475
+ function unwrap(msg) {
476
+ if (msg?.error)
477
+ throw new McpError(msg.error.message ?? "error", msg.error.code);
478
+ return msg?.result;
479
+ }
480
+ class Rpc {
481
+ #send;
482
+ #nextId = 1;
483
+ #pending = new Map();
484
+ #dead;
485
+ constructor(send) {
486
+ this.#send = send;
487
+ }
488
+ send(msg) {
489
+ this.#send(msg);
490
+ }
491
+ request(method, params, signal) {
492
+ if (this.#dead)
493
+ return Promise.reject(this.#dead);
494
+ const id = this.#nextId++;
495
+ return new Promise((resolve, reject) => {
496
+ const onAbort = () => {
497
+ this.#pending.delete(id);
498
+ this.#send({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: id, reason: "cancelled by the client" } });
499
+ reject(signal.reason ?? new McpError("aborted"));
500
+ };
501
+ if (signal.aborted)
502
+ return onAbort();
503
+ signal.addEventListener("abort", onAbort, { once: true });
504
+ this.#pending.set(id, {
505
+ resolve: (v) => (signal.removeEventListener("abort", onAbort), resolve(v)),
506
+ reject: (e) => (signal.removeEventListener("abort", onAbort), reject(e)),
507
+ });
508
+ this.#send({ jsonrpc: "2.0", id, method, ...(params ? { params } : {}) });
509
+ });
510
+ }
511
+ receive(msg) {
512
+ if (msg.method !== undefined) {
513
+ // 服务端发来的请求:只支持 ping,其他的回复"不支持",免得服务端一直等
514
+ if (msg.id === undefined)
515
+ return;
516
+ if (msg.method === "ping")
517
+ this.#send({ jsonrpc: "2.0", id: msg.id, result: {} });
518
+ else
519
+ this.#send({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: `jade does not support ${msg.method}` } });
520
+ return;
521
+ }
522
+ if (msg.id === undefined)
523
+ return;
524
+ const p = this.#pending.get(msg.id);
525
+ if (!p)
526
+ return;
527
+ this.#pending.delete(msg.id);
528
+ if (msg.error)
529
+ p.reject(new McpError(msg.error.message ?? "error", msg.error.code));
530
+ else
531
+ p.resolve(msg.result);
532
+ }
533
+ fail(err) {
534
+ this.#dead = err;
535
+ for (const p of this.#pending.values())
536
+ p.reject(err);
537
+ this.#pending.clear();
538
+ }
539
+ }
540
+ // ---------- 工具 ----------
541
+ /** mcp__<服务>__<工具>,和 Claude Code 一样;只保留字母数字、_、-,超长时截断并加上哈希避免重名 */
542
+ export function mcpToolName(server, tool) {
543
+ const clean = (s) => s.replace(/[^A-Za-z0-9_-]/g, "_");
544
+ const full = `mcp__${clean(server)}__${clean(tool)}`;
545
+ if (full.length <= MAX_TOOL_NAME)
546
+ return full;
547
+ const hash = createHash("sha256").update(`${server}\0${tool}`).digest("hex").slice(0, 8);
548
+ return `${full.slice(0, MAX_TOOL_NAME - 9)}_${hash}`;
549
+ }
550
+ /** 把已连接的服务的工具变成 jade 的工具;readOnly 为 true 时只要声明了只读的工具(给子 Agent) */
551
+ export function mcpTools(clients, opts = {}) {
552
+ const out = [];
553
+ const names = new Set();
554
+ for (const client of clients) {
555
+ if (client.status !== "connected")
556
+ continue;
557
+ for (const info of client.tools) {
558
+ const readOnly = info.annotations?.readOnlyHint === true;
559
+ if (opts.readOnly && !readOnly)
560
+ continue;
561
+ const name = mcpToolName(client.name, info.name);
562
+ if (names.has(name))
563
+ continue;
564
+ names.add(name);
565
+ const schema = info.inputSchema && typeof info.inputSchema === "object" ? info.inputSchema : { type: "object" };
566
+ out.push({
567
+ name,
568
+ description: `${(info.description ?? info.title ?? info.annotations?.title ?? info.name).trim()}\n\n(Tool "${info.name}" from the MCP server "${client.name}".)`,
569
+ inputSchema: { type: "object", ...schema },
570
+ // 服务没有声明只读的,都按有外部副作用处理:ask 和 auto-edit 模式下先问
571
+ effect: readOnly ? "read" : "external",
572
+ concurrency: readOnly ? "safe" : "exclusive",
573
+ idempotent: readOnly || info.annotations?.idempotentHint === true,
574
+ async execute(input, ctx) {
575
+ try {
576
+ const r = await client.callTool(info.name, input, ctx.signal);
577
+ return { content: toBlocks(name, r), isError: r?.isError === true };
578
+ }
579
+ catch (err) {
580
+ if (ctx.signal.aborted)
581
+ throw err;
582
+ return { content: `MCP server "${client.name}" failed: ${errorText(err)}`, isError: true };
583
+ }
584
+ },
585
+ });
586
+ }
587
+ }
588
+ return out;
589
+ }
590
+ /** MCP 的内容转成内容块:文本、图片照搬;音频、二进制资源只说明;没有内容时用 structuredContent */
591
+ export function toBlocks(tool, r) {
592
+ const origin = { by: "tool", name: tool };
593
+ const blocks = [];
594
+ let chars = 0;
595
+ const text = (t) => {
596
+ if (chars >= MAX_RESULT_CHARS)
597
+ return;
598
+ const room = MAX_RESULT_CHARS - chars;
599
+ const shown = t.length > room ? `${t.slice(0, room)}\n[… ${t.length - room} more characters omitted]` : t;
600
+ chars += shown.length;
601
+ blocks.push({ kind: "text", text: shown, origin, trust: "untrusted" });
602
+ };
603
+ for (const raw of r?.content ?? []) {
604
+ const c = raw;
605
+ switch (c?.type) {
606
+ case "text":
607
+ if (typeof c.text === "string")
608
+ text(c.text);
609
+ break;
610
+ case "image":
611
+ if (typeof c.data === "string" && typeof c.mimeType === "string") {
612
+ blocks.push({ kind: "image", source: { type: "base64", media_type: c.mimeType, data: c.data }, origin, trust: "untrusted" });
613
+ }
614
+ break;
615
+ case "resource": {
616
+ const res = c.resource;
617
+ if (typeof res?.text === "string")
618
+ text(`${res.uri ?? "resource"}:\n${res.text}`);
619
+ else
620
+ text(`[binary resource ${res?.uri ?? ""}${res?.mimeType ? ` (${res.mimeType})` : ""} omitted]`);
621
+ break;
622
+ }
623
+ case "resource_link":
624
+ text(`[resource ${c.name ? `${c.name} ` : ""}${c.uri ?? ""}]`);
625
+ break;
626
+ case "audio":
627
+ text(`[audio${c.mimeType ? ` (${c.mimeType})` : ""} omitted]`);
628
+ break;
629
+ }
630
+ }
631
+ if (blocks.length === 0 && r?.structuredContent !== undefined)
632
+ text(JSON.stringify(r.structuredContent, null, 2));
633
+ if (blocks.length === 0)
634
+ text("(no output)");
635
+ return blocks;
636
+ }
637
+ function errorText(err) {
638
+ return err instanceof Error ? err.message : String(err);
639
+ }
640
+ //# sourceMappingURL=mcp.js.map