@ai-zen/agents-sdk 1.2.0-alpha.2 → 2.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +77 -0
  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 +56 -6
  7. package/dist/agent-plugins/AutoMigratePlugin.js +64 -15
  8. package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +12 -9
  9. package/dist/agent-plugins/AutoRefreshToolsPlugin.js +6 -7
  10. package/dist/agent-plugins/ContextGuardPlugin.d.ts +32 -24
  11. package/dist/agent-plugins/ContextGuardPlugin.js +37 -22
  12. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +38 -46
  13. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +37 -50
  14. package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +15 -1
  15. package/dist/agent-plugins/UnknownToolHintPlugin.js +15 -1
  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 +22 -9
  26. package/dist/index.js +16 -6
  27. package/dist/runtime/AgentRuntime.d.ts +293 -0
  28. package/dist/runtime/AgentRuntime.js +457 -0
  29. package/dist/runtime/HandoffGuardPlugin.d.ts +85 -16
  30. package/dist/runtime/HandoffGuardPlugin.js +140 -19
  31. package/dist/runtime/HandoffService.d.ts +255 -91
  32. package/dist/runtime/HandoffService.js +392 -177
  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 +21 -11
  38. package/dist/runtime/SdkAgent.js +24 -8
  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 +42 -14
  50. package/dist/scope/Scope.js +55 -16
  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 +61 -9
  89. package/dist/scope/plugins/mcp/McpConnectionManager.js +174 -72
  90. package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +37 -4
  91. package/dist/scope/plugins/mcp/McpScopePlugin.js +100 -9
  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 +25 -0
  99. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +32 -0
  100. package/dist/scope/plugins/peers/peerSessionTools.d.ts +173 -0
  101. package/dist/scope/plugins/peers/peerSessionTools.js +292 -0
  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 +9 -8
  107. package/dist/scope/plugins/skills/skillTools.js +21 -13
  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 +14 -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 +8 -3
  123. package/dist/shared/errors.js +9 -4
  124. package/dist/shared/logger.d.ts +21 -10
  125. package/dist/shared/logger.js +9 -15
  126. package/dist/types/index.d.ts +38 -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
