@ai-zen/agents-sdk 2.0.0-alpha.0 → 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.
Files changed (131) hide show
  1. package/CHANGELOG.md +73 -16
  2. package/README.md +397 -113
  3. package/README.zh.md +314 -112
  4. package/dist/agent-plugins/AssetTransportPlugin.d.ts +51 -0
  5. package/dist/agent-plugins/AssetTransportPlugin.js +145 -0
  6. package/dist/agent-plugins/AutoMigratePlugin.d.ts +35 -14
  7. package/dist/agent-plugins/AutoMigratePlugin.js +36 -36
  8. package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +6 -6
  9. package/dist/agent-plugins/AutoRefreshToolsPlugin.js +2 -2
  10. package/dist/agent-plugins/ContextGuardPlugin.d.ts +20 -24
  11. package/dist/agent-plugins/ContextGuardPlugin.js +25 -24
  12. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +25 -35
  13. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +26 -41
  14. package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +14 -9
  15. package/dist/agent-plugins/UnknownToolHintPlugin.js +15 -13
  16. package/dist/config/ConfigManager.d.ts +13 -5
  17. package/dist/config/ConfigManager.js +58 -39
  18. package/dist/config/constants.d.ts +1 -1
  19. package/dist/config/constants.js +2 -2
  20. package/dist/config/factory-skills.js +2 -2
  21. package/dist/config/normalize.d.ts +93 -0
  22. package/dist/config/normalize.js +158 -0
  23. package/dist/crud/AgentRepository.d.ts +3 -1
  24. package/dist/crud/AgentRepository.js +4 -2
  25. package/dist/index.d.ts +19 -9
  26. package/dist/index.js +14 -7
  27. package/dist/runtime/AgentRuntime.d.ts +293 -0
  28. package/dist/runtime/AgentRuntime.js +457 -0
  29. package/dist/runtime/HandoffGuardPlugin.d.ts +82 -15
  30. package/dist/runtime/HandoffGuardPlugin.js +136 -17
  31. package/dist/runtime/HandoffService.d.ts +244 -119
  32. package/dist/runtime/HandoffService.js +373 -251
  33. package/dist/runtime/RuntimePeerSessions.d.ts +34 -0
  34. package/dist/runtime/RuntimePeerSessions.js +50 -0
  35. package/dist/runtime/Scopes.d.ts +123 -0
  36. package/dist/runtime/Scopes.js +169 -0
  37. package/dist/runtime/SdkAgent.d.ts +19 -8
  38. package/dist/runtime/SdkAgent.js +23 -6
  39. package/dist/runtime/completeOnce.d.ts +3 -3
  40. package/dist/runtime/completeOnce.js +3 -3
  41. package/dist/runtime/createAgent.d.ts +29 -7
  42. package/dist/runtime/createAgent.js +57 -12
  43. package/dist/runtime/createModel.d.ts +4 -4
  44. package/dist/runtime/createModel.js +6 -6
  45. package/dist/runtime/lastPromptTokens.d.ts +18 -0
  46. package/dist/runtime/lastPromptTokens.js +26 -0
  47. package/dist/runtime/resolveModel.d.ts +9 -9
  48. package/dist/runtime/resolveModel.js +8 -8
  49. package/dist/scope/Scope.d.ts +10 -9
  50. package/dist/scope/Scope.js +6 -6
  51. package/dist/scope/ScopePlugin.d.ts +2 -8
  52. package/dist/scope/disclosure.d.ts +1 -1
  53. package/dist/scope/disclosure.js +1 -1
  54. package/dist/scope/plugins/allInOne.d.ts +13 -1
  55. package/dist/scope/plugins/allInOne.js +9 -5
  56. package/dist/scope/plugins/builtin/AsyncExecTool.d.ts +12 -0
  57. package/dist/scope/plugins/builtin/AsyncExecTool.js +103 -0
  58. package/dist/scope/plugins/builtin/AsyncTimeoutTool.d.ts +10 -0
  59. package/dist/scope/plugins/builtin/AsyncTimeoutTool.js +90 -0
  60. package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.d.ts +1 -1
  61. package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.js +1 -1
  62. package/dist/scope/plugins/builtin/DownloadFileTool.js +1 -1
  63. package/dist/scope/plugins/builtin/ExecTool.js +10 -199
  64. package/dist/scope/plugins/builtin/FindTextTool.d.ts +1 -1
  65. package/dist/scope/plugins/builtin/FindTextTool.js +1 -1
  66. package/dist/scope/plugins/builtin/GenerateImageTool.d.ts +1 -4
  67. package/dist/scope/plugins/builtin/GenerateImageTool.js +2 -8
  68. package/dist/scope/plugins/builtin/InspectFileTool.js +1 -1
  69. package/dist/scope/plugins/builtin/SdkCallbackTool.d.ts +4 -4
  70. package/dist/scope/plugins/builtin/SdkCallbackTool.js +3 -3
  71. package/dist/scope/plugins/builtin/SleepTool.js +2 -3
  72. package/dist/scope/plugins/builtin/ViewImageTool.d.ts +2 -4
  73. package/dist/scope/plugins/builtin/ViewImageTool.js +4 -6
  74. package/dist/scope/plugins/builtin/WriteTool.d.ts +7 -0
  75. package/dist/scope/plugins/builtin/WriteTool.js +8 -1
  76. package/dist/scope/plugins/builtin/asyncTasks.d.ts +41 -0
  77. package/dist/scope/plugins/builtin/asyncTasks.js +97 -0
  78. package/dist/scope/plugins/builtin/commandOutput.d.ts +22 -0
  79. package/dist/scope/plugins/builtin/commandOutput.js +55 -0
  80. package/dist/scope/plugins/builtin/commandRun.d.ts +48 -0
  81. package/dist/scope/plugins/builtin/commandRun.js +169 -0
  82. package/dist/scope/plugins/builtin/discover.d.ts +1 -3
  83. package/dist/scope/plugins/builtin/discover.js +1 -3
  84. package/dist/scope/plugins/builtin/index.d.ts +5 -7
  85. package/dist/scope/plugins/builtin/index.js +7 -7
  86. package/dist/scope/plugins/builtin/outputGuard.d.ts +1 -5
  87. package/dist/scope/plugins/builtin/outputGuard.js +1 -5
  88. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +56 -11
  89. package/dist/scope/plugins/mcp/McpConnectionManager.js +169 -74
  90. package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +17 -7
  91. package/dist/scope/plugins/mcp/McpScopePlugin.js +36 -12
  92. package/dist/scope/plugins/mcp/discover.d.ts +9 -2
  93. package/dist/scope/plugins/mcp/discover.js +12 -14
  94. package/dist/scope/plugins/mcp/mcpTaskNotice.d.ts +52 -0
  95. package/dist/scope/plugins/mcp/mcpTaskNotice.js +8 -0
  96. package/dist/scope/plugins/mcp/mcpTools.d.ts +20 -2
  97. package/dist/scope/plugins/mcp/mcpTools.js +220 -39
  98. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +4 -7
  99. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +4 -7
  100. package/dist/scope/plugins/peers/peerSessionTools.d.ts +97 -46
  101. package/dist/scope/plugins/peers/peerSessionTools.js +147 -121
  102. package/dist/scope/plugins/skills/SkillsScopePlugin.d.ts +4 -0
  103. package/dist/scope/plugins/skills/SkillsScopePlugin.js +10 -4
  104. package/dist/scope/plugins/skills/discover.d.ts +15 -8
  105. package/dist/scope/plugins/skills/discover.js +15 -26
  106. package/dist/scope/plugins/skills/skillTools.d.ts +8 -7
  107. package/dist/scope/plugins/skills/skillTools.js +18 -14
  108. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.d.ts +4 -0
  109. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +4 -1
  110. package/dist/scope/plugins/subagents/discover.d.ts +7 -1
  111. package/dist/scope/plugins/subagents/discover.js +7 -3
  112. package/dist/scope/plugins/subagents/subAgentTools.d.ts +0 -1
  113. package/dist/scope/plugins/subagents/subAgentTools.js +11 -1
  114. package/dist/scope/plugins/usertools/UserToolsScopePlugin.d.ts +4 -0
  115. package/dist/scope/plugins/usertools/UserToolsScopePlugin.js +4 -1
  116. package/dist/scope/plugins/usertools/discover.d.ts +7 -8
  117. package/dist/scope/plugins/usertools/discover.js +17 -27
  118. package/dist/shared/EntityRepository.d.ts +22 -5
  119. package/dist/shared/EntityRepository.js +45 -29
  120. package/dist/shared/content-blocks.d.ts +9 -3
  121. package/dist/shared/content-blocks.js +12 -19
  122. package/dist/shared/errors.d.ts +5 -7
  123. package/dist/shared/errors.js +6 -8
  124. package/dist/shared/logger.d.ts +21 -10
  125. package/dist/shared/logger.js +9 -15
  126. package/dist/types/index.d.ts +36 -13
  127. package/package.json +2 -2
  128. package/dist/config/migrate.d.ts +0 -115
  129. package/dist/config/migrate.js +0 -200
  130. package/dist/scope/plugins/builtin/test-helpers.d.ts +0 -3
  131. package/dist/scope/plugins/builtin/test-helpers.js +0 -4
