@ai-zen/agents-sdk 1.2.0-alpha.2 → 2.0.0-alpha.1
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 +77 -0
- package/README.md +397 -113
- package/README.zh.md +314 -112
- package/dist/agent-plugins/AssetTransportPlugin.d.ts +51 -0
- package/dist/agent-plugins/AssetTransportPlugin.js +145 -0
- package/dist/agent-plugins/AutoMigratePlugin.d.ts +56 -6
- package/dist/agent-plugins/AutoMigratePlugin.js +64 -15
- package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +12 -9
- package/dist/agent-plugins/AutoRefreshToolsPlugin.js +6 -7
- package/dist/agent-plugins/ContextGuardPlugin.d.ts +32 -24
- package/dist/agent-plugins/ContextGuardPlugin.js +37 -22
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +38 -46
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +37 -50
- package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +15 -1
- package/dist/agent-plugins/UnknownToolHintPlugin.js +15 -1
- package/dist/config/ConfigManager.d.ts +13 -5
- package/dist/config/ConfigManager.js +58 -39
- package/dist/config/constants.d.ts +1 -1
- package/dist/config/constants.js +2 -2
- package/dist/config/factory-skills.js +2 -2
- package/dist/config/normalize.d.ts +93 -0
- package/dist/config/normalize.js +158 -0
- package/dist/crud/AgentRepository.d.ts +3 -1
- package/dist/crud/AgentRepository.js +4 -2
- package/dist/index.d.ts +22 -9
- package/dist/index.js +16 -6
- package/dist/runtime/AgentRuntime.d.ts +293 -0
- package/dist/runtime/AgentRuntime.js +457 -0
- package/dist/runtime/HandoffGuardPlugin.d.ts +85 -16
- package/dist/runtime/HandoffGuardPlugin.js +140 -19
- package/dist/runtime/HandoffService.d.ts +255 -91
- package/dist/runtime/HandoffService.js +392 -177
- package/dist/runtime/RuntimePeerSessions.d.ts +34 -0
- package/dist/runtime/RuntimePeerSessions.js +50 -0
- package/dist/runtime/Scopes.d.ts +123 -0
- package/dist/runtime/Scopes.js +169 -0
- package/dist/runtime/SdkAgent.d.ts +21 -11
- package/dist/runtime/SdkAgent.js +24 -8
- package/dist/runtime/completeOnce.d.ts +3 -3
- package/dist/runtime/completeOnce.js +3 -3
- package/dist/runtime/createAgent.d.ts +29 -7
- package/dist/runtime/createAgent.js +57 -12
- package/dist/runtime/createModel.d.ts +4 -4
- package/dist/runtime/createModel.js +6 -6
- package/dist/runtime/lastPromptTokens.d.ts +18 -0
- package/dist/runtime/lastPromptTokens.js +26 -0
- package/dist/runtime/resolveModel.d.ts +9 -9
- package/dist/runtime/resolveModel.js +8 -8
- package/dist/scope/Scope.d.ts +42 -14
- package/dist/scope/Scope.js +55 -16
- package/dist/scope/ScopePlugin.d.ts +2 -8
- package/dist/scope/disclosure.d.ts +1 -1
- package/dist/scope/disclosure.js +1 -1
- package/dist/scope/plugins/allInOne.d.ts +13 -1
- package/dist/scope/plugins/allInOne.js +9 -5
- package/dist/scope/plugins/builtin/AsyncExecTool.d.ts +12 -0
- package/dist/scope/plugins/builtin/AsyncExecTool.js +103 -0
- package/dist/scope/plugins/builtin/AsyncTimeoutTool.d.ts +10 -0
- package/dist/scope/plugins/builtin/AsyncTimeoutTool.js +90 -0
- package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.d.ts +1 -1
- package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.js +1 -1
- package/dist/scope/plugins/builtin/DownloadFileTool.js +1 -1
- package/dist/scope/plugins/builtin/ExecTool.js +10 -199
- package/dist/scope/plugins/builtin/FindTextTool.d.ts +1 -1
- package/dist/scope/plugins/builtin/FindTextTool.js +1 -1
- package/dist/scope/plugins/builtin/GenerateImageTool.d.ts +1 -4
- package/dist/scope/plugins/builtin/GenerateImageTool.js +2 -8
- package/dist/scope/plugins/builtin/InspectFileTool.js +1 -1
- package/dist/scope/plugins/builtin/SdkCallbackTool.d.ts +4 -4
- package/dist/scope/plugins/builtin/SdkCallbackTool.js +3 -3
- package/dist/scope/plugins/builtin/SleepTool.js +2 -3
- package/dist/scope/plugins/builtin/ViewImageTool.d.ts +2 -4
- package/dist/scope/plugins/builtin/ViewImageTool.js +4 -6
- package/dist/scope/plugins/builtin/WriteTool.d.ts +7 -0
- package/dist/scope/plugins/builtin/WriteTool.js +8 -1
- package/dist/scope/plugins/builtin/asyncTasks.d.ts +41 -0
- package/dist/scope/plugins/builtin/asyncTasks.js +97 -0
- package/dist/scope/plugins/builtin/commandOutput.d.ts +22 -0
- package/dist/scope/plugins/builtin/commandOutput.js +55 -0
- package/dist/scope/plugins/builtin/commandRun.d.ts +48 -0
- package/dist/scope/plugins/builtin/commandRun.js +169 -0
- package/dist/scope/plugins/builtin/discover.d.ts +1 -3
- package/dist/scope/plugins/builtin/discover.js +1 -3
- package/dist/scope/plugins/builtin/index.d.ts +5 -7
- package/dist/scope/plugins/builtin/index.js +7 -7
- package/dist/scope/plugins/builtin/outputGuard.d.ts +1 -5
- package/dist/scope/plugins/builtin/outputGuard.js +1 -5
- package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +61 -9
- package/dist/scope/plugins/mcp/McpConnectionManager.js +174 -72
- package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +37 -4
- package/dist/scope/plugins/mcp/McpScopePlugin.js +100 -9
- package/dist/scope/plugins/mcp/discover.d.ts +9 -2
- package/dist/scope/plugins/mcp/discover.js +12 -14
- package/dist/scope/plugins/mcp/mcpTaskNotice.d.ts +52 -0
- package/dist/scope/plugins/mcp/mcpTaskNotice.js +8 -0
- package/dist/scope/plugins/mcp/mcpTools.d.ts +20 -2
- package/dist/scope/plugins/mcp/mcpTools.js +220 -39
- package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +25 -0
- package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +32 -0
- package/dist/scope/plugins/peers/peerSessionTools.d.ts +173 -0
- package/dist/scope/plugins/peers/peerSessionTools.js +292 -0
- package/dist/scope/plugins/skills/SkillsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/skills/SkillsScopePlugin.js +10 -4
- package/dist/scope/plugins/skills/discover.d.ts +15 -8
- package/dist/scope/plugins/skills/discover.js +15 -26
- package/dist/scope/plugins/skills/skillTools.d.ts +9 -8
- package/dist/scope/plugins/skills/skillTools.js +21 -13
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +4 -1
- package/dist/scope/plugins/subagents/discover.d.ts +7 -1
- package/dist/scope/plugins/subagents/discover.js +7 -3
- package/dist/scope/plugins/subagents/subAgentTools.d.ts +0 -1
- package/dist/scope/plugins/subagents/subAgentTools.js +14 -1
- package/dist/scope/plugins/usertools/UserToolsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/usertools/UserToolsScopePlugin.js +4 -1
- package/dist/scope/plugins/usertools/discover.d.ts +7 -8
- package/dist/scope/plugins/usertools/discover.js +17 -27
- package/dist/shared/EntityRepository.d.ts +22 -5
- package/dist/shared/EntityRepository.js +45 -29
- package/dist/shared/content-blocks.d.ts +9 -3
- package/dist/shared/content-blocks.js +12 -19
- package/dist/shared/errors.d.ts +8 -3
- package/dist/shared/errors.js +9 -4
- package/dist/shared/logger.d.ts +21 -10
- package/dist/shared/logger.js +9 -15
- package/dist/types/index.d.ts +38 -13
- package/package.json +2 -2
- package/dist/config/migrate.d.ts +0 -115
- package/dist/config/migrate.js +0 -200
- package/dist/scope/plugins/builtin/test-helpers.d.ts +0 -3
- package/dist/scope/plugins/builtin/test-helpers.js +0 -4
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
import { CallbackTool } from "@ai-zen/agents-core";
|
|
2
|
+
import { GetTaskPayloadResultSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
2
3
|
import { fileToContentSection, resolveModelAndEndpoint } from "../../../shared/content-blocks.js";
|
|
3
4
|
import { createDisclosureParam } from "../../disclosure.js";
|
|
4
5
|
import { DEFAULT_MAX_TOOL_OUTPUT, guardOutput, headTailPreview } from "../builtin/outputGuard.js";
|
|
5
|
-
import {
|
|
6
|
+
import { SILENT_LOG } from "../../../shared/logger.js";
|
|
7
|
+
import { CANCEL_MCP_TASK_TOOL, GET_MCP_TASK_RESULT_TOOL } from "./mcpTaskNotice.js";
|
|
6
8
|
const EMPTY_HINT = "(No MCP servers available, ask the user to add one)";
|
|
7
9
|
/**
|
|
8
10
|
* 创建 load_mcp 工具。
|
|
9
11
|
* server 枚举由 filteredMcps (完整 McpServerConfig[])自动推导,
|
|
10
12
|
* 查找配置也直接使用 filteredMcps,与枚举来源一致。
|
|
13
|
+
*
|
|
14
|
+
* @param logger 日志口(可选):报「连上了、清单多大」那两句走它;不注入就不记(库缺省沉默)
|
|
11
15
|
*/
|
|
12
|
-
export function createLoadMcpTool(mcpManager, filteredMcps) {
|
|
16
|
+
export function createLoadMcpTool(mcpManager, filteredMcps, logger = SILENT_LOG) {
|
|
13
17
|
// 构建 id→config 查找表
|
|
14
18
|
const configMap = new Map();
|
|
15
19
|
for (const s of filteredMcps) {
|
|
@@ -69,7 +73,7 @@ export function createLoadMcpTool(mcpManager, filteredMcps) {
|
|
|
69
73
|
}
|
|
70
74
|
// 静默模式:只回吐摘要(清单仍留在管理器内,供 call_mcp_tool 使用)
|
|
71
75
|
if (!includeManifest) {
|
|
72
|
-
|
|
76
|
+
logger.info(`[load_mcp] ${serverName}: connected (manifest not disclosed: ${manifest.tools.length} tools, ${manifest.resources.length} resources)`);
|
|
73
77
|
return JSON.stringify({
|
|
74
78
|
server: serverName,
|
|
75
79
|
connected: true,
|
|
@@ -77,11 +81,16 @@ export function createLoadMcpTool(mcpManager, filteredMcps) {
|
|
|
77
81
|
resources: manifest.resources.length,
|
|
78
82
|
});
|
|
79
83
|
}
|
|
80
|
-
|
|
84
|
+
logger.info(`[load_mcp] ${serverName}:\n${JSON.stringify(manifest, null, 2)}`);
|
|
81
85
|
return JSON.stringify({ tools: manifest.tools, resources: manifest.resources });
|
|
82
86
|
},
|
|
83
87
|
});
|
|
84
88
|
}
|
|
89
|
+
/** 当前这次调用该按哪个端点、哪个模型处理媒体(模型名从执行体上现读) */
|
|
90
|
+
function mediaContextOf(env, ctx) {
|
|
91
|
+
const { model, endpoint } = resolveModelAndEndpoint(env.config, ctx?.agent?.model);
|
|
92
|
+
return { endpoint, model, signal: ctx?.signal, deps: env.deps };
|
|
93
|
+
}
|
|
85
94
|
/** MIME → 文件名后缀(仅用于上传时给文件一个好名字) */
|
|
86
95
|
const EXT_BY_MIME = {
|
|
87
96
|
"image/png": "png",
|
|
@@ -232,13 +241,63 @@ async function protectCallOutput(output, env) {
|
|
|
232
241
|
return isError ? `❌ Tool execution failed:\n${fullText}` : fullText;
|
|
233
242
|
return isError ? [{ type: "text", text: "❌ Tool execution failed:" }, ...sections] : sections;
|
|
234
243
|
}
|
|
244
|
+
/**
|
|
245
|
+
* 一次工具调用的结果(`CallToolResult` 那一格)→ 回给模型的内容。
|
|
246
|
+
*
|
|
247
|
+
* 两处共用这一份:同步调用的结果与任务结果的形状是同一个 —— 规范里 `tasks/result` 的载荷就是
|
|
248
|
+
* 原请求的结果类型,各写一遍只会让其中一处漏掉后来的修改。
|
|
249
|
+
*/
|
|
250
|
+
async function callResultToContent(raw, env, media) {
|
|
251
|
+
const result = (raw ?? {});
|
|
252
|
+
// 按 MCP content 原始顺序映射,文本与媒体的相对位置完整保留
|
|
253
|
+
const contents = result.content ?? [];
|
|
254
|
+
const isError = Boolean(result.isError);
|
|
255
|
+
// 没有 content 时退回原始 JSON(既有兜底)
|
|
256
|
+
if (contents.length === 0) {
|
|
257
|
+
const json = JSON.stringify(raw);
|
|
258
|
+
return await protectCallOutput({
|
|
259
|
+
sections: [{ type: "text", text: json }],
|
|
260
|
+
fullText: json,
|
|
261
|
+
chars: json.length,
|
|
262
|
+
isError,
|
|
263
|
+
}, env);
|
|
264
|
+
}
|
|
265
|
+
// Promise.all 保序:文本与媒体的相对位置不变
|
|
266
|
+
const sections = await Promise.all(contents.map((block) => toMessageSection(block, media)));
|
|
267
|
+
const textSections = sections.filter((s) => s.type === "text");
|
|
268
|
+
const fullText = textSections.map((s) => s.text).join("\n");
|
|
269
|
+
const chars = textSections.reduce((n, s) => n + s.text.length, 0);
|
|
270
|
+
return await protectCallOutput({ sections, fullText, chars, isError }, env);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* 拿到句柄时回给模型的那段话。
|
|
274
|
+
*
|
|
275
|
+
* 三件事要一次说全,缺一件模型就会在这里等一个不会自己回来的结果:这是个任务而不是结果、任务
|
|
276
|
+
* id 是什么、结果要自己拿哪一条工具去取(带齐两个参数的形状)。最后一句说清状态到了会有话过来,
|
|
277
|
+
* 那正是「不用在这儿等」的理由。
|
|
278
|
+
*/
|
|
279
|
+
function taskHandleText(server, task) {
|
|
280
|
+
return JSON.stringify({
|
|
281
|
+
task: true,
|
|
282
|
+
taskId: task.taskId,
|
|
283
|
+
status: task.status,
|
|
284
|
+
...(task.statusMessage === undefined ? {} : { statusMessage: task.statusMessage }),
|
|
285
|
+
hint: `This is a TASK, not a result: the server accepted the call and is working on it. ` +
|
|
286
|
+
`Nothing comes back through this call. Get the result with ${GET_MCP_TASK_RESULT_TOOL} ` +
|
|
287
|
+
`and the arguments {"server":"${server}","task_id":"${task.taskId}"}; ` +
|
|
288
|
+
`give it up with ${CANCEL_MCP_TASK_TOOL} and the same two. ` +
|
|
289
|
+
`When the task ends (completed / failed / cancelled) a message about it arrives in this ` +
|
|
290
|
+
`session, so there is no need to poll it.`,
|
|
291
|
+
});
|
|
292
|
+
}
|
|
235
293
|
/**
|
|
236
294
|
* 创建 call_mcp_tool 工具。
|
|
237
295
|
* 通过官方 Client.callTool() API 调用 MCP 服务器上的工具。
|
|
238
296
|
*
|
|
239
297
|
* 返回形态:
|
|
240
298
|
* - 仅文本 → 纯字符串;
|
|
241
|
-
* - 含媒体 →
|
|
299
|
+
* - 含媒体 → 内容块数组,按 MCP content 的原始顺序(文本块可能夹在中间);
|
|
300
|
+
* - 任务是任务时 → 一段带任务 id 的 JSON,结果不在这条路上回来(见 {@link taskHandleText})。
|
|
242
301
|
*
|
|
243
302
|
* env 仅用于读取 maxToolOutput(文本输出保护上限),与内置工具口径一致。
|
|
244
303
|
*/
|
|
@@ -250,13 +309,26 @@ export function createCallMcpTool(mcpManager, env, filteredMcps) {
|
|
|
250
309
|
return new CallbackTool({
|
|
251
310
|
function: {
|
|
252
311
|
name: "call_mcp_tool",
|
|
253
|
-
description: "Call a tool exposed by a connected MCP server. Connect the server with load_mcp first.
|
|
312
|
+
description: "Call a tool exposed by a connected MCP server. Connect the server with load_mcp first. " +
|
|
313
|
+
"Large text output is written to disk and only a head/tail preview is returned; images, " +
|
|
314
|
+
"audio and other media are preserved: uploaded and referenced by file_id when the " +
|
|
315
|
+
"endpoint supports the Files API, otherwise inlined as base64. " +
|
|
316
|
+
`Pass task=true to run a long call as a task: the call then returns a task id instead of ` +
|
|
317
|
+
`a result, and the result is fetched later with ${GET_MCP_TASK_RESULT_TOOL}. Tools that ` +
|
|
318
|
+
"require a task always run as one, tools that forbid it never do.",
|
|
254
319
|
parameters: {
|
|
255
320
|
type: "object",
|
|
256
321
|
properties: {
|
|
257
322
|
server: { type: "string", description: "MCP server name" },
|
|
258
323
|
tool: { type: "string", description: "Tool name" },
|
|
259
324
|
arguments: { type: "object", description: "Tool arguments" },
|
|
325
|
+
task: {
|
|
326
|
+
type: "boolean",
|
|
327
|
+
description: "Run this call as a task (optional). The call returns a task id at once and the " +
|
|
328
|
+
"result has to be fetched by that id; when the task ends a message about it arrives " +
|
|
329
|
+
"in this session. Only tools that allow task execution can do it — for the others " +
|
|
330
|
+
"this flag makes no difference.",
|
|
331
|
+
},
|
|
260
332
|
},
|
|
261
333
|
required: ["server", "tool", "arguments"],
|
|
262
334
|
additionalProperties: false,
|
|
@@ -275,39 +347,45 @@ export function createCallMcpTool(mcpManager, env, filteredMcps) {
|
|
|
275
347
|
if (!client) {
|
|
276
348
|
return `MCP server "${serverName}" client is not available`;
|
|
277
349
|
}
|
|
350
|
+
const toolName = input.tool;
|
|
351
|
+
const callArgs = {
|
|
352
|
+
name: toolName,
|
|
353
|
+
arguments: input.arguments,
|
|
354
|
+
};
|
|
355
|
+
// 三档怎么走:required 一定带任务参数(不带服务器会拒),optional 听调用方那一句,
|
|
356
|
+
// forbidden 与没声明这一格的忽略它
|
|
357
|
+
const support = mcpManager.taskSupportOf(serverName, toolName);
|
|
358
|
+
const asTask = support === "required" || (support === "optional" && input.task === true);
|
|
278
359
|
try {
|
|
279
360
|
mcpManager.touch(serverName);
|
|
280
|
-
const
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
// 按 MCP content 原始顺序映射,文本与媒体的相对位置完整保留
|
|
285
|
-
const contents = result.content ?? [];
|
|
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);
|
|
361
|
+
const media = mediaContextOf(env, ctx);
|
|
362
|
+
if (!asTask) {
|
|
363
|
+
const result = await client.callTool(callArgs, undefined, { signal: ctx?.signal });
|
|
364
|
+
return await callResultToContent(result, env, media);
|
|
296
365
|
}
|
|
297
|
-
//
|
|
298
|
-
|
|
299
|
-
const
|
|
300
|
-
|
|
301
|
-
model,
|
|
366
|
+
// 任务增强:这条流的第一条就是句柄(`taskCreated`),拿到它就返回 —— 不等任务跑完,
|
|
367
|
+
// 结果也不从这条路上回来
|
|
368
|
+
const stream = client.experimental.tasks.callToolStream(callArgs, undefined, {
|
|
369
|
+
task: {},
|
|
302
370
|
signal: ctx?.signal,
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
371
|
+
});
|
|
372
|
+
for await (const message of stream) {
|
|
373
|
+
switch (message.type) {
|
|
374
|
+
case "taskCreated":
|
|
375
|
+
// 记下这个任务是谁发起的:终态通知到了要投回这段会话
|
|
376
|
+
mcpManager.rememberTask(serverName, message.task.taskId, ctx.agent);
|
|
377
|
+
return taskHandleText(serverName, message.task);
|
|
378
|
+
case "result":
|
|
379
|
+
// 服务器没把它当任务(`optional` 档上它自己跑完了),结果就在这里
|
|
380
|
+
return await callResultToContent(message.result, env, media);
|
|
381
|
+
case "error":
|
|
382
|
+
return `❌ Failed to call "${toolName}": ${message.error.message}`;
|
|
383
|
+
default:
|
|
384
|
+
// taskStatus:句柄已经交出去了才会来,这一次调用已经不需要它
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return `❌ Failed to call "${toolName}": the task stream ended without a task or a result`;
|
|
311
389
|
}
|
|
312
390
|
catch (error) {
|
|
313
391
|
return `❌ Failed to call "${input.tool}": ${error?.message ?? error}`;
|
|
@@ -360,8 +438,7 @@ export function createReadMcpResourceTool(mcpManager, env, filteredMcps) {
|
|
|
360
438
|
signal: ctx?.signal,
|
|
361
439
|
deps: env.deps,
|
|
362
440
|
};
|
|
363
|
-
// 与 call_mcp_tool 同一套映射:文本归一为 text
|
|
364
|
-
// 不再把二进制资源(图片 / PDF)静默丢掉。
|
|
441
|
+
// 与 call_mcp_tool 同一套映射:文本归一为 text 块,媒体按端点能力上传或内联
|
|
365
442
|
const sections = await Promise.all(contents.map((content) => resourceToMessageSection(content, mediaContext)));
|
|
366
443
|
// 没有 contents 时退回原始 JSON(与 call_mcp_tool 同一兜底)
|
|
367
444
|
if (sections.length === 0) {
|
|
@@ -373,8 +450,6 @@ export function createReadMcpResourceTool(mcpManager, env, filteredMcps) {
|
|
|
373
450
|
isError: false,
|
|
374
451
|
}, env);
|
|
375
452
|
}
|
|
376
|
-
// 与 call_mcp_tool 共用同一套输出保护:文本超限落盘 result.txt,
|
|
377
|
-
// 媒体块原位保留;未超限时纯文本退化为字符串、含媒体返回块数组。
|
|
378
453
|
const textSections = sections.filter((section) => section.type === "text");
|
|
379
454
|
const fullText = textSections.map((section) => section.text).join("\n");
|
|
380
455
|
const chars = textSections.reduce((n, section) => n + section.text.length, 0);
|
|
@@ -386,3 +461,109 @@ export function createReadMcpResourceTool(mcpManager, env, filteredMcps) {
|
|
|
386
461
|
},
|
|
387
462
|
});
|
|
388
463
|
}
|
|
464
|
+
/**
|
|
465
|
+
* 创建 get_mcp_task_result 工具:按任务 id 去服务器取回结果。
|
|
466
|
+
*
|
|
467
|
+
* 结果原样交给模型:服务器存下来的就是一次工具调用的结果,与 `call_mcp_tool` 走同一套媒体映射
|
|
468
|
+
* 与输出保护(见 {@link callResultToContent})。
|
|
469
|
+
*/
|
|
470
|
+
export function createGetMcpTaskResultTool(mcpManager, env, filteredMcps) {
|
|
471
|
+
// 与 call_mcp_tool 同一白名单口径(见该工具的说明)
|
|
472
|
+
const allowed = new Set(filteredMcps);
|
|
473
|
+
const allowList = filteredMcps.join(", ") || "(none)";
|
|
474
|
+
return new CallbackTool({
|
|
475
|
+
function: {
|
|
476
|
+
name: GET_MCP_TASK_RESULT_TOOL,
|
|
477
|
+
description: "Get the result of a task started by call_mcp_tool with a task id. The result is handed " +
|
|
478
|
+
"back as it is (text and media, same output protection as call_mcp_tool). Use it when " +
|
|
479
|
+
"the session was told that the task ended; if the task has not finished yet the server " +
|
|
480
|
+
"may hold the call until it does.",
|
|
481
|
+
parameters: {
|
|
482
|
+
type: "object",
|
|
483
|
+
properties: {
|
|
484
|
+
server: { type: "string", description: "MCP server name" },
|
|
485
|
+
task_id: { type: "string", description: "Task id returned when the task was started" },
|
|
486
|
+
},
|
|
487
|
+
required: ["server", "task_id"],
|
|
488
|
+
additionalProperties: false,
|
|
489
|
+
},
|
|
490
|
+
},
|
|
491
|
+
callback: async (input, ctx) => {
|
|
492
|
+
const serverName = input.server;
|
|
493
|
+
if (!allowed.has(serverName)) {
|
|
494
|
+
return `❌ MCP server "${serverName}" is not available here. Available servers: ${allowList}`;
|
|
495
|
+
}
|
|
496
|
+
if (mcpManager.getState(serverName) !== "connected") {
|
|
497
|
+
return `Call load_mcp to connect "${serverName}" first`;
|
|
498
|
+
}
|
|
499
|
+
const client = mcpManager.getClient(serverName);
|
|
500
|
+
if (!client) {
|
|
501
|
+
return `MCP server "${serverName}" client is not available`;
|
|
502
|
+
}
|
|
503
|
+
const taskId = String(input.task_id ?? "");
|
|
504
|
+
try {
|
|
505
|
+
mcpManager.touch(serverName);
|
|
506
|
+
// 载荷的形状由原请求决定(`tasks/result` 返回的就是它的结果类型),所以取宽松的那一格:
|
|
507
|
+
// 具体怎么解释由 `callResultToContent` 按 content / isError 做
|
|
508
|
+
const payload = await client.experimental.tasks.getTaskResult(taskId, GetTaskPayloadResultSchema, { signal: ctx?.signal });
|
|
509
|
+
return await callResultToContent(payload, env, mediaContextOf(env, ctx));
|
|
510
|
+
}
|
|
511
|
+
catch (error) {
|
|
512
|
+
return `❌ Failed to get the result of task "${taskId}" on "${serverName}": ${error?.message ?? error}`;
|
|
513
|
+
}
|
|
514
|
+
},
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* 创建 cancel_mcp_task 工具:让服务器停掉一个已经发起的任务。
|
|
519
|
+
*
|
|
520
|
+
* 回给模型的是任务此刻那一格(`tasks/cancel` 的应答就是这个形状)。终态通知照旧会来:
|
|
521
|
+
* 取消也是终态,到了就把那条状态搁进 inbox。
|
|
522
|
+
*/
|
|
523
|
+
export function createCancelMcpTaskTool(mcpManager, filteredMcps) {
|
|
524
|
+
// 与 call_mcp_tool 同一白名单口径(见该工具的说明)
|
|
525
|
+
const allowed = new Set(filteredMcps);
|
|
526
|
+
const allowList = filteredMcps.join(", ") || "(none)";
|
|
527
|
+
return new CallbackTool({
|
|
528
|
+
function: {
|
|
529
|
+
name: CANCEL_MCP_TASK_TOOL,
|
|
530
|
+
description: "Cancel a task started by call_mcp_tool. The server stops working on it; a task that " +
|
|
531
|
+
"already ended cannot be cancelled and the call fails with the reason it gives.",
|
|
532
|
+
parameters: {
|
|
533
|
+
type: "object",
|
|
534
|
+
properties: {
|
|
535
|
+
server: { type: "string", description: "MCP server name" },
|
|
536
|
+
task_id: { type: "string", description: "Task id returned when the task was started" },
|
|
537
|
+
},
|
|
538
|
+
required: ["server", "task_id"],
|
|
539
|
+
additionalProperties: false,
|
|
540
|
+
},
|
|
541
|
+
},
|
|
542
|
+
callback: async (input, ctx) => {
|
|
543
|
+
const serverName = input.server;
|
|
544
|
+
if (!allowed.has(serverName)) {
|
|
545
|
+
return `❌ MCP server "${serverName}" is not available here. Available servers: ${allowList}`;
|
|
546
|
+
}
|
|
547
|
+
if (mcpManager.getState(serverName) !== "connected") {
|
|
548
|
+
return `Call load_mcp to connect "${serverName}" first`;
|
|
549
|
+
}
|
|
550
|
+
const client = mcpManager.getClient(serverName);
|
|
551
|
+
if (!client) {
|
|
552
|
+
return `MCP server "${serverName}" client is not available`;
|
|
553
|
+
}
|
|
554
|
+
const taskId = String(input.task_id ?? "");
|
|
555
|
+
try {
|
|
556
|
+
mcpManager.touch(serverName);
|
|
557
|
+
const task = await client.experimental.tasks.cancelTask(taskId, { signal: ctx?.signal });
|
|
558
|
+
return JSON.stringify({
|
|
559
|
+
taskId: task.taskId,
|
|
560
|
+
status: task.status,
|
|
561
|
+
...(task.statusMessage === undefined ? {} : { statusMessage: task.statusMessage }),
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
catch (error) {
|
|
565
|
+
return `❌ Failed to cancel task "${taskId}" on "${serverName}": ${error?.message ?? error}`;
|
|
566
|
+
}
|
|
567
|
+
},
|
|
568
|
+
});
|
|
569
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Tool } from "@ai-zen/agents-core";
|
|
2
|
+
import type { PeerSessionPort } from "./peerSessionTools.js";
|
|
3
|
+
import type { Scope, FilterOutput } from "../../Scope.js";
|
|
4
|
+
import type { ScopeCandidates, ScopePlugin } from "../../ScopePlugin.js";
|
|
5
|
+
/**
|
|
6
|
+
* 平级会话插件 —— 把宿主给的端口装成三个工具(`create_session` / `read_session_status` /
|
|
7
|
+
* `post_message`)。
|
|
8
|
+
*
|
|
9
|
+
* 与 `SubAgentsScopePlugin` 同构(`id` / `candidates` / `instantiate`):自己不发现任何东西
|
|
10
|
+
* (平级会话不是磁盘上的定义,是宿主的运行时能力),候选名是固定的三个。
|
|
11
|
+
*
|
|
12
|
+
* 为什么能力从端口进来而不是 SDK 自己实现:会话是宿主的财产(id、落库、模型解析、投递、
|
|
13
|
+
* 现读那一格全在那边),SDK 这一层只认识 Scope 与 Agent 定义。端口是唯一的一处接线,
|
|
14
|
+
* 于是「SDK 不依赖 host」这条分层不用破例。
|
|
15
|
+
*/
|
|
16
|
+
export declare class PeerSessionsScopePlugin implements ScopePlugin {
|
|
17
|
+
static readonly ID = "peer-sessions";
|
|
18
|
+
readonly id = "peer-sessions";
|
|
19
|
+
private readonly port?;
|
|
20
|
+
/** 不传端口 = 这个 Scope 没有平级会话能力 */
|
|
21
|
+
constructor(port?: PeerSessionPort);
|
|
22
|
+
candidates(): ScopeCandidates;
|
|
23
|
+
instantiate(_scope: Scope, filtered: FilterOutput): Tool[];
|
|
24
|
+
}
|
|
25
|
+
export type { PeerSessionPort };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createPeerSessionTools, PEER_SESSION_TOOL_NAMES } from "./peerSessionTools.js";
|
|
2
|
+
/**
|
|
3
|
+
* 平级会话插件 —— 把宿主给的端口装成三个工具(`create_session` / `read_session_status` /
|
|
4
|
+
* `post_message`)。
|
|
5
|
+
*
|
|
6
|
+
* 与 `SubAgentsScopePlugin` 同构(`id` / `candidates` / `instantiate`):自己不发现任何东西
|
|
7
|
+
* (平级会话不是磁盘上的定义,是宿主的运行时能力),候选名是固定的三个。
|
|
8
|
+
*
|
|
9
|
+
* 为什么能力从端口进来而不是 SDK 自己实现:会话是宿主的财产(id、落库、模型解析、投递、
|
|
10
|
+
* 现读那一格全在那边),SDK 这一层只认识 Scope 与 Agent 定义。端口是唯一的一处接线,
|
|
11
|
+
* 于是「SDK 不依赖 host」这条分层不用破例。
|
|
12
|
+
*/
|
|
13
|
+
export class PeerSessionsScopePlugin {
|
|
14
|
+
static ID = "peer-sessions";
|
|
15
|
+
id = PeerSessionsScopePlugin.ID;
|
|
16
|
+
port;
|
|
17
|
+
/** 不传端口 = 这个 Scope 没有平级会话能力 */
|
|
18
|
+
constructor(port) {
|
|
19
|
+
this.port = port;
|
|
20
|
+
}
|
|
21
|
+
candidates() {
|
|
22
|
+
if (!this.port)
|
|
23
|
+
return {};
|
|
24
|
+
return { tools: [...PEER_SESSION_TOOL_NAMES] };
|
|
25
|
+
}
|
|
26
|
+
instantiate(_scope, filtered) {
|
|
27
|
+
if (!this.port)
|
|
28
|
+
return [];
|
|
29
|
+
const allow = new Set(filtered.tools);
|
|
30
|
+
return createPeerSessionTools(this.port).filter((tool) => allow.has(tool.function.name));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import type { Agent, Tool } from "@ai-zen/agents-core";
|
|
2
|
+
/**
|
|
3
|
+
* 平级会话(peer session)的三个工具 —— **只负责把模型的话翻译成端口调用**。
|
|
4
|
+
*
|
|
5
|
+
* 端口({@link PeerSessionPort})由宿主实现:开一段会话、把一句话投进去、现读它此刻落在哪一格,
|
|
6
|
+
* 都是宿主的事(会话是宿主的财产,SDK 不认识会话)。SDK 这一侧只有三样东西:参数说明、
|
|
7
|
+
* **给模型看的那几句话**(别轮询:她说完会自己 `post_message` 回来;记不住 `sessionId` 就靠
|
|
8
|
+
* `label`),以及三个工具各自的返回形状。
|
|
9
|
+
*
|
|
10
|
+
* ## 为什么这几句话必须同时出现在 description 与返回文案两处
|
|
11
|
+
*
|
|
12
|
+
* 模型只读它拿到的东西 —— 第一次只看得到 description,之后每次调用只看得到返回值。少写一处,
|
|
13
|
+
* 模型就会开始忙等轮询(`read_session_status` 一个接一个),而每次轮询都要烧一次模型调用。
|
|
14
|
+
*
|
|
15
|
+
* ## 投递不承诺任何未来
|
|
16
|
+
*
|
|
17
|
+
* `post_message` 的回执只有「收下了」。那边忙不忙、什么时候取件、取走之后会做什么,**都不是
|
|
18
|
+
* 这一句话能定下的**,写在回执里就是对未来的断言 —— 而未来只能靠观测(`read_session_status`)
|
|
19
|
+
* 与对方自己发来的话去读。所以本文件的回执里没有「把它叫起来了」「排在它手头那批后面」这类话。
|
|
20
|
+
*
|
|
21
|
+
* ## 投递不看关系
|
|
22
|
+
*
|
|
23
|
+
* 谁都能给谁投:`post_message` 只问「目标在不在、活不活」,不问「你俩是什么关系」。平级之间
|
|
24
|
+
* 能不能互发、发了对方理不理,靠的是 agent 自己的知识(它在提示里就知道自己跟谁在说话),
|
|
25
|
+
* 不是一道校验。只有**创建**还有「只限一层」这条产品限制,它写在 `create_session` 那边。
|
|
26
|
+
*/
|
|
27
|
+
/** `create_session`:开一段平级会话,建完即回 */
|
|
28
|
+
export declare const CREATE_SESSION_TOOL = "create_session";
|
|
29
|
+
/** `read_session_status`:只问状态 + 一句摘要,绝不返回全量消息 */
|
|
30
|
+
export declare const READ_SESSION_STATUS_TOOL = "read_session_status";
|
|
31
|
+
/** `post_message`:给另一段会话投一句话(不等结果,投递不看关系) */
|
|
32
|
+
export declare const POST_MESSAGE_TOOL = "post_message";
|
|
33
|
+
/** 本插件向 `tools` 维度贡献的候选名(顺序即展示顺序) */
|
|
34
|
+
export declare const PEER_SESSION_TOOL_NAMES: readonly ["create_session", "read_session_status", "post_message"];
|
|
35
|
+
/**
|
|
36
|
+
* 忙不忙 —— **只读的观测值**,就是 core 的 `agent.state` 那两格(`PRD.md` 4.4),名字不改。
|
|
37
|
+
*
|
|
38
|
+
* 这里**没有** `paused`、也没有 `dead`:那两件事不是「忙不忙」—— 一个是输出闸关着(它闲着,
|
|
39
|
+
* 但不会自己动),一个是根本没有 agent 对象。挤进同一格,模型就分不清「它闲着」与「它压根
|
|
40
|
+
* 不是活的」。死活由同一个答复里的 `alive` 说;两道闸对平级会话不报(`PRD.md` 4.6 只要
|
|
41
|
+
* 「忙不忙 + 最近一句摘要」)。
|
|
42
|
+
*
|
|
43
|
+
* 也**没有** `running` / `failed` / `aborted`:失败是某条消息上的事实(那条消息的 `status` /
|
|
44
|
+
* `error`),不是一段会话此刻的状态;也**没有** `gone`:会话找不到就是 `found: false`。
|
|
45
|
+
*/
|
|
46
|
+
export type PeerSessionActivity = "working" | "idle";
|
|
47
|
+
/**
|
|
48
|
+
* `create_session` 被**结构化拒绝**的原因。
|
|
49
|
+
*
|
|
50
|
+
* 拒绝是返回结果而不是异常:模型要能读懂并改变策略(「这层不能开分身了,那我自己做」
|
|
51
|
+
* 「这个助手没有可用模型,换一个」「手头那几个还忙,先等一等或分给更少的会话」),异常只会
|
|
52
|
+
* 把它这一步打断。
|
|
53
|
+
*
|
|
54
|
+
* 三条都是**创建**的限制:`post_message` 没有「只限一层」「限额」这类判据 —— 投递只看目标
|
|
55
|
+
* 在不在、活不活。
|
|
56
|
+
*/
|
|
57
|
+
export type PeerSessionRejectReason = "depth_exceeded" | "model_unresolved" | "too_many_peers";
|
|
58
|
+
/**
|
|
59
|
+
* `create_session` 的答案。
|
|
60
|
+
*
|
|
61
|
+
* 成功只给两个字段:`sessionId`(新开那段会话的 id)与可读的 `label`。**没有结果** ——
|
|
62
|
+
* 建完即回:这里从来不等那边答完,也不会有任何东西被推回给发起者。
|
|
63
|
+
*/
|
|
64
|
+
export type PeerSessionCreated = {
|
|
65
|
+
ok: true;
|
|
66
|
+
sessionId: string;
|
|
67
|
+
label: string;
|
|
68
|
+
} | {
|
|
69
|
+
ok: false;
|
|
70
|
+
reason: PeerSessionRejectReason;
|
|
71
|
+
hint?: string;
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* `read_session_status` 的答案 —— **判别式**:要么「没有这一段」,要么「有这一段」并给出忙不忙与死活。
|
|
75
|
+
*
|
|
76
|
+
* `found: false` 那支的 `status` 就是 `null`:找不到不是一个状态值(忙不忙、活不活都是活对象
|
|
77
|
+
* 身上的事实,找不到就没有对象可读)。把它挤进同一格会让模型把「会话被删了」当成一种可等的情形。
|
|
78
|
+
*
|
|
79
|
+
* 有这一段时只有三格:**忙不忙**(`status`)、**叫什么**(`label`)、**最近一句说了什么**
|
|
80
|
+
* (`lastMessage`:最近一条助手消息的正文摘要,截断到 300 字,超出以省略号收尾;它还没说过话
|
|
81
|
+
* 就是 `null`)—— 这就是需求说的「忙不忙 + 最近一句摘要」的全部(`PRD.md` 2.3 / 4.6、
|
|
82
|
+
* `PLAN.md` 10.2)。
|
|
83
|
+
*
|
|
84
|
+
* **不给全量消息,也不给历史**(没有消息数组、没有条数、没有原文):给了原文模型就会把它当
|
|
85
|
+
* 上下文搬运,token 立刻炸,而且绕过了我们自己的上下文管理。
|
|
86
|
+
*/
|
|
87
|
+
export type PeerSessionStatus = {
|
|
88
|
+
found: false;
|
|
89
|
+
status: null;
|
|
90
|
+
} | {
|
|
91
|
+
found: true;
|
|
92
|
+
/** 忙不忙(两格,见 {@link PeerSessionActivity}) */
|
|
93
|
+
status: PeerSessionActivity;
|
|
94
|
+
/** 死活:那一段此刻还有没有 agent 对象(`false` = 死了,投过去也没人取件) */
|
|
95
|
+
alive: boolean;
|
|
96
|
+
label: string;
|
|
97
|
+
/** 最近一条助手消息的正文摘要(最多 300 字 + 省略号);还没说过话就是 `null` */
|
|
98
|
+
lastMessage: string | null;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* `post_message` 被拒绝的两种原因 —— 就是投递的两条判据。
|
|
102
|
+
*
|
|
103
|
+
* `gone`:这段会话不在(会话行被删了);
|
|
104
|
+
* `dead`:会话在,但那边没有 agent 对象,投过去也没有人会取件。
|
|
105
|
+
*
|
|
106
|
+
* 两者对模型是同一类答复:这句话没投出去,别等回音。
|
|
107
|
+
*/
|
|
108
|
+
export type PeerSessionSendRejectReason = "gone" | "dead";
|
|
109
|
+
/**
|
|
110
|
+
* `post_message` 的答案。
|
|
111
|
+
*
|
|
112
|
+
* 成功只有 `ok`,一个字段都不多:投递那一刻能定下的只有「收下了」。那边忙不忙、什么时候取件
|
|
113
|
+
* 都不是回执该说的话(那是对未来的断言)。
|
|
114
|
+
*/
|
|
115
|
+
export type PeerSessionSent = {
|
|
116
|
+
ok: true;
|
|
117
|
+
} | {
|
|
118
|
+
ok: false;
|
|
119
|
+
reason: PeerSessionSendRejectReason;
|
|
120
|
+
};
|
|
121
|
+
/** `post_message` 的入参(`caller` 由插件从 `ToolCallContext` 取,不由模型给) */
|
|
122
|
+
export interface PeerSessionSendInput {
|
|
123
|
+
/** 谁在调这个工具(`ctx.agent`)—— 宿主据此认领「哪一段会话在说话」与消息署名 */
|
|
124
|
+
caller: Agent;
|
|
125
|
+
sessionId: string;
|
|
126
|
+
content: string;
|
|
127
|
+
}
|
|
128
|
+
/** `create_session` 的入参(`caller` 由插件从 `ToolCallContext` 取,不由模型给) */
|
|
129
|
+
export interface PeerSessionCreateInput {
|
|
130
|
+
/** 谁在调这个工具(`ctx.agent`)—— 宿主据此认领「哪一段会话在开新会话」 */
|
|
131
|
+
caller: Agent;
|
|
132
|
+
prompt: string;
|
|
133
|
+
agentId?: string;
|
|
134
|
+
modelId?: string;
|
|
135
|
+
label?: string;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* 宿主实现给 SDK 的端口(**SDK 不依赖宿主**:这个接口是唯一的一处接线)。
|
|
139
|
+
*
|
|
140
|
+
* 不给端口时插件不产出任何工具。
|
|
141
|
+
*/
|
|
142
|
+
export interface PeerSessionPort {
|
|
143
|
+
/**
|
|
144
|
+
* 开一段会话,**建完立刻回** `{ sessionId, label }`。
|
|
145
|
+
*
|
|
146
|
+
* 「立刻」是这一格的全部意思:不在里面等那边答完,也不挂 `.then` 去接任何后续事实。
|
|
147
|
+
* 拒绝照 {@link PeerSessionCreated} 的样子回,不抛错。
|
|
148
|
+
*/
|
|
149
|
+
create(input: PeerSessionCreateInput): Promise<PeerSessionCreated>;
|
|
150
|
+
/**
|
|
151
|
+
* 现读那一格**加上最近一句的摘要**(不存镜像:状态是活对象身上的事实);找不到就是
|
|
152
|
+
* `found: false`。摘要只是「最近一条助手消息的开头一段」,不是消息列表。
|
|
153
|
+
*/
|
|
154
|
+
status(input: {
|
|
155
|
+
caller: Agent;
|
|
156
|
+
sessionId: string;
|
|
157
|
+
}): Promise<PeerSessionStatus>;
|
|
158
|
+
/**
|
|
159
|
+
* 把一句话投给一段会话(**不等结果,也不回状态**)。
|
|
160
|
+
*
|
|
161
|
+
* 与 `create` / `status` 同构:**只收 `caller`**,不收来源名 / label —— 正文那行
|
|
162
|
+
* 「来自 会话「…」」由宿主按调用方解析(模型说自己是谁不算数)。
|
|
163
|
+
*
|
|
164
|
+
* 收下了就是 `{ ok: true }`;没投出去给原因({@link PeerSessionSendRejectReason})。
|
|
165
|
+
*/
|
|
166
|
+
send(input: PeerSessionSendInput): Promise<PeerSessionSent>;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* 造三个工具(顺序即返回顺序)。
|
|
170
|
+
*
|
|
171
|
+
* 三个工具都是即时返回的 `CallbackTool`:真正的等待在宿主那一侧(那边的 agent 自己跑)。
|
|
172
|
+
*/
|
|
173
|
+
export declare function createPeerSessionTools(port: PeerSessionPort): Tool[];
|