@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,4 +1,5 @@
1
1
  import type { Tool } from "@ai-zen/agents-core";
2
+ import type { LogSink } from "../../../shared/logger.js";
2
3
  import type { Scope, FilterOutput } from "../../Scope.js";
3
4
  import type { ScopeCandidates, ScopePlugin } from "../../ScopePlugin.js";
4
5
  /**
@@ -17,8 +18,11 @@ export declare class SkillsScopePlugin implements ScopePlugin {
17
18
  private skills;
18
19
  /** 解析后的 skill 目录(供 instantiate 时传给工具读取正文) */
19
20
  private dirs;
21
+ /** 日志口(可选):合规校验没过时每条报一句;不注入就不记 */
22
+ private readonly logger?;
20
23
  constructor(options?: {
21
24
  paths?: string[];
25
+ logger?: LogSink;
22
26
  });
23
27
  discover(scope: Scope, options?: {
24
28
  silent?: boolean;
@@ -17,12 +17,18 @@ export class SkillsScopePlugin {
17
17
  skills = [];
18
18
  /** 解析后的 skill 目录(供 instantiate 时传给工具读取正文) */
19
19
  dirs = [];
20
+ /** 日志口(可选):合规校验没过时每条报一句;不注入就不记 */
21
+ logger;
20
22
  constructor(options) {
21
23
  this.paths = options?.paths ?? [];
24
+ this.logger = options?.logger;
22
25
  }
23
26
  async discover(scope, options) {
24
27
  this.dirs = this.paths.map((p) => (isAbsolute(p) ? p : join(scope.cwd, p)));
25
- this.skills = await discoverSkills(this.dirs, options);
28
+ this.skills = await discoverSkills(this.dirs, {
29
+ silent: options?.silent,
30
+ logger: this.logger,
31
+ });
26
32
  }
27
33
  candidates() {
28
34
  return {
@@ -36,11 +42,11 @@ export class SkillsScopePlugin {
36
42
  const filteredSkills = this.skills.filter((s) => allowedSkills.has(s.id));
37
43
  const result = [];
38
44
  if (allow.has("load_skill") && filteredSkills.length > 0) {
39
- result.push(createLoadSkillTool(this.dirs, filteredSkills));
45
+ result.push(createLoadSkillTool(this.dirs, filteredSkills, this.logger));
40
46
  }
41
- // call_skill_sub_agent:只要有支持子 Agent 的 skill 就注册
47
+ // call_skill_sub_agent:只要有支持 subagent 的 skill 就注册
42
48
  if (allow.has("call_skill_sub_agent") && filteredSkills.some((s) => s.subAgent)) {
43
- result.push(createCallSkillSubAgentTool(this.dirs, filteredSkills));
49
+ result.push(createCallSkillSubAgentTool(this.dirs, filteredSkills, this.logger));
44
50
  }
45
51
  return result;
46
52
  }
@@ -1,3 +1,4 @@
1
+ import { type LogSink } from "../../../shared/logger.js";
1
2
  export interface Frontmatter {
2
3
  name?: string;
3
4
  description?: string;
@@ -5,7 +6,7 @@ export interface Frontmatter {
5
6
  compatibility?: string;
6
7
  metadata?: Record<string, string>;
7
8
  allowedTools?: string[];
8
- /** @extension Claude Code 启发:声明此 Skill 可作为子 Agent 运行 */
9
+ /** @extension Claude Code 启发:声明此 Skill 可作为 subagent 运行 */
9
10
  subAgent?: boolean;
10
11
  }
11
12
  export interface SkillValidationError {
@@ -13,7 +14,10 @@ export interface SkillValidationError {
13
14
  field: string;
14
15
  message: string;
15
16
  }
16
- /** Skill 完整信息。id = 目录名 = SKILL.md 的 name 字段 */
17
+ /**
18
+ * Skill 完整信息。id = 目录名;`name` 取自 SKILL.md 的 frontmatter,
19
+ * 两者不一致时 `validateSkill()` 只报一条错误,不拦收录。
20
+ */
17
21
  export interface SkillInfo {
18
22
  id: string;
19
23
  name: string;
@@ -27,22 +31,25 @@ export interface SkillInfo {
27
31
  metadata?: Record<string, string>;
28
32
  allowedTools?: string[];
29
33
  }
34
+ /** 发现 / 读取一个 Skill 时的选项 */
35
+ export interface DiscoverSkillsOptions {
36
+ /** 静默:不写日志(批量探测 / 只读一层目录清单时用) */
37
+ silent?: boolean;
38
+ /** 日志口(可选):合规校验没过时每条报一句;不注入就不记(库缺省沉默) */
39
+ logger?: LogSink;
40
+ }
30
41
  /**
31
42
  * 扫描多个目录中发现的所有 Skill(含 SKILL.md 的子目录)。
32
43
  * 按优先级从高到低传入路径列表,同名 skill 靠前的路径优先(先到先得)。
33
44
  * 解析 YAML frontmatter 中的 name 和 description,同时校验合规。
34
45
  */
35
- export declare function discoverSkills(paths: string[], options?: {
36
- silent?: boolean;
37
- }): Promise<SkillInfo[]>;
46
+ export declare function discoverSkills(paths: string[], options?: DiscoverSkillsOptions): Promise<SkillInfo[]>;
38
47
  /**
39
48
  * 读取单个 Skill 的完整内容与元数据。
40
49
  * 按优先级从高到低传入路径列表,靠前的路径优先(先到先得)。
41
50
  * 返回 null 如果 skill 在所有目录中都不存在或 SKILL.md 不可读。
42
51
  */
43
- export declare function readSkill(skillDirs: string[], skillId: string, options?: {
44
- silent?: boolean;
45
- }): Promise<SkillInfo | null>;
52
+ export declare function readSkill(skillDirs: string[], skillId: string, options?: DiscoverSkillsOptions): Promise<SkillInfo | null>;
46
53
  /** @internal */
47
54
  export declare function parseFrontmatter(content: string): Frontmatter;
48
55
  /** @internal */
@@ -1,14 +1,12 @@
1
1
  import { promises as fs } from "node:fs";
2
- import { join } from "node:path";
3
- import { getLogger } from "../../../shared/logger.js";
4
- // ---- 发现(返回完整 SkillInfo,含 subAgent 等元数据)----
2
+ import { dirname, join } from "node:path";
3
+ import { SILENT_LOG } from "../../../shared/logger.js";
5
4
  /**
6
5
  * 扫描多个目录中发现的所有 Skill(含 SKILL.md 的子目录)。
7
6
  * 按优先级从高到低传入路径列表,同名 skill 靠前的路径优先(先到先得)。
8
7
  * 解析 YAML frontmatter 中的 name 和 description,同时校验合规。
9
8
  */
10
9
  export async function discoverSkills(paths, options) {
11
- const silent = options?.silent ?? false;
12
10
  const seen = new Set();
13
11
  const items = [];
14
12
  for (const dir of paths) {
@@ -31,13 +29,8 @@ export async function discoverSkills(paths, options) {
31
29
  if (seen.has(entry.name))
32
30
  continue;
33
31
  const skillMdPath = join(dir, entry.name, "SKILL.md");
34
- try {
35
- await fs.access(skillMdPath);
36
- }
37
- catch {
38
- continue;
39
- }
40
- const skill = await readSkillFromPath(entry.name, skillMdPath, silent);
32
+ // 不必先 `access`:`readSkillFromPath()` 自己 catch-all,读不到就回 null
33
+ const skill = await readSkillFromPath(entry.name, skillMdPath, options);
41
34
  if (skill) {
42
35
  seen.add(entry.name);
43
36
  items.push(skill);
@@ -46,38 +39,34 @@ export async function discoverSkills(paths, options) {
46
39
  }
47
40
  return items;
48
41
  }
49
- // ---- 完整读取(用于加载 Skill 正文和子 Agent 判断)----
42
+ // ---- 完整读取(用于加载 Skill 正文和 subagent 判断)----
50
43
  /**
51
44
  * 读取单个 Skill 的完整内容与元数据。
52
45
  * 按优先级从高到低传入路径列表,靠前的路径优先(先到先得)。
53
46
  * 返回 null 如果 skill 在所有目录中都不存在或 SKILL.md 不可读。
54
47
  */
55
48
  export async function readSkill(skillDirs, skillId, options) {
56
- const silent = options?.silent ?? false;
57
49
  for (const dir of skillDirs) {
58
- const candidate = join(dir, skillId, "SKILL.md");
59
- try {
60
- await fs.access(candidate);
61
- return await readSkillFromPath(skillId, candidate, silent);
62
- }
63
- catch {
64
- continue;
65
- }
50
+ // `readSkillFromPath()` 读不到就回 null,所以不必先探测再读
51
+ const skill = await readSkillFromPath(skillId, join(dir, skillId, "SKILL.md"), options);
52
+ if (skill)
53
+ return skill;
66
54
  }
67
55
  return null;
68
56
  }
69
57
  // ---- 内部 ----
70
- async function readSkillFromPath(skillId, skillMdPath, silent) {
58
+ async function readSkillFromPath(skillId, skillMdPath, options = {}) {
71
59
  try {
72
60
  const content = await fs.readFile(skillMdPath, "utf-8");
73
61
  const fm = parseFrontmatter(content);
74
62
  if (!fm.name)
75
63
  return null;
76
- // 规范合规校验
77
- if (!silent) {
64
+ // 规范合规校验(只报不拦;且 `silent` 时连校验都不跑)
65
+ if (!options.silent) {
78
66
  const errors = validateSkill(skillId, fm);
67
+ const logger = options.logger ?? SILENT_LOG;
79
68
  for (const err of errors) {
80
- getLogger().warn(`[skills] ${err.skillId}: ${err.field} — ${err.message}`);
69
+ logger.warn(`[skills] ${err.skillId}: ${err.field} — ${err.message}`);
81
70
  }
82
71
  }
83
72
  return {
@@ -86,7 +75,7 @@ async function readSkillFromPath(skillId, skillMdPath, silent) {
86
75
  description: fm.description ?? "",
87
76
  subAgent: fm.subAgent ?? false,
88
77
  content,
89
- dirPath: skillMdPath.replace(/\/SKILL\.md$/, ""),
78
+ dirPath: dirname(skillMdPath),
90
79
  license: fm.license,
91
80
  compatibility: fm.compatibility,
92
81
  metadata: fm.metadata,
@@ -1,17 +1,18 @@
1
1
  import { CallbackTool, AgentToolLazy } from "@ai-zen/agents-core";
2
2
  import type { SkillInfo } from "./discover.js";
3
+ import type { LogSink } from "../../../shared/logger.js";
3
4
  /**
4
5
  * 创建 load_skill 工具。
5
- * 枚举所有允许的 skill(不限是否支持子 Agent),由 filteredSkills 提供完整信息。
6
+ * 枚举所有允许的 skill(不限是否支持 subagent),由 filteredSkills 提供完整信息。
7
+ *
8
+ * @param logger 日志口(可选):加载时合规校验没过的那几句走它;不注入就不记
6
9
  */
7
- export declare function createLoadSkillTool(skillDirs: string[], filteredSkills: SkillInfo[]): CallbackTool;
10
+ export declare function createLoadSkillTool(skillDirs: string[], filteredSkills: SkillInfo[], logger?: LogSink): CallbackTool;
8
11
  /**
9
12
  * 创建 call_skill_sub_agent 工具。
10
- * 只展示 subAgent: true 的 Skill,枚举中自动排除不支持子 Agent 模式的 skill。
13
+ * 只展示 subAgent: true 的 Skill,枚举中自动排除不支持 subagent 模式的 skill。
11
14
  *
12
- * 工具由 AgentToolLazy 承载:子 Agent 在 exec 时构建,从而复用统一的委派边界
15
+ * 工具由 AgentToolLazy 承载:subagent 在 exec 时构建,从而复用统一的委派边界
13
16
  * (onSubAgentStart / onSubAgentEnd 钩子与 subAgentStarted / subAgentFinished 事件)。
14
- * 子 Agent 沿用父 Agent 的工具能力(不做权限过滤),但剔除 call_skill_sub_agent 自身,
15
- * 避免 skill 链式自递归。
16
17
  */
17
- export declare function createCallSkillSubAgentTool(skillDirs: string[], filteredSkills: SkillInfo[]): AgentToolLazy;
18
+ export declare function createCallSkillSubAgentTool(skillDirs: string[], filteredSkills: SkillInfo[], logger?: LogSink): AgentToolLazy;
@@ -1,13 +1,16 @@
1
1
  import { CallbackTool, Agent, AgentToolLazy, Message, } from "@ai-zen/agents-core";
2
2
  import { createDisclosureParam } from "../../disclosure.js";
3
3
  import { readSkill } from "./discover.js";
4
+ import { PEER_SESSION_TOOL_NAMES } from "../peers/peerSessionTools.js";
4
5
  import { promises as fs } from "node:fs";
5
6
  const EMPTY_HINT = "(No Skills are currently available, please ask the user to add one)";
6
7
  /**
7
8
  * 创建 load_skill 工具。
8
- * 枚举所有允许的 skill(不限是否支持子 Agent),由 filteredSkills 提供完整信息。
9
+ * 枚举所有允许的 skill(不限是否支持 subagent),由 filteredSkills 提供完整信息。
10
+ *
11
+ * @param logger 日志口(可选):加载时合规校验没过的那几句走它;不注入就不记
9
12
  */
10
- export function createLoadSkillTool(skillDirs, filteredSkills) {
13
+ export function createLoadSkillTool(skillDirs, filteredSkills, logger) {
11
14
  const ids = filteredSkills.map((s) => s.id);
12
15
  const allowedIds = new Set(ids);
13
16
  const param = createDisclosureParam(ids, "Select a Skill", EMPTY_HINT);
@@ -41,7 +44,7 @@ export function createLoadSkillTool(skillDirs, filteredSkills) {
41
44
  if (!allowedIds.has(skillId)) {
42
45
  return `❌ Skill "${skillId}" is not available here. Available skills: ${ids.join(", ") || "(none)"}`;
43
46
  }
44
- const skill = await readSkill(skillDirs, skillId);
47
+ const skill = await readSkill(skillDirs, skillId, { logger });
45
48
  if (!skill) {
46
49
  return `❌ Skill "${skillId}" not found, please verify the name`;
47
50
  }
@@ -72,15 +75,13 @@ export function createLoadSkillTool(skillDirs, filteredSkills) {
72
75
  }
73
76
  /**
74
77
  * 创建 call_skill_sub_agent 工具。
75
- * 只展示 subAgent: true 的 Skill,枚举中自动排除不支持子 Agent 模式的 skill。
78
+ * 只展示 subAgent: true 的 Skill,枚举中自动排除不支持 subagent 模式的 skill。
76
79
  *
77
- * 工具由 AgentToolLazy 承载:子 Agent 在 exec 时构建,从而复用统一的委派边界
80
+ * 工具由 AgentToolLazy 承载:subagent 在 exec 时构建,从而复用统一的委派边界
78
81
  * (onSubAgentStart / onSubAgentEnd 钩子与 subAgentStarted / subAgentFinished 事件)。
79
- * 子 Agent 沿用父 Agent 的工具能力(不做权限过滤),但剔除 call_skill_sub_agent 自身,
80
- * 避免 skill 链式自递归。
81
82
  */
82
- export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
83
- // 只保留支持子 Agent 模式的 skill
83
+ export function createCallSkillSubAgentTool(skillDirs, filteredSkills, logger) {
84
+ // 只保留支持 subagent 模式的 skill
84
85
  const subAgentSkills = filteredSkills.filter((s) => s.subAgent);
85
86
  const ids = subAgentSkills.map((s) => s.id);
86
87
  const allowedIds = new Set(ids);
@@ -113,7 +114,7 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
113
114
  },
114
115
  // 初始消息依赖运行时参数(skill_id → SKILL.md 内容),故不传 messages 模板,
115
116
  // 由 buildAgent 读取 SKILL.md 后自行决定;中断信号与委派边界由 AgentToolLazy 统一处理
116
- // (父的 `abort` 直接把 signal 交给子 agent 的 `runOnce`,不再有手工联动)
117
+ // (父的 `abort` 直接把 signal 交给 subagent 的 `runOnce`)
117
118
  buildAgent: async (parsedArgs, ctx) => {
118
119
  const skillId = parsedArgs.skill_id;
119
120
  const task = parsedArgs.task;
@@ -121,7 +122,7 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
121
122
  if (!allowedIds.has(skillId)) {
122
123
  throw new Error(`❌ Skill "${skillId}" is not available here. Available SubAgent skills: ${ids.join(", ") || "(none)"}`);
123
124
  }
124
- const skill = await readSkill(skillDirs, skillId);
125
+ const skill = await readSkill(skillDirs, skillId, { logger });
125
126
  if (!skill) {
126
127
  throw new Error(`❌ Skill "${skillId}" not found, please verify the name`);
127
128
  }
@@ -130,15 +131,18 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
130
131
  }
131
132
  // 沿用父 Agent 的工具能力(不做权限过滤),剔除自身以防自递归
132
133
  const parentAgent = ctx.agent;
133
- const tools = parentAgent.tools.filter((t) => t.function.name !== "call_skill_sub_agent");
134
+ // 一并排掉平级会话那三个工具:它们是会话级能力,父会话的执行体可以有,被派出去的执行体
135
+ // 不该有 —— 委派出来的执行体不属于任何一段会话,没有可以署名的身份(发话要写「来自哪
136
+ // 一段会话」),也开不出有人认领的新会话,留着这三个只会在调用时必错。
137
+ const peerSessionToolNames = new Set(PEER_SESSION_TOOL_NAMES);
138
+ const tools = parentAgent.tools.filter((t) => t.function.name !== "call_skill_sub_agent" && !peerSessionToolNames.has(t.function.name));
134
139
  return new Agent({
135
140
  client: parentAgent.client,
136
141
  model: parentAgent.model,
137
142
  modelConfig: parentAgent.modelConfig,
138
143
  messages: [Message.System(skill.content), Message.User(task)],
139
144
  tools,
140
- // 技能子 Agent 同样走委派:`buildAgent` 造出来的必须是**一次性**
141
- // (`CORE.md` §9)。它跑完就死透,不与父会话共用寿命。
145
+ // 一次性委派(`CORE.md` §9):跑完就死透,不与父会话共用寿命。
142
146
  lifetime: "one-shot",
143
147
  });
144
148
  },
@@ -1,4 +1,5 @@
1
1
  import type { Tool } from "@ai-zen/agents-core";
2
+ import type { LogSink } from "../../../shared/logger.js";
2
3
  import type { Scope, FilterOutput } from "../../Scope.js";
3
4
  import type { ScopeCandidates, ScopePlugin } from "../../ScopePlugin.js";
4
5
  /**
@@ -11,8 +12,11 @@ export declare class SubAgentsScopePlugin implements ScopePlugin {
11
12
  readonly id = "subagents";
12
13
  private readonly paths;
13
14
  private subagents;
15
+ /** 日志口(可选):有文件读不出来、被跳过时报一句;不注入就不记 */
16
+ private readonly logger?;
14
17
  constructor(options?: {
15
18
  paths?: string[];
19
+ logger?: LogSink;
16
20
  });
17
21
  discover(scope: Scope): Promise<void>;
18
22
  candidates(): ScopeCandidates;
@@ -11,12 +11,15 @@ export class SubAgentsScopePlugin {
11
11
  id = SubAgentsScopePlugin.ID;
12
12
  paths;
13
13
  subagents = [];
14
+ /** 日志口(可选):有文件读不出来、被跳过时报一句;不注入就不记 */
15
+ logger;
14
16
  constructor(options) {
15
17
  this.paths = options?.paths ?? [];
18
+ this.logger = options?.logger;
16
19
  }
17
20
  async discover(scope) {
18
21
  const dirs = this.paths.map((p) => (isAbsolute(p) ? p : join(scope.cwd, p)));
19
- this.subagents = await discoverSubAgents(dirs);
22
+ this.subagents = await discoverSubAgents(dirs, { logger: this.logger });
20
23
  }
21
24
  candidates() {
22
25
  return {
@@ -1,7 +1,13 @@
1
1
  import type { AgentDefinition } from "../../../types/index.js";
2
+ import { type LogSink } from "../../../shared/logger.js";
3
+ /** 发现 SubAgent 时的选项 */
4
+ export interface DiscoverSubAgentsOptions {
5
+ /** 日志口(可选):有文件读不出来、被跳过时报一句;不注入就不记(库缺省沉默) */
6
+ logger?: LogSink;
7
+ }
2
8
  /**
3
9
  * 扫描多个目录中发现的所有 SubAgent 完整定义。
4
10
  * 按优先级从高到低传入路径列表,同名 function.name 靠前的路径优先(先到先得)。
5
11
  * 跳过无 function 的普通 Agent 和解析失败的文件。
6
12
  */
7
- export declare function discoverSubAgents(paths: string[]): Promise<AgentDefinition[]>;
13
+ export declare function discoverSubAgents(paths: string[], options?: DiscoverSubAgentsOptions): Promise<AgentDefinition[]>;
@@ -1,11 +1,13 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { SILENT_LOG } from "../../../shared/logger.js";
3
4
  /**
4
5
  * 扫描多个目录中发现的所有 SubAgent 完整定义。
5
6
  * 按优先级从高到低传入路径列表,同名 function.name 靠前的路径优先(先到先得)。
6
7
  * 跳过无 function 的普通 Agent 和解析失败的文件。
7
8
  */
8
- export async function discoverSubAgents(paths) {
9
+ export async function discoverSubAgents(paths, options = {}) {
10
+ const logger = options.logger ?? SILENT_LOG;
9
11
  const seen = new Set();
10
12
  const agents = [];
11
13
  for (const dir of paths) {
@@ -35,8 +37,10 @@ export async function discoverSubAgents(paths) {
35
37
  }
36
38
  }
37
39
  }
38
- catch {
39
- // 跳过解析失败的文件
40
+ catch (error) {
41
+ // 跳过坏文件是对的(一个坏文件不该让整张 SubAgent 列表读不出来),但要留一行:
42
+ // 文件读不出来是个事实,静默跳过会让配置看着像生效了
43
+ logger.warn(`[subagents] ${join(dir, file)} 读不出来或不是合法定义,跳过:${String(error)}`);
40
44
  }
41
45
  }
42
46
  }
@@ -5,6 +5,5 @@ import type { Scope } from "../../Scope.js";
5
5
  * 创建 SubAgent 工具(AgentToolLazy)。
6
6
  *
7
7
  * SubAgent 是有 `function` 字段的 Agent,可被其他 Agent 作为工具调用。
8
- * 使用延迟构建(AgentToolLazy)避免工具列表构建阶段的递归创建问题。
9
8
  */
10
9
  export declare function createSubAgentTool(def: AgentDefinition, scope: Scope): Tool;
@@ -1,10 +1,11 @@
1
1
  import { Agent, AgentToolLazy } from "@ai-zen/agents-core";
2
2
  import { createModel } from "../../../runtime/createModel.js";
3
+ import { PEER_SESSION_TOOL_NAMES } from "../peers/peerSessionTools.js";
4
+ import { ASYNC_TASK_TOOL_NAMES } from "../builtin/asyncTasks.js";
3
5
  /**
4
6
  * 创建 SubAgent 工具(AgentToolLazy)。
5
7
  *
6
8
  * SubAgent 是有 `function` 字段的 Agent,可被其他 Agent 作为工具调用。
7
- * 使用延迟构建(AgentToolLazy)避免工具列表构建阶段的递归创建问题。
8
9
  */
9
10
  export function createSubAgentTool(def, scope) {
10
11
  if (!def.function) {
@@ -43,6 +44,15 @@ export function createSubAgentTool(def, scope) {
43
44
  const subFiltered = scope.filter(def, {
44
45
  exclude: {
45
46
  subagents: def.function?.name ? [def.function.name] : undefined,
47
+ // 平级会话那三个工具是会话级能力,被派出去的执行体手上不该有:它不属于任何一段
48
+ // 会话 —— 没有可以署名的身份(发话要写「来自哪一段会话」),也开不出有人认领的新
49
+ // 会话,所以这三个工具在它手上只有必错的路(发话在端口层直接抛,创建被判
50
+ // depth_exceeded)。取 exclude 而不动定义里的 permissions:定义文件是用户可编辑的
51
+ // 配置,这条规矩不长在那儿;而 filter 先按 exclude 剔除、再按权限过滤,定义写
52
+ // `allow: ["*"]` 也照样剔得掉。
53
+ //
54
+ // 两个后台工具同理:被派出去的是个一次性执行体,结果回来时它的调用栈已经退了。
55
+ tools: [...PEER_SESSION_TOOL_NAMES, ...ASYNC_TASK_TOOL_NAMES],
46
56
  },
47
57
  });
48
58
  const tools = scope.instantiate(subFiltered);
@@ -1,5 +1,6 @@
1
1
  import type { Tool } from "@ai-zen/agents-core";
2
2
  import type { AgentDefinition } from "../../../types/index.js";
3
+ import type { LogSink } from "../../../shared/logger.js";
3
4
  import type { Scope, FilterOutput } from "../../Scope.js";
4
5
  import type { ScopeCandidates, ScopePlugin } from "../../ScopePlugin.js";
5
6
  /**
@@ -13,8 +14,11 @@ export declare class UserToolsScopePlugin implements ScopePlugin {
13
14
  readonly id = "user-tools";
14
15
  private readonly paths;
15
16
  private tools;
17
+ /** 日志口(可选):某个文件被拒了报一句;不注入就不记 */
18
+ private readonly logger?;
16
19
  constructor(options?: {
17
20
  paths?: string[];
21
+ logger?: LogSink;
18
22
  });
19
23
  discover(scope: Scope, options?: {
20
24
  silent?: boolean;
@@ -11,12 +11,15 @@ export class UserToolsScopePlugin {
11
11
  id = UserToolsScopePlugin.ID;
12
12
  paths;
13
13
  tools = [];
14
+ /** 日志口(可选):某个文件被拒了报一句;不注入就不记 */
15
+ logger;
14
16
  constructor(options) {
15
17
  this.paths = options?.paths ?? [];
18
+ this.logger = options?.logger;
16
19
  }
17
20
  async discover(scope, options) {
18
21
  const dirs = this.paths.map((p) => (isAbsolute(p) ? p : join(scope.cwd, p)));
19
- this.tools = await discoverUserTools(dirs, options);
22
+ this.tools = await discoverUserTools(dirs, { silent: options?.silent, logger: this.logger });
20
23
  }
21
24
  candidates(_scope, _definition) {
22
25
  return { tools: this.tools.map((t) => t.function.name) };
@@ -1,8 +1,11 @@
1
1
  import { Tool } from "@ai-zen/agents-core";
2
+ import { type LogSink } from "../../../shared/logger.js";
2
3
  /** 单个用户工具文件的加载参数 */
3
4
  export interface DiscoverUserToolsOptions {
4
5
  /** 静默:不写日志(测试 / 批量探测用) */
5
6
  silent?: boolean;
7
+ /** 日志口(可选):某个文件被拒了从它报一句;不注入就不记(库缺省沉默) */
8
+ logger?: LogSink;
6
9
  /** 单文件 import 的超时(毫秒),默认 {@link DEFAULT_IMPORT_TIMEOUT_MS};`0` 表示不限 */
7
10
  importTimeoutMs?: number;
8
11
  }
@@ -10,8 +13,8 @@ export interface DiscoverUserToolsOptions {
10
13
  * 一个用户工具文件(加载成功的那一个):文件身份 + 加载出来的实例。
11
14
  *
12
15
  * 为什么要成对给:`Tool` 自己不记「我是从哪个文件来的」(它只是 core 的一个工具对象),
13
- * 而 `asset.list` 那类「把发现结果报给客户端看」的调用方需要的正是**文件**(路径、
14
- * 文件名)。让调用方拿着工具名去某个目录里找同名文件,就是第二套扫描规则。
16
+ * 而把发现结果报给上层的调用方(宿主 `DiscoveryService` 列配置层)需要的正是**文件**。
17
+ * 让调用方拿着工具名去某个目录里找同名文件,就是第二套扫描规则。
15
18
  */
16
19
  export interface UserToolFile {
17
20
  /** 文件名(不含扩展名):同一条扫描里的唯一键,也是发现顺序的依据 */
@@ -22,20 +25,16 @@ export interface UserToolFile {
22
25
  }
23
26
  /**
24
27
  * 扫描多个 tools/ 目录,发现所有 .js / .mjs 文件,动态加载为 Tool 实例。
25
- * 使用原生 dynamic import() 加载(在 "type": "module" 下 .js 也是 ESM),
26
- * 每次添加时间戳 querystring 防止缓存。
27
28
  *
28
29
  * 按优先级从高到低传入路径列表,同名工具靠前的路径优先(先到先得)。
29
30
  * 按文件名排序以保证确定性。
30
31
  *
31
- * 本体在 {@link discoverUserToolFiles}:两个出口共用同一条扫描规则(顺序、去重、导入护栏、
32
- * 超时都在那一处),否则「Agent 装了哪些工具」与「资产清单里列了哪些」迟早对不上。
32
+ * 本体在 {@link discoverUserToolFiles},这里只是取出 `tool`。
33
33
  */
34
34
  export declare function discoverUserTools(paths: string[], options?: DiscoverUserToolsOptions): Promise<Tool[]>;
35
35
  /**
36
36
  * 同 {@link discoverUserTools},但把**文件**也一起交出来(路径 / 文件名)。
37
37
  *
38
- * 发现规则只有一份:目录顺序、同名去重、扩展名、导入护栏、超时全部写在本函数里,
39
- * 另一个出口只是上面的 `map`。
38
+ * 扫描规则只写在本函数里,另一个出口只是上面的 `map`。
40
39
  */
41
40
  export declare function discoverUserToolFiles(paths: string[], options?: DiscoverUserToolsOptions): Promise<UserToolFile[]>;
@@ -2,8 +2,8 @@ import { promises as fs } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { Tool, CallbackTool } from "@ai-zen/agents-core";
5
- import { getLogger } from "../../../shared/logger.js";
6
- /** 默认的单文件 import 超时:工具目录里不该有需要长过它的模块求值 */
5
+ import { SILENT_LOG } from "../../../shared/logger.js";
6
+ /** 默认的单文件 import 超时(毫秒) */
7
7
  const DEFAULT_IMPORT_TIMEOUT_MS = 5000;
8
8
  // ==================================================================
9
9
  // 宿主护栏
@@ -20,11 +20,9 @@ const DEFAULT_IMPORT_TIMEOUT_MS = 5000;
20
20
  // · `console.log / info / debug` → 改指 stderr,不撕宿主的 stdout(TUI 画面);
21
21
  // · 顶层 await 永不 settle(异步挂死)→ 超时放弃该文件。
22
22
  //
23
- // **挡不住**的(只有进程隔离能解,而那正是 MCP 的职责):
23
+ // **挡不住**的(只有进程隔离能解,那正是 MCP 的职责):
24
24
  // · 顶层同步死循环——事件循环被占,连超时定时器都不会跑;
25
25
  // · `process.kill(process.pid)` 这类原生自杀。
26
- //
27
- // 所以 tools/ 的定位是**可信的本地扩展**;不可信的代码请写成 MCP 服务器。
28
26
  /** 正在被 import 的文件(护栏回报错误时用它定位) */
29
27
  let importingFile = null;
30
28
  /** 用户文件里调 `process.exit()` / `process.abort()` 时抛这个 —— 落进 loadToolFile 的 catch */
@@ -88,7 +86,7 @@ function installHostGuards() {
88
86
  * `import()` + 超时。
89
87
  *
90
88
  * 超时只是「不再等它」:ESM 求值**不可取消**,该模块随后仍可能被求值完并产生副作用,
91
- * 因此超时只记告警、不声称已终止。真正的隔离需要独立进程(即 MCP)。
89
+ * 因此超时只记告警、不声称已终止。
92
90
  */
93
91
  async function importWithTimeout(url, timeoutMs) {
94
92
  if (timeoutMs <= 0)
@@ -105,21 +103,18 @@ async function importWithTimeout(url, timeoutMs) {
105
103
  clearTimeout(timer);
106
104
  }
107
105
  }
108
- /** 「这个文件被拒了」的出口:只走 logger,怎么展示是宿主的事 */
106
+ /** 「这个文件被拒了」的出口:只走注入进来的日志,怎么展示是宿主的事 */
109
107
  function reportReject(file, reason, opts, level = "warn") {
110
108
  if (!opts.silent)
111
- getLogger()[level](`[usertools] ${file} — ${reason}`);
109
+ (opts.logger ?? SILENT_LOG)[level](`[usertools] ${file} — ${reason}`);
112
110
  }
113
111
  /**
114
112
  * 扫描多个 tools/ 目录,发现所有 .js / .mjs 文件,动态加载为 Tool 实例。
115
- * 使用原生 dynamic import() 加载(在 "type": "module" 下 .js 也是 ESM),
116
- * 每次添加时间戳 querystring 防止缓存。
117
113
  *
118
114
  * 按优先级从高到低传入路径列表,同名工具靠前的路径优先(先到先得)。
119
115
  * 按文件名排序以保证确定性。
120
116
  *
121
- * 本体在 {@link discoverUserToolFiles}:两个出口共用同一条扫描规则(顺序、去重、导入护栏、
122
- * 超时都在那一处),否则「Agent 装了哪些工具」与「资产清单里列了哪些」迟早对不上。
117
+ * 本体在 {@link discoverUserToolFiles},这里只是取出 `tool`。
123
118
  */
124
119
  export async function discoverUserTools(paths, options = {}) {
125
120
  return (await discoverUserToolFiles(paths, options)).map((item) => item.tool);
@@ -127,8 +122,7 @@ export async function discoverUserTools(paths, options = {}) {
127
122
  /**
128
123
  * 同 {@link discoverUserTools},但把**文件**也一起交出来(路径 / 文件名)。
129
124
  *
130
- * 发现规则只有一份:目录顺序、同名去重、扩展名、导入护栏、超时全部写在本函数里,
131
- * 另一个出口只是上面的 `map`。
125
+ * 扫描规则只写在本函数里,另一个出口只是上面的 `map`。
132
126
  */
133
127
  export async function discoverUserToolFiles(paths, options = {}) {
134
128
  const seen = new Set();
@@ -153,14 +147,10 @@ export async function discoverUserToolFiles(paths, options = {}) {
153
147
  if (!seen.has(name)) {
154
148
  seen.add(name);
155
149
  const path = join(dir, name + ext);
156
- try {
157
- const tool = await loadToolFile(path, options);
158
- if (tool) {
159
- items.push({ name, path, tool });
160
- }
161
- }
162
- catch {
163
- // 跳过加载失败的文件
150
+ // 不必再包一层:`loadToolFile()` 自己 catch-all,加载失败会走 `reportReject` 上报并回 null
151
+ const tool = await loadToolFile(path, options);
152
+ if (tool) {
153
+ items.push({ name, path, tool });
164
154
  }
165
155
  }
166
156
  }
@@ -196,12 +186,12 @@ async function loadToolFile(filepath, opts) {
196
186
  try {
197
187
  const url = `${pathToFileURL(filepath).href}?t=${Date.now()}`;
198
188
  const mod = (await importWithTimeout(url, opts.importTimeoutMs ?? DEFAULT_IMPORT_TIMEOUT_MS));
199
- // import() 返回模块命名空间对象,取其 default 导出
189
+ // import() 返回模块命名空间对象,优先取 default 导出;没有 default 时整个命名空间当导出
200
190
  const exported = mod.default ?? mod;
201
191
  if (!exported || (typeof exported === "object" && Object.keys(exported).length === 0)) {
202
192
  return null;
203
193
  }
204
- return normalizeToolExport({ default: exported }, filepath, opts.silent);
194
+ return normalizeToolExport({ default: exported }, filepath, opts);
205
195
  }
206
196
  catch (err) {
207
197
  reportReject(filepath, `failed to load — ${err?.message ?? err}`, opts, "error");
@@ -218,7 +208,7 @@ async function loadToolFile(filepath, opts) {
218
208
  /**
219
209
  * 统一各种导出格式为 Tool 实例。
220
210
  */
221
- function normalizeToolExport(exported, filepath, silent) {
211
+ function normalizeToolExport(exported, filepath, opts = {}) {
222
212
  // 情况 1:直接是 Tool 实例
223
213
  if (exported instanceof Tool) {
224
214
  return exported;
@@ -248,8 +238,8 @@ function normalizeToolExport(exported, filepath, silent) {
248
238
  callback: target.callback,
249
239
  });
250
240
  }
251
- if (!silent) {
252
- getLogger().error(`[usertools] Unrecognized tool format: ${filepath}`);
241
+ if (!opts.silent) {
242
+ (opts.logger ?? SILENT_LOG).error(`[usertools] Unrecognized tool format: ${filepath}`);
253
243
  }
254
244
  return null;
255
245
  }