@ai-zen/agents-sdk 1.0.0-alpha.8 → 1.0.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/CHANGELOG.md +661 -2
- package/README.md +22 -6
- package/README.zh.md +23 -7
- package/dist/agent-plugins/AutoMigratePlugin.d.ts +35 -9
- package/dist/agent-plugins/AutoMigratePlugin.js +21 -10
- package/dist/agent-plugins/AutoRefreshToolsPlugin.js +1 -3
- package/dist/agent-plugins/ContextGuardPlugin.d.ts +28 -16
- package/dist/agent-plugins/ContextGuardPlugin.js +23 -17
- package/dist/agent-plugins/UnknownToolHintPlugin.js +4 -4
- package/dist/config/ConfigManager.d.ts +57 -8
- package/dist/config/ConfigManager.js +167 -26
- package/dist/config/constants.d.ts +7 -0
- package/dist/config/constants.js +70 -43
- package/dist/config/factory-skills.d.ts +33 -0
- package/dist/config/factory-skills.js +126 -0
- package/dist/config/migrate.d.ts +106 -0
- package/dist/config/migrate.js +196 -0
- package/dist/config/reasoning-presets.d.ts +37 -0
- package/dist/config/reasoning-presets.js +64 -0
- package/dist/index.d.ts +13 -7
- package/dist/index.js +11 -3
- package/dist/runtime/HandoffGuardPlugin.d.ts +35 -0
- package/dist/runtime/HandoffGuardPlugin.js +65 -0
- package/dist/runtime/HandoffService.d.ts +246 -0
- package/dist/runtime/HandoffService.js +475 -0
- package/dist/runtime/SdkAgent.d.ts +7 -1
- package/dist/runtime/SdkAgent.js +3 -0
- package/dist/runtime/createAgent.d.ts +20 -1
- package/dist/runtime/createAgent.js +14 -9
- package/dist/runtime/createModel.d.ts +8 -4
- package/dist/runtime/createModel.js +22 -5
- package/dist/scope/PermissionEvaluator.js +1 -1
- package/dist/scope/Scope.d.ts +3 -1
- package/dist/scope/Scope.js +4 -2
- package/dist/scope/plugins/builtin/BatchEditTool.js +24 -14
- package/dist/scope/plugins/builtin/CopyTool.js +4 -4
- package/dist/scope/plugins/builtin/CwdTool.js +1 -1
- package/dist/scope/plugins/builtin/DownloadFileTool.d.ts +1 -0
- package/dist/scope/plugins/builtin/DownloadFileTool.js +58 -34
- package/dist/scope/plugins/builtin/EditTool.js +25 -25
- package/dist/scope/plugins/builtin/ExecTool.js +134 -25
- package/dist/scope/plugins/builtin/ExistTool.js +2 -2
- package/dist/scope/plugins/builtin/FindTextTool.js +15 -10
- package/dist/scope/plugins/builtin/GenerateImageTool.js +91 -25
- package/dist/scope/plugins/builtin/GlobTool.js +10 -5
- package/dist/scope/plugins/builtin/InspectFileTool.js +7 -7
- package/dist/scope/plugins/builtin/LsTool.js +5 -5
- package/dist/scope/plugins/builtin/MkdirTool.js +3 -3
- package/dist/scope/plugins/builtin/ReadTool.js +8 -8
- package/dist/scope/plugins/builtin/RenameTool.js +3 -3
- package/dist/scope/plugins/builtin/RmTool.js +3 -3
- package/dist/scope/plugins/builtin/SleepTool.js +6 -6
- package/dist/scope/plugins/builtin/SpawnTool.js +32 -49
- package/dist/scope/plugins/builtin/ViewImageTool.d.ts +6 -4
- package/dist/scope/plugins/builtin/ViewImageTool.js +50 -62
- package/dist/scope/plugins/builtin/WriteTool.js +3 -3
- 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 +95 -16
- package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +1 -1
- package/dist/scope/plugins/mcp/McpScopePlugin.js +8 -6
- package/dist/scope/plugins/mcp/discover.js +1 -1
- package/dist/scope/plugins/mcp/mcpTools.d.ts +9 -3
- package/dist/scope/plugins/mcp/mcpTools.js +247 -37
- package/dist/scope/plugins/skills/SkillsScopePlugin.js +2 -3
- package/dist/scope/plugins/skills/discover.js +28 -9
- package/dist/scope/plugins/skills/skillTools.js +30 -20
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +1 -3
- package/dist/scope/plugins/subagents/subAgentTools.js +4 -3
- package/dist/scope/plugins/usertools/discover.d.ts +8 -3
- package/dist/scope/plugins/usertools/discover.js +139 -12
- package/dist/shared/EntityRepository.d.ts +10 -1
- package/dist/shared/EntityRepository.js +18 -6
- package/dist/shared/content-blocks.d.ts +101 -0
- package/dist/shared/content-blocks.js +253 -0
- package/dist/shared/errors.d.ts +4 -8
- package/dist/shared/errors.js +8 -14
- package/dist/types/index.d.ts +170 -8
- package/package.json +16 -7
- package/dist/runtime/TaskMigrationService.d.ts +0 -128
- package/dist/runtime/TaskMigrationService.js +0 -211
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { CallbackTool } from "@ai-zen/agents-core";
|
|
2
|
+
import { fileToContentSection, resolveModelAndEndpoint, } from "../../../shared/content-blocks.js";
|
|
2
3
|
import { createDisclosureParam } from "../../disclosure.js";
|
|
4
|
+
import { DEFAULT_MAX_TOOL_OUTPUT, guardOutput, headTailPreview } from "../builtin/outputGuard.js";
|
|
3
5
|
import { getLogger } from "../../../shared/logger.js";
|
|
4
|
-
const EMPTY_HINT = "
|
|
5
|
-
const log = getLogger();
|
|
6
|
+
const EMPTY_HINT = "(No MCP servers available, ask the user to add one)";
|
|
6
7
|
/**
|
|
7
8
|
* 创建 load_mcp 工具。
|
|
8
9
|
* server 枚举由 filteredMcps (完整 McpServerConfig[])自动推导,
|
|
@@ -15,16 +16,16 @@ export function createLoadMcpTool(mcpManager, filteredMcps) {
|
|
|
15
16
|
configMap.set(s.id, s);
|
|
16
17
|
}
|
|
17
18
|
const ids = filteredMcps.map((s) => s.id);
|
|
18
|
-
const param = createDisclosureParam(ids, "
|
|
19
|
+
const param = createDisclosureParam(ids, "MCP server name", EMPTY_HINT);
|
|
19
20
|
// 拼接各 MCP 服务器的描述供 LLM 参考(对齐 load_skill 的处理方式)
|
|
20
21
|
const mcpDescriptions = filteredMcps
|
|
21
|
-
.map((s) => ` - ${s.id}: ${s.description || "
|
|
22
|
+
.map((s) => ` - ${s.id}: ${s.description || "No description"}`)
|
|
22
23
|
.join("\n");
|
|
23
|
-
const serverIdDescription = `${param.description}\n\
|
|
24
|
+
const serverIdDescription = `${param.description}\n\nAvailable MCP servers:\n${mcpDescriptions || " No MCP servers available"}`;
|
|
24
25
|
return new CallbackTool({
|
|
25
26
|
function: {
|
|
26
27
|
name: "load_mcp",
|
|
27
|
-
description: "
|
|
28
|
+
description: "Connect to the specified MCP server and get the list of tools and resources it exposes. Pass include_manifest=false to only establish the connection without returning the manifest (useful when the manifest is already in context).",
|
|
28
29
|
parameters: {
|
|
29
30
|
type: "object",
|
|
30
31
|
properties: {
|
|
@@ -35,7 +36,7 @@ export function createLoadMcpTool(mcpManager, filteredMcps) {
|
|
|
35
36
|
},
|
|
36
37
|
include_manifest: {
|
|
37
38
|
type: "boolean",
|
|
38
|
-
description: "
|
|
39
|
+
description: "Whether to return the server's full capability manifest (tools and resources). Optional, defaults to true. If the manifest is already in your context (for example it was loaded earlier in this session but the connection was dropped after a process restart), set it to false to only establish the connection and return a summary, saving context tokens",
|
|
39
40
|
default: true,
|
|
40
41
|
},
|
|
41
42
|
},
|
|
@@ -47,7 +48,7 @@ export function createLoadMcpTool(mcpManager, filteredMcps) {
|
|
|
47
48
|
const serverName = input.server;
|
|
48
49
|
const config = configMap.get(serverName);
|
|
49
50
|
if (!config) {
|
|
50
|
-
return `❌ MCP
|
|
51
|
+
return `❌ MCP server "${serverName}" is not configured`;
|
|
51
52
|
}
|
|
52
53
|
// 披露开关:默认返回完整清单;显式传 false 时仅建立连接、只返回摘要
|
|
53
54
|
const includeManifest = input.include_manifest !== false;
|
|
@@ -63,12 +64,12 @@ export function createLoadMcpTool(mcpManager, filteredMcps) {
|
|
|
63
64
|
manifest = await mcpManager.connect(serverName, config);
|
|
64
65
|
}
|
|
65
66
|
catch (error) {
|
|
66
|
-
return
|
|
67
|
+
return `Failed to connect to "${serverName}": ${error?.message ?? error}`;
|
|
67
68
|
}
|
|
68
69
|
}
|
|
69
70
|
// 静默模式:只回吐摘要(清单仍留在管理器内,供 call_mcp_tool 使用)
|
|
70
71
|
if (!includeManifest) {
|
|
71
|
-
|
|
72
|
+
getLogger().info(`[load_mcp] ${serverName}: connected (manifest not disclosed: ${manifest.tools.length} tools, ${manifest.resources.length} resources)`);
|
|
72
73
|
return JSON.stringify({
|
|
73
74
|
server: serverName,
|
|
74
75
|
connected: true,
|
|
@@ -76,26 +77,186 @@ export function createLoadMcpTool(mcpManager, filteredMcps) {
|
|
|
76
77
|
resources: manifest.resources.length,
|
|
77
78
|
});
|
|
78
79
|
}
|
|
79
|
-
|
|
80
|
+
getLogger().info(`[load_mcp] ${serverName}:\n${JSON.stringify(manifest, null, 2)}`);
|
|
80
81
|
return JSON.stringify({ tools: manifest.tools, resources: manifest.resources });
|
|
81
82
|
},
|
|
82
83
|
});
|
|
83
84
|
}
|
|
85
|
+
/** MIME → 文件名后缀(仅用于上传时给文件一个好名字) */
|
|
86
|
+
const EXT_BY_MIME = {
|
|
87
|
+
"image/png": "png",
|
|
88
|
+
"image/jpeg": "jpg",
|
|
89
|
+
"image/gif": "gif",
|
|
90
|
+
"image/webp": "webp",
|
|
91
|
+
"audio/wav": "wav",
|
|
92
|
+
"audio/mpeg": "mp3",
|
|
93
|
+
"application/pdf": "pdf",
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* MCP 媒体(base64 字符串)→ SDK 内容块。
|
|
97
|
+
*
|
|
98
|
+
* 统一交给 `fileToContentSection()` 决定传输方式:端点声明 Files API 能力就上传
|
|
99
|
+
* (`file` 块 + `file_id`,请求体小、不随历史反复膨胀),否则保持 base64 内联。
|
|
100
|
+
* 转换失败**不丢块**——退化为一条文本说明,避免整个工具调用因媒体问题失败。
|
|
101
|
+
*/
|
|
102
|
+
async function mediaSection(data, mime, media) {
|
|
103
|
+
const ext = EXT_BY_MIME[mime] ?? "bin";
|
|
104
|
+
try {
|
|
105
|
+
const { section } = await fileToContentSection({
|
|
106
|
+
source: {
|
|
107
|
+
base64: data,
|
|
108
|
+
mime,
|
|
109
|
+
filename: `mcp-media-${Date.now()}.${ext}`,
|
|
110
|
+
},
|
|
111
|
+
endpoint: media.endpoint,
|
|
112
|
+
model: media.model,
|
|
113
|
+
signal: media.signal,
|
|
114
|
+
deps: media.deps,
|
|
115
|
+
});
|
|
116
|
+
return section;
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
return {
|
|
120
|
+
type: "text",
|
|
121
|
+
text: `[media] Failed to convert (${mime}): ${error?.message ?? error}`,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* `read_mcp_resource` 的 resource contents → SDK 内容块。
|
|
127
|
+
*
|
|
128
|
+
* 注意形状差异:`callTool` 的 content 块带 `type` 判别字段,而 `readResource` 的
|
|
129
|
+
* contents 是 `{ uri, mimeType?, text }` 或 `{ uri, mimeType?, blob }`——**没有 type**。
|
|
130
|
+
* 若直接复用 `toMessageSection`,文本资源会掉进 default 分支被 JSON 化(实测踩过)。
|
|
131
|
+
*/
|
|
132
|
+
async function resourceToMessageSection(item, media) {
|
|
133
|
+
if (typeof item?.text === "string")
|
|
134
|
+
return { type: "text", text: item.text };
|
|
135
|
+
if (typeof item?.blob === "string") {
|
|
136
|
+
return mediaSection(item.blob, item.mimeType ?? "application/octet-stream", media);
|
|
137
|
+
}
|
|
138
|
+
return { type: "text", text: JSON.stringify(item) };
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* MCP content 块 → SDK 内容块。
|
|
142
|
+
*
|
|
143
|
+
* 文本类(text / resource.text / resource_link / 未知类型)归一为 `text` 块,
|
|
144
|
+
* 由调用方拼接成正文后进入输出保护;
|
|
145
|
+
* 媒体类(image / audio / resource.blob)经 `mediaSection()` → `fileToContentSection()`:
|
|
146
|
+
* 端点支持 Files API 时上传为 `file` 块,否则 base64 内联——图片不进字符闸门,也不丢弃。
|
|
147
|
+
*/
|
|
148
|
+
async function toMessageSection(block, media) {
|
|
149
|
+
switch (block?.type) {
|
|
150
|
+
case "image":
|
|
151
|
+
return await mediaSection(block.data, block.mimeType ?? "image/png", media);
|
|
152
|
+
case "audio":
|
|
153
|
+
// AgentNS 无独立音频块,以 `file` 块承载(支持上传的端点 → file_id,否则 file_data 内联)
|
|
154
|
+
return await mediaSection(block.data, block.mimeType ?? "audio/wav", media);
|
|
155
|
+
case "resource": {
|
|
156
|
+
const r = block.resource ?? {};
|
|
157
|
+
// 内嵌文本资源:本质是纯文本,并入正文(同样受输出保护)
|
|
158
|
+
if (typeof r.text === "string")
|
|
159
|
+
return { type: "text", text: r.text };
|
|
160
|
+
// 内嵌二进制资源:按 mimeType 选块类型,不丢弃
|
|
161
|
+
if (typeof r.blob === "string") {
|
|
162
|
+
const mime = r.mimeType ?? "application/octet-stream";
|
|
163
|
+
return await mediaSection(r.blob, mime, media);
|
|
164
|
+
}
|
|
165
|
+
return { type: "text", text: `[resource] ${r.uri ?? "(unknown URI)"}` };
|
|
166
|
+
}
|
|
167
|
+
case "resource_link": {
|
|
168
|
+
const parts = [block.name, block.uri, block.mimeType].filter(Boolean);
|
|
169
|
+
return { type: "text", text: `[resource_link] ${parts.join(" · ")}` };
|
|
170
|
+
}
|
|
171
|
+
case "text":
|
|
172
|
+
return { type: "text", text: block.text ?? "" };
|
|
173
|
+
default:
|
|
174
|
+
// 未知类型(如 tool_use)退化为 JSON 文本,仍受输出保护
|
|
175
|
+
return { type: "text", text: JSON.stringify(block) };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* 文本输出保护(保序):
|
|
180
|
+
*
|
|
181
|
+
* - **未超限**:原样返回映射后的块数组,不重排、不合并、不丢块;
|
|
182
|
+
* 纯文本时退化为单个字符串(历史行为)。
|
|
183
|
+
* - **超限**:全部文本落盘为 result.txt,只保留**一个**警告文本块占据
|
|
184
|
+
* 原首个文本块的位置,其余文本块丢弃(内容已落盘),媒体块原位不动。
|
|
185
|
+
* 这样即使文本夹在中间,媒体与位置的对应关系也不会被打乱。
|
|
186
|
+
*
|
|
187
|
+
* 判定用全部文本的字符总数——不能逐块判,否则 N 段各 3 万字符都不超限、合起来却能灌爆。
|
|
188
|
+
* 落盘只写文本正文,不写原始结果——后者可能含 image 的 base64,
|
|
189
|
+
* 落盘等于把几 MB 二进制再抄一遍磁盘。
|
|
190
|
+
*/
|
|
191
|
+
async function protectCallOutput(output, env) {
|
|
192
|
+
const limit = env.config.maxToolOutput ?? DEFAULT_MAX_TOOL_OUTPUT;
|
|
193
|
+
const { sections, fullText, chars, isError } = output;
|
|
194
|
+
const guarded = await guardOutput({
|
|
195
|
+
tool: "call_mcp_tool",
|
|
196
|
+
content: output,
|
|
197
|
+
isOverLimit: (o) => o.chars > limit,
|
|
198
|
+
dump: (_dir, o) => [{ name: "result.txt", content: o.fullText }],
|
|
199
|
+
buildWarning: (ctx) => {
|
|
200
|
+
const preview = headTailPreview(fullText);
|
|
201
|
+
return JSON.stringify({
|
|
202
|
+
outputTooLarge: true,
|
|
203
|
+
isError: isError || undefined,
|
|
204
|
+
warning: `Text output too large: ${chars} characters, exceeding the limit of ${limit} characters. ` +
|
|
205
|
+
`The full text has been written to disk (result.txt); use read to page through it.`,
|
|
206
|
+
files: ctx.files,
|
|
207
|
+
chars,
|
|
208
|
+
...preview,
|
|
209
|
+
});
|
|
210
|
+
},
|
|
211
|
+
});
|
|
212
|
+
// 超限:警告占据首个文本块的位置,其余文本块合并到它身上(内容已落盘),媒体原位
|
|
213
|
+
if (typeof guarded === "string") {
|
|
214
|
+
const collapsed = [];
|
|
215
|
+
let placed = false;
|
|
216
|
+
for (const section of sections) {
|
|
217
|
+
if (section.type === "text") {
|
|
218
|
+
if (!placed) {
|
|
219
|
+
collapsed.push({ type: "text", text: guarded });
|
|
220
|
+
placed = true;
|
|
221
|
+
}
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
collapsed.push(section);
|
|
225
|
+
}
|
|
226
|
+
// 仅一个文本块(无媒体):退化为字符串,与历史行为一致
|
|
227
|
+
return collapsed.length === 1 ? collapsed[0].text : collapsed;
|
|
228
|
+
}
|
|
229
|
+
// 未超限:无媒体 → 纯字符串;有媒体 → 原序块数组
|
|
230
|
+
const hasMedia = sections.some((s) => s.type !== "text");
|
|
231
|
+
if (!hasMedia)
|
|
232
|
+
return isError ? `❌ Tool execution failed:\n${fullText}` : fullText;
|
|
233
|
+
return isError ? [{ type: "text", text: "❌ Tool execution failed:" }, ...sections] : sections;
|
|
234
|
+
}
|
|
84
235
|
/**
|
|
85
236
|
* 创建 call_mcp_tool 工具。
|
|
86
237
|
* 通过官方 Client.callTool() API 调用 MCP 服务器上的工具。
|
|
238
|
+
*
|
|
239
|
+
* 返回形态:
|
|
240
|
+
* - 仅文本 → 纯字符串(与历史行为一致);
|
|
241
|
+
* - 含媒体 → 内容块数组:首块为受保护的文本,其后原样透传 image / file 块。
|
|
242
|
+
*
|
|
243
|
+
* env 仅用于读取 maxToolOutput(文本输出保护上限),与内置工具口径一致。
|
|
87
244
|
*/
|
|
88
|
-
export function createCallMcpTool(mcpManager) {
|
|
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)";
|
|
89
250
|
return new CallbackTool({
|
|
90
251
|
function: {
|
|
91
252
|
name: "call_mcp_tool",
|
|
92
|
-
description: "
|
|
253
|
+
description: "Call a tool exposed by a connected MCP server. Connect the server with load_mcp first. Large text output is written to disk and only a head/tail preview is returned; images, audio and other media are preserved: uploaded and referenced by file_id when the endpoint supports the Files API, otherwise inlined as base64.",
|
|
93
254
|
parameters: {
|
|
94
255
|
type: "object",
|
|
95
256
|
properties: {
|
|
96
|
-
server: { type: "string", description: "MCP
|
|
97
|
-
tool: { type: "string", description: "
|
|
98
|
-
arguments: { type: "object", description: "
|
|
257
|
+
server: { type: "string", description: "MCP server name" },
|
|
258
|
+
tool: { type: "string", description: "Tool name" },
|
|
259
|
+
arguments: { type: "object", description: "Tool arguments" },
|
|
99
260
|
},
|
|
100
261
|
required: ["server", "tool", "arguments"],
|
|
101
262
|
additionalProperties: false,
|
|
@@ -103,13 +264,16 @@ export function createCallMcpTool(mcpManager) {
|
|
|
103
264
|
},
|
|
104
265
|
callback: async (input, ctx) => {
|
|
105
266
|
const serverName = input.server;
|
|
267
|
+
if (!allowed.has(serverName)) {
|
|
268
|
+
return `❌ MCP server "${serverName}" is not available here. Available servers: ${allowList}`;
|
|
269
|
+
}
|
|
106
270
|
const state = mcpManager.getState(serverName);
|
|
107
271
|
if (state !== "connected") {
|
|
108
|
-
return
|
|
272
|
+
return `Call load_mcp to connect "${serverName}" first`;
|
|
109
273
|
}
|
|
110
274
|
const client = mcpManager.getClient(serverName);
|
|
111
275
|
if (!client) {
|
|
112
|
-
return `MCP
|
|
276
|
+
return `MCP server "${serverName}" client is not available`;
|
|
113
277
|
}
|
|
114
278
|
try {
|
|
115
279
|
mcpManager.touch(serverName);
|
|
@@ -117,18 +281,36 @@ export function createCallMcpTool(mcpManager) {
|
|
|
117
281
|
name: input.tool,
|
|
118
282
|
arguments: input.arguments,
|
|
119
283
|
}, undefined, { signal: ctx?.signal });
|
|
284
|
+
// 按 MCP content 原始顺序映射,文本与媒体的相对位置完整保留
|
|
120
285
|
const contents = result.content ?? [];
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
286
|
+
const isError = Boolean(result.isError);
|
|
287
|
+
// 没有 content 时退回原始 JSON(既有兜底)
|
|
288
|
+
if (contents.length === 0) {
|
|
289
|
+
const json = JSON.stringify(result);
|
|
290
|
+
return await protectCallOutput({
|
|
291
|
+
sections: [{ type: "text", text: json }],
|
|
292
|
+
fullText: json,
|
|
293
|
+
chars: json.length,
|
|
294
|
+
isError,
|
|
295
|
+
}, env);
|
|
127
296
|
}
|
|
128
|
-
|
|
297
|
+
// 按当前模型定位端点:决定媒体走 Files API 上传还是 base64 内联
|
|
298
|
+
const { model, endpoint } = resolveModelAndEndpoint(env.config, ctx?.agent?.model);
|
|
299
|
+
const mediaContext = {
|
|
300
|
+
endpoint,
|
|
301
|
+
model,
|
|
302
|
+
signal: ctx?.signal,
|
|
303
|
+
deps: env.deps,
|
|
304
|
+
};
|
|
305
|
+
// Promise.all 保序:文本与媒体的相对位置不变
|
|
306
|
+
const sections = await Promise.all(contents.map((block) => toMessageSection(block, mediaContext)));
|
|
307
|
+
const textSections = sections.filter((s) => s.type === "text");
|
|
308
|
+
const fullText = textSections.map((s) => s.text).join("\n");
|
|
309
|
+
const chars = textSections.reduce((n, s) => n + s.text.length, 0);
|
|
310
|
+
return await protectCallOutput({ sections, fullText, chars, isError }, env);
|
|
129
311
|
}
|
|
130
312
|
catch (error) {
|
|
131
|
-
return `❌
|
|
313
|
+
return `❌ Failed to call "${input.tool}": ${error?.message ?? error}`;
|
|
132
314
|
}
|
|
133
315
|
},
|
|
134
316
|
});
|
|
@@ -136,16 +318,19 @@ export function createCallMcpTool(mcpManager) {
|
|
|
136
318
|
/**
|
|
137
319
|
* 创建 read_mcp_resource 工具。
|
|
138
320
|
*/
|
|
139
|
-
export function createReadMcpResourceTool(mcpManager) {
|
|
321
|
+
export function createReadMcpResourceTool(mcpManager, env, filteredMcps) {
|
|
322
|
+
// 与 call_mcp_tool 同一白名单口径(见该工具的说明)
|
|
323
|
+
const allowed = new Set(filteredMcps);
|
|
324
|
+
const allowList = filteredMcps.join(", ") || "(none)";
|
|
140
325
|
return new CallbackTool({
|
|
141
326
|
function: {
|
|
142
327
|
name: "read_mcp_resource",
|
|
143
|
-
description: "
|
|
328
|
+
description: "Read a resource (document, data, image, etc.) from a connected MCP server. Text is returned as-is; images and other media are uploaded (file_id) or inlined as base64 depending on endpoint capabilities, and are never dropped.",
|
|
144
329
|
parameters: {
|
|
145
330
|
type: "object",
|
|
146
331
|
properties: {
|
|
147
|
-
server: { type: "string", description: "MCP
|
|
148
|
-
uri: { type: "string", description: "
|
|
332
|
+
server: { type: "string", description: "MCP server name" },
|
|
333
|
+
uri: { type: "string", description: "Resource URI" },
|
|
149
334
|
},
|
|
150
335
|
required: ["server", "uri"],
|
|
151
336
|
additionalProperties: false,
|
|
@@ -153,25 +338,50 @@ export function createReadMcpResourceTool(mcpManager) {
|
|
|
153
338
|
},
|
|
154
339
|
callback: async (input, ctx) => {
|
|
155
340
|
const serverName = input.server;
|
|
341
|
+
if (!allowed.has(serverName)) {
|
|
342
|
+
return `❌ MCP server "${serverName}" is not available here. Available servers: ${allowList}`;
|
|
343
|
+
}
|
|
156
344
|
const state = mcpManager.getState(serverName);
|
|
157
345
|
if (state !== "connected") {
|
|
158
|
-
return
|
|
346
|
+
return `Call load_mcp to connect "${serverName}" first`;
|
|
159
347
|
}
|
|
160
348
|
const client = mcpManager.getClient(serverName);
|
|
161
349
|
if (!client) {
|
|
162
|
-
return `MCP
|
|
350
|
+
return `MCP server "${serverName}" client is not available`;
|
|
163
351
|
}
|
|
164
352
|
try {
|
|
165
353
|
mcpManager.touch(serverName);
|
|
166
354
|
const result = await client.readResource({ uri: input.uri }, { signal: ctx?.signal });
|
|
167
355
|
const contents = result?.contents ?? [];
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
356
|
+
const { model, endpoint } = resolveModelAndEndpoint(env.config, ctx?.agent?.model);
|
|
357
|
+
const mediaContext = {
|
|
358
|
+
endpoint,
|
|
359
|
+
model,
|
|
360
|
+
signal: ctx?.signal,
|
|
361
|
+
deps: env.deps,
|
|
362
|
+
};
|
|
363
|
+
// 与 call_mcp_tool 同一套映射:文本归一为 text 块,媒体按端点能力上传或内联,
|
|
364
|
+
// 不再把二进制资源(图片 / PDF)静默丢掉。
|
|
365
|
+
const sections = await Promise.all(contents.map((content) => resourceToMessageSection(content, mediaContext)));
|
|
366
|
+
// 没有 contents 时退回原始 JSON(与 call_mcp_tool 同一兜底)
|
|
367
|
+
if (sections.length === 0) {
|
|
368
|
+
const json = JSON.stringify(result);
|
|
369
|
+
return await protectCallOutput({
|
|
370
|
+
sections: [{ type: "text", text: json }],
|
|
371
|
+
fullText: json,
|
|
372
|
+
chars: json.length,
|
|
373
|
+
isError: false,
|
|
374
|
+
}, env);
|
|
375
|
+
}
|
|
376
|
+
// 与 call_mcp_tool 共用同一套输出保护:文本超限落盘 result.txt,
|
|
377
|
+
// 媒体块原位保留;未超限时纯文本退化为字符串、含媒体返回块数组。
|
|
378
|
+
const textSections = sections.filter((section) => section.type === "text");
|
|
379
|
+
const fullText = textSections.map((section) => section.text).join("\n");
|
|
380
|
+
const chars = textSections.reduce((n, section) => n + section.text.length, 0);
|
|
381
|
+
return await protectCallOutput({ sections, fullText, chars, isError: false }, env);
|
|
172
382
|
}
|
|
173
383
|
catch (error) {
|
|
174
|
-
return `❌
|
|
384
|
+
return `❌ Failed to read resource "${input.uri}": ${error?.message ?? error}`;
|
|
175
385
|
}
|
|
176
386
|
},
|
|
177
387
|
});
|
|
@@ -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;
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { promises as fs } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { getLogger } from "../../../shared/logger.js";
|
|
4
|
-
const log = getLogger();
|
|
5
4
|
// ---- 发现(返回完整 SkillInfo,不再丢失 subAgent 等信息)----
|
|
6
5
|
/**
|
|
7
6
|
* 扫描多个目录中发现的所有 Skill(含 SKILL.md 的子目录)。
|
|
@@ -78,7 +77,7 @@ async function readSkillFromPath(skillId, skillMdPath, silent) {
|
|
|
78
77
|
if (!silent) {
|
|
79
78
|
const errors = validateSkill(skillId, fm);
|
|
80
79
|
for (const err of errors) {
|
|
81
|
-
|
|
80
|
+
getLogger().warn(`[skills] ${err.skillId}: ${err.field} — ${err.message}`);
|
|
82
81
|
}
|
|
83
82
|
}
|
|
84
83
|
return {
|
|
@@ -166,27 +165,47 @@ const VALID_NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
|
166
165
|
export function validateSkill(skillId, fm) {
|
|
167
166
|
const errors = [];
|
|
168
167
|
if (!fm.name || fm.name.length === 0) {
|
|
169
|
-
errors.push({ skillId, field: "name", message: "
|
|
168
|
+
errors.push({ skillId, field: "name", message: "Must be present and non-empty" });
|
|
170
169
|
}
|
|
171
170
|
else {
|
|
172
171
|
if (fm.name.length > 64) {
|
|
173
|
-
errors.push({
|
|
172
|
+
errors.push({
|
|
173
|
+
skillId,
|
|
174
|
+
field: "name",
|
|
175
|
+
message: `Exceeds 64 characters (currently ${fm.name.length})`,
|
|
176
|
+
});
|
|
174
177
|
}
|
|
175
178
|
if (!VALID_NAME_RE.test(fm.name)) {
|
|
176
|
-
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
|
+
});
|
|
177
184
|
}
|
|
178
185
|
if (fm.name !== skillId) {
|
|
179
|
-
errors.push({
|
|
186
|
+
errors.push({
|
|
187
|
+
skillId,
|
|
188
|
+
field: "name",
|
|
189
|
+
message: `"${fm.name}" does not match the directory name "${skillId}"`,
|
|
190
|
+
});
|
|
180
191
|
}
|
|
181
192
|
}
|
|
182
193
|
if (!fm.description || fm.description.length === 0) {
|
|
183
|
-
errors.push({ skillId, field: "description", message: "
|
|
194
|
+
errors.push({ skillId, field: "description", message: "Must be present and non-empty" });
|
|
184
195
|
}
|
|
185
196
|
else if (fm.description.length > 1024) {
|
|
186
|
-
errors.push({
|
|
197
|
+
errors.push({
|
|
198
|
+
skillId,
|
|
199
|
+
field: "description",
|
|
200
|
+
message: `Exceeds 1024 characters (currently ${fm.description.length})`,
|
|
201
|
+
});
|
|
187
202
|
}
|
|
188
203
|
if (fm.compatibility && fm.compatibility.length > 500) {
|
|
189
|
-
errors.push({
|
|
204
|
+
errors.push({
|
|
205
|
+
skillId,
|
|
206
|
+
field: "compatibility",
|
|
207
|
+
message: `Exceeds 500 characters (currently ${fm.compatibility.length})`,
|
|
208
|
+
});
|
|
190
209
|
}
|
|
191
210
|
return errors;
|
|
192
211
|
}
|
|
@@ -1,26 +1,25 @@
|
|
|
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
|
-
import { getLogger } from "../../../shared/logger.js";
|
|
5
4
|
import { promises as fs } from "node:fs";
|
|
6
|
-
const
|
|
7
|
-
const EMPTY_HINT = "(当前没有可用的 Skill,请联系用户添加)";
|
|
5
|
+
const EMPTY_HINT = "(No Skills are currently available, please ask the user to add one)";
|
|
8
6
|
/**
|
|
9
7
|
* 创建 load_skill 工具。
|
|
10
8
|
* 枚举所有允许的 skill(不限是否支持子 Agent),由 filteredSkills 提供完整信息。
|
|
11
9
|
*/
|
|
12
10
|
export function createLoadSkillTool(skillDirs, filteredSkills) {
|
|
13
11
|
const ids = filteredSkills.map((s) => s.id);
|
|
14
|
-
const
|
|
12
|
+
const allowedIds = new Set(ids);
|
|
13
|
+
const param = createDisclosureParam(ids, "Select a Skill", EMPTY_HINT);
|
|
15
14
|
// 拼接各 skill 的描述供 LLM 参考
|
|
16
15
|
const skillDescriptions = filteredSkills
|
|
17
|
-
.map((s) => ` - ${s.id}: ${s.description || "
|
|
16
|
+
.map((s) => ` - ${s.id}: ${s.description || "No description"}`)
|
|
18
17
|
.join("\n");
|
|
19
|
-
const skillIdDescription = `${param.description}\n\
|
|
18
|
+
const skillIdDescription = `${param.description}\n\nSkill descriptions:\n${skillDescriptions || " No Skills available"}`;
|
|
20
19
|
return new CallbackTool({
|
|
21
20
|
function: {
|
|
22
21
|
name: "load_skill",
|
|
23
|
-
description: "
|
|
22
|
+
description: "Load the full guidance document of a Skill. A Skill is pre-authored expert guidance that is expanded into the context once loaded.",
|
|
24
23
|
parameters: {
|
|
25
24
|
type: "object",
|
|
26
25
|
properties: {
|
|
@@ -36,9 +35,15 @@ export function createLoadSkillTool(skillDirs, filteredSkills) {
|
|
|
36
35
|
},
|
|
37
36
|
callback: async function (input) {
|
|
38
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
|
+
}
|
|
39
44
|
const skill = await readSkill(skillDirs, skillId);
|
|
40
45
|
if (!skill) {
|
|
41
|
-
return `❌ Skill "${skillId}"
|
|
46
|
+
return `❌ Skill "${skillId}" not found, please verify the name`;
|
|
42
47
|
}
|
|
43
48
|
// 扫描 skill 目录下的文件列表
|
|
44
49
|
let fileList = "";
|
|
@@ -48,18 +53,18 @@ export function createLoadSkillTool(skillDirs, filteredSkills) {
|
|
|
48
53
|
const suffix = e.isDirectory() ? "/" : "";
|
|
49
54
|
return ` - ${e.name}${suffix}`;
|
|
50
55
|
});
|
|
51
|
-
fileList = `\n\nSkill
|
|
56
|
+
fileList = `\n\nSkill directory files:\n${files.join("\n")}`;
|
|
52
57
|
}
|
|
53
58
|
catch {
|
|
54
59
|
fileList = "";
|
|
55
60
|
}
|
|
56
61
|
return [
|
|
57
|
-
`Skill "${skillId}"
|
|
62
|
+
`Skill "${skillId}" loaded:`,
|
|
58
63
|
``,
|
|
59
|
-
`Skill
|
|
64
|
+
`Skill directory path: ${skill.dirPath}`,
|
|
60
65
|
fileList,
|
|
61
66
|
``,
|
|
62
|
-
`--- Skill
|
|
67
|
+
`--- Skill content starts ---`,
|
|
63
68
|
skill.content,
|
|
64
69
|
].join("\n");
|
|
65
70
|
},
|
|
@@ -78,16 +83,17 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
|
|
|
78
83
|
// 只保留支持子 Agent 模式的 skill
|
|
79
84
|
const subAgentSkills = filteredSkills.filter((s) => s.subAgent);
|
|
80
85
|
const ids = subAgentSkills.map((s) => s.id);
|
|
81
|
-
const
|
|
86
|
+
const allowedIds = new Set(ids);
|
|
87
|
+
const param = createDisclosureParam(ids, "Select a Skill that supports SubAgent mode", EMPTY_HINT);
|
|
82
88
|
// 拼接各 skill 的描述供 LLM 参考
|
|
83
89
|
const skillDescriptions = subAgentSkills
|
|
84
|
-
.map((s) => ` - ${s.id}: ${s.description || "
|
|
90
|
+
.map((s) => ` - ${s.id}: ${s.description || "No description"}`)
|
|
85
91
|
.join("\n");
|
|
86
|
-
const skillIdDescription = `${param.description}\n\
|
|
92
|
+
const skillIdDescription = `${param.description}\n\nSkill descriptions:\n${skillDescriptions || " No Skills available"}`;
|
|
87
93
|
return new AgentToolLazy({
|
|
88
94
|
function: {
|
|
89
95
|
name: "call_skill_sub_agent",
|
|
90
|
-
description: "
|
|
96
|
+
description: "Delegate a task to the specified Skill SubAgent, which completes it independently and returns the result.",
|
|
91
97
|
parameters: {
|
|
92
98
|
type: "object",
|
|
93
99
|
properties: {
|
|
@@ -98,7 +104,7 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
|
|
|
98
104
|
},
|
|
99
105
|
task: {
|
|
100
106
|
type: "string",
|
|
101
|
-
description: "
|
|
107
|
+
description: "Task description to delegate to the SubAgent",
|
|
102
108
|
},
|
|
103
109
|
},
|
|
104
110
|
required: ["skill_id", "task"],
|
|
@@ -110,12 +116,16 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
|
|
|
110
116
|
buildAgent: async (parsedArgs, ctx) => {
|
|
111
117
|
const skillId = parsedArgs.skill_id;
|
|
112
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
|
+
}
|
|
113
123
|
const skill = await readSkill(skillDirs, skillId);
|
|
114
124
|
if (!skill) {
|
|
115
|
-
throw new Error(`❌ Skill "${skillId}"
|
|
125
|
+
throw new Error(`❌ Skill "${skillId}" not found, please verify the name`);
|
|
116
126
|
}
|
|
117
127
|
if (!skill.subAgent) {
|
|
118
|
-
throw new Error(`Skill "${skillId}"
|
|
128
|
+
throw new Error(`Skill "${skillId}" does not support SubAgent mode, use load_skill to load its guidance and handle the task yourself`);
|
|
119
129
|
}
|
|
120
130
|
// 沿用父 Agent 的工具能力(不做权限过滤),剔除自身以防自递归
|
|
121
131
|
const parentAgent = ctx.agent;
|
|
@@ -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) {
|