@uncarved/jade 0.2.0 → 0.3.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.
- package/README.md +277 -0
- package/assets/logo.svg +1 -0
- package/bin/jade.js +15 -0
- package/dist/api.d.ts +5 -250
- package/dist/api.js +5 -7
- package/dist/api.js.map +1 -1
- package/dist/fetch.d.ts +8 -0
- package/dist/fetch.js +19 -17
- package/dist/fetch.js.map +1 -1
- package/dist/host.d.ts +12 -1
- package/dist/host.js +49 -1
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.js +28 -5
- package/dist/main.js.map +1 -1
- package/dist/remote.js +4 -0
- package/dist/remote.js.map +1 -1
- package/dist/session.d.ts +2 -0
- package/dist/session.js +133 -13
- package/dist/session.js.map +1 -1
- package/dist/source.d.ts +2 -10
- package/dist/source.js.map +1 -1
- package/dist/update.d.ts +8 -20
- package/dist/update.js +12 -1
- package/dist/update.js.map +1 -1
- package/package.json +6 -4
- package/plugins/approval/index.ts +246 -84
- package/plugins/approval/plugin.json +5 -1
- package/plugins/approval/policy.ts +27 -6
- package/plugins/approval/review.ts +1 -1
- package/plugins/ask/index.ts +2 -2
- package/plugins/budget/index.ts +1 -1
- package/plugins/checks/checks.ts +3 -2
- package/plugins/checks/index.ts +2 -5
- package/plugins/commands/index.ts +2 -44
- package/plugins/compact/compact.ts +15 -4
- package/plugins/compact/index.ts +13 -16
- package/plugins/continue/index.ts +1 -1
- package/plugins/cost/index.ts +143 -0
- package/plugins/cost/plugin.json +13 -0
- package/plugins/custom-commands/index.ts +85 -0
- package/plugins/custom-commands/plugin.json +8 -0
- package/plugins/editor/index.ts +88 -0
- package/plugins/editor/plugin.json +17 -0
- package/plugins/fs/fs.ts +110 -17
- package/plugins/fs/grep.ts +41 -11
- package/plugins/fs/index.ts +9 -7
- package/plugins/fs/renderers.ts +1 -1
- package/plugins/hooks/index.ts +152 -0
- package/plugins/hooks/plugin.json +14 -0
- package/plugins/keys/index.ts +2 -18
- package/plugins/mcp/index.ts +40 -12
- package/plugins/mcp/install.ts +139 -0
- package/plugins/mcp/mcp.ts +2 -1
- package/plugins/mcp/plugin.json +1 -1
- package/plugins/mcp/project.ts +37 -1
- package/plugins/memory/index.ts +4 -9
- package/plugins/memory/plugin.json +1 -1
- package/plugins/mentions/index.ts +33 -13
- package/plugins/models/configure.ts +258 -150
- package/plugins/models/context.ts +2 -2
- package/plugins/models/index.ts +50 -42
- package/plugins/models/plugin.json +1 -1
- package/plugins/models/provider.ts +22 -4
- package/plugins/models/saved.ts +8 -4
- package/plugins/modes/index.ts +2 -17
- package/plugins/plugins/index.ts +2 -2
- package/plugins/print/index.ts +60 -12
- package/plugins/print/plugin.json +1 -0
- package/plugins/prompts/index.ts +50 -14
- package/plugins/{memory → prompts}/notes.ts +21 -9
- package/plugins/prompts/plugin.json +8 -2
- package/plugins/prompts/prompts.ts +14 -8
- package/plugins/prompts/results.ts +63 -0
- package/plugins/prompts/sys.ts +16 -4
- package/plugins/renderers/index.ts +2 -43
- package/plugins/repeats/index.ts +1 -1
- package/plugins/schedule/index.ts +2 -2
- package/plugins/scratch/index.ts +2 -3
- package/plugins/screenshot/index.ts +26 -13
- package/plugins/screenshot/plugin.json +1 -1
- package/plugins/sessions/index.ts +2 -17
- package/plugins/shell/index.ts +56 -6
- package/plugins/shell/plugin.json +3 -1
- package/plugins/shell/renderers.ts +1 -1
- package/plugins/shell/service.ts +2 -13
- package/plugins/shell/shell.ts +31 -16
- package/plugins/skills/index.ts +172 -37
- package/plugins/skills/install.ts +212 -0
- package/plugins/skills/plugin.json +3 -2
- package/plugins/skills/project.ts +38 -1
- package/plugins/skills/skills.ts +28 -9
- package/plugins/steer/index.ts +142 -0
- package/plugins/steer/plugin.json +8 -0
- package/plugins/suggest/index.ts +16 -11
- package/plugins/suggest/plugin.json +1 -1
- package/plugins/task/index.ts +8 -16
- package/plugins/task/plugin.json +9 -2
- package/plugins/task/subagent.ts +119 -15
- package/plugins/todo/index.ts +4 -4
- package/plugins/tui/editor.ts +10 -2
- package/plugins/tui/frontend.ts +130 -25
- package/plugins/tui/index.ts +3 -8
- package/plugins/tui/markdown.ts +51 -6
- package/plugins/tui/mascot.ts +505 -0
- package/plugins/tui/mentions.ts +48 -8
- package/plugins/tui/plugin.json +2 -2
- package/plugins/tui/screen.ts +6 -0
- package/plugins/tui/transcript.ts +22 -3
- package/plugins/tui/tui.ts +323 -95
- package/plugins/tui/vendor.ts +16 -0
- package/plugins/undo/checkpoint.ts +26 -2
- package/plugins/undo/index.ts +86 -24
- package/plugins/undo/plugin.json +8 -2
- package/plugins/undo/snapshot.ts +129 -0
- package/plugins/update/index.ts +11 -15
- package/plugins/update/plugin.json +2 -1
- package/plugins/web/index.ts +2 -5
- package/plugins/web/renderers.ts +1 -1
- package/plugins/web/web.ts +6 -5
- package/plugins-dist/approval/index.js +232 -50
- package/plugins-dist/approval/plugin.json +5 -1
- package/plugins-dist/approval/policy.js +27 -5
- package/plugins-dist/ask/index.js +1 -1
- package/plugins-dist/budget/index.js +1 -1
- package/plugins-dist/checks/checks.js +2 -1
- package/plugins-dist/checks/index.js +1 -1
- package/plugins-dist/commands/index.js +1 -1
- package/plugins-dist/compact/compact.js +13 -2
- package/plugins-dist/compact/index.js +12 -8
- package/plugins-dist/continue/index.js +1 -1
- package/plugins-dist/cost/index.js +135 -0
- package/plugins-dist/cost/plugin.json +16 -0
- package/plugins-dist/custom-commands/index.js +86 -0
- package/plugins-dist/custom-commands/plugin.json +12 -0
- package/plugins-dist/editor/index.js +89 -0
- package/plugins-dist/editor/plugin.json +21 -0
- package/plugins-dist/fs/fs.js +106 -17
- package/plugins-dist/fs/grep.js +40 -12
- package/plugins-dist/fs/index.js +8 -5
- package/plugins-dist/hooks/index.js +145 -0
- package/plugins-dist/hooks/plugin.json +19 -0
- package/plugins-dist/keys/index.js +1 -1
- package/plugins-dist/mcp/index.js +41 -9
- package/plugins-dist/mcp/install.js +160 -0
- package/plugins-dist/mcp/mcp.js +2 -1
- package/plugins-dist/mcp/plugin.json +2 -1
- package/plugins-dist/mcp/project.js +42 -1
- package/plugins-dist/memory/index.js +3 -5
- package/plugins-dist/memory/plugin.json +1 -1
- package/plugins-dist/mentions/index.js +29 -11
- package/plugins-dist/models/configure.js +252 -151
- package/plugins-dist/models/context.js +2 -2
- package/plugins-dist/models/index.js +53 -16
- package/plugins-dist/models/plugin.json +1 -1
- package/plugins-dist/models/provider.js +4 -2
- package/plugins-dist/models/saved.js +9 -4
- package/plugins-dist/modes/index.js +1 -1
- package/plugins-dist/plugins/index.js +1 -1
- package/plugins-dist/print/index.js +62 -9
- package/plugins-dist/print/plugin.json +3 -0
- package/plugins-dist/prompts/index.js +49 -2
- package/plugins-dist/{memory → prompts}/notes.js +10 -7
- package/plugins-dist/prompts/plugin.json +8 -2
- package/plugins-dist/prompts/prompts.js +13 -8
- package/plugins-dist/prompts/results.js +60 -0
- package/plugins-dist/prompts/sys.js +15 -3
- package/plugins-dist/renderers/index.js +1 -1
- package/plugins-dist/repeats/index.js +1 -1
- package/plugins-dist/schedule/index.js +1 -1
- package/plugins-dist/scratch/index.js +1 -1
- package/plugins-dist/screenshot/index.js +25 -11
- package/plugins-dist/screenshot/plugin.json +1 -1
- package/plugins-dist/sessions/index.js +1 -1
- package/plugins-dist/shell/index.js +55 -3
- package/plugins-dist/shell/plugin.json +3 -1
- package/plugins-dist/shell/shell.js +26 -8
- package/plugins-dist/skills/index.js +184 -35
- package/plugins-dist/skills/install.js +178 -0
- package/plugins-dist/skills/plugin.json +6 -2
- package/plugins-dist/skills/project.js +43 -1
- package/plugins-dist/skills/skills.js +27 -10
- package/plugins-dist/steer/index.js +135 -0
- package/plugins-dist/steer/plugin.json +12 -0
- package/plugins-dist/suggest/index.js +15 -9
- package/plugins-dist/suggest/plugin.json +1 -1
- package/plugins-dist/task/index.js +7 -4
- package/plugins-dist/task/plugin.json +10 -2
- package/plugins-dist/task/subagent.js +106 -15
- package/plugins-dist/todo/index.js +3 -3
- package/plugins-dist/tui/editor.js +7 -2
- package/plugins-dist/tui/frontend.js +135 -18
- package/plugins-dist/tui/index.js +2 -1
- package/plugins-dist/tui/markdown.js +48 -6
- package/plugins-dist/tui/mascot.js +439 -0
- package/plugins-dist/tui/mentions.js +44 -6
- package/plugins-dist/tui/plugin.json +3 -2
- package/plugins-dist/tui/screen.js +2 -0
- package/plugins-dist/tui/transcript.js +19 -2
- package/plugins-dist/tui/tui.js +303 -83
- package/plugins-dist/tui/vendor.js +13822 -0
- package/plugins-dist/undo/checkpoint.js +28 -1
- package/plugins-dist/undo/index.js +92 -22
- package/plugins-dist/undo/plugin.json +10 -3
- package/plugins-dist/undo/snapshot.js +111 -0
- package/plugins-dist/update/index.js +9 -10
- package/plugins-dist/update/plugin.json +4 -1
- package/plugins-dist/web/index.js +1 -1
- package/plugins-dist/web/web.js +6 -5
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/sdk/python/jade_plugin.py +8 -0
- package/src/api.ts +7 -262
- package/src/fetch.ts +18 -16
- package/src/host.ts +49 -1
- package/src/index.ts +1 -1
- package/src/main.ts +25 -6
- package/src/remote.ts +2 -0
- package/src/session.ts +134 -15
- package/src/source.ts +2 -11
- package/src/update.ts +16 -10
- package/plugins/undo/notes.ts +0 -43
- package/plugins-dist/undo/notes.js +0 -36
package/plugins-dist/fs/grep.js
CHANGED
|
@@ -29,7 +29,8 @@ export function grepTool(cwd, opts = {}) {
|
|
|
29
29
|
path: { type: "string" },
|
|
30
30
|
include: { type: "string" },
|
|
31
31
|
ignore_case: { type: "boolean" },
|
|
32
|
-
|
|
32
|
+
// files_with_matches 是 ripgrep / Claude Code 的叫法,很多模型会这样传,当作 files
|
|
33
|
+
output_mode: { type: "string", enum: ["content", "files", "count", "files_with_matches"] },
|
|
33
34
|
context: { type: "integer" },
|
|
34
35
|
},
|
|
35
36
|
required: ["pattern"],
|
|
@@ -40,6 +41,7 @@ export function grepTool(cwd, opts = {}) {
|
|
|
40
41
|
idempotent: true,
|
|
41
42
|
async execute(input, { signal }) {
|
|
42
43
|
const { pattern, path: p = ".", include, ignore_case = false, output_mode = "content", context = 0 } = input;
|
|
44
|
+
const mode = output_mode === "files_with_matches" ? "files" : output_mode;
|
|
43
45
|
let re;
|
|
44
46
|
try {
|
|
45
47
|
re = new RegExp(pattern, ignore_case ? "i" : "");
|
|
@@ -53,8 +55,8 @@ export function grepTool(cwd, opts = {}) {
|
|
|
53
55
|
pattern,
|
|
54
56
|
ignoreCase: ignore_case,
|
|
55
57
|
include,
|
|
56
|
-
context:
|
|
57
|
-
mode
|
|
58
|
+
context: mode === "content" ? Math.min(Math.max(context, 0), MAX_CONTEXT) : 0,
|
|
59
|
+
mode,
|
|
58
60
|
signal,
|
|
59
61
|
};
|
|
60
62
|
let found;
|
|
@@ -196,6 +198,32 @@ async function ripgrep(rg, s) {
|
|
|
196
198
|
}
|
|
197
199
|
}
|
|
198
200
|
// ---------- JS ----------
|
|
201
|
+
/** 同时读几个文件。逐个等 stat、readFile 时,几万个文件的仓库要好几秒(多数时间花在等 IO 上) */
|
|
202
|
+
const READ_AHEAD = 16;
|
|
203
|
+
/** 读出可以搜的文本;不存在(git 列出的文件可能已在工作区删除)、太大、二进制的返回 undefined */
|
|
204
|
+
async function readSearchable(file) {
|
|
205
|
+
const info = await statOrUndefined(file);
|
|
206
|
+
if (!info?.isFile() || info.size > MAX_FILE_BYTES)
|
|
207
|
+
return undefined;
|
|
208
|
+
const buf = await readFile(file).catch(() => undefined);
|
|
209
|
+
return buf && !buf.includes(0) ? buf : undefined;
|
|
210
|
+
}
|
|
211
|
+
/** 按 items 的顺序产出 fn 的结果,最多 n 个同时进行;调用方提前停止时,已经开始的读取随它结束 */
|
|
212
|
+
async function* ordered(items, n, fn) {
|
|
213
|
+
const pending = [];
|
|
214
|
+
for await (const item of items) {
|
|
215
|
+
const result = fn(item);
|
|
216
|
+
// 先挂上处理,免得提前停止时没人等的 Promise 报 unhandled rejection
|
|
217
|
+
result.catch(() => { });
|
|
218
|
+
pending.push({ item, result });
|
|
219
|
+
if (pending.length >= n) {
|
|
220
|
+
const head = pending.shift();
|
|
221
|
+
yield [head.item, await head.result];
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
for (const p of pending)
|
|
225
|
+
yield [p.item, await p.result];
|
|
226
|
+
}
|
|
199
227
|
async function jsGrep(s) {
|
|
200
228
|
// 和 ripgrep 的 --glob 一致:不含 / 的模式("*.ts")匹配任意深度的文件名
|
|
201
229
|
const filter = s.include ? globMatcher(s.include.includes("/") ? s.include : `**/${s.include}`) : undefined;
|
|
@@ -204,17 +232,17 @@ async function jsGrep(s) {
|
|
|
204
232
|
const single = (await stat(s.root)).isFile();
|
|
205
233
|
const candidates = single ? [s.root] : await listFiles(s.root, s.signal);
|
|
206
234
|
const sorted = Array.isArray(candidates) ? [...candidates].sort() : candidates;
|
|
207
|
-
|
|
235
|
+
const wanted = async function* () {
|
|
236
|
+
for await (const file of sorted) {
|
|
237
|
+
if (filter && !single && !filter(path.relative(s.root, file).split(path.sep).join("/")))
|
|
238
|
+
continue;
|
|
239
|
+
yield file;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
for await (const [file, buf] of ordered(wanted(), READ_AHEAD, readSearchable)) {
|
|
208
243
|
s.signal.throwIfAborted();
|
|
209
|
-
if (
|
|
210
|
-
continue;
|
|
211
|
-
// git 列出的文件可能已在工作区删除
|
|
212
|
-
const info = await statOrUndefined(file);
|
|
213
|
-
if (!info?.isFile() || info.size > MAX_FILE_BYTES)
|
|
244
|
+
if (!buf)
|
|
214
245
|
continue;
|
|
215
|
-
const buf = await readFile(file);
|
|
216
|
-
if (buf.includes(0))
|
|
217
|
-
continue; // 二进制文件
|
|
218
246
|
const all = buf.toString("utf8").split(/\r?\n/);
|
|
219
247
|
if (all.at(-1) === "")
|
|
220
248
|
all.pop();
|
package/plugins-dist/fs/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// jade/fs:文件工具 read_file、write_file、edit_file、multi_edit、list_dir、glob、grep。
|
|
2
|
-
import { definePlugin } from "
|
|
3
|
-
import { fsTools } from "./fs.js";
|
|
2
|
+
import { definePlugin } from "@uncarved/jade-api";
|
|
3
|
+
import { fsTools, SeenFiles } from "./fs.js";
|
|
4
4
|
import { fsRenderers } from "./renderers.js";
|
|
5
5
|
export default definePlugin({
|
|
6
6
|
process(ctx) {
|
|
@@ -11,16 +11,19 @@ export default definePlugin({
|
|
|
11
11
|
renderers.tool(r);
|
|
12
12
|
},
|
|
13
13
|
session(ctx) {
|
|
14
|
-
//
|
|
14
|
+
// 数模型调用的次数:同一次回复里先读后改的,改的内容是看到读取结果之前写好的。
|
|
15
|
+
// 同时按最终发给模型的消息让被压缩(jade/compact 总结或清理)掉的读取失效:那些文件要重新读才能改
|
|
15
16
|
const responses = { calls: 0 };
|
|
17
|
+
const seen = new SeenFiles();
|
|
16
18
|
ctx.kernel.hook({
|
|
17
19
|
kind: "transform",
|
|
18
20
|
point: "model.before",
|
|
19
|
-
fn: () => {
|
|
21
|
+
fn: (request) => {
|
|
20
22
|
responses.calls++;
|
|
23
|
+
seen.prune(request.messages);
|
|
21
24
|
},
|
|
22
25
|
});
|
|
23
|
-
for (const tool of fsTools(ctx.cwd, { responses }))
|
|
26
|
+
for (const tool of fsTools(ctx.cwd, { responses, seen }))
|
|
24
27
|
ctx.kernel.tool(tool);
|
|
25
28
|
// 子 Agent(jade/task)的只读工具:另一套实例,子 Agent 读过的文件不算主会话读过
|
|
26
29
|
// jade/task 被隔离时它的服务已失效:子 Agent 没有文件工具,文件工具本身照常
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// jade/hooks:不写插件,在配置里写几条 shell 命令,就能在工具调用前后、一轮结束时做点事。
|
|
2
|
+
//
|
|
3
|
+
// $JADE_HOME/config.json(项目层的配置设不了这一项:克隆的仓库不能让你的机器跑命令):
|
|
4
|
+
//
|
|
5
|
+
// { "jade/hooks": { "hooks": [
|
|
6
|
+
// { "on": "before", "tool": "bash", "command": "python ~/.jade/guard.py" },
|
|
7
|
+
// { "on": "after", "tool": "edit_file", "command": "bunx prettier --write \"$JADE_TOOL_PATH\"" },
|
|
8
|
+
// { "on": "turn", "command": "powershell -c \"New-BurntToastNotification -Text 'jade is done'\"" }
|
|
9
|
+
// ] } }
|
|
10
|
+
//
|
|
11
|
+
// - before:工具执行前(审批的关卡里)运行。退出码不是 0 时这次调用被拒绝,命令的输出作为理由告诉模型;是 0 时不表态。
|
|
12
|
+
// - after:工具成功执行后运行。退出码不是 0 时把输出留给模型看(下一次请求时附上),不改工具的结果。
|
|
13
|
+
// - turn:一轮结束后运行,结果不影响会话。
|
|
14
|
+
// tool 是工具名,不写或写 "*" 表示所有工具。命令经 shell@1 在工作目录里运行(和 bash 工具同一个 shell),环境变量:
|
|
15
|
+
// JADE_TOOL(工具名)、JADE_TOOL_INPUT(参数的 JSON 文件的路径)、JADE_TOOL_PATH(参数里有 path 时)。
|
|
16
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
17
|
+
import os from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { definePlugin } from "@uncarved/jade-api";
|
|
20
|
+
const DEFAULT_TIMEOUT_SECONDS = 60;
|
|
21
|
+
const MAX_TIMEOUT_SECONDS = 600;
|
|
22
|
+
const MAX_OUTPUT_CHARS = 4000;
|
|
23
|
+
/** 检查配置里的 hooks;写错的条目说明原因,其余的照用 */
|
|
24
|
+
export function parseHooks(value) {
|
|
25
|
+
if (value === undefined)
|
|
26
|
+
return { hooks: [], problems: [] };
|
|
27
|
+
if (!Array.isArray(value))
|
|
28
|
+
return { hooks: [], problems: ["hooks must be a list"] };
|
|
29
|
+
const hooks = [];
|
|
30
|
+
const problems = [];
|
|
31
|
+
for (const [i, raw] of value.entries()) {
|
|
32
|
+
const h = (raw ?? {});
|
|
33
|
+
const where = `hooks[${i}]`;
|
|
34
|
+
if (h.on !== "before" && h.on !== "after" && h.on !== "turn")
|
|
35
|
+
problems.push(`${where}: "on" must be "before", "after" or "turn"`);
|
|
36
|
+
else if (typeof h.command !== "string" || !h.command.trim())
|
|
37
|
+
problems.push(`${where}: "command" must be a shell command`);
|
|
38
|
+
else if (h.tool !== undefined && typeof h.tool !== "string")
|
|
39
|
+
problems.push(`${where}: "tool" must be a tool name`);
|
|
40
|
+
else if (h.timeoutSeconds !== undefined && !(typeof h.timeoutSeconds === "number" && h.timeoutSeconds > 0 && h.timeoutSeconds <= MAX_TIMEOUT_SECONDS)) {
|
|
41
|
+
problems.push(`${where}: "timeoutSeconds" must be a number up to ${MAX_TIMEOUT_SECONDS}`);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
hooks.push({
|
|
45
|
+
on: h.on,
|
|
46
|
+
command: h.command,
|
|
47
|
+
timeoutMs: (h.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1000,
|
|
48
|
+
...(typeof h.tool === "string" && h.tool !== "*" ? { tool: h.tool } : {}),
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return { hooks, problems };
|
|
53
|
+
}
|
|
54
|
+
/** 单引号括起来,给 POSIX shell 用 */
|
|
55
|
+
const quote = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
|
|
56
|
+
const clip = (s) => (s.length > MAX_OUTPUT_CHARS ? `${s.slice(0, MAX_OUTPUT_CHARS)}\n… (${s.length - MAX_OUTPUT_CHARS} more characters)` : s);
|
|
57
|
+
let warned = false;
|
|
58
|
+
export default definePlugin({
|
|
59
|
+
session(ctx) {
|
|
60
|
+
const { hooks, problems } = parseHooks(ctx.config.hooks);
|
|
61
|
+
const ui = () => ctx.service("ui@1");
|
|
62
|
+
if (problems.length > 0 && !warned) {
|
|
63
|
+
warned = true;
|
|
64
|
+
ui()?.notify(`jade/hooks: ${problems.join("; ")}`, "warning");
|
|
65
|
+
}
|
|
66
|
+
if (hooks.length === 0)
|
|
67
|
+
return;
|
|
68
|
+
const shell = ctx.require("shell@1");
|
|
69
|
+
const sessionId = ctx.session.id;
|
|
70
|
+
/** 运行一条 hook;call 给了就把工具名和参数经环境变量交给它 */
|
|
71
|
+
const run = async (hook, call, signal) => {
|
|
72
|
+
let dir;
|
|
73
|
+
try {
|
|
74
|
+
let exports = "";
|
|
75
|
+
if (call) {
|
|
76
|
+
dir = await mkdtemp(path.join(os.tmpdir(), "jade-hook-"));
|
|
77
|
+
const file = path.join(dir, "input.json");
|
|
78
|
+
await writeFile(file, JSON.stringify(call.input ?? null));
|
|
79
|
+
const p = call.input?.path;
|
|
80
|
+
// 路径用正斜杠:Git Bash 里反斜杠是转义符
|
|
81
|
+
const vars = { JADE_TOOL: call.name, JADE_TOOL_INPUT: file.split(path.sep).join("/"), ...(typeof p === "string" ? { JADE_TOOL_PATH: p.split(path.sep).join("/") } : {}) };
|
|
82
|
+
exports = `export ${Object.entries(vars).map(([k, v]) => `${k}=${quote(v)}`).join(" ")}; `;
|
|
83
|
+
}
|
|
84
|
+
const r = await shell.run(exports + hook.command, { cwd: ctx.cwd, timeoutMs: hook.timeoutMs, ...(signal ? { signal } : {}) });
|
|
85
|
+
return { ok: r.code === 0, output: r.timedOut ? `timed out after ${hook.timeoutMs / 1000}s` : clip(r.output.trim()) };
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
if (dir)
|
|
89
|
+
await rm(dir, { recursive: true, force: true }).catch(() => { });
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
const matching = (on, tool) => hooks.filter((h) => h.on === on && (h.tool === undefined || h.tool === tool));
|
|
93
|
+
if (hooks.some((h) => h.on === "before")) {
|
|
94
|
+
ctx.kernel.hook({
|
|
95
|
+
kind: "gate",
|
|
96
|
+
point: "tool.gate",
|
|
97
|
+
timeoutMs: MAX_TIMEOUT_SECONDS * 1000,
|
|
98
|
+
fn: async (call, hook) => {
|
|
99
|
+
for (const h of matching("before", call.name)) {
|
|
100
|
+
const r = await run(h, call, hook.signal);
|
|
101
|
+
if (!r.ok)
|
|
102
|
+
return { decision: "deny", reason: `A hook the user configured (${h.command}) refused this ${call.name} call${r.output ? `:\n${r.output}` : "."}` };
|
|
103
|
+
}
|
|
104
|
+
return { decision: "abstain" };
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
if (hooks.some((h) => h.on === "after")) {
|
|
109
|
+
ctx.kernel.hook({
|
|
110
|
+
kind: "transform",
|
|
111
|
+
point: "tool.after",
|
|
112
|
+
timeoutMs: MAX_TIMEOUT_SECONDS * 1000,
|
|
113
|
+
// 出错时只是这条 hook 没跑,不影响工具的结果
|
|
114
|
+
optional: true,
|
|
115
|
+
fn: async (out) => {
|
|
116
|
+
if (out.isError)
|
|
117
|
+
return undefined;
|
|
118
|
+
for (const h of matching("after", out.call.name)) {
|
|
119
|
+
const r = await run(h, out.call);
|
|
120
|
+
if (r.ok)
|
|
121
|
+
continue;
|
|
122
|
+
const text = `The user's hook after ${out.call.name} (${h.command}) failed${r.output ? `:\n${r.output}` : "."}`;
|
|
123
|
+
ui()?.notify(text, "warning");
|
|
124
|
+
ctx.service("prompts@1")?.note(sessionId, text);
|
|
125
|
+
}
|
|
126
|
+
return undefined;
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
if (hooks.some((h) => h.on === "turn")) {
|
|
131
|
+
ctx.kernel.hook({
|
|
132
|
+
kind: "observe",
|
|
133
|
+
point: "event",
|
|
134
|
+
fn: (e) => {
|
|
135
|
+
if (e.type !== "turn.ended")
|
|
136
|
+
return;
|
|
137
|
+
// 不等它:一轮结束不该被用户的命令拖住
|
|
138
|
+
for (const h of matching("turn")) {
|
|
139
|
+
void run(h, undefined, ctx.signal).then((r) => void (r.ok || ui()?.notify(`jade/hooks: ${h.command} failed${r.output ? `: ${r.output}` : ""}`, "warning")), () => { });
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
});
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "jade/hooks",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"api": "^1",
|
|
5
|
+
"entry": "./index.js",
|
|
6
|
+
"requires": [
|
|
7
|
+
"shell@1"
|
|
8
|
+
],
|
|
9
|
+
"optional": [
|
|
10
|
+
"ui@1",
|
|
11
|
+
"prompts@1"
|
|
12
|
+
],
|
|
13
|
+
"config": {
|
|
14
|
+
"hooks": {
|
|
15
|
+
"default": [],
|
|
16
|
+
"description": "shell commands to run around tool calls: a list of { \"on\": \"before\" | \"after\" | \"turn\", \"tool\": \"<name>\" (optional), \"command\": \"...\", \"timeoutSeconds\": 60 }. A failing \"before\" command denies the call; a failing \"after\" command is reported to the agent; \"turn\" runs when a turn ends"
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// jade/keys:快捷键的注册表。前端在输入框有焦点时按下自己不用的键,查这里找到插件的处理函数。
|
|
2
|
-
import { definePlugin } from "
|
|
2
|
+
import { definePlugin } from "@uncarved/jade-api";
|
|
3
3
|
/** "ctrl+<字母>"、"alt+<字母或数字>" 或 "shift+tab" */
|
|
4
4
|
export const KEY_SPEC = /^(ctrl\+[a-z]|alt\+[a-z0-9]|shift\+tab)$/;
|
|
5
5
|
/**
|
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
// jade/mcp:配置的 MCP 服务的工具交给模型(声明只读的也经 task@1 交给子 Agent);/mcp
|
|
1
|
+
// jade/mcp:配置的 MCP 服务的工具交给模型(声明只读的也经 task@1 交给子 Agent);/mcp 查看状态、重连,
|
|
2
|
+
// /mcp add、/mcp remove 改配置文件(见 install.ts;终端里是 jade mcp add|remove)。
|
|
2
3
|
//
|
|
3
4
|
// 服务是进程级的资源:第一个会话打开时读配置、确认项目层的服务、连接,之后各会话共用;进程退出时(进程作用域关闭)全部关掉。
|
|
4
5
|
// 一个会话里的工具列表不变(否则提示缓存失效):第一个会话最多等 STARTUP_WAIT_MS,没连上的在后台接着连,
|
|
5
6
|
// 它们的工具从下一个会话(/clear)开始提供。不能交互时(-p)只有这一个会话,照常等到每个服务连上或超时。
|
|
6
7
|
// 服务进程退出后,下一次调用它的工具时重新连接一次。
|
|
7
8
|
import path from "node:path";
|
|
8
|
-
import { definePlugin } from "
|
|
9
|
+
import { definePlugin } from "@uncarved/jade-api";
|
|
9
10
|
import { describeServer, loadMcpConfig, McpClient, mcpTools, mcpTrustHash } from "./mcp.js";
|
|
10
|
-
import {
|
|
11
|
+
import { manageMcp, manageUsage } from "./install.js";
|
|
12
|
+
import { bold, clip, dim, display, estimateTokens, green, realPath, red, repoRoot, splitArgs, TrustFile, yellow } from "./project.js";
|
|
11
13
|
const ID = "jade/mcp";
|
|
12
14
|
/** 第一个会话最多等 MCP 服务连接这么久(能交互时),没连上的在后台接着连 */
|
|
13
15
|
const STARTUP_WAIT_MS = 5000;
|
|
@@ -117,6 +119,11 @@ function instructions(clients) {
|
|
|
117
119
|
|
|
118
120
|
${c.instructions}`);
|
|
119
121
|
}
|
|
122
|
+
/** 一个服务每次请求都带着的大约多少 token:发给模型的工具定义,加上它的使用说明。没连上时为 0 */
|
|
123
|
+
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);
|
|
126
|
+
}
|
|
120
127
|
/** 当前进程的服务;process() 里创建,session() 里用 */
|
|
121
128
|
let current;
|
|
122
129
|
export default definePlugin({
|
|
@@ -127,13 +134,28 @@ export default definePlugin({
|
|
|
127
134
|
await ctx.effect(() => () => servers.close());
|
|
128
135
|
ctx.service("commands@1")?.register({
|
|
129
136
|
name: "mcp",
|
|
130
|
-
args: "[reconnect <name>]",
|
|
131
|
-
description: "MCP servers: status and tools",
|
|
137
|
+
args: "[reconnect <name> | add <name> … | remove <name>] [--project]",
|
|
138
|
+
description: "MCP servers: status and tools; add or remove one",
|
|
132
139
|
instant: true,
|
|
133
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
|
+
}
|
|
134
157
|
await servers.start();
|
|
135
158
|
const clients = servers.clients;
|
|
136
|
-
const words = args.trim().split(/\s+/).filter(Boolean);
|
|
137
159
|
if (words[0] === "reconnect") {
|
|
138
160
|
const c = clients.find((x) => x.name === words[1]);
|
|
139
161
|
if (!c)
|
|
@@ -148,15 +170,18 @@ export default definePlugin({
|
|
|
148
170
|
}
|
|
149
171
|
}
|
|
150
172
|
if (words.length > 0)
|
|
151
|
-
return red(
|
|
173
|
+
return red(`usage: /mcp [reconnect <name>]\n${manageUsage("/mcp")}`);
|
|
152
174
|
if (clients.length === 0) {
|
|
153
|
-
return dim(`(no MCP servers) configure them in ${display(ctx.cwd, path.join(ctx.home, "mcp.json"))}, .mcp.json or .jade/mcp.json`);
|
|
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`);
|
|
154
176
|
}
|
|
155
177
|
const lines = [];
|
|
178
|
+
let total = 0;
|
|
156
179
|
for (const c of clients) {
|
|
157
180
|
const state = c.status === "connected" ? green("connected") : c.status === "failed" ? red("failed") : yellow(c.status);
|
|
158
181
|
const info = c.serverInfo?.name ? ` · ${c.serverInfo.name}${c.serverInfo.version ? ` ${c.serverInfo.version}` : ""}` : "";
|
|
159
|
-
|
|
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` : ""}`)}`);
|
|
160
185
|
if (c.error)
|
|
161
186
|
lines.push(red(` ${c.error}`));
|
|
162
187
|
if (c.tools.length)
|
|
@@ -164,9 +189,16 @@ export default definePlugin({
|
|
|
164
189
|
if (c.status === "failed" && c.stderr.length)
|
|
165
190
|
lines.push(dim(c.stderr.map((l) => ` │ ${clip(l, 200)}`).join("\n")));
|
|
166
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`));
|
|
167
194
|
return lines.join("\n");
|
|
168
195
|
},
|
|
169
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
|
+
});
|
|
170
202
|
},
|
|
171
203
|
async session(ctx) {
|
|
172
204
|
const servers = current;
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// /mcp add|remove(终端里是 jade mcp add|remove):往配置文件里加一个 MCP 服务或删掉它,不用手改 JSON。
|
|
2
|
+
//
|
|
3
|
+
// 不加 --project 写 $JADE_HOME/mcp.json,加了写 <工作目录>/.jade/mcp.json;文件里其他的内容原样保留。
|
|
4
|
+
// 这里只写配置,不启动服务:进程里的服务只在第一个会话打开时连接,新加的重启 jade 后生效。
|
|
5
|
+
// 项目层的服务照旧在第一次启动前请用户确认:命令不顺带记下确认。这个命令也有命令行的写法(jade mcp add),
|
|
6
|
+
// 模型能经 shell 跑它;如果加了就算确认,模型就能绕过确认。
|
|
7
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { checkConfig, describeServer } from "./mcp.js";
|
|
10
|
+
import { display } from "./project.js";
|
|
11
|
+
/** cmd 是 "/mcp" 或 "jade mcp" */
|
|
12
|
+
export const manageUsage = (cmd) => `usage: ${cmd} add <name> [--project] [--env KEY=VALUE]… [--force] [--] <command> [args…]
|
|
13
|
+
${cmd} add <name> --url <url> [--project] [--header "Name: value"]… [--force]
|
|
14
|
+
${cmd} remove <name> [--project]
|
|
15
|
+
|
|
16
|
+
--project write <cwd>/.jade/mcp.json instead of $JADE_HOME/mcp.json
|
|
17
|
+
--env an environment variable for a stdio server; values may use \${VAR}
|
|
18
|
+
--header an HTTP header for a --url server; values may use \${VAR}
|
|
19
|
+
--force replace a server with the same name
|
|
20
|
+
Everything after <command> is passed to it unchanged, e.g. ${cmd} add fs npx -y @modelcontextprotocol/server-filesystem .`;
|
|
21
|
+
/** 不加 --project 写 $JADE_HOME/mcp.json,加了写 <工作目录>/.jade/mcp.json */
|
|
22
|
+
export const mcpConfigFile = (home, cwd, project) => (project ? path.join(cwd, ".jade", "mcp.json") : path.join(home, "mcp.json"));
|
|
23
|
+
/** add / remove,参数已经切好;返回给用户看的结果,用法错误或失败时抛错。cmd 用在提示里 */
|
|
24
|
+
export async function manageMcp(argv, env) {
|
|
25
|
+
const usage = manageUsage(env.cmd);
|
|
26
|
+
const [sub, ...tail] = argv;
|
|
27
|
+
if (sub === "-h" || sub === "--help")
|
|
28
|
+
return usage;
|
|
29
|
+
if (sub === "add") {
|
|
30
|
+
const { name, project, force, config } = parseAdd(tail, usage);
|
|
31
|
+
const file = mcpConfigFile(env.home, env.cwd, project);
|
|
32
|
+
await edit(file, (servers) => {
|
|
33
|
+
if (servers[name] !== undefined && !force)
|
|
34
|
+
throw new Error(`${display(env.cwd, file)} already has an MCP server named ${name}; add --force to replace it`);
|
|
35
|
+
servers[name] = config;
|
|
36
|
+
});
|
|
37
|
+
return [
|
|
38
|
+
`added MCP server ${name} to ${display(env.cwd, file)}: ${describeServer(config)}`,
|
|
39
|
+
`restart jade to start it${project ? "; jade asks you to confirm it the first time" : ""}`,
|
|
40
|
+
].join("\n");
|
|
41
|
+
}
|
|
42
|
+
if (sub === "remove" || sub === "rm") {
|
|
43
|
+
const project = tail.includes("--project");
|
|
44
|
+
const rest = tail.filter((a) => a !== "--project");
|
|
45
|
+
if (rest.length !== 1 || rest[0].startsWith("-"))
|
|
46
|
+
throw new Error(usage);
|
|
47
|
+
const name = rest[0];
|
|
48
|
+
const file = mcpConfigFile(env.home, env.cwd, project);
|
|
49
|
+
await edit(file, (servers) => {
|
|
50
|
+
if (servers[name] === undefined)
|
|
51
|
+
throw new Error(`${display(env.cwd, file)} has no MCP server named ${name}`);
|
|
52
|
+
delete servers[name];
|
|
53
|
+
});
|
|
54
|
+
return `removed MCP server ${name} from ${display(env.cwd, file)}; restart jade to stop it`;
|
|
55
|
+
}
|
|
56
|
+
throw new Error(usage);
|
|
57
|
+
}
|
|
58
|
+
function parseAdd(tail, usage) {
|
|
59
|
+
let name;
|
|
60
|
+
let project = false;
|
|
61
|
+
let force = false;
|
|
62
|
+
let url;
|
|
63
|
+
const envVars = {};
|
|
64
|
+
const headers = {};
|
|
65
|
+
let command;
|
|
66
|
+
for (let i = 0; i < tail.length; i++) {
|
|
67
|
+
const a = tail[i];
|
|
68
|
+
const value = () => {
|
|
69
|
+
const v = tail[++i];
|
|
70
|
+
if (v === undefined)
|
|
71
|
+
throw new Error(`${a} needs a value\n${usage}`);
|
|
72
|
+
return v;
|
|
73
|
+
};
|
|
74
|
+
if (a === "--") {
|
|
75
|
+
command = tail.slice(i + 1);
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
else if (a === "--project")
|
|
79
|
+
project = true;
|
|
80
|
+
else if (a === "--force" || a === "-f")
|
|
81
|
+
force = true;
|
|
82
|
+
else if (a === "--url")
|
|
83
|
+
url = value();
|
|
84
|
+
else if (a === "--env" || a === "-e") {
|
|
85
|
+
const v = value();
|
|
86
|
+
const eq = v.indexOf("=");
|
|
87
|
+
if (eq <= 0)
|
|
88
|
+
throw new Error(`--env needs KEY=VALUE, got ${JSON.stringify(v)}`);
|
|
89
|
+
envVars[v.slice(0, eq)] = v.slice(eq + 1);
|
|
90
|
+
}
|
|
91
|
+
else if (a === "--header" || a === "-H") {
|
|
92
|
+
const v = value();
|
|
93
|
+
const colon = v.indexOf(":");
|
|
94
|
+
if (colon <= 0)
|
|
95
|
+
throw new Error(`--header needs "Name: value", got ${JSON.stringify(v)}`);
|
|
96
|
+
headers[v.slice(0, colon).trim()] = v.slice(colon + 1).trim();
|
|
97
|
+
}
|
|
98
|
+
else if (a.startsWith("-"))
|
|
99
|
+
throw new Error(`unknown option ${a}\n${usage}`);
|
|
100
|
+
else if (name === undefined)
|
|
101
|
+
name = a;
|
|
102
|
+
else {
|
|
103
|
+
// 名字之后第一个不是选项的参数是服务的命令,后面的都原样交给它(npx -y … 里的 -y 不是 jade 的选项)
|
|
104
|
+
command = tail.slice(i);
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (name === undefined)
|
|
109
|
+
throw new Error(usage);
|
|
110
|
+
if (url !== undefined && command?.length)
|
|
111
|
+
throw new Error(`give either --url or a command, not both\n${usage}`);
|
|
112
|
+
if (url === undefined && !command?.length)
|
|
113
|
+
throw new Error(`give a command or --url\n${usage}`);
|
|
114
|
+
let config;
|
|
115
|
+
if (url !== undefined) {
|
|
116
|
+
// 含 ${VAR} 的地址要到读配置时才知道展开后是什么,那时再检查
|
|
117
|
+
if (!/^https?:\/\//.test(url) && !url.includes("${"))
|
|
118
|
+
throw new Error(`--url must start with http:// or https://`);
|
|
119
|
+
if (Object.keys(envVars).length)
|
|
120
|
+
throw new Error("--env is for servers started with a command; a --url server takes --header");
|
|
121
|
+
config = { type: "http", url, ...(Object.keys(headers).length ? { headers } : {}) };
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
if (Object.keys(headers).length)
|
|
125
|
+
throw new Error("--header is for --url servers; a command takes --env");
|
|
126
|
+
const [cmd, ...args] = command;
|
|
127
|
+
config = { command: cmd, ...(args.length ? { args } : {}), ...(Object.keys(envVars).length ? { env: envVars } : {}) };
|
|
128
|
+
}
|
|
129
|
+
const problem = checkConfig(name, config);
|
|
130
|
+
if (problem)
|
|
131
|
+
throw new Error(`MCP server ${JSON.stringify(name)}: ${problem}`);
|
|
132
|
+
return { name, project, force, config };
|
|
133
|
+
}
|
|
134
|
+
/** 读配置文件、改 mcpServers、写回;文件坏了时报错,不覆盖 */
|
|
135
|
+
async function edit(file, change) {
|
|
136
|
+
let json = {};
|
|
137
|
+
let text;
|
|
138
|
+
try {
|
|
139
|
+
text = await readFile(file, "utf8");
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
// 还没有这个文件
|
|
143
|
+
}
|
|
144
|
+
if (text !== undefined && text.trim()) {
|
|
145
|
+
try {
|
|
146
|
+
json = JSON.parse(text);
|
|
147
|
+
}
|
|
148
|
+
catch (e) {
|
|
149
|
+
throw new Error(`${file}: ${e instanceof Error ? e.message : String(e)}; fix it by hand first`);
|
|
150
|
+
}
|
|
151
|
+
if (typeof json !== "object" || json === null || Array.isArray(json))
|
|
152
|
+
throw new Error(`${file}: expected { "mcpServers": { ... } }; fix it by hand first`);
|
|
153
|
+
}
|
|
154
|
+
const servers = (json.mcpServers ??= {});
|
|
155
|
+
if (typeof servers !== "object" || servers === null || Array.isArray(servers))
|
|
156
|
+
throw new Error(`${file}: "mcpServers" is not an object; fix it by hand first`);
|
|
157
|
+
change(servers);
|
|
158
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
159
|
+
await writeFile(file, JSON.stringify(json, null, 2) + "\n");
|
|
160
|
+
}
|
package/plugins-dist/mcp/mcp.js
CHANGED
|
@@ -90,7 +90,8 @@ export async function loadMcpConfig(opts) {
|
|
|
90
90
|
return { servers: [...out.values()], warnings };
|
|
91
91
|
}
|
|
92
92
|
const SERVER_NAME = /^[A-Za-z0-9_.-]+$/;
|
|
93
|
-
|
|
93
|
+
/** 一条服务配置的问题;没问题时为 undefined。/mcp add 写入前也用它检查 */
|
|
94
|
+
export function checkConfig(name, raw) {
|
|
94
95
|
if (!SERVER_NAME.test(name))
|
|
95
96
|
return "the name may only contain letters, digits, '.', '_' and '-'";
|
|
96
97
|
if (typeof raw !== "object" || raw === null || Array.isArray(raw))
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// 仓库目录、确认记录、显示用的小工具、斜杠命令参数的切分、token 估算。插件之间不共享代码(只能共享类型),jade/skills、jade/checks 各有一份。
|
|
2
2
|
import { existsSync, realpathSync } from "node:fs";
|
|
3
3
|
import { appendFile, mkdir, readFile } from "node:fs/promises";
|
|
4
4
|
import path from "node:path";
|
|
@@ -88,3 +88,44 @@ export const red = paint("31", "39");
|
|
|
88
88
|
export const green = paint("32", "39");
|
|
89
89
|
export const yellow = paint("33", "39");
|
|
90
90
|
export const bold = paint("1", "22");
|
|
91
|
+
/** 斜杠命令的参数按空白切开;"…" 或 '…' 里的空白不切(不处理反斜杠,Windows 路径照写) */
|
|
92
|
+
export function splitArgs(text) {
|
|
93
|
+
const out = [];
|
|
94
|
+
let cur = "";
|
|
95
|
+
let started = false;
|
|
96
|
+
let quote;
|
|
97
|
+
for (const ch of text) {
|
|
98
|
+
if (quote) {
|
|
99
|
+
if (ch === quote)
|
|
100
|
+
quote = undefined;
|
|
101
|
+
else
|
|
102
|
+
cur += ch;
|
|
103
|
+
}
|
|
104
|
+
else if (ch === '"' || ch === "'") {
|
|
105
|
+
quote = ch;
|
|
106
|
+
started = true;
|
|
107
|
+
}
|
|
108
|
+
else if (/\s/.test(ch)) {
|
|
109
|
+
if (started)
|
|
110
|
+
out.push(cur);
|
|
111
|
+
cur = "";
|
|
112
|
+
started = false;
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
cur += ch;
|
|
116
|
+
started = true;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (quote)
|
|
120
|
+
throw new Error(`unclosed ${quote}`);
|
|
121
|
+
if (started)
|
|
122
|
+
out.push(cur);
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
/** 中日韩文字和全角符号:大约一个字一个 token(和 jade/compact 的估算一致) */
|
|
126
|
+
const WIDE = /[ -鿿가-豈--]/g;
|
|
127
|
+
/** 粗略估算一段文字发给模型时占多少 token:英文和代码约 4 个字符 1 个,中日韩文字每字约 1 个 */
|
|
128
|
+
export function estimateTokens(text) {
|
|
129
|
+
const wide = text.match(WIDE)?.length ?? 0;
|
|
130
|
+
return Math.ceil((text.length - wide) / 4 + wide);
|
|
131
|
+
}
|