@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,145 @@
1
+ import { AgentNS } from "@ai-zen/agents-core";
2
+ import { fileToContentSection, resolveModelAndEndpoint } from "../shared/content-blocks.js";
3
+ /** 段上的本地标记:内容段里指回宿主素材行的 id(PRD 原文:`__asset_id` 只是本地标记) */
4
+ const ASSET_ID_KEY = "__asset_id";
5
+ /**
6
+ * 附件传输插件 —— 发出去之前把带 `__asset_id` 的段按**当前生效的模型与端点**重建成厂商要的形状。
7
+ *
8
+ * 内容在库里只有一份(落库那份就是原本那份,一个字都不清理:prompt caching 要的是前后两次请求
9
+ * 的前缀逐字一致);`__asset_id` 那一段只是「这是本地的哪一份素材」,出网的那一份每次现造:
10
+ *
11
+ * | 这一份素材 | 发出去的样子 |
12
+ * |---|---|
13
+ * | 端点声明了 `capabilities.filesApi` | `file` 段 + `file_id`(每次调用都真上传,不复用上一份 id) |
14
+ * | 其余端点 + 图片 | `image_url` + base64 data URL |
15
+ * | 模型看不见图(`vision !== true`) | 一段文本提示,并把 warning 单独说清 |
16
+ * | 素材已不在 / 重建失败 / 上传失败 | 一段说得清的文本,**不重试** |
17
+ *
18
+ * ## 为什么落在 `onInnerLoopStart`,而不是 `formatContentSection`
19
+ *
20
+ * 后者是 core 拼请求体时用的格式化层,**同步**;而重建要读字节(宿主那边是一次文件读取)、
21
+ * 还可能上传一次 —— 只能异步。`onInnerLoopStart` 恰恰是异步的,而且按 core 的注释它本来就
22
+ * 允许改这一次要发出去的请求体(`ctx.body` 是「这一次请求」的唯一一份)。
23
+ *
24
+ * ## 为什么这里不拒(`onInnerLoopStart` 是能拒的钩子)
25
+ *
26
+ * 拒了等于整次请求不发。需求要的是「失败就报失败、不重试…绝不假成功,全失败就退回纯文本并说
27
+ * 清楚」:一段发不出去就换成一句话说明,别的段与这条消息本身照发。所以这个插件**永远不返回判决**。
28
+ *
29
+ * ## 素材字节从哪来
30
+ *
31
+ * 只有 `deps.readAsset` 一个口:素材库是宿主的财产(行、字节、引用关系都在它那儿),SDK 只认
32
+ * 这一个函数。没有注入它就等于「哪一份都取不到」—— 每一段都会退化成一句「已不在」,这比抛错
33
+ * 好(请求照发),也比假装成功好。
34
+ */
35
+ export class AssetTransportPlugin {
36
+ options;
37
+ constructor(options) {
38
+ this.options = options;
39
+ }
40
+ async onInnerLoopStart(ctx) {
41
+ const sent = ctx.body.messages;
42
+ // 一条一条配上它在记忆里的那一份(`__asset_id` 只在那儿,见 `pairWithSources`)
43
+ const sources = pairWithSources(sent, ctx.agent.messages);
44
+ // 一句素材引用都没有:这一次请求体一个字都不动(连换一个段对象都不做)
45
+ if (!sources.some((source) => hasAssetSection(source.content)))
46
+ return;
47
+ // 端点与模型**现读**:`file_id` 是端点维度资源,传错端点会得到 not found
48
+ const { model, endpoint } = resolveModelAndEndpoint(this.options.config(), ctx.agent.model);
49
+ for (let index = 0; index < sources.length; index += 1) {
50
+ const source = sources[index];
51
+ if (!Array.isArray(source.content))
52
+ continue;
53
+ const target = sent[index];
54
+ if (typeof target !== "object" || target === null)
55
+ continue;
56
+ const formatted = target.content;
57
+ // 段数对不上就不动这一条(理由同 `pairWithSources`:宁可不换,不硬套)
58
+ if (!Array.isArray(formatted) || formatted.length !== source.content.length)
59
+ continue;
60
+ const sections = [];
61
+ let rebuilt = false;
62
+ for (let at = 0; at < source.content.length; at += 1) {
63
+ const local = source.content[at];
64
+ const outgoing = formatted[at];
65
+ const assetId = assetIdOf(local);
66
+ // 位置对不上(出网那一段的类型与库里那一段不同)就不换这一处:发一段空的引用,
67
+ // 也好过把别的段顶掉
68
+ if (assetId === null || typeOf(outgoing) !== local.type) {
69
+ sections.push(outgoing);
70
+ continue;
71
+ }
72
+ rebuilt = true;
73
+ sections.push(...(await this.transport(assetId, model, endpoint)));
74
+ }
75
+ if (rebuilt)
76
+ target.content = sections;
77
+ }
78
+ }
79
+ /**
80
+ * 一段素材 → 这一次能发出去的那一段(可能的产物是两段:说清 warning 的那一句 + 文本提示)。
81
+ *
82
+ * 三种结局都不抛:这里抛出去会把整次请求打断,而需求要的是「全失败就退回纯文本并说清楚」。
83
+ * 上传失败也一样 —— **不重试**(换一种传输方式偷偷再试一次,用户就不知道发出去的到底是
84
+ * 哪一份了)。
85
+ */
86
+ async transport(assetId, model, endpoint) {
87
+ const asset = this.options.deps.readAsset?.(assetId);
88
+ if (asset === undefined)
89
+ return [text(`附件 ${assetId} 已不在(可能被删了)`)];
90
+ try {
91
+ const result = await fileToContentSection({
92
+ source: { data: asset.bytes, mime: asset.mime, filename: asset.name },
93
+ endpoint,
94
+ model,
95
+ deps: this.options.deps,
96
+ });
97
+ // 退化成文本(模型看不见图):把原因单独说清 —— 那一段文本本身只说「当前模型不支持图片
98
+ // 输入」,用户还得知道「这张图因此没被发出去」这件事从哪来
99
+ if (result.warning === undefined)
100
+ return [result.section];
101
+ return [text(`附件 ${asset.name ?? assetId}:${result.warning}`), result.section];
102
+ }
103
+ catch (error) {
104
+ return [text(`附件 ${asset.name ?? assetId} 无法发送:${messageOf(error)}`)];
105
+ }
106
+ }
107
+ }
108
+ /**
109
+ * 这一次要发出去的每一条消息,配上它在**记忆里**的那一份。
110
+ *
111
+ * 为什么要配:`ctx.body.messages` 是 core 的 `formatHistory()` 的产物 —— 它按字段白名单重建每
112
+ * 一段,`__asset_id`(本机扩展键)在那一步就没了。也就是说请求体里**认不出**哪一段是素材引用,
113
+ * 认得出的只有 `agent.messages` 里那一条(落库那份原样带着它)。
114
+ *
115
+ * 两份一对一:`formatHistory` 只筛消息(`status` 是完成了的、`omit` 没立起来的),既不重排消息
116
+ * 也不重排段。所以按下标配就够。
117
+ *
118
+ * 条数对不上就返回空(这一次一条都不换,不猜):那说明 core 那一侧的筛法变了,此时按位置硬套
119
+ * 会把 A 消息的素材塞进 B 消息里 —— 发出去是一张别人的图,比「没重建」坏得多。
120
+ */
121
+ function pairWithSources(sent, messages) {
122
+ // 这三个条件就是 core 的 `formatHistory` 那一条筛法(`Agent.formatHistory`)
123
+ const sources = messages.filter((message) => (message.status === undefined || message.status === AgentNS.MessageStatus.Completed) &&
124
+ !message.omit);
125
+ return sources.length === sent.length ? sources : [];
126
+ }
127
+ /** 这一段是不是一份素材引用 */
128
+ function hasAssetSection(content) {
129
+ return Array.isArray(content) && content.some((section) => assetIdOf(section) !== null);
130
+ }
131
+ function assetIdOf(section) {
132
+ const assetId = section[ASSET_ID_KEY];
133
+ return typeof assetId === "string" ? assetId : null;
134
+ }
135
+ function typeOf(section) {
136
+ if (typeof section !== "object" || section === null)
137
+ return undefined;
138
+ return section.type;
139
+ }
140
+ function text(content) {
141
+ return { type: "text", text: content };
142
+ }
143
+ function messageOf(error) {
144
+ return error instanceof Error ? error.message : String(error);
145
+ }
@@ -1,5 +1,6 @@
1
- import type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
1
+ import type { AgentPlugin, OuterLoopContext } from "@ai-zen/agents-core";
2
2
  import type { HandoffMode, HandoffService } from "../runtime/HandoffService.js";