@@ -0,0 +1,292 @@
1
+ import { CallbackTool } from "@ai-zen/agents-core";
2
+ /**
3
+ * 平级会话(peer session)的三个工具 —— **只负责把模型的话翻译成端口调用**。
4
+ *
5
+ * 端口({@link PeerSessionPort})由宿主实现:开一段会话、把一句话投进去、现读它此刻落在哪一格,
6
+ * 都是宿主的事(会话是宿主的财产,SDK 不认识会话)。SDK 这一侧只有三样东西:参数说明、
7
+ * **给模型看的那几句话**(别轮询:她说完会自己 `post_message` 回来;记不住 `sessionId` 就靠
8
+ * `label`),以及三个工具各自的返回形状。
9
+ *
10
+ * ## 为什么这几句话必须同时出现在 description 与返回文案两处
11
+ *
12
+ * 模型只读它拿到的东西 —— 第一次只看得到 description,之后每次调用只看得到返回值。少写一处,
13
+ * 模型就会开始忙等轮询(`read_session_status` 一个接一个),而每次轮询都要烧一次模型调用。
14
+ *
15
+ * ## 投递不承诺任何未来
16
+ *
17
+ * `post_message` 的回执只有「收下了」。那边忙不忙、什么时候取件、取走之后会做什么,**都不是
18
+ * 这一句话能定下的**,写在回执里就是对未来的断言 —— 而未来只能靠观测(`read_session_status`)
19
+ * 与对方自己发来的话去读。所以本文件的回执里没有「把它叫起来了」「排在它手头那批后面」这类话。
20
+ *
21
+ * ## 投递不看关系
22
+ *
23
+ * 谁都能给谁投:`post_message` 只问「目标在不在、活不活」,不问「你俩是什么关系」。平级之间
24
+ * 能不能互发、发了对方理不理,靠的是 agent 自己的知识(它在提示里就知道自己跟谁在说话),
25
+ * 不是一道校验。只有**创建**还有「只限一层」这条产品限制,它写在 `create_session` 那边。
26
+ */
27
+ /** `create_session`:开一段平级会话,建完即回 */
28
+ export const CREATE_SESSION_TOOL = "create_session";
29
+ /** `read_session_status`:只问状态 + 一句摘要,绝不返回全量消息 */
30
+ export const READ_SESSION_STATUS_TOOL = "read_session_status";
31
+ /** `post_message`:给另一段会话投一句话(不等结果,投递不看关系) */
32
+ export const POST_MESSAGE_TOOL = "post_message";
33
+ /** 本插件向 `tools` 维度贡献的候选名(顺序即展示顺序) */
34
+ export const PEER_SESSION_TOOL_NAMES = [
35
+ CREATE_SESSION_TOOL,
36
+ READ_SESSION_STATUS_TOOL,
37
+ POST_MESSAGE_TOOL,
38
+ ];
39
+ /**
40
+ * 「别轮询」那半句:**她说完会自己 post_message 回来**。
41
+ *
42
+ * 这是唯一一句能替模型省下轮询的话:投递不看关系(谁都能给谁投),所以对方真有话要说时不必
43
+ * 等谁去问。
44
+ */
45
+ const NO_POLL_HINT = "Do not poll it: when that session has something for me it calls post_message on me itself.";
46
+ /** 「靠 label 认会话」那半句:`sessionId` 是 UUID,长会话里记不住 */
47
+ const LABEL_HINT = "Keep `label` next to `sessionId`: if I forget the id later, `label` is how I name this session.";
48
+ /** 拒绝各自的一句话:说清「为什么」与「接下来能做什么」(宿主没给 hint 时用它) */
49
+ const REJECT_HINTS = {
50
+ depth_exceeded: "This session is itself a peer session, and peer sessions cannot open further ones " +
51
+ "(creating is one level only — posting a message is not limited this way). Do the work here " +
52
+ "instead, or report back and let the session that started this one open it.",
53
+ model_unresolved: "No model could be resolved for that session (no session override, no modelId on the agent " +
54
+ "definition, no global default model). Pass `modelId`, or pass an `agentId` that has a model " +
55
+ "bound.",
56
+ too_many_peers: "This session already has the maximum number of peer sessions busy at the same time. " +
57
+ "Wait until some of them are free (read_session_status tells me which one is idle), or give " +
58
+ "the work to fewer sessions instead of opening another one.",
59
+ };
60
+ /**
61
+ * `post_message` 被拒绝的两种原因各自的一句话(端口只回原因,不给文案)。
62
+ *
63
+ * 两条都要说清「这句话没投出去、不会有人回音」,否则模型会等一条永远不会到的话。两者都不建议
64
+ * 重试:目标还在就等它自己说话,目标已经不在就自己把活干掉。
65
+ */
66
+ const SEND_REJECT_HINTS = {
67
+ gone: "There is no such session any more: it was deleted, or the host restarted and that in-process " +
68
+ "record is gone (it is now an ordinary session that still shows up in the session list). " +
69
+ "Nothing was sent and no answer will arrive — do the work here instead.",
70
+ dead: "That session exists but there is no agent behind it any more, so nobody will take the " +
71
+ "message. Nothing was sent and no answer will arrive — do the work here instead.",
72
+ };
73
+ /**
74
+ * 「摘要那一格」那半句:答案里另给一格**最近一句**的摘要 —— 不是全量、不是历史。
75
+ *
76
+ * 写它的理由与 {@link NO_POLL_HINT} 一样:模型会照着自己拿到的那段话理解能力边界,不说清
77
+ * 「这只是摘要」,它下一句就会以为自己在读对方的会话。
78
+ */
79
+ const EXCERPT_HINT = "`lastMessage` in this answer is only the beginning of the last thing it said (cut at 300 " +
80
+ "characters), and it is all I get: never that session's full transcript, never its history, " +
81
+ "no message count — do not use this answer to fetch context.";
82
+ /**
83
+ * 「收下了」那半句:只说两件当场能定下的事 —— ① 已进那边的 inbox;② 别轮询。
84
+ *
85
+ * **不写**「它现在在忙 / 会把它叫起来」,也不写「不会自动推给我」:后者与「她说完会自己
86
+ * post_message 回来」相互打脸,而且两者都是对未来的断言。真正能说的只有
87
+ * {@link NO_POLL_HINT} 那一句(“真要说话时会自己发过来”),它刚好把「别轮询」说清。
88
+ */
89
+ const SEND_ACCEPTED_HINT = "Accepted: the message is in that session's inbox now. That is all this call confirms — " +
90
+ "whether or when that session acts on it is not promised. This call does not come back. " +
91
+ `${NO_POLL_HINT} ${LABEL_HINT}`;
92
+ /**
93
+ * 给模型的一句话:先把「忙不忙 / 还活不活着」说清(两件事,各自一个字段,不合成一格),
94
+ * 再带上「摘要只是摘要」与「靠 label」两句,活着的时候再加「别轮询」。
95
+ */
96
+ function statusHint(status, alive) {
97
+ if (!alive) {
98
+ return ("There is no agent behind that session any more (it is dead): nothing will be taken in " +
99
+ `there and no answer will arrive. Do the work here instead. ${EXCERPT_HINT} ${LABEL_HINT}`);
100
+ }
101
+ if (status === "working") {
102
+ return `It is working: it has work in hand right now. ${NO_POLL_HINT} ${EXCERPT_HINT} ${LABEL_HINT}`;
103
+ }
104
+ return `It is idle: it exists and has nothing in hand at this moment. ${NO_POLL_HINT} ${EXCERPT_HINT} ${LABEL_HINT}`;
105
+ }
106
+ /** 会话根本找不到(`found: false`)时给模型的一句话:这不是第五格,是「没有这一段」 */
107
+ const NOT_FOUND_HINT = "There is no record of that session any more: it was deleted, or the host restarted and " +
108
+ "that in-process record is gone (in that case it is now an ordinary session that " +
109
+ "still shows up in the session list). No answer will arrive there. If I only remember the " +
110
+ "`label`, that session can no longer be looked up by it.";
111
+ /**
112
+ * 造三个工具(顺序即返回顺序)。
113
+ *
114
+ * 三个工具都是即时返回的 `CallbackTool`:真正的等待在宿主那一侧(那边的 agent 自己跑)。
115
+ */
116
+ export function createPeerSessionTools(port) {
117
+ return [createSessionTool(port), readSessionStatusTool(port), post_messageTool(port)];
118
+ }
119
+ /** `create_session({ prompt, agentId?, modelId?, label? })` → `{ sessionId, label }` */
120
+ function createSessionTool(port) {
121
+ return new CallbackTool({
122
+ function: {
123
+ name: CREATE_SESSION_TOOL,
124
+ description: [
125
+ "Open a PEER SESSION: a separate session with its own agent that works on `prompt`",
126
+ "alongside this one (own context, own usage, and it stays readable in the session list",
127
+ "afterwards). Use it for work that can happen in parallel with mine instead of blocking me.",
128
+ "This call returns as soon as the session exists: it does not wait for any answer and no",
129
+ "answer is delivered to me here.",
130
+ "Talk to it afterwards with post_message; do not poll it — when that session has something",
131
+ "for me it calls post_message on me itself.",
132
+ "Creating is limited to one level (a peer session cannot open another one); posting a",
133
+ "message is not limited that way — any session may post a message to any other.",
134
+ "Remember the returned `label` as well as `sessionId`: in a long session I may no",
135
+ "longer recall the id, and the label is how I refer to this session.",
136
+ ].join(" "),
137
+ parameters: {
138
+ type: "object",
139
+ properties: {
140
+ prompt: {
141
+ type: "string",
142
+ description: "What that session should do. Write it as a self-contained task: the new session " +
143
+ "starts from an empty context and cannot see this session.",
144
+ },
145
+ agentId: {
146
+ type: "string",
147
+ description: "Agent (by id) that runs the new session (optional, defaults to the agent of this " +
148
+ "session)",
149
+ },
150
+ modelId: {
151
+ type: "string",
152
+ description: "Model id for the new session (optional, defaults to the usual resolution: session " +
153
+ "> agent definition > global default)",
154
+ },
155
+ label: {
156
+ type: "string",
157
+ description: 'Short readable name for this session (optional, e.g. "run the tests"). It is what ' +
158
+ "read_session_status shows and what I use to refer to it later.",
159
+ },
160
+ },
161
+ required: ["prompt"],
162
+ additionalProperties: false,
163
+ },
164
+ },
165
+ callback: async (input, ctx) => {
166
+ const created = await port.create({
167
+ caller: ctx.agent,
168
+ prompt: typeof input.prompt === "string" ? input.prompt : String(input.prompt ?? ""),
169
+ ...optionalString("agentId", input.agentId),
170
+ ...optionalString("modelId", input.modelId),
171
+ ...optionalString("label", input.label),
172
+ });
173
+ // 结构化拒绝:模型能按字段分支,不用去读自由文本(宿主没给 hint 时用 SDK 这一份)
174
+ if (!created.ok)
175
+ return { rejected: created.reason, hint: created.hint ?? REJECT_HINTS[created.reason] };
176
+ return {
177
+ sessionId: created.sessionId,
178
+ label: created.label,
179
+ hint: `${NO_POLL_HINT} ${LABEL_HINT}`,
180
+ };
181
+ },
182
+ });
183
+ }
184
+ /** `read_session_status({ sessionId })` → `{ found, status, label, lastMessage, hint }` */
185
+ function readSessionStatusTool(port) {
186
+ return new CallbackTool({
187
+ function: {
188
+ name: READ_SESSION_STATUS_TOOL,
189
+ description: [
190
+ "Check a session created earlier: whether it is working or idle right now, and whether it",
191
+ "is still alive (`alive: false` means no agent is behind it any more), or that there is no",
192
+ "such session at all (found: false).",
193
+ "About that session the answer gives exactly two facts: whether it is busy (that one state)",
194
+ "and `lastMessage` — a short excerpt of the last thing it said (cut at 300 characters; null",
195
+ "while it has not said anything yet); the `label` is only the name it was created with.",
196
+ "That excerpt is all I get: the answer is never the full transcript",
197
+ "and never its history, it carries no message list and no message count, and it does not",
198
+ "say what that session is doing — so do not use it to fetch context.",
199
+ "This is a single check, not a waiting loop: which of those states it is in (or that it",
200
+ "is not there any more) is a fact about this moment only, and it does not tell me when",
201
+ "anything will happen. Do not poll —",
202
+ "when that session has something for me it calls post_message on me itself.",
203
+ "If I no longer remember the `sessionId`, the `label` returned by create_session is what",
204
+ "identifies the session — it comes back in the answer, so I can tell them apart.",
205
+ ].join(" "),
206
+ parameters: {
207
+ type: "object",
208
+ properties: {
209
+ sessionId: {
210
+ type: "string",
211
+ description: "The sessionId returned by create_session (that is the peer session's own id)",
212
+ },
213
+ },
214
+ required: ["sessionId"],
215
+ additionalProperties: false,
216
+ },
217
+ },
218
+ callback: async (input, ctx) => {
219
+ const status = await port.status({
220
+ caller: ctx.agent,
221
+ sessionId: typeof input.sessionId === "string" ? input.sessionId : "",
222
+ });
223
+ // 两种形状原样转给模型:找不到就是 `found: false` + `status: null`,不挤成一个状态值
224
+ if (!status.found)
225
+ return { found: false, status: null, hint: NOT_FOUND_HINT };
226
+ // 有这一段就给四样:忙不忙、还活不活着、那个名字、最近一句的摘要(`null` = 还没说过话)。
227
+ // 消息数组 / 条数 / 历史一概不带:需求要的就是「忙不忙 + 最近一句摘要」。
228
+ return {
229
+ found: true,
230
+ status: status.status,
231
+ alive: status.alive,
232
+ label: status.label,
233
+ lastMessage: status.lastMessage,
234
+ hint: statusHint(status.status, status.alive),
235
+ };
236
+ },
237
+ });
238
+ }
239
+ /** `post_message({ sessionId, content })` → `{ accepted, hint }` / `{ rejected, hint }` */
240
+ function post_messageTool(port) {
241
+ return new CallbackTool({
242
+ function: {
243
+ name: POST_MESSAGE_TOOL,
244
+ description: [
245
+ "Post a message to another session (one created by create_session, or any session I know",
246
+ "the id of) — it is how I talk to that side instead of opening a new one. Whoever it is,",
247
+ "the message is accepted as long as that session exists and has a live agent: posting",
248
+ "does not depend on how the two of us are related.",
249
+ "The call returns whether the message was taken. It does not wait for anything: no answer",
250
+ "comes back here and nothing is delivered to me automatically — when that side has",
251
+ "something to tell me it posts a message to me itself.",
252
+ "Do not poll it: how it acts on the message is its own business, and read_session_status",
253
+ "only tells me which state it is in at that moment.",
254
+ "If I no longer remember the `sessionId`, the `label` returned by create_session is how I",
255
+ "identify that session.",
256
+ ].join(" "),
257
+ parameters: {
258
+ type: "object",
259
+ properties: {
260
+ sessionId: {
261
+ type: "string",
262
+ description: "The sessionId returned by create_session (that is the peer session's own id)",
263
+ },
264
+ content: {
265
+ type: "string",
266
+ description: "What to say to that side. Write it as a self-contained instruction: it cannot see " +
267
+ "this session, it only has its own history.",
268
+ },
269
+ },
270
+ required: ["sessionId", "content"],
271
+ additionalProperties: false,
272
+ },
273
+ },
274
+ callback: async (input, ctx) => {
275
+ const sent = await port.send({
276
+ caller: ctx.agent,
277
+ sessionId: typeof input.sessionId === "string" ? input.sessionId : "",
278
+ content: typeof input.content === "string" ? input.content : String(input.content ?? ""),
279
+ });
280
+ // 结构化拒绝:模型能按字段分支,不用去读自由文本
281
+ if (!sent.ok)
282
+ return { rejected: sent.reason, hint: SEND_REJECT_HINTS[sent.reason] };
283
+ return { accepted: true, hint: SEND_ACCEPTED_HINT };
284
+ },
285
+ });
286
+ }
287
+ /** 可选的字符串参数:空串与非字符串都当作「没给」,不往端口里塞一个假值 */
288
+ function optionalString(key, value) {
289
+ if (typeof value !== "string" || value.length === 0)
290
+ return {};
291
+ return { [key]: value };
292
+ }
@@ -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 时构建,从而复用统一的委派边界
13
- * (onSubAgentStart / onSubAgentEnd 钩子与 sub-agent-start / sub-agent-end 事件)。
14
- * 子 Agent 沿用父 Agent 的工具能力(不做权限过滤),但剔除 call_skill_sub_agent 自身,
15
- * 避免 skill 链式自递归。
15
+ * 工具由 AgentToolLazy 承载:subagent 在 exec 时构建,从而复用统一的委派边界
16
+ * (onSubAgentStart / onSubAgentEnd 钩子与 subAgentStarted / subAgentFinished 事件)。
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 时构建,从而复用统一的委派边界
78
- * (onSubAgentStart / onSubAgentEnd 钩子与 sub-agent-start / sub-agent-end 事件)。
79
- * 子 Agent 沿用父 Agent 的工具能力(不做权限过滤),但剔除 call_skill_sub_agent 自身,
80
- * 避免 skill 链式自递归。
80
+ * 工具由 AgentToolLazy 承载:subagent 在 exec 时构建,从而复用统一的委派边界
81
+ * (onSubAgentStart / onSubAgentEnd 钩子与 subAgentStarted / subAgentFinished 事件)。
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);
@@ -112,7 +113,8 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
112
113
  },
