@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
@@ -13,9 +13,7 @@ function isLocalUrl(value) {
13
13
  return !!m && /^(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)$/i.test(m[1]);
14
14
  }
15
15
  /**
16
- * 查看图片工具 — 让 Agent 主动查看/分析一张图片。**仅对视觉模型可用**:
17
- * 由 `isAvailable(config, definition)` 声明(从 definition.modelId 解析模型,检查 Model.vision),
18
- * buildTools 阶段按声明过滤——非视觉模型不会拿到该工具,故无需运行时重复校验。
16
+ * 查看图片工具 — 让 Agent 主动查看/分析一张图片。
19
17
  *
20
18
  * 输入 `path_or_url`:
21
19
  * - http(s) URL → 直接以 `image_url` 内容块返回;
@@ -27,7 +25,7 @@ function isLocalUrl(value) {
27
25
  * 资源,传错端点会返回 not found。
28
26
  */
29
27
  export class ViewImageTool extends SdkCallbackTool {
30
- /** 仅视觉模型可用:从 definition.modelId 解析当前模型,非视觉模型由 buildTools 过滤 */
28
+ /** 仅视觉模型可用:从 definition.modelId 解析当前模型,非视觉模型不进候选集 */
31
29
  isAvailable(config, definition) {
32
30
  const modelId = definition.modelId;
33
31
  const model = (config.models ?? []).find((m) => m.id === modelId);
@@ -97,14 +95,14 @@ export class ViewImageTool extends SdkCallbackTool {
97
95
  : result.transport === "inline"
98
96
  ? `, inlined as base64 (${(result.bytes / 1024).toFixed(0)} KB)`
99
97
  : "";
100
- const extra = result.warning ? ` (fallback: ${result.warning})` : "";
101
- return [{ type: "text", text: `${label}${how}${extra}` }, result.section];
98
+ return [{ type: "text", text: `${label}${how}` }, result.section];
102
99
  }
103
100
  catch (error) {
104
101
  // 中断(abort)时返回明确的中断结果
105
102
  if (signal?.aborted) {
106
103
  return "Image view aborted";
107
104
  }
105
+ // 上传失败等一律走这里:这一次没成,原因原样交给模型(不降级成内联 base64)
108
106
  return `Failed to view image: ${error instanceof Error ? error.message : String(error)}`;
109
107
  }
110
108
  }
@@ -1,6 +1,13 @@
1
1
  import { SdkCallbackTool } from "./SdkCallbackTool.js";
2
2
  import type { ToolEnv } from "../../../types/index.js";
3
3
  import type { AgentNS } from "@ai-zen/agents-core";
4
+ /**
5
+ * `write` 这个工具名只在这里命名一次。
6
+ *
7
+ * 别处(交接守卫的门、「这一段有没有 write 工具」的判据)都引它 —— 一个工具名散成四处
8
+ * 字面量,改一处漏三处的时候不会报错,只会默默失效。
9
+ */
10
+ export declare const WRITE_TOOL_NAME = "write";
4
11
  export declare class WriteTool extends SdkCallbackTool {
5
12
  function: AgentNS.FunctionDefine;
6
13
  constructor(env: ToolEnv);
@@ -1,9 +1,16 @@
1
1
  import * as fsp from "fs/promises";
2
2
  import * as path from "path";
3
3
  import { SdkCallbackTool } from "./SdkCallbackTool.js";
4
+ /**
5
+ * `write` 这个工具名只在这里命名一次。
6
+ *
7
+ * 别处(交接守卫的门、「这一段有没有 write 工具」的判据)都引它 —— 一个工具名散成四处
8
+ * 字面量,改一处漏三处的时候不会报错,只会默默失效。
9
+ */
10
+ export const WRITE_TOOL_NAME = "write";
4
11
  export class WriteTool extends SdkCallbackTool {
5
12
  function = {
6
- name: "write",
13
+ name: WRITE_TOOL_NAME,
7
14
  description: "Write a file",
8
15
  parameters: {
9
16
  type: "object",
@@ -0,0 +1,41 @@
1
+ import type { Agent } from "@ai-zen/agents-core";
2
+ import { type LogSink } from "../../../shared/logger.js";
3
+ /** `async_exec`:起一条命令就跑,结果推回发起它的会话 */
4
+ export declare const ASYNC_EXEC_TOOL = "async_exec";
5
+ /** `async_timeout`:定时器,到点推一条回发起它的会话 */
6
+ export declare const ASYNC_TIMEOUT_TOOL = "async_timeout";
7
+ /**
8
+ * 两个后台工具的名字。
9
+ *
10
+ * 组装执行体时按这份名单把它们从一次性执行体手上摘掉:它们的结果在将来某个时刻才回来,
11
+ * 那时一次性执行体的调用栈已经退了,没有收件人。
12
+ */
13
+ export declare const ASYNC_TASK_TOOL_NAMES: readonly ["async_exec", "async_timeout"];
14
+ /**
15
+ * 下一个任务 id。
16
+ *
17
+ * 序号按执行体递增,两个工具共用一个序号、靠前缀区分是谁,于是同一个执行体上开过的任务
18
+ * id 不会撞;结果推回来时,模型与人都能按它对上「这是哪一次」。
19
+ */
20
+ export declare function nextTaskId(agent: Agent, kind: string): string;
21
+ /** 登记一条还没结束的后台命令;交回来的函数在它自己结束时摘掉这一项 */
22
+ export declare function trackCommand(agent: Agent, run: {
23
+ kill(): void;
24
+ }, log?: LogSink): () => void;
25
+ /** 登记一个还没到点的定时器;交回来的函数在它到点(或被清掉)之后摘掉这一项 */
26
+ export declare function trackTimer(agent: Agent, timer: NodeJS.Timeout, log?: LogSink): () => void;
27
+ /**
28
+ * 把一次后台任务的结果投回发起它的那段会话 —— 只有这一个动作。
29
+ *
30
+ * 投递不创建、也不复活会话:那段会话已经没有执行体、或者队列已经关门时,`push` 抛错,
31
+ * 这条结果就此丢掉并记一行日志。不抛给谁、不重试、不留下来等。
32
+ *
33
+ * 优先级取低:结果不该插进那段会话手上那一批的工具调用之间,它排在队尾,那一批跑完就取到。
34
+ */
35
+ export declare function deliverAsyncResult(input: {
36
+ agent: Agent;
37
+ /** 来源标签,同时是工具名 */
38
+ label: string;
39
+ content: string;
40
+ log?: LogSink;
41
+ }): void;
@@ -0,0 +1,97 @@
1
+ import { SILENT_LOG } from "../../../shared/logger.js";
2
+ /** `async_exec`:起一条命令就跑,结果推回发起它的会话 */
3
+ export const ASYNC_EXEC_TOOL = "async_exec";
4
+ /** `async_timeout`:定时器,到点推一条回发起它的会话 */
5
+ export const ASYNC_TIMEOUT_TOOL = "async_timeout";
6
+ /**
7
+ * 两个后台工具的名字。
8
+ *
9
+ * 组装执行体时按这份名单把它们从一次性执行体手上摘掉:它们的结果在将来某个时刻才回来,
10
+ * 那时一次性执行体的调用栈已经退了,没有收件人。
11
+ */
12
+ export const ASYNC_TASK_TOOL_NAMES = [ASYNC_EXEC_TOOL, ASYNC_TIMEOUT_TOOL];
13
+ const registry = new WeakMap();
14
+ function tasksOf(agent) {
15
+ let tasks = registry.get(agent);
16
+ if (tasks === undefined) {
17
+ tasks = { commands: new Set(), timers: new Set(), supervised: false, count: 0 };
18
+ registry.set(agent, tasks);
19
+ }
20
+ return tasks;
21
+ }
22
+ /**
23
+ * 挂上「要没了」那一拍:执行体关门或被杀时,把名下还没结束的后台命令与定时器一起收掉。
24
+ *
25
+ * 挂在 `onStop` / `onKill` 上而不是由工具自己等:工具调用当场就返回了,此后手上没有第二个
26
+ * 时机知道这个执行体已经被收掉。两个钩子在 core 里先于「已经死了」那一步跑,所以这一刻
27
+ * 队列已经关门(推回来的结果会在投递那一步被丢掉并记一行日志)。
28
+ *
29
+ * 一个执行体只挂一次:同一段会话上先后开的多个后台任务共用这一份清点。
30
+ */
31
+ function supervise(agent, log) {
32
+ const tasks = tasksOf(agent);
33
+ if (tasks.supervised)
34
+ return tasks;
35
+ tasks.supervised = true;
36
+ const reap = (how) => {
37
+ const commands = [...tasks.commands];
38
+ const timers = [...tasks.timers];
39
+ tasks.commands.clear();
40
+ tasks.timers.clear();
41
+ for (const command of commands)
42
+ command.kill();
43
+ for (const timer of timers)
44
+ clearTimeout(timer);
45
+ if (commands.length > 0 || timers.length > 0) {
46
+ log.info(`[async] agent ${agent.id} ${how}: ${commands.length} command(s) killed, ` +
47
+ `${timers.length} timer(s) cleared`);
48
+ }
49
+ };
50
+ const plugin = {
51
+ onStop: () => reap("stopped"),
52
+ onKill: () => reap("killed"),
53
+ };
54
+ agent.use(plugin);
55
+ return tasks;
56
+ }
57
+ /**
58
+ * 下一个任务 id。
59
+ *
60
+ * 序号按执行体递增,两个工具共用一个序号、靠前缀区分是谁,于是同一个执行体上开过的任务
61
+ * id 不会撞;结果推回来时,模型与人都能按它对上「这是哪一次」。
62
+ */
63
+ export function nextTaskId(agent, kind) {
64
+ const tasks = tasksOf(agent);
65
+ tasks.count += 1;
66
+ return `${kind}-${tasks.count}`;
67
+ }
68
+ /** 登记一条还没结束的后台命令;交回来的函数在它自己结束时摘掉这一项 */
69
+ export function trackCommand(agent, run, log) {
70
+ const tasks = supervise(agent, log ?? SILENT_LOG);
71
+ tasks.commands.add(run);
72
+ return () => tasks.commands.delete(run);
73
+ }
74
+ /** 登记一个还没到点的定时器;交回来的函数在它到点(或被清掉)之后摘掉这一项 */
75
+ export function trackTimer(agent, timer, log) {
76
+ const tasks = supervise(agent, log ?? SILENT_LOG);
77
+ tasks.timers.add(timer);
78
+ return () => tasks.timers.delete(timer);
79
+ }
80
+ /**
81
+ * 把一次后台任务的结果投回发起它的那段会话 —— 只有这一个动作。
82
+ *
83
+ * 投递不创建、也不复活会话:那段会话已经没有执行体、或者队列已经关门时,`push` 抛错,
84
+ * 这条结果就此丢掉并记一行日志。不抛给谁、不重试、不留下来等。
85
+ *
86
+ * 优先级取低:结果不该插进那段会话手上那一批的工具调用之间,它排在队尾,那一批跑完就取到。
87
+ */
88
+ export function deliverAsyncResult(input) {
89
+ const { agent, label, content } = input;
90
+ const log = input.log ?? SILENT_LOG;
91
+ try {
92
+ agent.push({ content, priority: "low", source: { kind: "system", label } });
93
+ }
94
+ catch (error) {
95
+ log.warn(`[${label}] result could not be delivered to agent ${agent.id}; dropped`, { error });
96
+ }
97
+ }
@@ -0,0 +1,22 @@
1
+ import { type CommandResult } from "./commandRun.js";
2
+ /**
3
+ * 一条命令的结果交给模型的那段正文 —— `exec` 与后台版共用这一份。
4
+ *
5
+ * 两件事只有这里做:
6
+ *
7
+ * - 输出保护:stdout + stderr 合计超过上限时,全文分文件落盘,正文换成「警告 + 头尾预览 +
8
+ * 统计 + 缩小范围的办法」;
9
+ * - 截断说明:输出撞到内存上限时,正文里必须说清尾部已经丢了,不能看起来像完整结果。
10
+ *
11
+ * `fields` 是调用方要一起带出去的字段(后台版用它写明这是哪一次任务),它们与结果同层,
12
+ * 落盘那一支也一并带上。
13
+ */
14
+ export declare function commandOutputContent(options: {
15
+ /** 工具名,落盘目录按它命名 */
16
+ tool: string;
17
+ /** 正文里额外带的字段 */
18
+ fields?: Record<string, unknown>;
19
+ result: CommandResult;
20
+ /** 正文的字符上限(stdout + stderr 合计) */
21
+ limit: number;
22
+ }): Promise<string>;
@@ -0,0 +1,55 @@
1
+ import { guardOutput, headTailPreview } from "./outputGuard.js";
2
+ import { MAX_BUFFER } from "./commandRun.js";
3
+ /**
4
+ * 一条命令的结果交给模型的那段正文 —— `exec` 与后台版共用这一份。
5
+ *
6
+ * 两件事只有这里做:
7
+ *
8
+ * - 输出保护:stdout + stderr 合计超过上限时,全文分文件落盘,正文换成「警告 + 头尾预览 +
9
+ * 统计 + 缩小范围的办法」;
10
+ * - 截断说明:输出撞到内存上限时,正文里必须说清尾部已经丢了,不能看起来像完整结果。
11
+ *
12
+ * `fields` 是调用方要一起带出去的字段(后台版用它写明这是哪一次任务),它们与结果同层,
13
+ * 落盘那一支也一并带上。
14
+ */
15
+ export async function commandOutputContent(options) {
16
+ const { tool, fields = {}, result, limit } = options;
17
+ const truncationNote = result.truncated
18
+ ? `Output exceeded the ${MAX_BUFFER}-byte in-memory cap: the process was terminated and the output was truncated there, so the tail is lost.`
19
+ : undefined;
20
+ const content = { ...fields, ...result };
21
+ const guarded = await guardOutput({
22
+ tool,
23
+ content,
24
+ isOverLimit: (output) => output.stdout.length + output.stderr.length > limit,
25
+ dump: (_dir, output) => [
26
+ { name: "stdout.log", content: output.stdout },
27
+ { name: "stderr.log", content: output.stderr },
28
+ ],
29
+ buildWarning: (ctx) => {
30
+ const stdout = headTailPreview(result.stdout);
31
+ const stderr = headTailPreview(result.stderr);
32
+ return JSON.stringify({
33
+ ...fields,
34
+ outputTooLarge: true,
35
+ warning: `Output too large: stdout + stderr total ${result.stdout.length + result.stderr.length} characters, ` +
36
+ `exceeds the limit of ${limit} characters. The output as captured is available in separate files (stdout.log / stderr.log); use read to fetch it in chunks`,
37
+ ...(truncationNote ? { truncated: true, truncationNote } : {}),
38
+ files: ctx.files,
39
+ stdout: { chars: result.stdout.length, lines: countLines(result.stdout), ...stdout },
40
+ stderr: { chars: result.stderr.length, lines: countLines(result.stderr), ...stderr },
41
+ exitCode: result.exitCode,
42
+ killed: result.killed,
43
+ terminated: result.terminated,
44
+ });
45
+ },
46
+ });
47
+ // 未超限:content 为原始结果对象,按原有结构序列化;超限:buildWarning 已生成返回字符串
48
+ if (typeof guarded === "string")
49
+ return guarded;
50
+ return JSON.stringify(result.truncated ? { ...guarded, truncated: true, truncationNote } : guarded);
51
+ }
52
+ /** 统计文本行数(空文本记 0 行) */
53
+ function countLines(text) {
54
+ return text.length === 0 ? 0 : text.split("\n").length;
55
+ }
@@ -0,0 +1,48 @@
1
+ import { type ChildProcess } from "node:child_process";
2
+ /**
3
+ * stdout + stderr 的内存上限(字节,两流合计)。
4
+ *
5
+ * 超限就杀掉整个进程组并把已到的输出截在那里,结果里带 `truncated`(尾部内容已丢失)。
6
+ */
7
+ export declare const MAX_BUFFER: number;
8
+ /** 一条命令的收场:输出、退出状态、因何终止 */
9
+ export interface CommandResult {
10
+ stdout: string;
11
+ stderr: string;
12
+ exitCode: number | null;
13
+ killed: boolean;
14
+ terminated?: "timeout" | "aborted";
15
+ /** 输出达到 MAX_BUFFER 被截断(尾部丢失,进程因此被终止) */
16
+ truncated?: boolean;
17
+ }
18
+ /** 起好的一条命令:结果另走一句 promise,回收自己拿 `kill()` */
19
+ export interface CommandRun {
20
+ /** 子进程;`signal` 传入时已经 aborted 的话不起进程,这里为 `undefined` */
21
+ readonly child: ChildProcess | undefined;
22
+ /** 按进程组回收这条命令 */
23
+ kill(): void;
24
+ /** 结果,不会 reject */
25
+ readonly result: Promise<CommandResult>;
26
+ }
27
+ export interface RunCommandOptions {
28
+ command: string;
29
+ cwd: string;
30
+ /** 超时(毫秒);不给就一直跑到进程自己结束 */
31
+ timeoutMs?: number;
32
+ signal?: AbortSignal;
33
+ }
34
+ /**
35
+ * 起一条命令,收回它的输出与退出状态。
36
+ *
37
+ * 三处写法与 `spawn` 的裸调用不同,各有原因:
38
+ *
39
+ * - `detached: true` 让子进程成为新进程组的组长,于是 `-pid` 就是「该组所有进程」。只杀 shell
40
+ * 会把后代留成孤儿(`cmd | cat`、`sh -c 'sleep 100 &'` 都会漏)。Windows 不支持负 pid,
41
+ * 那边回退为只杀子进程。
42
+ * - 输出攒在两个缓冲区里并合计计数,到 {@link MAX_BUFFER} 就停手并杀掉进程组 —— 再攒也存不下。
43
+ * - 收尾不只听 `close`:子进程已退出而 stdio 仍被后代占着时,攒完已到达的输出就收尾,
44
+ * 否则要等那些后代自己退出。
45
+ *
46
+ * `child_process.exec()` 会忽略 `detached`(实测 Node 26),所以这里用 `spawn`。
47
+ */
48
+ export declare function runCommand(options: RunCommandOptions): CommandRun;
@@ -0,0 +1,169 @@
1
+ import { spawn } from "node:child_process";
2
+ /**
3
+ * stdout + stderr 的内存上限(字节,两流合计)。
4
+ *
5
+ * 超限就杀掉整个进程组并把已到的输出截在那里,结果里带 `truncated`(尾部内容已丢失)。
6
+ */
7
+ export const MAX_BUFFER = 16 * 1024 * 1024;
8
+ /** 进程组 SIGKILL 之后等待回调的兜底时长:万一管道被孤儿进程占住,也不至于永久挂起 */
9
+ const KILL_GRACE_MS = 2000;
10
+ /** 子进程已退出、但 stdio 仍被后代占住时,攒完已到达的输出就收尾 */
11
+ const STDIO_DRAIN_MS = 200;
12
+ /**
13
+ * 起一条命令,收回它的输出与退出状态。
14
+ *
15
+ * 三处写法与 `spawn` 的裸调用不同,各有原因:
16
+ *
17
+ * - `detached: true` 让子进程成为新进程组的组长,于是 `-pid` 就是「该组所有进程」。只杀 shell
18
+ * 会把后代留成孤儿(`cmd | cat`、`sh -c 'sleep 100 &'` 都会漏)。Windows 不支持负 pid,
19
+ * 那边回退为只杀子进程。
20
+ * - 输出攒在两个缓冲区里并合计计数,到 {@link MAX_BUFFER} 就停手并杀掉进程组 —— 再攒也存不下。
21
+ * - 收尾不只听 `close`:子进程已退出而 stdio 仍被后代占着时,攒完已到达的输出就收尾,
22
+ * 否则要等那些后代自己退出。
23
+ *
24
+ * `child_process.exec()` 会忽略 `detached`(实测 Node 26),所以这里用 `spawn`。
25
+ */
26
+ export function runCommand(options) {
27
+ const { command, cwd, timeoutMs, signal } = options;
28
+ let child;
29
+ let settled = false;
30
+ let terminated;
31
+ let truncated = false;
32
+ let bytes = 0;
33
+ const out = [];
34
+ const err = [];
35
+ let timeoutTimer;
36
+ let graceTimer;
37
+ let drainTimer;
38
+ let exitCode = null;
39
+ let exitSignal = null;
40
+ let exited = false;
41
+ let resolveResult = () => undefined;
42
+ const result = new Promise((resolve) => {
43
+ resolveResult = resolve;
44
+ });
45
+ const settle = (value) => {
46
+ if (settled)
47
+ return;
48
+ settled = true;
49
+ if (timeoutTimer)
50
+ clearTimeout(timeoutTimer);
51
+ if (graceTimer)
52
+ clearTimeout(graceTimer);
53
+ if (drainTimer)
54
+ clearTimeout(drainTimer);
55
+ signal?.removeEventListener("abort", onAbort);
56
+ resolveResult(value);
57
+ };
58
+ /** 用已收集到的输出收尾(子进程已退出或被杀) */
59
+ const settleFromCollected = (forced) => {
60
+ settle({
61
+ stdout: Buffer.concat(out).toString(),
62
+ stderr: Buffer.concat(err).toString(),
63
+ exitCode,
64
+ killed: terminated !== undefined || exitSignal !== null,
65
+ terminated: terminated ?? forced,
66
+ truncated: truncated || undefined,
67
+ });
68
+ };
69
+ /** 杀整个进程组(不是只杀 shell,理由见 {@link runCommand}) */
70
+ function killProcessGroup() {
71
+ if (!child?.pid)
72
+ return;
73
+ if (process.platform === "win32") {
74
+ child.kill("SIGKILL");
75
+ return;
76
+ }
77
+ try {
78
+ process.kill(-child.pid, "SIGKILL");
79
+ }
80
+ catch {
81
+ child.kill("SIGKILL");
82
+ }
83
+ }
84
+ // 声明成函数而不是常量:`settle` 要摘掉它,而最前面那条「已经 aborted」的收场也走 `settle`
85
+ function onAbort() {
86
+ terminated = "aborted";
87
+ killProcessGroup();
88
+ settle({
89
+ stdout: "",
90
+ stderr: "Process aborted",
91
+ exitCode: null,
92
+ killed: true,
93
+ terminated: "aborted",
94
+ });
95
+ }
96
+ if (signal?.aborted) {
97
+ settle({
98
+ stdout: "",
99
+ stderr: "Process aborted",
100
+ exitCode: null,
101
+ killed: true,
102
+ terminated: "aborted",
103
+ });
104
+ return { child: undefined, kill: killProcessGroup, result };
105
+ }
106
+ child = spawn(command, {
107
+ cwd,
108
+ shell: true,
109
+ detached: process.platform !== "win32",
110
+ stdio: ["ignore", "pipe", "pipe"],
111
+ // 输出走管道,不需要也不该给用户弹一个终端窗口。这一条尤其要紧 —— 服务端自己是
112
+ // detached 起的、没有控制台,不 hide 的话每次调用都会新分配一个控制台窗口。
113
+ windowsHide: true,
114
+ });
115
+ const collect = (target) => (chunk) => {
116
+ if (truncated)
117
+ return;
118
+ bytes += chunk.length;
119
+ target.push(chunk);
120
+ if (bytes > MAX_BUFFER) {
121
+ truncated = true;
122
+ killProcessGroup();
123
+ }
124
+ };
125
+ child.stdout?.on("data", collect(out));
126
+ child.stderr?.on("data", collect(err));
127
+ child.on("error", (e) => {
128
+ settle({
129
+ stdout: "",
130
+ stderr: e.message,
131
+ exitCode: null,
132
+ killed: false,
133
+ terminated,
134
+ });
135
+ });
136
+ child.on("exit", (code, sig) => {
137
+ exited = true;
138
+ exitCode = code;
139
+ exitSignal = sig;
140
+ // 已退出但 stdio 可能还被后代占着(如 `cmd &`):只等一小会儿就收尾
141
+ drainTimer = setTimeout(() => settleFromCollected(), STDIO_DRAIN_MS);
142
+ });
143
+ child.on("close", (code, sig) => {
144
+ if (!exited) {
145
+ exitCode = code;
146
+ exitSignal = sig;
147
+ }
148
+ settleFromCollected();
149
+ });
150
+ // 中断:整组回收,并立即返回(不等回调,避免挂起)
151
+ signal?.addEventListener("abort", onAbort, { once: true });
152
+ // 超时:整组回收后优先等回调,好把已收集到的输出带回去
153
+ if (timeoutMs !== undefined) {
154
+ timeoutTimer = setTimeout(() => {
155
+ terminated = "timeout";
156
+ killProcessGroup();
157
+ graceTimer = setTimeout(() => {
158
+ settle({
159
+ stdout: Buffer.concat(out).toString(),
160
+ stderr: Buffer.concat(err).toString(),
161
+ exitCode: null,
162
+ killed: true,
163
+ terminated: "timeout",
164
+ });
165
+ }, KILL_GRACE_MS);
166
+ }, timeoutMs);
167
+ }
168
+ return { child, kill: killProcessGroup, result };
169
+ }
@@ -2,8 +2,6 @@ import type { Tool } from "@ai-zen/agents-core";
2
2
  import type { ToolEnv } from "../../../types/index.js";
3
3
  /**
4
4
  * 发现内置工具:按静态注册表实例化全部内置工具(无任何过滤)。
5
- *
6
- * 工具的可用性由各工具自行声明(SdkCallbackTool.isAvailable,入参含完整 config
7
- * + 模型信息),在 buildTools/filter 阶段(模型已知)按声明过滤。
5
+ * 可用性判断落在 `BuiltinToolsScopePlugin.candidates()`,不在这一层。
8
6
  */
9
7
  export declare function discoverBuiltinTools(env: ToolEnv): Tool[];
@@ -1,9 +1,7 @@
1
1
  import { BUILTIN_TOOL_CLASSES } from "./index.js";
2
2
  /**
3
3
  * 发现内置工具:按静态注册表实例化全部内置工具(无任何过滤)。
4
- *
5
- * 工具的可用性由各工具自行声明(SdkCallbackTool.isAvailable,入参含完整 config
6
- * + 模型信息),在 buildTools/filter 阶段(模型已知)按声明过滤。
4
+ * 可用性判断落在 `BuiltinToolsScopePlugin.candidates()`,不在这一层。
7
5
  */
8
6
  export function discoverBuiltinTools(env) {
9
7
  return BUILTIN_TOOL_CLASSES.map((Cls) => new Cls(env));
@@ -18,15 +18,13 @@ import { BatchEditTool } from "./BatchEditTool.js";
18
18
  import { EditTool } from "./EditTool.js";
19
19
  import { SpawnTool } from "./SpawnTool.js";
20
20
  import { SleepTool } from "./SleepTool.js";
21
+ import { AsyncExecTool } from "./AsyncExecTool.js";
22
+ import { AsyncTimeoutTool } from "./AsyncTimeoutTool.js";
21
23
  import { ViewImageTool } from "./ViewImageTool.js";
22
24
  import { GenerateImageTool } from "./GenerateImageTool.js";
23
25
  /**
24
- * 全部内置工具类(20 个)。
25
- * 工具类由 Scope 的内置工具插件(BuiltinToolsScopePlugin)用 ToolEnv 实例化(每个 Scope 一套实例,注入其 cwd)。
26
- *
27
- * 发现层不做任何过滤——工具的可用性由各工具自行声明(SdkCallbackTool.isAvailable,
28
- * 入参含完整 config + 模型信息),在 buildTools/filter 阶段按声明过滤。
29
- * 如 GenerateImageTool 依赖 defaultImageModel、ViewImageTool 仅视觉模型可用。
26
+ * 全部内置工具类(22 个)。
27
+ * 由 BuiltinToolsScopePlugin 用 ToolEnv 实例化(每个 Scope 一套实例,注入其 cwd)。
30
28
  */
31
29
  export declare const BUILTIN_TOOL_CLASSES: Array<new (env: ToolEnv) => SdkCallbackTool>;
32
- export { CwdTool, ReadTool, InspectFileTool, WriteTool, ExecTool, MkdirTool, RmTool, GlobTool, LsTool, ExistTool, FindTextTool, DownloadFileTool, RenameTool, CopyTool, BatchEditTool, EditTool, SpawnTool, SleepTool, ViewImageTool, GenerateImageTool, };
30
+ export { CwdTool, ReadTool, InspectFileTool, WriteTool, ExecTool, MkdirTool, RmTool, GlobTool, LsTool, ExistTool, FindTextTool, DownloadFileTool, RenameTool, CopyTool, BatchEditTool, EditTool, SpawnTool, SleepTool, AsyncExecTool, AsyncTimeoutTool, ViewImageTool, GenerateImageTool, };
@@ -16,15 +16,13 @@ import { BatchEditTool } from "./BatchEditTool.js";
16
16
  import { EditTool } from "./EditTool.js";
17
17
  import { SpawnTool } from "./SpawnTool.js";
18
18
  import { SleepTool } from "./SleepTool.js";
19
+ import { AsyncExecTool } from "./AsyncExecTool.js";
20
+ import { AsyncTimeoutTool } from "./AsyncTimeoutTool.js";
19
21
  import { ViewImageTool } from "./ViewImageTool.js";
20
22
  import { GenerateImageTool } from "./GenerateImageTool.js";
21
23
  /**
22
- * 全部内置工具类(20 个)。
23
- * 工具类由 Scope 的内置工具插件(BuiltinToolsScopePlugin)用 ToolEnv 实例化(每个 Scope 一套实例,注入其 cwd)。
24
- *
25
- * 发现层不做任何过滤——工具的可用性由各工具自行声明(SdkCallbackTool.isAvailable,
26
- * 入参含完整 config + 模型信息),在 buildTools/filter 阶段按声明过滤。
27
- * 如 GenerateImageTool 依赖 defaultImageModel、ViewImageTool 仅视觉模型可用。
24
+ * 全部内置工具类(22 个)。
25
+ * 由 BuiltinToolsScopePlugin 用 ToolEnv 实例化(每个 Scope 一套实例,注入其 cwd)。
28
26
  */
29
27
  export const BUILTIN_TOOL_CLASSES = [
30
28
  CwdTool,
@@ -45,7 +43,9 @@ export const BUILTIN_TOOL_CLASSES = [
45
43
  EditTool,
46
44
  SpawnTool,
47
45
  SleepTool,
46
+ AsyncExecTool,
47
+ AsyncTimeoutTool,
48
48
  ViewImageTool,
49
49
  GenerateImageTool,
50
50
  ];
51
- export { CwdTool, ReadTool, InspectFileTool, WriteTool, ExecTool, MkdirTool, RmTool, GlobTool, LsTool, ExistTool, FindTextTool, DownloadFileTool, RenameTool, CopyTool, BatchEditTool, EditTool, SpawnTool, SleepTool, ViewImageTool, GenerateImageTool, };
51
+ export { CwdTool, ReadTool, InspectFileTool, WriteTool, ExecTool, MkdirTool, RmTool, GlobTool, LsTool, ExistTool, FindTextTool, DownloadFileTool, RenameTool, CopyTool, BatchEditTool, EditTool, SpawnTool, SleepTool, AsyncExecTool, AsyncTimeoutTool, ViewImageTool, GenerateImageTool, };
@@ -38,11 +38,7 @@ export interface OutputGuardOptions<T> {
38
38
  /**
39
39
  * 标准输出保护骨架。
40
40
  *
41
- * 各工具在 call() 出口调用,只需提供三个回调:
42
- * 1) isOverLimit —— 是否超过上限(工具自读 config 判定,未被超限即原样返回 content);
43
- * 2) dump —— 超限时落盘哪些文件(可省略 = 只警告不落盘);
44
- * 3) buildWarning —— 超限时返回给模型的内容。
45
- *
41
+ * 各工具在 call() 出口调用,三个回调的含义见 {@link OutputGuardOptions}。
46
42
  * 骨架职责:判定 → 未超限原样返回 / 超限时创建独立目录并写文件 → 交给 buildWarning。
47
43
  *
48
44
  * 落盘目录:<os.tmpdir()>/ai-zen/tool-output/<tool>-<时间戳>-<随机串>/,
@@ -11,11 +11,7 @@ export const DEFAULT_MAX_TOOL_OUTPUT = 32_768;
11
11
  /**
12
12
  * 标准输出保护骨架。
13
13
  *
14
- * 各工具在 call() 出口调用,只需提供三个回调:
15
- * 1) isOverLimit —— 是否超过上限(工具自读 config 判定,未被超限即原样返回 content);
16
- * 2) dump —— 超限时落盘哪些文件(可省略 = 只警告不落盘);
17
- * 3) buildWarning —— 超限时返回给模型的内容。
18
- *
14
+ * 各工具在 call() 出口调用,三个回调的含义见 {@link OutputGuardOptions}。
19
15
  * 骨架职责:判定 → 未超限原样返回 / 超限时创建独立目录并写文件 → 交给 buildWarning。
20
16
  *
21
17
  * 落盘目录:<os.tmpdir()>/ai-zen/tool-output/<tool>-<时间戳>-<随机串>/,