3
+ import { type LogSink } from "../shared/logger.js";
3
4
  /** 触发迁移时的用量信息(供执行者选择、确认文案使用) */
4
5
  export interface AutoMigrateTriggerInfo {
5
6
  /** 当前 prompt token 用量 */
@@ -25,6 +26,35 @@ export interface AutoMigrateOptions {
25
26
  * 或直接返回 `null` 表达「本次不迁移」——**无需**再继承本插件。
26
27
  */
27
28
  resolveMode?: AutoMigrateModeResolver;
29
+ /**
30
+ * 迁移完成之后的回声(可选):`mode` 是这一趟用的执行者。宿主据此落「这段会话压缩过」这类
31
+ * 观测事实 —— 插件自己不认识存储层。
32
+ *
33
+ * 钩子抛错就让这一次迁移报错(本插件不接):写钩子的是宿主,它写崩了该在自己的调用栈里
34
+ * 炸出来,而不是被吞成一行日志。
35
+ */
36
+ onMigrated?: (info: AutoMigrateTriggerInfo & {
37
+ mode: HandoffMode;
38
+ }) => void | Promise<void>;
39
+ /**
40
+ * 迁移**没成**的回声(可选):模型没有写出来、写出来不够长、落库失败、端点 4xx……
41
+ *
42
+ * **取消不算失败**(用户按了停那条不叫它):那是回到交接前,没什么要收尾的。
43
+ * 宿主拿它把输出闸开回来 —— 闸是交接那一批的批头关上的,而开闸只有宿主能决定
44
+ * (SDK 不认识「记忆换完了」这件事,见 `HandoffService.runHandoff` 的注释)。
45
+ *
46
+ * 钩子抛错就让这一次迁移报错(本插件不接):这一道是「把闸开回来」的唯一一道门,
47
+ * 它自己崩了被吞成一行日志,闸就可能一直关着。
48
+ */
49
+ onFailed?: (info: AutoMigrateTriggerInfo & {
50
+ error: unknown;
51
+ }) => void | Promise<void>;
52
+ /**
53
+ * 日志口(可选):迁移失败且没有被回应声接住的那一条从前走全局日志,现在从这里出去。
54
+ *
55
+ * 不注入就不记 —— 库不替调用方往 stdout 写(宿主注入自己那份,带上来源标签)。
56
+ */
57
+ logger?: LogSink;
28
58
  }
29
59
  /**
30
60
  * 自动迁移插件 —— 只负责「何时触发」,实际迁移统一委托给持有的 `HandoffService`。
@@ -40,13 +70,33 @@ export interface AutoMigrateOptions {
40
70
  * }));
41
71
  * ```
42
72
  *
43
- * 两层让行(缺一不可):
44
- * - `service.busy`:交接回合本身就是一次 `send()`,其 `onAfterSend` 会再次到这里;
45
- * 不跳过就会「交接触发迁移 → 迁移再交接」无限递归;
46
- * - 交接回合结束后的用量也仍可能超阈值,故 busy 判断必须覆盖整个交接 + 迁移过程。
73
+ * ## 为什么落在 `onIdle`(旧的 `onAfterSend` 已删除)
74
+ *
75
+ * 迁移是「**彻底不动了才做**」的事:它要在原会话里再跑一个交接回合写文档,换记忆则在
76
+ * 宿主那一侧(服务只管产出文档)。「这一次回答完了」还不够 ——
77
+ * 内循环可能还要接着跑工具、队列里可能还压着别的投递,那些都还在写同一个数组。
78
+ * `onIdle` 的语义正是「手上没活、队列也空」(`CORE.md` §4),此刻开工才不会
79
+ * 踩到正在跑的那一次请求;而 `onOuterLoopEnd` 只保证「这一批跑完了」,队列里可能还有货。
80
+ *
81
+ * ## 两层让行(缺一不可)
82
+ * - `service.handingOff`:交接回合本身就是「往同一个 agent 里再投一次」,它跑完后 agent 又会
83
+ * 变闲一次,`onIdle` 会再次到这里;不跳过就会「交接触发交接 → 交接再交接」无限递归;
84
+ * - 交接回合结束后的用量也仍可能超阈值,故 handingOff 判断必须覆盖整个交接过程。
85
+ *
86
+ * ## `onIdle()` 不带 ctx:agent 从 `onOuterLoopStart` 认领
87
+ *
88
+ * core 的死活钩子(`onIdle` / `onStart` / `onStop` …)没有参数,而交接必须有 agent。
89
+ * 于是这里在 `onOuterLoopStart`(每一批事件开头必到,且排在 `onIdle` 之前)把 agent
90
+ * 记下来 —— 那一步只做登记,不做任何判断。
47
91
  */
48
92
  export declare class AutoMigratePlugin implements AgentPlugin {
49
93
  private options;
94
+ /** 日志口(构造时定下缺省:不注入就是 {@link SILENT_LOG}) */
95
+ private readonly logger;
96
+ /** 认领到的 agent(见类注释最后一段:`onIdle()` 不带 ctx) */
97
+ private agent?;
50
98
  constructor(options: AutoMigrateOptions);
51
- onAfterSend(ctx: SendContext): Promise<void>;
99
+ /** 只登记 agent:`onIdle()` 没有 ctx,而交接需要它。不做任何判断。 */
100
+ onOuterLoopStart(ctx: OuterLoopContext): void;
101
+ onIdle(): Promise<void>;
52
102
  }
@@ -1,5 +1,7 @@
1
+ import { AgentError } from "@ai-zen/agents-core";
1
2
  import { HandoffAbortedError } from "../runtime/HandoffService.js";
2
- import { getLogger } from "../shared/logger.js";
3
+ import { lastPromptTokens } from "../runtime/lastPromptTokens.js";
4
+ import { SILENT_LOG } from "../shared/logger.js";
3
5
  /**
4
6
  * 自动迁移插件 —— 只负责「何时触发」,实际迁移统一委托给持有的 `HandoffService`。
5
7
  *
@@ -14,39 +16,86 @@ import { getLogger } from "../shared/logger.js";
14
16
  * }));
15
17
  * ```
16
18
  *
17
- * 两层让行(缺一不可):
18
- * - `service.busy`:交接回合本身就是一次 `send()`,其 `onAfterSend` 会再次到这里;
19
- * 不跳过就会「交接触发迁移 → 迁移再交接」无限递归;
20
- * - 交接回合结束后的用量也仍可能超阈值,故 busy 判断必须覆盖整个交接 + 迁移过程。
19
+ * ## 为什么落在 `onIdle`(旧的 `onAfterSend` 已删除)
20
+ *
21
+ * 迁移是「**彻底不动了才做**」的事:它要在原会话里再跑一个交接回合写文档,换记忆则在
22
+ * 宿主那一侧(服务只管产出文档)。「这一次回答完了」还不够 ——
23
+ * 内循环可能还要接着跑工具、队列里可能还压着别的投递,那些都还在写同一个数组。
24
+ * `onIdle` 的语义正是「手上没活、队列也空」(`CORE.md` §4),此刻开工才不会
25
+ * 踩到正在跑的那一次请求;而 `onOuterLoopEnd` 只保证「这一批跑完了」,队列里可能还有货。
26
+ *
27
+ * ## 两层让行(缺一不可)
28
+ * - `service.handingOff`:交接回合本身就是「往同一个 agent 里再投一次」,它跑完后 agent 又会
29
+ * 变闲一次,`onIdle` 会再次到这里;不跳过就会「交接触发交接 → 交接再交接」无限递归;
30
+ * - 交接回合结束后的用量也仍可能超阈值,故 handingOff 判断必须覆盖整个交接过程。
31
+ *
32
+ * ## `onIdle()` 不带 ctx:agent 从 `onOuterLoopStart` 认领
33
+ *
34
+ * core 的死活钩子(`onIdle` / `onStart` / `onStop` …)没有参数,而交接必须有 agent。
35
+ * 于是这里在 `onOuterLoopStart`(每一批事件开头必到,且排在 `onIdle` 之前)把 agent
36
+ * 记下来 —— 那一步只做登记,不做任何判断。
21
37
  */
22
38
  export class AutoMigratePlugin {
23
39
  options;
40
+ /** 日志口(构造时定下缺省:不注入就是 {@link SILENT_LOG}) */
41
+ logger;
42
+ /** 认领到的 agent(见类注释最后一段:`onIdle()` 不带 ctx) */
43
+ agent;
24
44
  constructor(options) {
25
45
  this.options = options;
46
+ this.logger = options.logger ?? SILENT_LOG;
26
47
  }
27
- async onAfterSend(ctx) {
28
- const agent = ctx.agent;
29
- const { service, handoffTokens, resolveMode } = this.options;
30
- // 交接/迁移进行中:让行(防递归)
31
- if (service.busy)
48
+ /** 只登记 agent:`onIdle()` 没有 ctx,而交接需要它。不做任何判断。 */
49
+ onOuterLoopStart(ctx) {
50
+ this.agent = ctx.agent;
51
+ }
52
+ async onIdle() {
53
+ const agent = this.agent;
54
+ if (!agent)
55
+ return;
56
+ const { service, handoffTokens, resolveMode, onMigrated, onFailed } = this.options;
57
+ // 交接进行中(本服务这一趟还在跑):让行(防递归)
58
+ if (service.handingOff)
32
59
  return;
33
- const promptTokens = agent.lastUsage?.prompt_tokens;
60
+ // 上一次回答的 prompt 用量:只从消息上读(与 `ContextGuardPlugin` 同一份事实、同一个读法)
61
+ const promptTokens = lastPromptTokens(agent);
34
62
  if (promptTokens == null)
35
63
  return;
36
64
  if (promptTokens <= handoffTokens)
37
65
  return;
66
+ // 迁移本身(写文档 + 换记忆)失败:报一句、把失败回声叫起来
67
+ let migrated;
38
68
  try {
39
69
  const mode = resolveMode ? await resolveMode({ promptTokens, handoffTokens }) : undefined;
40
70
  if (mode === null)
41
- return; // 用户选择跳过本次迁移
42
- await service.migrate({ agent, promptTokens, handoffTokens, mode: mode ?? undefined });
71
+ return; // 用户选择跳过本次交接
72
+ // 自动交接走 `migrate()`:**写文档 + 换记忆**。记忆长什么样只有 SDK 这一处算,
73
+ // 落在哪儿看服务有没有注入落库接缝(宿主注入了,于是它落库、落内存;外部使用者没注入,
74
+ // 于是 SDK 自己换 `agent.messages`)—— 不是两套实现,是同一份结果两个落点。
75
+ migrated = await service.migrate({
76
+ agent,
77
+ promptTokens,
78
+ handoffTokens,
79
+ mode: mode ?? undefined,
80
+ });
43
81
  }
44
82
  catch (err) {
45
83
  // 用户主动取消不是失败:服务已把会话退回交接前,这里再报错只会在界面上
46
- // 凭空多一条「迁移失败」(默认 logger 是 console.error,TUI 下直接撕画面)
84
+ // 凭空多一条「迁移失败」(日志口是注入的,宿主那格可能是终端)
47
85
  if (err instanceof HandoffAbortedError)
48
86
  return;
49
- getLogger().error(`[autoMigrate] migration failed: ${err?.message ?? err}`);
87
+ // agent 已经关门/被硬杀(`stop()` / `kill()` 之后又走到 idle):没什么可交接的。
88
+ // 不报错、也不换执行者 —— 那会为一个已经没有的会话白烧一次全量输入。
89
+ if (err instanceof AgentError && err.code === "closed")
90
+ return;
91
+ this.logger.error(`[autoMigrate] handoff failed: ${err?.message ?? err}`);
92
+ // 失败回声是「把闸开回来」的那一道:它自己抛错不在这里接,让它在这个调用栈里炸出来
93
+ await onFailed?.({ promptTokens, handoffTokens, error: err });
94
+ return;
50
95
  }
96
+ // 记忆已经换完:这时候才报「压过了」(实际执行者以服务报的为准)。
97
+ // 它故意留在上面那个 try 之外:回声自己崩了不是「交接失败」,不该被当成失败再报一遍
98
+ // 失败回声 —— 它就在这个调用栈里炸出来(与 `commitMemory` 同一个口径)。
99
+ await onMigrated?.({ promptTokens, handoffTokens, mode: migrated.mode });
51
100
  }
52
101
  }
@@ -1,4 +1,4 @@
1
- import type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
1
+ import type { AgentPlugin, InnerLoopContext, OuterLoopContext } from "@ai-zen/agents-core";
2
2
  /**
3
3
  * 自动刷新能力的时机。
4
4
  *
@@ -6,13 +6,16 @@ import type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
6
6
  *
7
7
  * | 档位 | 钩子 | 会话中新装的 MCP / skill / 工具什么时候能被模型看见 |
8
8
  * |------|------|---------------------------------------------|
9
- * | `inner-loop-start` | `onInnerLoopStart`(每次请求发出前) | 同一轮里下一次请求就看见(含工具回合的空档) |
10
- * | `outer-loop-start` | `onBeforeSend`(整个 `send()` 开头) | 下一轮对话才看见;一轮只刷一次,开销最小 |
9
+ * | `inner-loop-start` | `onInnerLoopStart`(每次请求发出前) | 这一次回答里的下一次请求就看见(含工具回合的空档) |
10
+ * | `outer-loop-start` | `onOuterLoopStart`(每一批事件开头,一批只刷一次) | 下一次被叫起来才看见;一批只刷一次,开销最小 |
11
11
  * | `off` | 不装插件 | 只靠 `/reload` |
12
12
  *
13
- * 为什么不是「每轮固定刷一次」:一次 `refresh()` 会重扫 MCP 配置、按需建连接,
14
- * 长工具链的一轮里可能要跑好几次。默认 `inner-loop-start` 是时效优先的取舍,
13
+ * 为什么不是「每次请求固定刷一次」:一次 `refresh()` 会重扫 MCP 配置、按需建连接,
14
+ * 一条长工具链里可能要跑好几次。默认 `inner-loop-start` 是时效优先的取舍,
15
15
  * 嫌开销大就换成 `outer-loop-start`。
16
+ *
17
+ * 档位名沿用 `outer-loop-start`(配置里写着它):它映射到的钩子就是 core 的外循环开头
18
+ * —— 原来是 `onBeforeSend`(一次 `send()` 的开头),而 `send()` 已经不存在了。
16
19
  */
17
20
  export type AutoRefreshWhen = "inner-loop-start" | "outer-loop-start";
18
21
  /**
@@ -32,8 +35,8 @@ export declare class AutoRefreshToolsPlugin implements AgentPlugin {
32
35
  constructor(options?: {
33
36
  when?: AutoRefreshWhen;
34
37
  });
35
- /** 内循环开始(每次请求前):能力变化在同一轮里就能生效 */
36
- onInnerLoopStart(ctx: SendContext): Promise<void>;
37
- /** 外循环开始(整个 `send()` 一次):最省,代价是要等到下一轮 */
38
- onBeforeSend(ctx: SendContext): Promise<void>;
38
+ /** 内循环开始(每次请求前):能力变化在同一次回答里就能生效 */
39
+ onInnerLoopStart(ctx: InnerLoopContext): Promise<void>;
40
+ /** 外循环开始(这一批事件的开头):最省,代价是要等到下一次被叫起来 */
41
+ onOuterLoopStart(ctx: OuterLoopContext): Promise<void>;
39
42
  }
@@ -15,22 +15,21 @@ export class AutoRefreshToolsPlugin {
15
15
  constructor(options = {}) {
16
16
  this.when = options.when ?? "inner-loop-start";
17
17
  }
18
- /** 内循环开始(每次请求前):能力变化在同一轮里就能生效 */
18
+ /** 内循环开始(每次请求前):能力变化在同一次回答里就能生效 */
19
19
  async onInnerLoopStart(ctx) {
20
20
  if (this.when !== "inner-loop-start")
21
21
  return;
22
- await refreshTools(ctx);
22
+ await refreshTools(ctx.agent);
23
23
  }
24
- /** 外循环开始(整个 `send()` 一次):最省,代价是要等到下一轮 */
25
- async onBeforeSend(ctx) {
24
+ /** 外循环开始(这一批事件的开头):最省,代价是要等到下一次被叫起来 */
25
+ async onOuterLoopStart(ctx) {
26
26
  if (this.when !== "outer-loop-start")
27
27
  return;
28
- await refreshTools(ctx);
28
+ await refreshTools(ctx.agent);
29
29
  }
30
30
  }
31
31
  /** 重新发现 + 按新结果重建工具集(两个档位共用同一段,免得两处漂) */
32
- async function refreshTools(ctx) {
33
- const agent = ctx.agent;
32
+ async function refreshTools(agent) {
34
33
  await agent.scope.refresh({ silent: true });
35
34
  agent.tools = agent.scope.buildTools(agent.definition, {
36
35
  exclude: {
@@ -1,46 +1,54 @@
1
- import type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
1
+ import type { AgentPlugin, InnerLoopContext } from "@ai-zen/agents-core";
2
2
  export interface ContextGuardOptions {
3
3
  /**
4
4
  * 强行阻断阈值(tokens,绝对值)。
5
5
  *
6
- * 语义只有一条:请求前上一轮用量超过它 → 中断本轮。没有倍数、没有放宽档——
6
+ * 语义只有一条:请求前上一次回答的用量超过它 → 中断这一次请求。没有倍数、没有放宽档——
7
7
  * 想调松就把它调大,「安全边界写多少就是多少」比「隐式乘以某个系数」可预测得多。
8
- */
9
- guardTokens: number;
10
- /**
11
- * 临时让行:返回 `true` 时本轮不做超限判定(默认 `false`)。
12
8
  *
13
- * 用于交接/迁移回合 —— 那些回合本身就是「上下文已满」时才发起的,若不放宽必定被打回。
14
- * 语义是「谁做限制谁放宽」:限制在护栏自己身上,放宽也必须由护栏自己表达,
15
- * 而不是由调用方去改写用量数据。典型接线:`isSuspended: () => handoffService.busy`。
9
+ * 这一格可以是一个 getter(`get guardTokens(): number`):那样每次判定都现读,改阈值不必
10
+ * 重建执行体(两条阈值改了不重建 agent,见 `dev-docs/prd/05-control.md`)。
16
11
  */
17
- isSuspended?: () => boolean;
12
+ guardTokens: number;
18
13
  }
19
14
  /**
20
15
  * 上下文安全护栏插件。
21
16
  *
22
- * 在每次内循环**发请求前**检测上一轮用量(usage.prompt_tokens):超过 `guardTokens`
23
- * 即抛 `ContextOverflowError` 中断对话,交由上层向用户报错。
17
+ * 在每次内循环**发请求前**检测上一次回答的用量(usage.prompt_tokens):超过 `guardTokens`
18
+ * 就**拒绝这一次请求**,交由上层向用户报错。
24
19
  *
25
- * 与迁移插件职责分离:
26
- * - `ContextGuardPlugin`:硬线,只做「严重超限即中断」的安全兜底,绝不继续对话/迁移;
27
- * - `AutoMigratePlugin`:软线(`tokenThresholds.handoff`),在正常范围内做交接迁移。
20
+ * 与自动交接插件职责分离:
21
+ * - `ContextGuardPlugin`:硬线,只做「严重超限即中断」的安全兜底,绝不继续会话/交接;
22
+ * - `AutoMigratePlugin`:软线(`tokenThresholds.handoff`),在正常范围内做自动交接。
28
23
  * 两条线都是绝对值,`guard` 应当明显大于 `handoff`,交接回合的额外请求才有余量。
29
24
  *
30
25
  * ```ts
31
26
  * const { handoff, guard } = config.models[i].tokenThresholds;
32
- * agent.use(
33
- * new ContextGuardPlugin({
34
- * guardTokens: guard,
35
- * isSuspended: () => handoffService.busy, // 交接回合让行
36
- * }),
37
- * );
27
+ * agent.use(new ContextGuardPlugin({ guardTokens: guard }));
38
28
  * agent.use(new AutoMigratePlugin({ service: handoffService, handoffTokens: handoff }));
39
29
  * ```
30
+ *
31
+ * ## 交接那一趟也不让路
32
+ *
33
+ * 需求拍定的是**交接那一次请求也不让路**:硬线照旧拦,要避免撞线就把阈值配得够宽。所以这里
34
+ * 没有、也不该有「交接回合让行」的开关 —— 此前那一格(`isSuspended`)的全部用途就是让交接
35
+ * 回合绕过硬线,留着它等于留一个能把硬线关掉的开关。
36
+ *
37
+ * ## 为什么是「返回字符串」而不是「抛错」
38
+ *
39
+ * 新 core(`CORE.md` §11)里 `onInnerLoopStart` 能拒:**返回 string = 这一次请求压根没发出去**
40
+ * —— 不会留下一类「永远 Pending 的助手占位」,core 报一个 `denied` 事件(带钩子名与理由),
41
+ * 然后回外循环等下一个事件,循环还活着。
42
+ *
43
+ * 抛错不是「更硬的拒绝」:钩子里的异常会穿到 `start()` 外面,把整个循环打死
44
+ * (`start()` 的 promise 直接 resolve、循环不再取件),agent 从此变成「塞进去也不动」的
45
+ * 僵尸。这也是为什么老的「抛 `ContextOverflowError` 让上层接住」不能照搬 —— 上层现在能从
46
+ * `denied` 事件和 `message` 的历史里看到同一件事,不需要一个把 agent 弄死的异常。
40
47
  */
41
48
  export declare class ContextGuardPlugin implements AgentPlugin {
42
- private readonly guardTokens;
43
- private readonly isSuspended?;
49
+ private readonly options;
50
+ /** 选项按**引用**存下:阈值每次判定现读(它可能是一个 getter),不存装配那一刻的快照 */
44
51
  constructor(options: ContextGuardOptions);
45
- onInnerLoopStart(ctx: SendContext): Promise<void>;
52
+ /** 返回 string = 拒这一次请求(这一次不会发出去,历史里一个字都不多) */
53
+ onInnerLoopStart(ctx: InnerLoopContext): Promise<string | undefined>;
46
54
  }
@@ -1,43 +1,58 @@
1
1
  import { ContextOverflowError } from "../shared/errors.js";
2
+ import { lastPromptTokens } from "../runtime/lastPromptTokens.js";
2
3
  /**
3
4
  * 上下文安全护栏插件。
4
5
  *
5
- * 在每次内循环**发请求前**检测上一轮用量(usage.prompt_tokens):超过 `guardTokens`
6
- * 即抛 `ContextOverflowError` 中断对话,交由上层向用户报错。
6
+ * 在每次内循环**发请求前**检测上一次回答的用量(usage.prompt_tokens):超过 `guardTokens`
7
+ * 就**拒绝这一次请求**,交由上层向用户报错。
7
8
  *
8
- * 与迁移插件职责分离:
9
- * - `ContextGuardPlugin`:硬线,只做「严重超限即中断」的安全兜底,绝不继续对话/迁移;
10
- * - `AutoMigratePlugin`:软线(`tokenThresholds.handoff`),在正常范围内做交接迁移。
9
+ * 与自动交接插件职责分离:
10
+ * - `ContextGuardPlugin`:硬线,只做「严重超限即中断」的安全兜底,绝不继续会话/交接;
11
+ * - `AutoMigratePlugin`:软线(`tokenThresholds.handoff`),在正常范围内做自动交接。
11
12
  * 两条线都是绝对值,`guard` 应当明显大于 `handoff`,交接回合的额外请求才有余量。
12
13
  *
13
14
  * ```ts
14
15
  * const { handoff, guard } = config.models[i].tokenThresholds;
15
- * agent.use(
16
- * new ContextGuardPlugin({
17
- * guardTokens: guard,
18
- * isSuspended: () => handoffService.busy, // 交接回合让行
19
- * }),
20
- * );
16
+ * agent.use(new ContextGuardPlugin({ guardTokens: guard }));
21
17
  * agent.use(new AutoMigratePlugin({ service: handoffService, handoffTokens: handoff }));
22
18
  * ```
19
+ *
20
+ * ## 交接那一趟也不让路
21
+ *
22
+ * 需求拍定的是**交接那一次请求也不让路**:硬线照旧拦,要避免撞线就把阈值配得够宽。所以这里
23
+ * 没有、也不该有「交接回合让行」的开关 —— 此前那一格(`isSuspended`)的全部用途就是让交接
24
+ * 回合绕过硬线,留着它等于留一个能把硬线关掉的开关。
25
+ *
26
+ * ## 为什么是「返回字符串」而不是「抛错」
27
+ *
28
+ * 新 core(`CORE.md` §11)里 `onInnerLoopStart` 能拒:**返回 string = 这一次请求压根没发出去**
29
+ * —— 不会留下一类「永远 Pending 的助手占位」,core 报一个 `denied` 事件(带钩子名与理由),
30
+ * 然后回外循环等下一个事件,循环还活着。
31
+ *
32
+ * 抛错不是「更硬的拒绝」:钩子里的异常会穿到 `start()` 外面,把整个循环打死
33
+ * (`start()` 的 promise 直接 resolve、循环不再取件),agent 从此变成「塞进去也不动」的
34
+ * 僵尸。这也是为什么老的「抛 `ContextOverflowError` 让上层接住」不能照搬 —— 上层现在能从
35
+ * `denied` 事件和 `message` 的历史里看到同一件事,不需要一个把 agent 弄死的异常。
23
36
  */
24
37
  export class ContextGuardPlugin {
25
- guardTokens;
26
- isSuspended;
38
+ options;
39
+ /** 选项按**引用**存下:阈值每次判定现读(它可能是一个 getter),不存装配那一刻的快照 */
27
40
  constructor(options) {
28
- this.guardTokens = options.guardTokens;
29
- this.isSuspended = options.isSuspended;
41
+ this.options = options;
30
42
  }
43
+ /** 返回 string = 拒这一次请求(这一次不会发出去,历史里一个字都不多) */
31
44
  async onInnerLoopStart(ctx) {
32
- // 交接/迁移回合让行(见 `isSuspended`)
33
- if (this.isSuspended?.())
34
- return;
35
- const promptTokens = ctx.agent.lastUsage?.prompt_tokens;
36
- // 首轮请求前尚无用量数据,跳过(只能在发出首轮请求、拿到 usage 后才有据可查)
45
+ // 不看「此刻在不在交接」:交接那一趟也不让路,任何时刻都只看用量
46
+ const guardTokens = this.options.guardTokens;
47
+ // 上一次回答的 prompt 用量:只从消息上读(同一份事实、不另立快照,见 `lastPromptTokens`)
48
+ const promptTokens = lastPromptTokens(ctx.agent);
49
+ // 第一条请求之前尚无用量数据,跳过(只能在发出第一条请求、拿到 usage 后才有据可查)
37
50
  if (promptTokens == null)
38
51
  return;
39
- if (promptTokens > this.guardTokens) {
40
- throw new ContextOverflowError(promptTokens, this.guardTokens);
52
+ if (promptTokens > guardTokens) {
53
+ // 理由就是给用户看的那句话:`denied` 事件里只有字符串这一个通道,
54
+ // 所以用量与阈值一并写进去(`ContextOverflowError` 只用来拼这句话,不往外抛)
55
+ return new ContextOverflowError(promptTokens, guardTokens).message;
41
56
  }
42
57
  }
43
58
  }