@ai-zen/agents-sdk 1.0.0-alpha.25 → 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 +134 -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.js +1 -3
- 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.js +1 -3
- 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 +4 -5
|
@@ -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;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CallbackTool } from "@ai-zen/agents-core";
|
|
2
|
-
import { fileToContentSection, resolveModelAndEndpoint } from "../../../shared/content-blocks.js";
|
|
2
|
+
import { fileToContentSection, resolveModelAndEndpoint, } from "../../../shared/content-blocks.js";
|
|
3
3
|
import { createDisclosureParam } from "../../disclosure.js";
|
|
4
4
|
import { DEFAULT_MAX_TOOL_OUTPUT, guardOutput, headTailPreview } from "../builtin/outputGuard.js";
|
|
5
5
|
import { getLogger } from "../../../shared/logger.js";
|
|
@@ -111,6 +111,7 @@ async function mediaSection(data, mime, media) {
|
|
|
111
111
|
endpoint: media.endpoint,
|
|
112
112
|
model: media.model,
|
|
113
113
|
signal: media.signal,
|
|
114
|
+
deps: media.deps,
|
|
114
115
|
});
|
|
115
116
|
return section;
|
|
116
117
|
}
|
|
@@ -229,9 +230,7 @@ async function protectCallOutput(output, env) {
|
|
|
229
230
|
const hasMedia = sections.some((s) => s.type !== "text");
|
|
230
231
|
if (!hasMedia)
|
|
231
232
|
return isError ? `❌ Tool execution failed:\n${fullText}` : fullText;
|
|
232
|
-
return isError
|
|
233
|
-
? [{ type: "text", text: "❌ Tool execution failed:" }, ...sections]
|
|
234
|
-
: sections;
|
|
233
|
+
return isError ? [{ type: "text", text: "❌ Tool execution failed:" }, ...sections] : sections;
|
|
235
234
|
}
|
|
236
235
|
/**
|
|
237
236
|
* 创建 call_mcp_tool 工具。
|
|
@@ -243,7 +242,11 @@ async function protectCallOutput(output, env) {
|
|
|
243
242
|
*
|
|
244
243
|
* env 仅用于读取 maxToolOutput(文本输出保护上限),与内置工具口径一致。
|
|
245
244
|
*/
|
|
246
|
-
export function createCallMcpTool(mcpManager, env) {
|
|
245
|
+
export function createCallMcpTool(mcpManager, env, filteredMcps) {
|
|
246
|
+
// 权限白名单:`filteredMcps` 是本 Scope 允许的 server。
|
|
247
|
+
// 连接管理器是全局共享的,只按"是否 connected"判断会让任一 Agent 连上的 server 对其他 Scope 敞开。
|
|
248
|
+
const allowed = new Set(filteredMcps);
|
|
249
|
+
const allowList = filteredMcps.join(", ") || "(none)";
|
|
247
250
|
return new CallbackTool({
|
|
248
251
|
function: {
|
|
249
252
|
name: "call_mcp_tool",
|
|
@@ -261,6 +264,9 @@ export function createCallMcpTool(mcpManager, env) {
|
|
|
261
264
|
},
|
|
262
265
|
callback: async (input, ctx) => {
|
|
263
266
|
const serverName = input.server;
|
|
267
|
+
if (!allowed.has(serverName)) {
|
|
268
|
+
return `❌ MCP server "${serverName}" is not available here. Available servers: ${allowList}`;
|
|
269
|
+
}
|
|
264
270
|
const state = mcpManager.getState(serverName);
|
|
265
271
|
if (state !== "connected") {
|
|
266
272
|
return `Call load_mcp to connect "${serverName}" first`;
|
|
@@ -281,11 +287,21 @@ export function createCallMcpTool(mcpManager, env) {
|
|
|
281
287
|
// 没有 content 时退回原始 JSON(既有兜底)
|
|
282
288
|
if (contents.length === 0) {
|
|
283
289
|
const json = JSON.stringify(result);
|
|
284
|
-
return await protectCallOutput({
|
|
290
|
+
return await protectCallOutput({
|
|
291
|
+
sections: [{ type: "text", text: json }],
|
|
292
|
+
fullText: json,
|
|
293
|
+
chars: json.length,
|
|
294
|
+
isError,
|
|
295
|
+
}, env);
|
|
285
296
|
}
|
|
286
297
|
// 按当前模型定位端点:决定媒体走 Files API 上传还是 base64 内联
|
|
287
298
|
const { model, endpoint } = resolveModelAndEndpoint(env.config, ctx?.agent?.model);
|
|
288
|
-
const mediaContext = {
|
|
299
|
+
const mediaContext = {
|
|
300
|
+
endpoint,
|
|
301
|
+
model,
|
|
302
|
+
signal: ctx?.signal,
|
|
303
|
+
deps: env.deps,
|
|
304
|
+
};
|
|
289
305
|
// Promise.all 保序:文本与媒体的相对位置不变
|
|
290
306
|
const sections = await Promise.all(contents.map((block) => toMessageSection(block, mediaContext)));
|
|
291
307
|
const textSections = sections.filter((s) => s.type === "text");
|
|
@@ -302,7 +318,10 @@ export function createCallMcpTool(mcpManager, env) {
|
|
|
302
318
|
/**
|
|
303
319
|
* 创建 read_mcp_resource 工具。
|
|
304
320
|
*/
|
|
305
|
-
export function createReadMcpResourceTool(mcpManager, env) {
|
|
321
|
+
export function createReadMcpResourceTool(mcpManager, env, filteredMcps) {
|
|
322
|
+
// 与 call_mcp_tool 同一白名单口径(见该工具的说明)
|
|
323
|
+
const allowed = new Set(filteredMcps);
|
|
324
|
+
const allowList = filteredMcps.join(", ") || "(none)";
|
|
306
325
|
return new CallbackTool({
|
|
307
326
|
function: {
|
|
308
327
|
name: "read_mcp_resource",
|
|
@@ -319,6 +338,9 @@ export function createReadMcpResourceTool(mcpManager, env) {
|
|
|
319
338
|
},
|
|
320
339
|
callback: async (input, ctx) => {
|
|
321
340
|
const serverName = input.server;
|
|
341
|
+
if (!allowed.has(serverName)) {
|
|
342
|
+
return `❌ MCP server "${serverName}" is not available here. Available servers: ${allowList}`;
|
|
343
|
+
}
|
|
322
344
|
const state = mcpManager.getState(serverName);
|
|
323
345
|
if (state !== "connected") {
|
|
324
346
|
return `Call load_mcp to connect "${serverName}" first`;
|
|
@@ -332,14 +354,24 @@ export function createReadMcpResourceTool(mcpManager, env) {
|
|
|
332
354
|
const result = await client.readResource({ uri: input.uri }, { signal: ctx?.signal });
|
|
333
355
|
const contents = result?.contents ?? [];
|
|
334
356
|
const { model, endpoint } = resolveModelAndEndpoint(env.config, ctx?.agent?.model);
|
|
335
|
-
const mediaContext = {
|
|
357
|
+
const mediaContext = {
|
|
358
|
+
endpoint,
|
|
359
|
+
model,
|
|
360
|
+
signal: ctx?.signal,
|
|
361
|
+
deps: env.deps,
|
|
362
|
+
};
|
|
336
363
|
// 与 call_mcp_tool 同一套映射:文本归一为 text 块,媒体按端点能力上传或内联,
|
|
337
364
|
// 不再把二进制资源(图片 / PDF)静默丢掉。
|
|
338
365
|
const sections = await Promise.all(contents.map((content) => resourceToMessageSection(content, mediaContext)));
|
|
339
366
|
// 没有 contents 时退回原始 JSON(与 call_mcp_tool 同一兜底)
|
|
340
367
|
if (sections.length === 0) {
|
|
341
368
|
const json = JSON.stringify(result);
|
|
342
|
-
return await protectCallOutput({
|
|
369
|
+
return await protectCallOutput({
|
|
370
|
+
sections: [{ type: "text", text: json }],
|
|
371
|
+
fullText: json,
|
|
372
|
+
chars: json.length,
|
|
373
|
+
isError: false,
|
|
374
|
+
}, env);
|
|
343
375
|
}
|
|
344
376
|
// 与 call_mcp_tool 共用同一套输出保护:文本超限落盘 result.txt,
|
|
345
377
|
// 媒体块原位保留;未超限时纯文本退化为字符串、含媒体返回块数组。
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isAbsolute, join } from "node:path";
|
|
2
2
|
import { discoverSkills } from "./discover.js";
|
|
3
|
-
import { createCallSkillSubAgentTool, createLoadSkillTool
|
|
3
|
+
import { createCallSkillSubAgentTool, createLoadSkillTool } from "./skillTools.js";
|
|
4
4
|
/**
|
|
5
5
|
* Skill 插件 —— 发现 SKILL.md + 装配渐进式披露元工具。
|
|
6
6
|
*
|
|
@@ -39,8 +39,7 @@ export class SkillsScopePlugin {
|
|
|
39
39
|
result.push(createLoadSkillTool(this.dirs, filteredSkills));
|
|
40
40
|
}
|
|
41
41
|
// call_skill_sub_agent:只要有支持子 Agent 的 skill 就注册
|
|
42
|
-
if (allow.has("call_skill_sub_agent") &&
|
|
43
|
-
filteredSkills.some((s) => s.subAgent)) {
|
|
42
|
+
if (allow.has("call_skill_sub_agent") && filteredSkills.some((s) => s.subAgent)) {
|
|
44
43
|
result.push(createCallSkillSubAgentTool(this.dirs, filteredSkills));
|
|
45
44
|
}
|
|
46
45
|
return result;
|
|
@@ -169,23 +169,43 @@ export function validateSkill(skillId, fm) {
|
|
|
169
169
|
}
|
|
170
170
|
else {
|
|
171
171
|
if (fm.name.length > 64) {
|
|
172
|
-
errors.push({
|
|
172
|
+
errors.push({
|
|
173
|
+
skillId,
|
|
174
|
+
field: "name",
|
|
175
|
+
message: `Exceeds 64 characters (currently ${fm.name.length})`,
|
|
176
|
+
});
|
|
173
177
|
}
|
|
174
178
|
if (!VALID_NAME_RE.test(fm.name)) {
|
|
175
|
-
errors.push({
|
|
179
|
+
errors.push({
|
|
180
|
+
skillId,
|
|
181
|
+
field: "name",
|
|
182
|
+
message: `"${fm.name}" is not valid: only lowercase letters, digits and hyphens are allowed, and it must not start, end or contain consecutive hyphens`,
|
|
183
|
+
});
|
|
176
184
|
}
|
|
177
185
|
if (fm.name !== skillId) {
|
|
178
|
-
errors.push({
|
|
186
|
+
errors.push({
|
|
187
|
+
skillId,
|
|
188
|
+
field: "name",
|
|
189
|
+
message: `"${fm.name}" does not match the directory name "${skillId}"`,
|
|
190
|
+
});
|
|
179
191
|
}
|
|
180
192
|
}
|
|
181
193
|
if (!fm.description || fm.description.length === 0) {
|
|
182
194
|
errors.push({ skillId, field: "description", message: "Must be present and non-empty" });
|
|
183
195
|
}
|
|
184
196
|
else if (fm.description.length > 1024) {
|
|
185
|
-
errors.push({
|
|
197
|
+
errors.push({
|
|
198
|
+
skillId,
|
|
199
|
+
field: "description",
|
|
200
|
+
message: `Exceeds 1024 characters (currently ${fm.description.length})`,
|
|
201
|
+
});
|
|
186
202
|
}
|
|
187
203
|
if (fm.compatibility && fm.compatibility.length > 500) {
|
|
188
|
-
errors.push({
|
|
204
|
+
errors.push({
|
|
205
|
+
skillId,
|
|
206
|
+
field: "compatibility",
|
|
207
|
+
message: `Exceeds 500 characters (currently ${fm.compatibility.length})`,
|
|
208
|
+
});
|
|
189
209
|
}
|
|
190
210
|
return errors;
|
|
191
211
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CallbackTool, Agent, AgentToolLazy, Message } from "@ai-zen/agents-core";
|
|
1
|
+
import { CallbackTool, Agent, AgentToolLazy, Message, } from "@ai-zen/agents-core";
|
|
2
2
|
import { createDisclosureParam } from "../../disclosure.js";
|
|
3
3
|
import { readSkill } from "./discover.js";
|
|
4
4
|
import { promises as fs } from "node:fs";
|
|
@@ -9,6 +9,7 @@ const EMPTY_HINT = "(No Skills are currently available, please ask the user to a
|
|
|
9
9
|
*/
|
|
10
10
|
export function createLoadSkillTool(skillDirs, filteredSkills) {
|
|
11
11
|
const ids = filteredSkills.map((s) => s.id);
|
|
12
|
+
const allowedIds = new Set(ids);
|
|
12
13
|
const param = createDisclosureParam(ids, "Select a Skill", EMPTY_HINT);
|
|
13
14
|
// 拼接各 skill 的描述供 LLM 参考
|
|
14
15
|
const skillDescriptions = filteredSkills
|
|
@@ -34,6 +35,12 @@ export function createLoadSkillTool(skillDirs, filteredSkills) {
|
|
|
34
35
|
},
|
|
35
36
|
callback: async function (input) {
|
|
36
37
|
const skillId = input.skill_id;
|
|
38
|
+
// 权限白名单:`filteredSkills` 才是本 Scope 允许的技能。
|
|
39
|
+
// 只靠枚举 + 描述里列名字不算限制(deny 的技能照样能被点名加载),
|
|
40
|
+
// 顺带堵掉 "../../etc" 这类越出 skillDirs 的 id。
|
|
41
|
+
if (!allowedIds.has(skillId)) {
|
|
42
|
+
return `❌ Skill "${skillId}" is not available here. Available skills: ${ids.join(", ") || "(none)"}`;
|
|
43
|
+
}
|
|
37
44
|
const skill = await readSkill(skillDirs, skillId);
|
|
38
45
|
if (!skill) {
|
|
39
46
|
return `❌ Skill "${skillId}" not found, please verify the name`;
|
|
@@ -76,6 +83,7 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
|
|
|
76
83
|
// 只保留支持子 Agent 模式的 skill
|
|
77
84
|
const subAgentSkills = filteredSkills.filter((s) => s.subAgent);
|
|
78
85
|
const ids = subAgentSkills.map((s) => s.id);
|
|
86
|
+
const allowedIds = new Set(ids);
|
|
79
87
|
const param = createDisclosureParam(ids, "Select a Skill that supports SubAgent mode", EMPTY_HINT);
|
|
80
88
|
// 拼接各 skill 的描述供 LLM 参考
|
|
81
89
|
const skillDescriptions = subAgentSkills
|
|
@@ -108,6 +116,10 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
|
|
|
108
116
|
buildAgent: async (parsedArgs, ctx) => {
|
|
109
117
|
const skillId = parsedArgs.skill_id;
|
|
110
118
|
const task = parsedArgs.task;
|
|
119
|
+
// 与 load_skill 同一白名单口径:被权限过滤掉的技能不能被点名启动
|
|
120
|
+
if (!allowedIds.has(skillId)) {
|
|
121
|
+
throw new Error(`❌ Skill "${skillId}" is not available here. Available SubAgent skills: ${ids.join(", ") || "(none)"}`);
|
|
122
|
+
}
|
|
111
123
|
const skill = await readSkill(skillDirs, skillId);
|
|
112
124
|
if (!skill) {
|
|
113
125
|
throw new Error(`❌ Skill "${skillId}" not found, please verify the name`);
|
|
@@ -20,9 +20,7 @@ export class SubAgentsScopePlugin {
|
|
|
20
20
|
}
|
|
21
21
|
candidates() {
|
|
22
22
|
return {
|
|
23
|
-
subagents: this.subagents
|
|
24
|
-
.filter((d) => d.function)
|
|
25
|
-
.map((d) => d.function.name),
|
|
23
|
+
subagents: this.subagents.filter((d) => d.function).map((d) => d.function.name),
|
|
26
24
|
};
|
|
27
25
|
}
|
|
28
26
|
instantiate(scope, filtered) {
|
|
@@ -217,14 +217,20 @@ function normalizeToolExport(exported, filepath, silent) {
|
|
|
217
217
|
return target;
|
|
218
218
|
}
|
|
219
219
|
// 情况 3:{ function, exec } 格式 → 适配为 CallbackTool
|
|
220
|
-
if (target &&
|
|
220
|
+
if (target &&
|
|
221
|
+
typeof target === "object" &&
|
|
222
|
+
target.function &&
|
|
223
|
+
typeof target.exec === "function") {
|
|
221
224
|
return new CallbackTool({
|
|
222
225
|
function: target.function,
|
|
223
226
|
callback: target.exec,
|
|
224
227
|
});
|
|
225
228
|
}
|
|
226
229
|
// 情况 4:{ function, callback } 格式 → 适配为 CallbackTool
|
|
227
|
-
if (target &&
|
|
230
|
+
if (target &&
|
|
231
|
+
typeof target === "object" &&
|
|
232
|
+
target.function &&
|
|
233
|
+
typeof target.callback === "function") {
|
|
228
234
|
return new CallbackTool({
|
|
229
235
|
function: target.function,
|
|
230
236
|
callback: target.callback,
|
|
@@ -40,9 +40,7 @@ export class EntityRepository {
|
|
|
40
40
|
return [];
|
|
41
41
|
}
|
|
42
42
|
const entries = await fs.readdir(this.dir);
|
|
43
|
-
const ids = entries
|
|
44
|
-
.filter((f) => f.endsWith(".json"))
|
|
45
|
-
.map((f) => f.replace(/\.json$/, ""));
|
|
43
|
+
const ids = entries.filter((f) => f.endsWith(".json")).map((f) => f.replace(/\.json$/, ""));
|
|
46
44
|
const entities = [];
|
|
47
45
|
for (const id of ids) {
|
|
48
46
|
const entity = await this.read(id);
|