@@ -1,5 +1,5 @@
1
1
  import { promises as fs } from "node:fs";
2
- import { getLogger } from "../../../shared/logger.js";
2
+ import { SILENT_LOG } from "../../../shared/logger.js";
3
3
  /**
4
4
  * 归一化原始 MCP server 配置为内部 McpServerConfig。
5
5
  * 处理业界标准中的字段别名差异。
@@ -22,6 +22,10 @@ function normalizeConfig(id, raw) {
22
22
  env: raw.env,
23
23
  url: raw.url,
24
24
  headers: raw.headers,
25
+ // oauth 是对象就原样带上(形状见 McpServerConfig["oauth"]),否则视为没配
26
+ oauth: typeof raw.oauth === "object" && raw.oauth !== null && !Array.isArray(raw.oauth)
27
+ ? raw.oauth
28
+ : undefined,
25
29
  };
26
30
  return config;
27
31
  }
@@ -43,17 +47,8 @@ function normalizeTransport(type, raw) {
43
47
  return "http";
44
48
  return null;
45
49
  }
46
- /**
47
- * 从 mcp.json 文件列表中发现所有 MCP server 配置。
48
- *
49
- * 遵循业界标准格式:
50
- * ```json
51
- * { "mcpServers": { "server-id": { "type": "stdio", "command": "npx", ... } } }
52
- * ```
53
- *
54
- * 按优先级从高到低传入路径列表,同名 server 靠前的文件优先(先到先得)。
55
- */
56
- export async function discoverMcpServers(paths) {
50
+ export async function discoverMcpServers(paths, options = {}) {
51
+ const logger = options.logger ?? SILENT_LOG;
57
52
  const seen = new Set();
58
53
  const items = [];
59
54
  for (const path of paths) {
@@ -74,15 +69,18 @@ export async function discoverMcpServers(paths) {
74
69
  const rawServer = servers[id];
75
70
  if (!rawServer || typeof rawServer !== "object")
76
71
  continue;
72
+ // 名字先认领,再决定收不收:写成 `disabled: true` 的那一条也是这一层对这个名字的
73
+ // 发言,远处同名的定义不该越过它生效。放到收进结果之后再认领,停用条目就不占名字
74
+ // —— 人写「别用」,合并出来的却是一条能用的。
75
+ seen.add(id);
77
76
  const normalized = normalizeConfig(id, rawServer);
78
77
  if (!normalized)
79
78
  continue;
80
- seen.add(id);
81
79
  items.push(normalized);
82
80
  }
83
81
  }
84
82
  catch (err) {
85
- getLogger().warn(`[sdk] Failed to parse MCP config: ${path} — ${err?.message ?? err}`);
83
+ logger.warn(`[sdk] Failed to parse MCP config: ${path} — ${err?.message ?? err}`);
86
84
  }
87
85
  }
88
86
  return items;
@@ -0,0 +1,52 @@
1
+ import type { Agent } from "@ai-zen/agents-core";
2
+ /** 取任务结果那一条工具的名字:任务通知的正文里要写出它,模型才知道去哪儿取 */
3
+ export declare const GET_MCP_TASK_RESULT_TOOL = "get_mcp_task_result";
4
+ /** 取消任务那一条工具的名字 */
5
+ export declare const CANCEL_MCP_TASK_TOOL = "cancel_mcp_task";
6
+ /** 任务的终态:到这三格才算结束,才有「结果可以取了」这回事 */
7
+ export type McpTaskTerminalStatus = "completed" | "failed" | "cancelled";
8
+ /** 判定终态;中间态(`working` / `input_required`)不是「有事要人动手」,不投递 */
9
+ export declare function isTerminalTaskStatus(status: string): status is McpTaskTerminalStatus;
10
+ /**
11
+ * 一条任务到了终态时要投进 inbox 的事实。
12
+ *
13
+ * 只有事实,没有一句话文案:这段文字会变成会话里的一条消息给人看,而语言与用户可见文案归宿主
14
+ * 那一层(它才知道界面那一侧该用什么语言说话)。
15
+ */
16
+ export interface McpTaskNotice {
17
+ /** 服务器名(配置里的那个 id) */
18
+ server: string;
19
+ /** 服务器给的任务 id */
20
+ taskId: string;
21
+ /** 终态 */
22
+ status: McpTaskTerminalStatus;
23
+ /** 服务器随状态给的一句说明(它没给就没有这一格) */
24
+ statusMessage?: string;
25
+ }
26
+ /**
27
+ * 任务状态通知的投递口。
28
+ *
29
+ * 服务器推来的状态是「一条通知」,它要落到的地方是发起那次调用的那段会话的 inbox。这条路上两头
30
+ * 都不在 SDK 手里:谁活着、往哪张表写、推给哪个客户端,只有宿主答得出来。所以这里只留一个形状,
31
+ * 由宿主实现,连接管理器只认这两个方法:
32
+ *
33
+ * - {@link McpTaskNoticePort.sessionOf}:发起调用的执行体属于哪一段会话;
34
+ * - {@link McpTaskNoticePort.deliver}:把一条终态通知投进那段会话。
35
+ *
36
+ * SDK 这一侧不记「谁活着」:任务 id 到会话 id 的对应关系留在连接管理器里(进程没了就没了,
37
+ * 任务本身在服务器那边),会话此刻在不在、该不该复活,一概问这个口。
38
+ */
39
+ export interface McpTaskNoticePort {
40
+ /**
41
+ * 这个执行体属于哪一段会话;不属于任何一段(被派出去的 subagent、一次性执行体)时是
42
+ * `undefined` —— 那种调用发起的任务没有会话可以回报。
43
+ */
44
+ sessionOf(agent: Agent): string | undefined;
45
+ /**
46
+ * 把一条终态通知投进那段会话的 inbox。
47
+ *
48
+ * 返回 `false` 表示那段会话已经不在(没有执行体),这条通知被丢掉了 —— 投递不创建、也不复活
49
+ * 会话,丢不丢、记不记日志都由实现那一侧决定,调用方拿到 `false` 只是不再往下做。
50
+ */
51
+ deliver(sessionId: string, notice: McpTaskNotice): Promise<boolean>;
52
+ }
@@ -0,0 +1,8 @@
1
+ /** 取任务结果那一条工具的名字:任务通知的正文里要写出它,模型才知道去哪儿取 */
2
+ export const GET_MCP_TASK_RESULT_TOOL = "get_mcp_task_result";
3
+ /** 取消任务那一条工具的名字 */
4
+ export const CANCEL_MCP_TASK_TOOL = "cancel_mcp_task";
5
+ /** 判定终态;中间态(`working` / `input_required`)不是「有事要人动手」,不投递 */
6
+ export function isTerminalTaskStatus(status) {
7
+ return status === "completed" || status === "failed" || status === "cancelled";
8
+ }
@@ -1,19 +1,23 @@
1
1
  import { CallbackTool } from "@ai-zen/agents-core";
2
+ import { type LogSink } from "../../../shared/logger.js";
2
3
  import type { McpConnectionManager } from "./McpConnectionManager.js";
3
4
  import type { McpServerConfig, ToolEnv } from "../../../types/index.js";
4
5
  /**
5
6
  * 创建 load_mcp 工具。
6
7
  * server 枚举由 filteredMcps (完整 McpServerConfig[])自动推导,
7
8
  * 查找配置也直接使用 filteredMcps,与枚举来源一致。
9
+ *
10
+ * @param logger 日志口(可选):报「连上了、清单多大」那两句走它;不注入就不记(库缺省沉默)
8
11
  */
9
- export declare function createLoadMcpTool(mcpManager: McpConnectionManager, filteredMcps: McpServerConfig[]): CallbackTool;
12
+ export declare function createLoadMcpTool(mcpManager: McpConnectionManager, filteredMcps: McpServerConfig[], logger?: LogSink): CallbackTool;
10
13
  /**
11
14
  * 创建 call_mcp_tool 工具。
12
15
  * 通过官方 Client.callTool() API 调用 MCP 服务器上的工具。
13
16
  *
14
17
  * 返回形态:
15
18
  * - 仅文本 → 纯字符串;
16
- * - 含媒体 → 内容块数组:首块为受保护的文本,其后原样透传 image / file 块。
19
+ * - 含媒体 → 内容块数组,按 MCP content 的原始顺序(文本块可能夹在中间);
20
+ * - 任务是任务时 → 一段带任务 id 的 JSON,结果不在这条路上回来(见 {@link taskHandleText})。
17
21
  *
18
22
  * env 仅用于读取 maxToolOutput(文本输出保护上限),与内置工具口径一致。
19
23
  */
@@ -22,3 +26,17 @@ export declare function createCallMcpTool(mcpManager: McpConnectionManager, env:
22
26
  * 创建 read_mcp_resource 工具。
23
27
  */
24
28
  export declare function createReadMcpResourceTool(mcpManager: McpConnectionManager, env: ToolEnv, filteredMcps: string[]): CallbackTool;
29
+ /**
30
+ * 创建 get_mcp_task_result 工具:按任务 id 去服务器取回结果。
31
+ *
32
+ * 结果原样交给模型:服务器存下来的就是一次工具调用的结果,与 `call_mcp_tool` 走同一套媒体映射
33
+ * 与输出保护(见 {@link callResultToContent})。
34
+ */
35
+ export declare function createGetMcpTaskResultTool(mcpManager: McpConnectionManager, env: ToolEnv, filteredMcps: string[]): CallbackTool;
36
+ /**
37
+ * 创建 cancel_mcp_task 工具:让服务器停掉一个已经发起的任务。
38
+ *
39
+ * 回给模型的是任务此刻那一格(`tasks/cancel` 的应答就是这个形状)。终态通知照旧会来:
40
+ * 取消也是终态,到了就把那条状态搁进 inbox。
41
+ */
42
+ export declare function createCancelMcpTaskTool(mcpManager: McpConnectionManager, filteredMcps: string[]): CallbackTool;
@@ -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 { getLogger } from "../../../shared/logger.js";
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
- getLogger().info(`[load_mcp] ${serverName}: connected (manifest not disclosed: ${manifest.tools.length} tools, ${manifest.resources.length} resources)`);
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
- getLogger().info(`[load_mcp] ${serverName}:\n${JSON.stringify(manifest, null, 2)}`);
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
- * - 含媒体 → 内容块数组:首块为受保护的文本,其后原样透传 image / file 块。
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. 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.",
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 result = await client.callTool({
281
- name: input.tool,
282
- arguments: input.arguments,
283
- }, undefined, { signal: ctx?.signal });
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
- // 按当前模型定位端点:决定媒体走 Files API 上传还是 base64 内联
298
- const { model, endpoint } = resolveModelAndEndpoint(env.config, ctx?.agent?.model);
299
- const mediaContext = {
300
- endpoint,
301
- model,
366
+ // 任务增强:这条流的第一条就是句柄(`taskCreated`),拿到它就返回 —— 不等任务跑完,
367
+ // 结果也不从这条路上回来
368
+ const stream = client.experimental.tasks.callToolStream(callArgs, undefined, {
369
+ task: {},
302
370
  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);
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
+ }
@@ -4,23 +4,20 @@ import type { Scope, FilterOutput } from "../../Scope.js";
4
4
  import type { ScopeCandidates, ScopePlugin } from "../../ScopePlugin.js";
5
5
  /**
6
6
  * 平级会话插件 —— 把宿主给的端口装成三个工具(`create_session` / `read_session_status` /
7
- * `send_to_session`)。
7
+ * `post_message`)。
8
8
  *
9
9
  * 与 `SubAgentsScopePlugin` 同构(`id` / `candidates` / `instantiate`):自己不发现任何东西
10
10
  * (平级会话不是磁盘上的定义,是宿主的运行时能力),候选名是固定的三个。
11
11
  *
12
- * **不给端口就什么都不产出**:`candidates()` 回空、`instantiate()` 回空数组 —— 没有宿主接线
13
- * 的 SDK 用户(CLI 脚本、用例、只有 Scope 的库使用者)看到的能力面一个字都不变。
14
- *
15
- * 为什么能力从端口进来而不是 SDK 自己实现:会话是宿主的财产(id、落库、模型解析、跑一轮、
16
- * 把结果投回去全在那边),SDK 这一层只认识 Scope 与 Agent 定义。端口是唯一的一处接线,
12
+ * 为什么能力从端口进来而不是 SDK 自己实现:会话是宿主的财产(id、落库、模型解析、投递、
13
+ * 现读那一格全在那边),SDK 这一层只认识 Scope 与 Agent 定义。端口是唯一的一处接线,
17
14
  * 于是「SDK 不依赖 host」这条分层不用破例。
18
15
  */
19
16
  export declare class PeerSessionsScopePlugin implements ScopePlugin {
20
17
  static readonly ID = "peer-sessions";
21
18
  readonly id = "peer-sessions";
22
19
  private readonly port?;
23
- /** 不传端口 = 这个 Scope 没有平级会话能力(老行为) */
20
+ /** 不传端口 = 这个 Scope 没有平级会话能力 */
24
21
  constructor(port?: PeerSessionPort);
25
22
  candidates(): ScopeCandidates;
26
23
  instantiate(_scope: Scope, filtered: FilterOutput): Tool[];
@@ -1,23 +1,20 @@
1
1
  import { createPeerSessionTools, PEER_SESSION_TOOL_NAMES } from "./peerSessionTools.js";
2
2
  /**
3
3
  * 平级会话插件 —— 把宿主给的端口装成三个工具(`create_session` / `read_session_status` /
4
- * `send_to_session`)。
4
+ * `post_message`)。
5
5
  *
6
6
  * 与 `SubAgentsScopePlugin` 同构(`id` / `candidates` / `instantiate`):自己不发现任何东西
7
7
  * (平级会话不是磁盘上的定义,是宿主的运行时能力),候选名是固定的三个。
8
8
  *
9
- * **不给端口就什么都不产出**:`candidates()` 回空、`instantiate()` 回空数组 —— 没有宿主接线
10
- * 的 SDK 用户(CLI 脚本、用例、只有 Scope 的库使用者)看到的能力面一个字都不变。
11
- *
12
- * 为什么能力从端口进来而不是 SDK 自己实现:会话是宿主的财产(id、落库、模型解析、跑一轮、
13
- * 把结果投回去全在那边),SDK 这一层只认识 Scope 与 Agent 定义。端口是唯一的一处接线,
9
+ * 为什么能力从端口进来而不是 SDK 自己实现:会话是宿主的财产(id、落库、模型解析、投递、
10
+ * 现读那一格全在那边),SDK 这一层只认识 Scope 与 Agent 定义。端口是唯一的一处接线,
14
11
  * 于是「SDK 不依赖 host」这条分层不用破例。
15
12
  */
16
13
  export class PeerSessionsScopePlugin {
17
14
  static ID = "peer-sessions";
18
15
  id = PeerSessionsScopePlugin.ID;
19
16
  port;
20
- /** 不传端口 = 这个 Scope 没有平级会话能力(老行为) */
17
+ /** 不传端口 = 这个 Scope 没有平级会话能力 */
21
18
  constructor(port) {
22
19
  this.port = port;
23
20
  }