@ai-zen/agents-sdk 1.0.0-alpha.24 → 1.0.0-alpha.26
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/CHANGELOG.md +209 -0
- package/README.md +5 -5
- package/README.zh.md +5 -5
- package/dist/agent-plugins/AutoMigratePlugin.js +1 -3
- package/dist/agent-plugins/AutoRefreshToolsPlugin.js +1 -3
- package/dist/agent-plugins/ContextGuardPlugin.d.ts +15 -1
- package/dist/agent-plugins/ContextGuardPlugin.js +11 -1
- package/dist/config/ConfigManager.js +1 -1
- package/dist/config/constants.js +5 -8
- package/dist/config/migrate.d.ts +31 -0
- package/dist/config/migrate.js +52 -4
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/runtime/HandoffService.d.ts +5 -4
- package/dist/runtime/HandoffService.js +17 -14
- package/dist/runtime/createAgent.js +1 -3
- package/dist/scope/Scope.d.ts +3 -1
- package/dist/scope/Scope.js +3 -1
- package/dist/scope/plugins/builtin/BatchEditTool.js +15 -8
- package/dist/scope/plugins/builtin/DownloadFileTool.d.ts +1 -0
- package/dist/scope/plugins/builtin/DownloadFileTool.js +54 -30
- package/dist/scope/plugins/builtin/EditTool.js +13 -18
- package/dist/scope/plugins/builtin/ExecTool.js +127 -18
- package/dist/scope/plugins/builtin/FindTextTool.js +6 -1
- package/dist/scope/plugins/builtin/GenerateImageTool.js +80 -14
- package/dist/scope/plugins/builtin/GlobTool.js +6 -1
- package/dist/scope/plugins/builtin/SpawnTool.js +28 -45
- package/dist/scope/plugins/builtin/ViewImageTool.js +6 -2
- package/dist/scope/plugins/builtin/searchBase.d.ts +9 -0
- package/dist/scope/plugins/builtin/searchBase.js +17 -0
- package/dist/scope/plugins/builtin/test-helpers.d.ts +3 -3
- package/dist/scope/plugins/builtin/test-helpers.js +3 -3
- package/dist/scope/plugins/builtin/textEdit.d.ts +17 -0
- package/dist/scope/plugins/builtin/textEdit.js +37 -0
- package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +9 -1
- package/dist/scope/plugins/mcp/McpConnectionManager.js +88 -9
- package/dist/scope/plugins/mcp/McpScopePlugin.js +7 -6
- package/dist/scope/plugins/mcp/mcpTools.d.ts +2 -2
- package/dist/scope/plugins/mcp/mcpTools.js +42 -10
- package/dist/scope/plugins/skills/SkillsScopePlugin.js +2 -3
- package/dist/scope/plugins/skills/discover.js +25 -5
- package/dist/scope/plugins/skills/skillTools.js +13 -1
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +1 -3
- package/dist/scope/plugins/usertools/discover.js +8 -2
- package/dist/shared/EntityRepository.d.ts +10 -1
- package/dist/shared/EntityRepository.js +18 -6
- package/dist/shared/content-blocks.d.ts +5 -12
- package/dist/shared/content-blocks.js +1 -1
- package/dist/types/index.d.ts +48 -0
- package/package.json +5 -6
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
import OpenAI from "openai";
|
|
2
|
+
import * as fsp from "fs/promises";
|
|
3
|
+
import * as os from "os";
|
|
4
|
+
import * as path from "path";
|
|
5
|
+
import { randomBytes } from "crypto";
|
|
2
6
|
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
7
|
+
/** 默认图片生成实现:走 OpenAI SDK 的 `images.generate`(任何 OpenAI 兼容端点均可) */
|
|
8
|
+
const defaultGenerateImage = async ({ endpoint, model, prompt, size, quality, signal, }) => {
|
|
9
|
+
const client = new OpenAI({ apiKey: endpoint.apiKey, baseURL: endpoint.baseUrl });
|
|
10
|
+
// 厂商特有字段(size / quality)用 any 透传
|
|
11
|
+
const result = await client.images.generate({ model, prompt, size, quality }, { signal });
|
|
12
|
+
return {
|
|
13
|
+
created: result.created,
|
|
14
|
+
// 有的端点只返回 b64_json,两类字段都原样带出去,由调用方决定怎么落地
|
|
15
|
+
data: (result.data ?? []),
|
|
16
|
+
};
|
|
17
|
+
};
|
|
3
18
|
/**
|
|
4
19
|
* 根据文字描述生成图片。**统一返回字符串**(JSON,含图片 URL 列表):
|
|
5
20
|
* 生成结果如何处理(查看/下载/转发)由模型与上层自由决定——
|
|
@@ -29,7 +44,7 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
29
44
|
},
|
|
30
45
|
size: {
|
|
31
46
|
type: "string",
|
|
32
|
-
description:
|
|
47
|
+
description: "Image size. Defaults to the model default size. cogview series: 1024x1024, 768x1344, 864x1152, 1344x768, 1152x864, 1440x720, 720x1440. glm-image: 1280x1280, 1568x1056, 1056x1568, 1472x1088, 1088x1472, 1728x960, 960x1728.",
|
|
33
48
|
},
|
|
34
49
|
quality: {
|
|
35
50
|
type: "string",
|
|
@@ -83,31 +98,52 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
83
98
|
error: `API Key for endpoint "${endpoint.name}" is not set`,
|
|
84
99
|
});
|
|
85
100
|
}
|
|
86
|
-
const client = new OpenAI({
|
|
87
|
-
apiKey: endpoint.apiKey,
|
|
88
|
-
baseURL: endpoint.baseUrl,
|
|
89
|
-
});
|
|
90
101
|
const modelName = input.model || imageModel.modelName;
|
|
91
|
-
//
|
|
92
|
-
const
|
|
102
|
+
// 出网动作走注入的 deps(缺省时用 OpenAI SDK),测试无需 mock openai 模块
|
|
103
|
+
const generateImage = this.env.deps?.generateImage ?? defaultGenerateImage;
|
|
104
|
+
const result = await generateImage({
|
|
105
|
+
endpoint,
|
|
93
106
|
model: modelName,
|
|
94
107
|
prompt: prompt.trim(),
|
|
95
108
|
size: input.size || imageModel.defaultSize || undefined,
|
|
96
109
|
quality: input.quality || imageModel.defaultQuality || undefined,
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
110
|
+
signal,
|
|
111
|
+
});
|
|
112
|
+
// 逐个收集:有 url 的直接给链接;只有 b64_json 的端点则落盘后给本地路径。
|
|
113
|
+
// 只看 url 会把「只返回 b64_json 的模型」变成 success: true + images: [](假成功)。
|
|
114
|
+
const images = [];
|
|
115
|
+
for (const [index, item] of (result.data ?? []).entries()) {
|
|
116
|
+
if (item.url) {
|
|
117
|
+
images.push({ index, url: item.url });
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (item.b64_json) {
|
|
121
|
+
images.push({ index, filePath: await saveBase64Image(item.b64_json) });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (images.length === 0) {
|
|
125
|
+
return JSON.stringify({
|
|
126
|
+
success: false,
|
|
127
|
+
model: imageModel.name,
|
|
128
|
+
modelId: imageModel.id,
|
|
129
|
+
created: result.created,
|
|
130
|
+
images: [],
|
|
131
|
+
error: "The endpoint returned no image: neither `url` nor `b64_json` was present in the response",
|
|
132
|
+
});
|
|
133
|
+
}
|
|
101
134
|
// 统一返回字符串(JSON):生成结果如何处理(查看/下载/转发)由模型与上层自由决定,
|
|
102
|
-
// 不替模型做「看或不看」的假设。需要让模型看图 → 模型可主动调用 view_image
|
|
135
|
+
// 不替模型做「看或不看」的假设。需要让模型看图 → 模型可主动调用 view_image;
|
|
103
136
|
// 需要保存 → download_file 下载。
|
|
137
|
+
const hasUrl = images.some((img) => img.url);
|
|
104
138
|
return JSON.stringify({
|
|
105
139
|
success: true,
|
|
106
140
|
model: imageModel.name,
|
|
107
141
|
modelId: imageModel.id,
|
|
108
142
|
created: result.created,
|
|
109
|
-
images
|
|
110
|
-
note:
|
|
143
|
+
images,
|
|
144
|
+
note: hasUrl
|
|
145
|
+
? "Image links are temporary and expire after 30 days. To inspect the image content, use the view_image tool (pass the image URL); to save it, use download_file."
|
|
146
|
+
: "The endpoint returned base64 images; they were written to local files, so use view_image with the filePath to inspect them.",
|
|
111
147
|
}, null, 2);
|
|
112
148
|
}
|
|
113
149
|
catch (error) {
|
|
@@ -126,3 +162,33 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
126
162
|
}
|
|
127
163
|
}
|
|
128
164
|
}
|
|
165
|
+
/** 依据 base64 头部字节判断图片扩展名(判断不了就当 png) */
|
|
166
|
+
function imageExtension(buffer) {
|
|
167
|
+
if (buffer.length >= 8 && buffer.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"))) {
|
|
168
|
+
return "png";
|
|
169
|
+
}
|
|
170
|
+
if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
|
|
171
|
+
return "jpg";
|
|
172
|
+
}
|
|
173
|
+
if (buffer.length >= 6 && buffer.subarray(0, 3).toString("latin1") === "GIF")
|
|
174
|
+
return "gif";
|
|
175
|
+
if (buffer.length >= 12 &&
|
|
176
|
+
buffer.subarray(0, 4).toString("latin1") === "RIFF" &&
|
|
177
|
+
buffer.subarray(8, 12).toString("latin1") === "WEBP") {
|
|
178
|
+
return "webp";
|
|
179
|
+
}
|
|
180
|
+
return "png";
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* 把 `b64_json` 写成本地文件,返回绝对路径。
|
|
184
|
+
*
|
|
185
|
+
* 落盘到系统临时目录下的独立子目录(与工具输出落盘同一习惯),不污染工作目录。
|
|
186
|
+
*/
|
|
187
|
+
async function saveBase64Image(b64) {
|
|
188
|
+
const buffer = Buffer.from(b64, "base64");
|
|
189
|
+
const dir = path.join(os.tmpdir(), "ai-zen", "generated-images");
|
|
190
|
+
await fsp.mkdir(dir, { recursive: true });
|
|
191
|
+
const filePath = path.join(dir, `image-${Date.now()}-${randomBytes(4).toString("hex")}.${imageExtension(buffer)}`);
|
|
192
|
+
await fsp.writeFile(filePath, buffer);
|
|
193
|
+
return filePath;
|
|
194
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as fsp from "fs/promises";
|
|
2
2
|
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
3
3
|
import { DEFAULT_MAX_TOOL_OUTPUT, guardOutput, headPreview } from "./outputGuard.js";
|
|
4
|
+
import { checkBaseDirectory } from "./searchBase.js";
|
|
4
5
|
export class GlobTool extends SdkCallbackTool {
|
|
5
6
|
function = {
|
|
6
7
|
name: "glob",
|
|
@@ -18,7 +19,7 @@ export class GlobTool extends SdkCallbackTool {
|
|
|
18
19
|
},
|
|
19
20
|
exclude: {
|
|
20
21
|
type: "array",
|
|
21
|
-
description:
|
|
22
|
+
description: 'Glob patterns to exclude. When omitted, defaults to ["**/node_modules/**"]; pass an explicit list to override.',
|
|
22
23
|
items: {
|
|
23
24
|
type: "string",
|
|
24
25
|
},
|
|
@@ -35,6 +36,10 @@ export class GlobTool extends SdkCallbackTool {
|
|
|
35
36
|
const signal = ctx?.signal;
|
|
36
37
|
try {
|
|
37
38
|
const cwd = input.path ? this.resolve(input.path) : this.env.cwd;
|
|
39
|
+
// 基目录不存在/不是目录时明确报错:静默返回 [] 会被模型当成「文件不存在」
|
|
40
|
+
const baseError = await checkBaseDirectory(cwd);
|
|
41
|
+
if (baseError)
|
|
42
|
+
return baseError;
|
|
38
43
|
const result = [];
|
|
39
44
|
for await (const file of fsp.glob(input.pattern, {
|
|
40
45
|
exclude: input.exclude || ["**/node_modules/**"],
|
|
@@ -31,7 +31,13 @@ export class SpawnTool extends SdkCallbackTool {
|
|
|
31
31
|
const command = input.command;
|
|
32
32
|
const cwd = input.cwd ? this.resolve(input.cwd) : this.env.cwd;
|
|
33
33
|
const detached = input.detached ?? false;
|
|
34
|
-
|
|
34
|
+
/**
|
|
35
|
+
* 本工具只回答「进程是否已启动」,**不跟踪退出状态**。
|
|
36
|
+
*
|
|
37
|
+
* 它 spawn 后立刻返回,输出也走 `stdio: "ignore"` 丢弃;因此命令不存在、语法错误、
|
|
38
|
+
* 脚本起来就崩这类「早退失败」在这里一律看不见 —— 以前会把它们报成 `success: true`,
|
|
39
|
+
* 现在如实命名为 `started`,并在 note 里说清。需要成败/输出/退出码请用 exec。
|
|
40
|
+
*/
|
|
35
41
|
return new Promise((resolve) => {
|
|
36
42
|
const child = spawn(command, [], {
|
|
37
43
|
cwd,
|
|
@@ -41,57 +47,34 @@ export class SpawnTool extends SdkCallbackTool {
|
|
|
41
47
|
windowsHide: true,
|
|
42
48
|
});
|
|
43
49
|
let resolved = false;
|
|
44
|
-
|
|
50
|
+
let timer;
|
|
51
|
+
const done = (payload) => {
|
|
45
52
|
if (resolved)
|
|
46
53
|
return;
|
|
47
54
|
resolved = true;
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
55
|
+
if (timer)
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
resolve(JSON.stringify(payload));
|
|
58
|
+
};
|
|
59
|
+
const startedPayload = () => ({
|
|
60
|
+
started: true,
|
|
61
|
+
pid: child.pid ?? null,
|
|
62
|
+
message: `Process started (PID: ${child.pid ?? "unknown"})`,
|
|
63
|
+
note: "This tool only reports that the process was started; it does not track the exit status. Use exec if you need the exit code or the output.",
|
|
53
64
|
});
|
|
54
|
-
child.on("
|
|
55
|
-
|
|
56
|
-
return;
|
|
57
|
-
resolved = true;
|
|
58
|
-
resolve(JSON.stringify({
|
|
59
|
-
success: true,
|
|
60
|
-
pid: child.pid ?? null,
|
|
61
|
-
message: `Process started (PID: ${child.pid ?? "unknown"})`,
|
|
62
|
-
}));
|
|
65
|
+
child.on("error", (err) => {
|
|
66
|
+
done({ started: false, pid: null, message: `Failed to start: ${err.message}` });
|
|
63
67
|
});
|
|
64
|
-
child.on("
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
resolved = true;
|
|
68
|
-
resolve(JSON.stringify({
|
|
69
|
-
success: code === 0,
|
|
70
|
-
pid: child.pid ?? null,
|
|
71
|
-
exitCode: code,
|
|
72
|
-
message: code === null
|
|
73
|
-
? `Process exited (PID: ${child.pid ?? "unknown"})`
|
|
74
|
-
: `Process exited (PID: ${child.pid ?? "unknown"}, exit code: ${code})`,
|
|
75
|
-
}));
|
|
68
|
+
child.on("spawn", () => {
|
|
69
|
+
child.unref();
|
|
70
|
+
done(startedPayload());
|
|
76
71
|
});
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
resolve(JSON.stringify({
|
|
82
|
-
success: true,
|
|
83
|
-
pid: child.pid ?? null,
|
|
84
|
-
message: `Process started (PID: ${child.pid ?? "unknown"})`,
|
|
85
|
-
}));
|
|
72
|
+
// 兜底:`spawn` 事件理论上必然触发,这里保证工具不会挂住
|
|
73
|
+
timer = setTimeout(() => {
|
|
74
|
+
child.unref();
|
|
75
|
+
done(startedPayload());
|
|
86
76
|
}, 500);
|
|
87
|
-
|
|
88
|
-
clearTimeout(timeout);
|
|
89
|
-
child.removeAllListeners();
|
|
90
|
-
};
|
|
91
|
-
child.on("spawn", cleanup);
|
|
92
|
-
child.on("error", cleanup);
|
|
93
|
-
child.on("exit", cleanup);
|
|
94
|
-
child.unref();
|
|
77
|
+
timer.unref?.();
|
|
95
78
|
});
|
|
96
79
|
}
|
|
97
80
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { promises as fs } from "node:fs";
|
|
3
3
|
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
4
|
-
import { fileToContentSection, mimeOf, resolveModelAndEndpoint } from "../../../shared/content-blocks.js";
|
|
4
|
+
import { fileToContentSection, mimeOf, resolveModelAndEndpoint, } from "../../../shared/content-blocks.js";
|
|
5
5
|
/**
|
|
6
6
|
* 是否为"本地 URL"——指向本地/回环地址,API 服务商无法下载访问。
|
|
7
7
|
* 覆盖 file:// 等本地协议,以及指向本机的 http(s) 地址(localhost、127.0.0.1、[::1]、0.0.0.0)。
|
|
@@ -86,8 +86,12 @@ export class ViewImageTool extends SdkCallbackTool {
|
|
|
86
86
|
endpoint,
|
|
87
87
|
model,
|
|
88
88
|
signal,
|
|
89
|
+
// 出网动作走注入的 deps(缺省时 content-blocks 自己调 OpenAI SDK)
|
|
90
|
+
deps: this.env.deps,
|
|
89
91
|
});
|
|
90
|
-
const label = isUrl
|
|
92
|
+
const label = isUrl
|
|
93
|
+
? `Fetched remote image: ${value}`
|
|
94
|
+
: `Fetched local image (${path.basename(value)})`;
|
|
91
95
|
const how = result.transport === "files-api"
|
|
92
96
|
? `, uploaded to the Files API (file_id: ${result.section.file_id ?? "?"})`
|
|
93
97
|
: result.transport === "inline"
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import * as fsp from "fs/promises";
|
|
2
|
+
/**
|
|
3
|
+
* 校验遍历/搜索的基目录。
|
|
4
|
+
*
|
|
5
|
+
* 没有这层校验时,`fsp.glob()` 对不存在的目录只会安静地返回空结果,模型会据此得出
|
|
6
|
+
* 「这些文件不存在」的错误结论(`ls` 在同场景下是抛 `ENOENT` 的)。
|
|
7
|
+
*
|
|
8
|
+
* 返回错误文本;目录正常时返回 `null`。
|
|
9
|
+
*/
|
|
10
|
+
export async function checkBaseDirectory(dir) {
|
|
11
|
+
const stat = await fsp.stat(dir).catch(() => null);
|
|
12
|
+
if (!stat)
|
|
13
|
+
return `Path does not exist: ${dir}`;
|
|
14
|
+
if (!stat.isDirectory())
|
|
15
|
+
return `Not a directory: ${dir}`;
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import type { AppConfig, ToolEnv } from "../../../types/index.js";
|
|
2
|
-
/** 构造测试用 ToolEnv */
|
|
3
|
-
export declare function makeEnv(cwd?: string, config?: AppConfig): ToolEnv;
|
|
1
|
+
import type { AppConfig, ToolEnv, ToolEnvDeps } from "../../../types/index.js";
|
|
2
|
+
/** 构造测试用 ToolEnv(deps 用于注入出网依赖,避免 mock openai 模块) */
|
|
3
|
+
export declare function makeEnv(cwd?: string, config?: AppConfig, deps?: ToolEnvDeps): ToolEnv;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** 构造测试用 ToolEnv */
|
|
2
|
-
export function makeEnv(cwd = process.cwd(), config = {}) {
|
|
3
|
-
return { cwd, config };
|
|
1
|
+
/** 构造测试用 ToolEnv(deps 用于注入出网依赖,避免 mock openai 模块) */
|
|
2
|
+
export function makeEnv(cwd = process.cwd(), config = {}, deps) {
|
|
3
|
+
return deps ? { cwd, config, deps } : { cwd, config };
|
|
4
4
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 文本替换的公共实现(`edit` / `batch_edit` 共用)。
|
|
3
|
+
*/
|
|
4
|
+
/** 统计 `text` 在 `content` 中非重叠的出现次数(`text` 为空时返回 0) */
|
|
5
|
+
export declare function countOccurrences(content: string, text: string): number;
|
|
6
|
+
/**
|
|
7
|
+
* 执行一次替换,返回新内容与**实际替换次数**。
|
|
8
|
+
*
|
|
9
|
+
* 必须用回调式 replacer:字符串形式的替换值里,`$&`、`` $` ``、`$'`、`$$` 会被
|
|
10
|
+
* `String.replace` 当作替换模式展开(写入的不再是字面量),而回调的返回值一律按字面量处理。
|
|
11
|
+
*
|
|
12
|
+
* `oldText` 为空时不做替换(空串会匹配每一个位置):替换次数恒为 0,由调用方给出提示。
|
|
13
|
+
*/
|
|
14
|
+
export declare function replaceText(content: string, oldText: string, newText: string, isReplaceAll: boolean): {
|
|
15
|
+
content: string;
|
|
16
|
+
replacedCount: number;
|
|
17
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 文本替换的公共实现(`edit` / `batch_edit` 共用)。
|
|
3
|
+
*/
|
|
4
|
+
/** 统计 `text` 在 `content` 中非重叠的出现次数(`text` 为空时返回 0) */
|
|
5
|
+
export function countOccurrences(content, text) {
|
|
6
|
+
if (text === "")
|
|
7
|
+
return 0;
|
|
8
|
+
let count = 0;
|
|
9
|
+
let pos = 0;
|
|
10
|
+
while (true) {
|
|
11
|
+
pos = content.indexOf(text, pos);
|
|
12
|
+
if (pos === -1)
|
|
13
|
+
break;
|
|
14
|
+
count++;
|
|
15
|
+
pos += text.length;
|
|
16
|
+
}
|
|
17
|
+
return count;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* 执行一次替换,返回新内容与**实际替换次数**。
|
|
21
|
+
*
|
|
22
|
+
* 必须用回调式 replacer:字符串形式的替换值里,`$&`、`` $` ``、`$'`、`$$` 会被
|
|
23
|
+
* `String.replace` 当作替换模式展开(写入的不再是字面量),而回调的返回值一律按字面量处理。
|
|
24
|
+
*
|
|
25
|
+
* `oldText` 为空时不做替换(空串会匹配每一个位置):替换次数恒为 0,由调用方给出提示。
|
|
26
|
+
*/
|
|
27
|
+
export function replaceText(content, oldText, newText, isReplaceAll) {
|
|
28
|
+
const matches = countOccurrences(content, oldText);
|
|
29
|
+
if (matches === 0)
|
|
30
|
+
return { content, replacedCount: 0 };
|
|
31
|
+
return {
|
|
32
|
+
content: isReplaceAll
|
|
33
|
+
? content.replaceAll(oldText, () => newText)
|
|
34
|
+
: content.replace(oldText, () => newText),
|
|
35
|
+
replacedCount: isReplaceAll ? matches : 1,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -2,8 +2,10 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
|
2
2
|
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
3
3
|
import type { McpServerConfig, McpServerManifest, McpConnectionState } from "../../../types/index.js";
|
|
4
4
|
export interface McpConnectOptions {
|
|
5
|
-
/** 空闲超时(毫秒),默认 stdio: 30min, http: 5min */
|
|
5
|
+
/** 空闲超时(毫秒),默认 stdio: 30min, http/sse: 5min */
|
|
6
6
|
idleTimeoutMs?: number;
|
|
7
|
+
/** 建连超时(毫秒),默认 60s;超时即断开并抛错,避免工具永久挂起 */
|
|
8
|
+
connectTimeoutMs?: number;
|
|
7
9
|
/** 失败时自动重连 */
|
|
8
10
|
autoReconnect?: boolean;
|
|
9
11
|
/** 最大重试次数,默认 3 */
|
|
@@ -26,8 +28,14 @@ export declare class McpConnectionManager {
|
|
|
26
28
|
getManifest(name: string): McpServerManifest | undefined;
|
|
27
29
|
getClient(name: string): Client | undefined;
|
|
28
30
|
connect(name: string, config: McpServerConfig, options?: McpConnectOptions): Promise<McpServerManifest>;
|
|
31
|
+
/** 给建连套上超时:超时即取消连接并清掉半成品状态 */
|
|
32
|
+
private withConnectTimeout;
|
|
29
33
|
private connectWithRetry;
|
|
30
34
|
private doConnect;
|
|
35
|
+
/** 静默关闭连接资源(断开/取消路径共用) */
|
|
36
|
+
private closeQuietly;
|
|
37
|
+
/** 运行期断线:标记 disconnected 并记日志(已在连接状态才处理,避免重复日志) */
|
|
38
|
+
private markDisconnected;
|
|
31
39
|
/**
|
|
32
40
|
* 根据配置创建对应的 Transport 实例。
|
|
33
41
|
* 如果设置了自定义工厂(测试用),则使用自定义工厂。
|
|
@@ -3,6 +3,13 @@ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
|
3
3
|
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
4
4
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
5
5
|
import { getLogger } from "../../../shared/logger.js";
|
|
6
|
+
/**
|
|
7
|
+
* 建连超时缺省值(毫秒)。
|
|
8
|
+
*
|
|
9
|
+
* 没有上限时,配置错误的 SSE / HTTP 端点会让 `load_mcp` 永久挂起(SSE 在服务端不发
|
|
10
|
+
* 响应头时尤其如此,fetch 只对建链有兜底,对"连上了但永不回话"没有)。与请求超时同口径。
|
|
11
|
+
*/
|
|
12
|
+
const DEFAULT_CONNECT_TIMEOUT_MS = 60_000;
|
|
6
13
|
const DEFAULT_IDLE_TIMEOUT = {
|
|
7
14
|
stdio: 30 * 60 * 1000,
|
|
8
15
|
http: 5 * 60 * 1000,
|
|
@@ -56,9 +63,14 @@ export class McpConnectionManager {
|
|
|
56
63
|
timeoutMs,
|
|
57
64
|
cancelled: false,
|
|
58
65
|
});
|
|
66
|
+
const connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
|
|
59
67
|
try {
|
|
60
|
-
await pendingPromise;
|
|
68
|
+
await this.withConnectTimeout(name, pendingPromise, connectTimeoutMs);
|
|
61
69
|
const entry = this.servers.get(name);
|
|
70
|
+
// 建连期间被 disconnect()/dispose():不要复活连接
|
|
71
|
+
if (entry.cancelled || entry.state === "disconnected") {
|
|
72
|
+
throw new Error(`Connection to "${name}" was cancelled`);
|
|
73
|
+
}
|
|
62
74
|
this.servers.set(name, {
|
|
63
75
|
...entry,
|
|
64
76
|
state: "connected",
|
|
@@ -77,6 +89,30 @@ export class McpConnectionManager {
|
|
|
77
89
|
throw err;
|
|
78
90
|
}
|
|
79
91
|
}
|
|
92
|
+
/** 给建连套上超时:超时即取消连接并清掉半成品状态 */
|
|
93
|
+
async withConnectTimeout(name, promise, timeoutMs) {
|
|
94
|
+
let timer;
|
|
95
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
96
|
+
timer = setTimeout(() => {
|
|
97
|
+
reject(new Error(`MCP server "${name}" connection timed out after ${timeoutMs}ms (check the transport config: command/url/headers)`));
|
|
98
|
+
}, timeoutMs);
|
|
99
|
+
timer.unref?.();
|
|
100
|
+
});
|
|
101
|
+
try {
|
|
102
|
+
await Promise.race([promise, timeout]);
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
if (String(err?.message ?? "").includes("timed out")) {
|
|
106
|
+
// 取消挂着的建连,并清掉它可能建好的资源
|
|
107
|
+
await this.disconnect(name).catch(() => { });
|
|
108
|
+
}
|
|
109
|
+
throw err;
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
if (timer)
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
80
116
|
async connectWithRetry(name, config, options, attempt) {
|
|
81
117
|
try {
|
|
82
118
|
await this.doConnect(name, config);
|
|
@@ -171,6 +207,24 @@ export class McpConnectionManager {
|
|
|
171
207
|
}
|
|
172
208
|
}
|
|
173
209
|
const entry = this.servers.get(name) ?? { state: "connecting" };
|
|
210
|
+
// 建连期间被 disconnect()/dispose()(启动即退出是正常序列):关掉刚建好的资源,
|
|
211
|
+
// 绝不写回 connected,否则连接会"复活"、stdio 子进程也再没人关。
|
|
212
|
+
if (entry.cancelled) {
|
|
213
|
+
await this.closeQuietly(client, transport);
|
|
214
|
+
throw new Error(`Connection to "${name}" was cancelled`);
|
|
215
|
+
}
|
|
216
|
+
// 断线检测:运行期 transport 关掉时把状态标回 disconnected,避免 load_mcp / 状态栏
|
|
217
|
+
// 一直展示过期清单(不做自动重连:重连策略属于上层)。
|
|
218
|
+
const prevOnClose = transport.onclose;
|
|
219
|
+
transport.onclose = () => {
|
|
220
|
+
prevOnClose?.();
|
|
221
|
+
this.markDisconnected(name);
|
|
222
|
+
};
|
|
223
|
+
const prevOnError = transport.onerror;
|
|
224
|
+
transport.onerror = (error) => {
|
|
225
|
+
prevOnError?.(error);
|
|
226
|
+
getLogger().error(`[McpConnectionManager] Transport error for "${name}": ${error?.message ?? error}`);
|
|
227
|
+
};
|
|
174
228
|
this.servers.set(name, {
|
|
175
229
|
...entry,
|
|
176
230
|
state: "connected",
|
|
@@ -180,6 +234,26 @@ export class McpConnectionManager {
|
|
|
180
234
|
cancelled: false,
|
|
181
235
|
});
|
|
182
236
|
}
|
|
237
|
+
/** 静默关闭连接资源(断开/取消路径共用) */
|
|
238
|
+
async closeQuietly(client, transport) {
|
|
239
|
+
try {
|
|
240
|
+
await client?.close();
|
|
241
|
+
}
|
|
242
|
+
catch { }
|
|
243
|
+
try {
|
|
244
|
+
await transport?.close();
|
|
245
|
+
}
|
|
246
|
+
catch { }
|
|
247
|
+
}
|
|
248
|
+
/** 运行期断线:标记 disconnected 并记日志(已在连接状态才处理,避免重复日志) */
|
|
249
|
+
markDisconnected(name) {
|
|
250
|
+
const entry = this.servers.get(name);
|
|
251
|
+
if (!entry || entry.state !== "connected")
|
|
252
|
+
return;
|
|
253
|
+
getLogger().error(`[McpConnectionManager] MCP server "${name}" disconnected`);
|
|
254
|
+
this.clearTimeout(name);
|
|
255
|
+
this.servers.set(name, { state: "disconnected" });
|
|
256
|
+
}
|
|
183
257
|
/**
|
|
184
258
|
* 根据配置创建对应的 Transport 实例。
|
|
185
259
|
* 如果设置了自定义工厂(测试用),则使用自定义工厂。
|
|
@@ -233,14 +307,19 @@ export class McpConnectionManager {
|
|
|
233
307
|
entry.retryTimer = undefined;
|
|
234
308
|
}
|
|
235
309
|
this.clearTimeout(name);
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
310
|
+
// 断开失败也清理状态。注意保留 `cancelled`:建连中的 await 回来后要据此放弃写入。
|
|
311
|
+
await this.closeQuietly(entry.client, entry.transport);
|
|
312
|
+
this.servers.set(name, {
|
|
313
|
+
...entry,
|
|
314
|
+
state: "disconnected",
|
|
315
|
+
client: undefined,
|
|
316
|
+
transport: undefined,
|
|
317
|
+
manifest: undefined,
|
|
318
|
+
pendingPromise: undefined,
|
|
319
|
+
timeoutTimer: undefined,
|
|
320
|
+
retryTimer: undefined,
|
|
321
|
+
cancelRetryWait: undefined,
|
|
322
|
+
});
|
|
244
323
|
}
|
|
245
324
|
async disconnectAll() {
|
|
246
325
|
const names = Array.from(this.servers.keys());
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isAbsolute, join } from "node:path";
|
|
2
2
|
import { discoverMcpServers } from "./discover.js";
|
|
3
|
-
import { createCallMcpTool, createLoadMcpTool, createReadMcpResourceTool
|
|
3
|
+
import { createCallMcpTool, createLoadMcpTool, createReadMcpResourceTool } from "./mcpTools.js";
|
|
4
4
|
import { McpConnectionManager } from "./McpConnectionManager.js";
|
|
5
5
|
/**
|
|
6
6
|
* MCP 插件 —— 发现 mcp.json + 自持连接管理器 + 装配渐进式披露元工具。
|
|
@@ -20,8 +20,7 @@ export class McpScopePlugin {
|
|
|
20
20
|
servers = [];
|
|
21
21
|
constructor(options) {
|
|
22
22
|
this.paths = options?.paths ?? [];
|
|
23
|
-
this.mcpManager =
|
|
24
|
-
this.paths.length > 0 ? new McpConnectionManager() : undefined;
|
|
23
|
+
this.mcpManager = this.paths.length > 0 ? new McpConnectionManager() : undefined;
|
|
25
24
|
}
|
|
26
25
|
async discover(scope) {
|
|
27
26
|
const files = this.paths.map((p) => (isAbsolute(p) ? p : join(scope.cwd, p)));
|
|
@@ -41,17 +40,19 @@ export class McpScopePlugin {
|
|
|
41
40
|
const allow = new Set(filtered.tools);
|
|
42
41
|
const allowedMcps = new Set(filtered.mcps);
|
|
43
42
|
const filteredMcps = this.servers.filter((s) => allowedMcps.has(s.id));
|
|
43
|
+
const mcps = filteredMcps.map((s) => s.id);
|
|
44
44
|
const m = this.mcpManager;
|
|
45
45
|
const result = [];
|
|
46
46
|
if (allow.has("load_mcp") && m && filteredMcps.length > 0) {
|
|
47
47
|
result.push(createLoadMcpTool(m, filteredMcps));
|
|
48
48
|
}
|
|
49
49
|
if (allow.has("call_mcp_tool") && m) {
|
|
50
|
-
// env 供 call_mcp_tool 读取 maxToolOutput
|
|
51
|
-
|
|
50
|
+
// env 供 call_mcp_tool 读取 maxToolOutput,与内置工具共用同一上限口径;
|
|
51
|
+
// filteredMcps 是权限白名单(连接管理器全局共享,必须按 Scope 过滤)
|
|
52
|
+
result.push(createCallMcpTool(m, scope.env, mcps));
|
|
52
53
|
}
|
|
53
54
|
if (allow.has("read_mcp_resource") && m) {
|
|
54
|
-
result.push(createReadMcpResourceTool(m, scope.env));
|
|
55
|
+
result.push(createReadMcpResourceTool(m, scope.env, mcps));
|
|
55
56
|
}
|
|
56
57
|
return result;
|
|
57
58
|
}
|
|
@@ -17,8 +17,8 @@ export declare function createLoadMcpTool(mcpManager: McpConnectionManager, filt
|
|
|
17
17
|
*
|
|
18
18
|
* env 仅用于读取 maxToolOutput(文本输出保护上限),与内置工具口径一致。
|
|
19
19
|
*/
|
|
20
|
-
export declare function createCallMcpTool(mcpManager: McpConnectionManager, env: ToolEnv): CallbackTool;
|
|
20
|
+
export declare function createCallMcpTool(mcpManager: McpConnectionManager, env: ToolEnv, filteredMcps: string[]): CallbackTool;
|
|
21
21
|
/**
|
|
22
22
|
* 创建 read_mcp_resource 工具。
|
|
23
23
|
*/
|
|
24
|
-
export declare function createReadMcpResourceTool(mcpManager: McpConnectionManager, env: ToolEnv): CallbackTool;
|
|
24
|
+
export declare function createReadMcpResourceTool(mcpManager: McpConnectionManager, env: ToolEnv, filteredMcps: string[]): CallbackTool;
|