113
114
  },
114
115
  // 初始消息依赖运行时参数(skill_id → SKILL.md 内容),故不传 messages 模板,
115
- // 由 buildAgent 读取 SKILL.md 后自行决定;abort 联动与委派边界由 AgentToolLazy 统一处理
116
+ // 由 buildAgent 读取 SKILL.md 后自行决定;中断信号与委派边界由 AgentToolLazy 统一处理
117
+ // (父的 `abort` 直接把 signal 交给 subagent 的 `runOnce`)
116
118
  buildAgent: async (parsedArgs, ctx) => {
117
119
  const skillId = parsedArgs.skill_id;
118
120
  const task = parsedArgs.task;
@@ -120,7 +122,7 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
120
122
  if (!allowedIds.has(skillId)) {
121
123
  throw new Error(`❌ Skill "${skillId}" is not available here. Available SubAgent skills: ${ids.join(", ") || "(none)"}`);
122
124
  }
123
- const skill = await readSkill(skillDirs, skillId);
125
+ const skill = await readSkill(skillDirs, skillId, { logger });
124
126
  if (!skill) {
125
127
  throw new Error(`❌ Skill "${skillId}" not found, please verify the name`);
126
128
  }
@@ -129,13 +131,19 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
129
131
  }
130
132
  // 沿用父 Agent 的工具能力(不做权限过滤),剔除自身以防自递归
131
133
  const parentAgent = ctx.agent;
132
- 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));
133
139
  return new Agent({
134
140
  client: parentAgent.client,
135
141
  model: parentAgent.model,
136
142
  modelConfig: parentAgent.modelConfig,
137
143
  messages: [Message.System(skill.content), Message.User(task)],
138
144
  tools,
145
+ // 一次性委派(`CORE.md` §9):跑完就死透,不与父会话共用寿命。
146
+ lifetime: "one-shot",
139
147
  });
140
148
  },
141
149
  });
@@ -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 {