@ai-zen/agents-sdk 1.0.0-alpha.9 → 1.0.0
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.
- package/CHANGELOG.md +651 -2
- package/README.md +22 -6
- package/README.zh.md +23 -7
- package/dist/agent-plugins/AutoMigratePlugin.d.ts +35 -9
- package/dist/agent-plugins/AutoMigratePlugin.js +21 -10
- package/dist/agent-plugins/AutoRefreshToolsPlugin.js +1 -3
- package/dist/agent-plugins/ContextGuardPlugin.d.ts +28 -16
- package/dist/agent-plugins/ContextGuardPlugin.js +23 -17
- package/dist/agent-plugins/UnknownToolHintPlugin.js +4 -4
- package/dist/config/ConfigManager.d.ts +57 -8
- package/dist/config/ConfigManager.js +167 -26
- package/dist/config/constants.d.ts +7 -0
- package/dist/config/constants.js +70 -43
- package/dist/config/factory-skills.d.ts +33 -0
- package/dist/config/factory-skills.js +126 -0
- package/dist/config/migrate.d.ts +106 -0
- package/dist/config/migrate.js +196 -0
- package/dist/config/reasoning-presets.d.ts +37 -0
- package/dist/config/reasoning-presets.js +64 -0
- package/dist/index.d.ts +13 -7
- package/dist/index.js +11 -3
- package/dist/runtime/HandoffGuardPlugin.d.ts +35 -0
- package/dist/runtime/HandoffGuardPlugin.js +65 -0
- package/dist/runtime/HandoffService.d.ts +246 -0
- package/dist/runtime/HandoffService.js +475 -0
- package/dist/runtime/SdkAgent.d.ts +7 -1
- package/dist/runtime/SdkAgent.js +3 -0
- package/dist/runtime/createAgent.d.ts +20 -1
- package/dist/runtime/createAgent.js +14 -9
- package/dist/runtime/createModel.d.ts +8 -4
- package/dist/runtime/createModel.js +22 -5
- package/dist/scope/PermissionEvaluator.js +1 -1
- package/dist/scope/Scope.d.ts +3 -1
- package/dist/scope/Scope.js +4 -2
- package/dist/scope/plugins/builtin/BatchEditTool.js +24 -14
- package/dist/scope/plugins/builtin/CopyTool.js +4 -4
- package/dist/scope/plugins/builtin/CwdTool.js +1 -1
- package/dist/scope/plugins/builtin/DownloadFileTool.d.ts +1 -0
- package/dist/scope/plugins/builtin/DownloadFileTool.js +58 -34
- package/dist/scope/plugins/builtin/EditTool.js +25 -25
- package/dist/scope/plugins/builtin/ExecTool.js +134 -25
- package/dist/scope/plugins/builtin/ExistTool.js +2 -2
- package/dist/scope/plugins/builtin/FindTextTool.js +15 -10
- package/dist/scope/plugins/builtin/GenerateImageTool.js +91 -25
- package/dist/scope/plugins/builtin/GlobTool.js +10 -5
- package/dist/scope/plugins/builtin/InspectFileTool.js +7 -7
- package/dist/scope/plugins/builtin/LsTool.js +5 -5
- package/dist/scope/plugins/builtin/MkdirTool.js +3 -3
- package/dist/scope/plugins/builtin/ReadTool.js +8 -8
- package/dist/scope/plugins/builtin/RenameTool.js +3 -3
- package/dist/scope/plugins/builtin/RmTool.js +3 -3
- package/dist/scope/plugins/builtin/SleepTool.js +6 -6
- package/dist/scope/plugins/builtin/SpawnTool.js +32 -49
- package/dist/scope/plugins/builtin/ViewImageTool.d.ts +6 -4
- package/dist/scope/plugins/builtin/ViewImageTool.js +50 -62
- package/dist/scope/plugins/builtin/WriteTool.js +3 -3
- package/dist/scope/plugins/builtin/searchBase.d.ts +9 -0
- package/dist/scope/plugins/builtin/searchBase.js +17 -0
- package/dist/scope/plugins/builtin/test-helpers.d.ts +3 -3
- package/dist/scope/plugins/builtin/test-helpers.js +3 -3
- package/dist/scope/plugins/builtin/textEdit.d.ts +17 -0
- package/dist/scope/plugins/builtin/textEdit.js +37 -0
- package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +9 -1
- package/dist/scope/plugins/mcp/McpConnectionManager.js +95 -16
- package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +1 -1
- package/dist/scope/plugins/mcp/McpScopePlugin.js +8 -6
- package/dist/scope/plugins/mcp/discover.js +1 -1
- package/dist/scope/plugins/mcp/mcpTools.d.ts +9 -3
- package/dist/scope/plugins/mcp/mcpTools.js +247 -37
- package/dist/scope/plugins/skills/SkillsScopePlugin.js +2 -3
- package/dist/scope/plugins/skills/discover.js +28 -9
- package/dist/scope/plugins/skills/skillTools.js +30 -20
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +1 -3
- package/dist/scope/plugins/subagents/subAgentTools.js +4 -3
- package/dist/scope/plugins/usertools/discover.d.ts +8 -3
- package/dist/scope/plugins/usertools/discover.js +139 -12
- package/dist/shared/EntityRepository.d.ts +10 -1
- package/dist/shared/EntityRepository.js +18 -6
- package/dist/shared/content-blocks.d.ts +101 -0
- package/dist/shared/content-blocks.js +253 -0
- package/dist/shared/errors.d.ts +4 -8
- package/dist/shared/errors.js +8 -14
- package/dist/types/index.d.ts +170 -8
- package/package.json +16 -7
- package/dist/runtime/TaskMigrationService.d.ts +0 -128
- package/dist/runtime/TaskMigrationService.js +0 -211
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
import { promises as fs } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve as resolvePath } from "node:path";
|
|
3
|
+
import { Message } from "@ai-zen/agents-core";
|
|
4
|
+
import { getLogger } from "../shared/logger.js";
|
|
5
|
+
import { readSkill } from "../scope/plugins/skills/discover.js";
|
|
6
|
+
import { FALLBACK_HANDOFF_TEMPLATE, HANDOFF_SKILL_ID } from "../config/factory-skills.js";
|
|
7
|
+
import { HandoffGuardPlugin } from "./HandoffGuardPlugin.js";
|
|
8
|
+
/**
|
|
9
|
+
* 交接被调用方取消(`AbortSignal` 触发)。
|
|
10
|
+
*
|
|
11
|
+
* 单独成类型而不是复用 `Error`,原因有两个:
|
|
12
|
+
* - 调用方(如 TUI)要把「用户按了 Ctrl+C」与「交接真的失败了」区分开 ——
|
|
13
|
+
* 前者应静默收尾并提示「已取消」,后者才该报错;
|
|
14
|
+
* - 它**不可降级**:`self` 被取消后绝不能退到 `summary` 再跑一遍。
|
|
15
|
+
* 把「用户中止」当成「模型没写出文档」,会白白多烧一轮全量输入。
|
|
16
|
+
*/
|
|
17
|
+
export class HandoffAbortedError extends Error {
|
|
18
|
+
constructor() {
|
|
19
|
+
super("Handoff cancelled");
|
|
20
|
+
this.name = "HandoffAbortedError";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* 错误是否来自取消。
|
|
25
|
+
*
|
|
26
|
+
* 两条路径都要认:
|
|
27
|
+
* - 调用方传了 `signal` 且已 `aborted`(`agent.abort()` 就是这种情况 ——
|
|
28
|
+
* 它**不抛错**,core 层把消息标记成 Aborted 后正常返回);
|
|
29
|
+
* - OpenAI SDK 在请求被 abort 时抛的 `APIUserAbortError`(`name` 为 `AbortError`)。
|
|
30
|
+
*/
|
|
31
|
+
function isAbortError(err, signal) {
|
|
32
|
+
if (signal?.aborted)
|
|
33
|
+
return true;
|
|
34
|
+
const name = err?.name;
|
|
35
|
+
return name === "AbortError" || name === "APIUserAbortError";
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* 任务交接服务。
|
|
39
|
+
*
|
|
40
|
+
* 职责分层(这是本模块唯一的设计主线):
|
|
41
|
+
* - `handoff()`:**只产出交接文档**(停工 → 写文档 → 校验 → 失败降级),不动会话;
|
|
42
|
+
* - `migrate()`:`handoff()` 之后清历史并开新会话(原「任务迁移」语义)。
|
|
43
|
+
*
|
|
44
|
+
* 模板的唯一真相源是 `handoff` Skill(`SKILL.md`);代码只负责
|
|
45
|
+
* 「读正文 → 注入 → 校验文件 → 读不到时用兜底模板」,不持有第二份章节清单。
|
|
46
|
+
*
|
|
47
|
+
* 重入:`handoff()` 与 `migrate()` 共用 `busy` 标志。交接回合本身也是一次 `send()`,
|
|
48
|
+
* 若不在 busy 期间让 `AutoMigratePlugin` / `ContextGuardPlugin` 让行,就会「交接触发迁移、
|
|
49
|
+
* 迁移再触发交接」无限递归,或在最满的时刻被护栏直接击杀。
|
|
50
|
+
*/
|
|
51
|
+
export class HandoffService {
|
|
52
|
+
/** 交接文档兜底模板(仅在读不到 Skill 时使用) */
|
|
53
|
+
static FALLBACK_TEMPLATE = FALLBACK_HANDOFF_TEMPLATE;
|
|
54
|
+
handoffDirPath;
|
|
55
|
+
defaultMode;
|
|
56
|
+
defaultStrategy;
|
|
57
|
+
skillDirs;
|
|
58
|
+
client;
|
|
59
|
+
model;
|
|
60
|
+
modelConfig;
|
|
61
|
+
minHandoffBytes;
|
|
62
|
+
onBeforeHandoff;
|
|
63
|
+
onHandoff;
|
|
64
|
+
onMigrated;
|
|
65
|
+
logger;
|
|
66
|
+
/** 交接/迁移进行中标志(插件据此让行) */
|
|
67
|
+
_busy = false;
|
|
68
|
+
/** 交接回合的工具守卫(同一实例复用 + arm/disarm,避免插件数组无限增长) */
|
|
69
|
+
guard;
|
|
70
|
+
/** 已注册过守卫的 agent(每个 agent 只 use 一次) */
|
|
71
|
+
guardedAgents = new WeakSet();
|
|
72
|
+
constructor(options = {}) {
|
|
73
|
+
const { handoffDir, mode, strategy, skillDirs, client, model, modelConfig, minHandoffBytes, onBeforeHandoff, onHandoff, onMigrated, logger, } = options;
|
|
74
|
+
this.handoffDirPath = resolvePath(handoffDir ?? join(process.cwd(), ".ai-zen", "handoffs"));
|
|
75
|
+
this.defaultMode = mode ?? "self";
|
|
76
|
+
this.defaultStrategy = strategy ?? "omit";
|
|
77
|
+
this.skillDirs = skillDirs ?? [];
|
|
78
|
+
this.client = client;
|
|
79
|
+
this.model = model;
|
|
80
|
+
this.modelConfig = modelConfig;
|
|
81
|
+
this.minHandoffBytes = minHandoffBytes ?? 400;
|
|
82
|
+
this.onBeforeHandoff = onBeforeHandoff;
|
|
83
|
+
this.onHandoff = onHandoff;
|
|
84
|
+
this.onMigrated = onMigrated;
|
|
85
|
+
this.logger = logger ?? getLogger();
|
|
86
|
+
}
|
|
87
|
+
/** 是否正在交接/迁移(`AutoMigratePlugin` / `ContextGuardPlugin` 据此让行) */
|
|
88
|
+
get busy() {
|
|
89
|
+
return this._busy;
|
|
90
|
+
}
|
|
91
|
+
/** 交接文档目录 */
|
|
92
|
+
get handoffDir() {
|
|
93
|
+
return this.handoffDirPath;
|
|
94
|
+
}
|
|
95
|
+
// ==================================================================
|
|
96
|
+
// 静态纯工具(供上层复用 / 单测)
|
|
97
|
+
// ==================================================================
|
|
98
|
+
/**
|
|
99
|
+
* 交接文件名:`<YYYYMMDD-HHmmss>.md`(本地时间,便于人眼归档)。
|
|
100
|
+
*
|
|
101
|
+
* 只有到秒的时间戳。同一秒内两次交接会撞名 —— 不做去重兜底:同一时刻并发交接
|
|
102
|
+
* 本来就是调用方该避免的事,加随机后缀只会让文件名更难认。
|
|
103
|
+
*/
|
|
104
|
+
static createHandoffFileName(date = new Date()) {
|
|
105
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
106
|
+
const stamp = `${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}` +
|
|
107
|
+
`-${p(date.getHours())}${p(date.getMinutes())}${p(date.getSeconds())}`;
|
|
108
|
+
return `${stamp}.md`;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* 拼装「本轮交接」指令:`[Skill 正文] + [本次交接参数]`。
|
|
112
|
+
*
|
|
113
|
+
* 不在 Skill 正文里发明占位符(本体系没有模板变量引擎),参数一律由代码拼在后面,
|
|
114
|
+
* 这样 Skill 只讲「怎么写」、代码只讲「写到哪、有什么能力」。
|
|
115
|
+
*/
|
|
116
|
+
static createHandoffInstruction(params) {
|
|
117
|
+
const { skillContent, handoffPath, toolsAvailable } = params;
|
|
118
|
+
const tail = toolsAvailable
|
|
119
|
+
? [
|
|
120
|
+
"Start writing now: use the write tool to put the complete document at the path given above (use the path exactly as given, do not rename it and do not move it to another directory).",
|
|
121
|
+
"After writing, read it back once with the read tool to confirm it is complete, then reply with a single confirmation of no more than 40 words, **do not restate the document content**.",
|
|
122
|
+
]
|
|
123
|
+
: [
|
|
124
|
+
"Output the complete document body directly: no explanations, do not wrap it in a code block, the caller will persist it to disk itself.",
|
|
125
|
+
];
|
|
126
|
+
return [
|
|
127
|
+
"You are now to write a task handoff document for this conversation. The following handoff rules are mandatory.",
|
|
128
|
+
"",
|
|
129
|
+
"---",
|
|
130
|
+
"",
|
|
131
|
+
skillContent.trim(),
|
|
132
|
+
"",
|
|
133
|
+
"---",
|
|
134
|
+
"",
|
|
135
|
+
"## Handoff parameters",
|
|
136
|
+
`- Handoff document absolute path: ${handoffPath}`,
|
|
137
|
+
`- Tools available: ${toolsAvailable
|
|
138
|
+
? "yes (read / exec, etc., use them to verify the actual state)"
|
|
139
|
+
: "no (you cannot inspect the disk, so for any state information always write '⚠️ Unverified', never speculate)"}`,
|
|
140
|
+
"",
|
|
141
|
+
...tail,
|
|
142
|
+
].join("\n");
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* 生成迁移后追加的「交接断点」消息(role=user):只给路径,让接手方自己 read。
|
|
146
|
+
*
|
|
147
|
+
* 为什么不内联全文:接手方第一次真正需要的是「去哪里取交接」,读一次文件的输入成本
|
|
148
|
+
* 与内联全文相当,但内联会让每条请求都携带全文;路径方案把成本推迟到真正需要时。
|
|
149
|
+
*/
|
|
150
|
+
static createPostMessages(handoffPath) {
|
|
151
|
+
const content = [
|
|
152
|
+
"The previous conversation has been handed off, the handoff document is saved at:",
|
|
153
|
+
handoffPath,
|
|
154
|
+
"",
|
|
155
|
+
"Read that file first with the read tool, and once you understand the context and the unfinished work, continue helping the user with the task.",
|
|
156
|
+
].join("\n");
|
|
157
|
+
return [Message.User(content)];
|
|
158
|
+
}
|
|
159
|
+
/** 序列化消息为 `[role]: content` 文本(仅 `summary` 模式使用) */
|
|
160
|
+
static serializeMessages(messages) {
|
|
161
|
+
return messages
|
|
162
|
+
.map((m) => {
|
|
163
|
+
const role = m.role ?? "unknown";
|
|
164
|
+
const content = typeof m.content === "string" ? m.content : JSON.stringify(m.content);
|
|
165
|
+
return `[${role}]: ${content}`;
|
|
166
|
+
})
|
|
167
|
+
.join("\n\n");
|
|
168
|
+
}
|
|
169
|
+
// ==================================================================
|
|
170
|
+
// 公开流程
|
|
171
|
+
// ==================================================================
|
|
172
|
+
/**
|
|
173
|
+
* 只产出交接文档,**不改动会话**(`/handoff`)。
|
|
174
|
+
*
|
|
175
|
+
* 不清理历史:交接回合(指令 + 工具调用 + 回执)会留在 `agent.messages` 里,
|
|
176
|
+
* 用户可继续让 agent 打磨这份文档(重写同一路径即可)。
|
|
177
|
+
*/
|
|
178
|
+
async handoff(params) {
|
|
179
|
+
return this.withBusy(() => this.runCatchingAbort(params, false));
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* 交接 + 开新会话(`/migrate`、自动迁移)。
|
|
183
|
+
*
|
|
184
|
+
* 策略(`strategy`):
|
|
185
|
+
* - `omit`(默认):历史标记 `omit: true`(保留可审计),末尾追加交接断点;
|
|
186
|
+
* - `prune`:物理剔除历史,只留 `definition.messages` + 交接断点。
|
|
187
|
+
*/
|
|
188
|
+
async migrate(params) {
|
|
189
|
+
return this.withBusy(async () => {
|
|
190
|
+
const ctx = await this.runCatchingAbort(params, true);
|
|
191
|
+
const { agent } = ctx;
|
|
192
|
+
const strategy = params.strategy ?? this.defaultStrategy;
|
|
193
|
+
const breakpointMessages = HandoffService.createPostMessages(ctx.handoffPath);
|
|
194
|
+
// 交接回合可能已经把 messages 换成新会话,definition 也可能是手写的(没有 messages):
|
|
195
|
+
// 这里按空模板处理,好让报错落在"模型该补的配置"上,而不是原生 TypeError
|
|
196
|
+
const templateMessages = agent.definition.messages ?? [];
|
|
197
|
+
if (strategy === "prune") {
|
|
198
|
+
// 浅拷贝模板消息,避免污染 definition.messages 引用的对象
|
|
199
|
+
agent.messages = [...templateMessages, ...breakpointMessages];
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
const preserveCount = Math.min(templateMessages.length, agent.messages.length);
|
|
203
|
+
agent.messages = [
|
|
204
|
+
...agent.messages.map((m, i) => ({
|
|
205
|
+
...m,
|
|
206
|
+
omit: i >= preserveCount ? true : m.omit,
|
|
207
|
+
})),
|
|
208
|
+
...breakpointMessages,
|
|
209
|
+
];
|
|
210
|
+
}
|
|
211
|
+
await this.safeHook(this.onMigrated, ctx);
|
|
212
|
+
return ctx;
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
// ==================================================================
|
|
216
|
+
// 内部
|
|
217
|
+
// ==================================================================
|
|
218
|
+
/** 串行化 + 防重入:交接与迁移共用同一把锁 */
|
|
219
|
+
async withBusy(fn) {
|
|
220
|
+
if (this._busy)
|
|
221
|
+
throw new Error("A handoff is already in progress, wait for it to finish");
|
|
222
|
+
this._busy = true;
|
|
223
|
+
try {
|
|
224
|
+
return await fn();
|
|
225
|
+
}
|
|
226
|
+
finally {
|
|
227
|
+
this._busy = false;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* 把底层各种「取消」形态统一成 {@link HandoffAbortedError}。
|
|
232
|
+
*
|
|
233
|
+
* 取消可能从三处冒上来:`self` 回合后的主动检查(已是 HandoffAbortedError)、
|
|
234
|
+
* `summary` 请求被 abort 时 OpenAI SDK 抛的 `APIUserAbortError`、以及
|
|
235
|
+
* `readSkillContent` 这类前置 await 期间被取消。调用方只需要认一个类型。
|
|
236
|
+
*/
|
|
237
|
+
async runCatchingAbort(params, migrating) {
|
|
238
|
+
try {
|
|
239
|
+
return await this.runHandoff(params, migrating);
|
|
240
|
+
}
|
|
241
|
+
catch (err) {
|
|
242
|
+
if (err instanceof HandoffAbortedError)
|
|
243
|
+
throw err;
|
|
244
|
+
if (isAbortError(err, params.signal))
|
|
245
|
+
throw new HandoffAbortedError();
|
|
246
|
+
throw err;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/** 取消点检查:每跨过一个阶段就确认一次,避免取消后继续往下一步冲 */
|
|
250
|
+
throwIfAborted(signal) {
|
|
251
|
+
if (signal?.aborted)
|
|
252
|
+
throw new HandoffAbortedError();
|
|
253
|
+
}
|
|
254
|
+
async fileExists(path) {
|
|
255
|
+
try {
|
|
256
|
+
await fs.access(path);
|
|
257
|
+
return true;
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* 取消后清掉半成品文档。
|
|
265
|
+
*
|
|
266
|
+
* 只删「本次新建」的文件:交接文件名含时间戳,正常不会撞已有文件,但调用方也
|
|
267
|
+
* 可以把 `handoffDir` 指向人工目录;不管怎样都不该删掉别人的文件。
|
|
268
|
+
* 留着半成品更糟 —— 下一轮接手方会把不完整的内容当成真实交接读进去。
|
|
269
|
+
*/
|
|
270
|
+
async discardPartialFile(path, existedBefore) {
|
|
271
|
+
if (existedBefore)
|
|
272
|
+
return;
|
|
273
|
+
try {
|
|
274
|
+
await fs.unlink(path);
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
/* 文件本就没写出来:忽略 */
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
async runHandoff(params, migrating) {
|
|
281
|
+
const { agent, promptTokens, handoffTokens, signal } = params;
|
|
282
|
+
const requestedMode = params.mode ?? this.defaultMode;
|
|
283
|
+
const handoffPath = join(this.handoffDirPath, HandoffService.createHandoffFileName(new Date()));
|
|
284
|
+
const model = this.model ?? agent.model;
|
|
285
|
+
const messageCountBefore = agent.messages.length;
|
|
286
|
+
// 迁移前上下文(不含文档,语义固定)
|
|
287
|
+
const beforeCtx = {
|
|
288
|
+
agent,
|
|
289
|
+
mode: requestedMode,
|
|
290
|
+
requestedMode,
|
|
291
|
+
handoffPath,
|
|
292
|
+
model,
|
|
293
|
+
promptTokens,
|
|
294
|
+
handoffTokens,
|
|
295
|
+
migrating,
|
|
296
|
+
messageCountBefore,
|
|
297
|
+
historyText: "",
|
|
298
|
+
};
|
|
299
|
+
await this.safeHook(this.onBeforeHandoff, beforeCtx);
|
|
300
|
+
this.throwIfAborted(signal);
|
|
301
|
+
// ---- 执行者:self 优先,失败/不可用则单向降级 summary ----
|
|
302
|
+
let mode = requestedMode;
|
|
303
|
+
let handoffDoc;
|
|
304
|
+
let historyText = "";
|
|
305
|
+
if (mode === "self" && !this.supportsSelfHandoff(agent)) {
|
|
306
|
+
this.logger.warn("[handoff] agent has no write tool or send capability, falling back to standalone summary mode");
|
|
307
|
+
mode = "summary";
|
|
308
|
+
}
|
|
309
|
+
if (mode === "self") {
|
|
310
|
+
const ok = await this.runSelfHandoff(agent, handoffPath, signal);
|
|
311
|
+
if (!ok) {
|
|
312
|
+
this.logger.warn("[handoff] self handoff failed, falling back to standalone summary mode");
|
|
313
|
+
mode = "summary";
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (mode === "summary") {
|
|
317
|
+
historyText = HandoffService.serializeMessages(agent.messages.filter((m) => !m.omit));
|
|
318
|
+
handoffDoc = await this.generateSummary(agent, historyText, handoffPath, signal);
|
|
319
|
+
await this.writeHandoffFile(handoffPath, handoffDoc);
|
|
320
|
+
}
|
|
321
|
+
// 最后一道取消点:即使两步都跑完,只要期间被取消就不能算成功
|
|
322
|
+
this.throwIfAborted(signal);
|
|
323
|
+
const ctx = {
|
|
324
|
+
agent,
|
|
325
|
+
mode,
|
|
326
|
+
requestedMode,
|
|
327
|
+
handoffPath,
|
|
328
|
+
handoffDoc,
|
|
329
|
+
model,
|
|
330
|
+
promptTokens,
|
|
331
|
+
handoffTokens,
|
|
332
|
+
migrating,
|
|
333
|
+
messageCountBefore,
|
|
334
|
+
historyText,
|
|
335
|
+
};
|
|
336
|
+
await this.safeHook(this.onHandoff, ctx);
|
|
337
|
+
return ctx;
|
|
338
|
+
}
|
|
339
|
+
/** 自交接是否可用:需要 `write` 工具 + `send` 能力 */
|
|
340
|
+
supportsSelfHandoff(agent) {
|
|
341
|
+
if (typeof agent.send !== "function")
|
|
342
|
+
return false;
|
|
343
|
+
return Boolean(agent.tools?.some((tool) => tool.function?.name === "write"));
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* 自交接回合:让原 agent 停工、核实、写文档,并校验文件确实落盘。
|
|
347
|
+
*
|
|
348
|
+
* 失败判定(任一成立即视为失败,交由上层单向降级 summary):
|
|
349
|
+
* - 文件不存在 / 小于阈值;
|
|
350
|
+
* - 模型/工具链抛错(例如没有权限、被护栏中断)。
|
|
351
|
+
*
|
|
352
|
+
* **取消不算失败**:`signal` 已触发时抛 {@link HandoffAbortedError},既不走
|
|
353
|
+
* 「文件没写好→重试一次」也不降级 summary。 这条分支必须显式写:
|
|
354
|
+
* `agent.abort()` 不抛错(core 把消息标记为 Aborted 后正常返回),否则「用户
|
|
355
|
+
* 按了 Ctrl+C」会被下面的文件校验误判成「模型没写出文档」,于是重试一轮、再降级
|
|
356
|
+
* 一轮 —— 用户以为取消了,实际多烧了两轮全量输入。
|
|
357
|
+
*/
|
|
358
|
+
async runSelfHandoff(agent, handoffPath, signal) {
|
|
359
|
+
const guard = this.ensureGuard(agent);
|
|
360
|
+
const skillContent = await this.readSkillContent();
|
|
361
|
+
const cwd = agent.scope?.cwd ?? process.cwd();
|
|
362
|
+
// 取消时只删本次新建的文件,不碰本已存在的同名文件
|
|
363
|
+
const existedBefore = await this.fileExists(handoffPath);
|
|
364
|
+
/*
|
|
365
|
+
* 交接回合的护栏让行由 `ContextGuardPlugin.isSuspended` 负责(接线为
|
|
366
|
+
* `() => handoffService.busy`),这里不再去改写用量数据:
|
|
367
|
+
* - `lastUsage` 是从 `messages` 派生的只读值,本就不可写;
|
|
368
|
+
* - 「谁做限制谁放宽」—— 限制在护栏自己身上,放宽也必须写在护栏的选项里。
|
|
369
|
+
*/
|
|
370
|
+
guard.arm(handoffPath, cwd);
|
|
371
|
+
try {
|
|
372
|
+
await agent.send(HandoffService.createHandoffInstruction({
|
|
373
|
+
skillContent,
|
|
374
|
+
handoffPath,
|
|
375
|
+
toolsAvailable: true,
|
|
376
|
+
}));
|
|
377
|
+
// `agent.abort()` 不抛错,必须主动检查(见方法注释)
|
|
378
|
+
this.throwIfAborted(signal);
|
|
379
|
+
if (await this.isHandoffFileReady(handoffPath))
|
|
380
|
+
return true;
|
|
381
|
+
this.logger.warn(`[handoff] handoff document missing or too small, retrying once: ${handoffPath}`);
|
|
382
|
+
await agent.send([
|
|
383
|
+
`The handoff document does not exist or is too small to deliver: ${handoffPath}`,
|
|
384
|
+
"Use the write tool right now to write the **complete** handoff document to that path (use the path exactly as given) and do nothing else.",
|
|
385
|
+
].join("\n"));
|
|
386
|
+
this.throwIfAborted(signal);
|
|
387
|
+
return await this.isHandoffFileReady(handoffPath);
|
|
388
|
+
}
|
|
389
|
+
catch (err) {
|
|
390
|
+
if (isAbortError(err, signal)) {
|
|
391
|
+
await this.discardPartialFile(handoffPath, existedBefore);
|
|
392
|
+
throw new HandoffAbortedError();
|
|
393
|
+
}
|
|
394
|
+
this.logger.error(`[handoff] self handoff round failed: ${err?.message ?? err}`);
|
|
395
|
+
return false;
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
guard.disarm();
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/** 独立摘要:一次模型调用,用同一份 Skill 正文作为规范 */
|
|
402
|
+
async generateSummary(agent, historyText, handoffPath, signal) {
|
|
403
|
+
const client = this.client ?? agent.client;
|
|
404
|
+
const model = this.model ?? agent.model;
|
|
405
|
+
const modelConfig = this.modelConfig ?? agent.modelConfig;
|
|
406
|
+
const skillContent = await this.readSkillContent();
|
|
407
|
+
this.throwIfAborted(signal);
|
|
408
|
+
// `signal` 走 RequestOptions(第二参数),与 `core/Agent.ts` 调用模型时一致:
|
|
409
|
+
// 放在 body 里不会被 OpenAI SDK 当成取消信号。
|
|
410
|
+
const response = await client.chat.completions.create({
|
|
411
|
+
model,
|
|
412
|
+
...(modelConfig ?? {}),
|
|
413
|
+
messages: [
|
|
414
|
+
{
|
|
415
|
+
role: "system",
|
|
416
|
+
content: HandoffService.createHandoffInstruction({
|
|
417
|
+
skillContent,
|
|
418
|
+
handoffPath,
|
|
419
|
+
toolsAvailable: false,
|
|
420
|
+
}),
|
|
421
|
+
},
|
|
422
|
+
{ role: "user", content: historyText },
|
|
423
|
+
],
|
|
424
|
+
}, signal ? { signal } : undefined);
|
|
425
|
+
const handoffDoc = response.choices[0]?.message?.content;
|
|
426
|
+
if (!handoffDoc || !handoffDoc.trim()) {
|
|
427
|
+
throw new Error("Failed to generate the handoff document");
|
|
428
|
+
}
|
|
429
|
+
return handoffDoc;
|
|
430
|
+
}
|
|
431
|
+
/** 落盘(仅 `summary` 模式需要;`self` 模式由 agent 的 write 工具完成) */
|
|
432
|
+
async writeHandoffFile(handoffPath, content) {
|
|
433
|
+
await fs.mkdir(dirname(handoffPath), { recursive: true });
|
|
434
|
+
await fs.writeFile(handoffPath, content, "utf-8");
|
|
435
|
+
}
|
|
436
|
+
/** 交接文档是否可用:文件存在且不小于阈值(不读内容,避免二次读取) */ async isHandoffFileReady(handoffPath) {
|
|
437
|
+
try {
|
|
438
|
+
const stat = await fs.stat(handoffPath);
|
|
439
|
+
return stat.isFile() && stat.size >= this.minHandoffBytes;
|
|
440
|
+
}
|
|
441
|
+
catch {
|
|
442
|
+
return false;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
/** 读取 `handoff` Skill 正文;读不到时回落到兜底模板 */
|
|
446
|
+
async readSkillContent() {
|
|
447
|
+
if (this.skillDirs.length > 0) {
|
|
448
|
+
const skill = await readSkill(this.skillDirs, HANDOFF_SKILL_ID, { silent: true });
|
|
449
|
+
if (skill?.content?.trim())
|
|
450
|
+
return skill.content;
|
|
451
|
+
}
|
|
452
|
+
this.logger.warn(`[handoff] ${HANDOFF_SKILL_ID} skill not found, using the built-in fallback template (paths: ${this.skillDirs.join(", ") || "none configured"})`);
|
|
453
|
+
return FALLBACK_HANDOFF_TEMPLATE;
|
|
454
|
+
}
|
|
455
|
+
/** 守卫按 agent 注册一次(`Agent.use()` 无移除 API,故复用实例 + 开关) */
|
|
456
|
+
ensureGuard(agent) {
|
|
457
|
+
const guard = (this.guard ??= new HandoffGuardPlugin());
|
|
458
|
+
if (!this.guardedAgents.has(agent)) {
|
|
459
|
+
agent.use(guard);
|
|
460
|
+
this.guardedAgents.add(agent);
|
|
461
|
+
}
|
|
462
|
+
return guard;
|
|
463
|
+
}
|
|
464
|
+
/** 钩子容错:抛错只记录,不中断交接(与既有迁移钩子语义一致) */
|
|
465
|
+
async safeHook(hook, ctx) {
|
|
466
|
+
if (!hook)
|
|
467
|
+
return;
|
|
468
|
+
try {
|
|
469
|
+
await hook(ctx);
|
|
470
|
+
}
|
|
471
|
+
catch (err) {
|
|
472
|
+
this.logger.error(`[handoff] hook execution failed: ${err?.message ?? err}`);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type OpenAI from "openai";
|
|
2
2
|
import { Agent } from "@ai-zen/agents-core";
|
|
3
|
-
import type { AgentNS, Tool } from "@ai-zen/agents-core";
|
|
3
|
+
import type { AbortedMessageStrategy, AbortedToolRoundStrategy, AgentNS, Tool } from "@ai-zen/agents-core";
|
|
4
4
|
import type { AgentDefinition } from "../types/index.js";
|
|
5
5
|
import type { Scope } from "../scope/Scope.js";
|
|
6
6
|
export type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
|
|
@@ -30,5 +30,11 @@ export declare class SdkAgent extends Agent {
|
|
|
30
30
|
messages?: AgentNS.Message[];
|
|
31
31
|
tools?: Tool[];
|
|
32
32
|
allowJsonParseError?: boolean;
|
|
33
|
+
/** 工具轮次被中断时的归一策略(core 默认 `fill`) */
|
|
34
|
+
abortedToolRoundStrategy?: AbortedToolRoundStrategy;
|
|
35
|
+
/** `fill` 策略下未完成工具结果的填充原因 */
|
|
36
|
+
abortedToolRoundReason?: string;
|
|
37
|
+
/** 被中断的 assistant(内容/思考)是否保留(core 默认 `drop`) */
|
|
38
|
+
abortedMessageStrategy?: AbortedMessageStrategy;
|
|
33
39
|
});
|
|
34
40
|
}
|
package/dist/runtime/SdkAgent.js
CHANGED
|
@@ -24,6 +24,9 @@ export class SdkAgent extends Agent {
|
|
|
24
24
|
messages: params.messages,
|
|
25
25
|
tools: params.tools,
|
|
26
26
|
allowJsonParseError: params.allowJsonParseError,
|
|
27
|
+
abortedToolRoundStrategy: params.abortedToolRoundStrategy,
|
|
28
|
+
abortedToolRoundReason: params.abortedToolRoundReason,
|
|
29
|
+
abortedMessageStrategy: params.abortedMessageStrategy,
|
|
27
30
|
});
|
|
28
31
|
this.scope = params.scope;
|
|
29
32
|
this.definition = params.definition;
|
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
import { SdkAgent } from "./SdkAgent.js";
|
|
2
2
|
import type { Scope } from "../scope/Scope.js";
|
|
3
|
+
import type { AbortedMessageStrategy, AbortedToolRoundStrategy } from "@ai-zen/agents-core";
|
|
4
|
+
/**
|
|
5
|
+
* `createAgent` 的可选行为开关。
|
|
6
|
+
*
|
|
7
|
+
* 不传时先取 `scope.config`(`config.json`)里的同名配置,再往下才是 core 默认值:
|
|
8
|
+
* 中断策略属于**产品配置**,调用方不该自己读配置再转一道参数。
|
|
9
|
+
*/
|
|
10
|
+
export interface CreateAgentOptions {
|
|
11
|
+
/** 工具轮次被中断(或结果不完整)时的归一策略(core 默认 `fill`) */
|
|
12
|
+
abortedToolRoundStrategy?: AbortedToolRoundStrategy;
|
|
13
|
+
/** `fill` 策略下,未完成工具结果的填充原因 */
|
|
14
|
+
abortedToolRoundReason?: string;
|
|
15
|
+
/**
|
|
16
|
+
* 被中断的 assistant 消息(已输出的内容 / 思考)如何处置(未传时取 `scope.config`,
|
|
17
|
+
* 再缺则用 core 默认 `drop`)。
|
|
18
|
+
* `keep` 可让模型在下一轮接着半截往下说,而不是忘掉自己说过什么。
|
|
19
|
+
*/
|
|
20
|
+
abortedMessageStrategy?: AbortedMessageStrategy;
|
|
21
|
+
}
|
|
3
22
|
/**
|
|
4
23
|
* 从磁盘创建 Agent。
|
|
5
24
|
*
|
|
@@ -10,4 +29,4 @@ import type { Scope } from "../scope/Scope.js";
|
|
|
10
29
|
* // agent 是 SdkAgent,可直接注册插件、发送消息
|
|
11
30
|
* ```
|
|
12
31
|
*/
|
|
13
|
-
export declare function createAgent(scope: Scope, agentId: string): Promise<SdkAgent>;
|
|
32
|
+
export declare function createAgent(scope: Scope, agentId: string, options?: CreateAgentOptions): Promise<SdkAgent>;
|
|
@@ -11,19 +11,18 @@ import { createModel } from "./createModel.js";
|
|
|
11
11
|
* // agent 是 SdkAgent,可直接注册插件、发送消息
|
|
12
12
|
* ```
|
|
13
13
|
*/
|
|
14
|
-
export async function createAgent(scope, agentId) {
|
|
14
|
+
export async function createAgent(scope, agentId, options = {}) {
|
|
15
15
|
const definition = await new AgentRepository(scope.agentsDir).read(agentId);
|
|
16
16
|
if (!definition)
|
|
17
|
-
throw new Error(`Agent "${agentId}"
|
|
18
|
-
const modelId = definition.modelId
|
|
19
|
-
if (!modelId)
|
|
20
|
-
throw new Error("
|
|
21
|
-
|
|
17
|
+
throw new Error(`Agent "${agentId}" not found`);
|
|
18
|
+
const modelId = definition.modelId;
|
|
19
|
+
if (!modelId) {
|
|
20
|
+
throw new Error(`Agent "${agentId}" has no model bound (modelId is missing). Assign a model to it in the config`);
|
|
21
|
+
}
|
|
22
|
+
const { client, model, modelConfig } = createModel(scope, modelId, definition.modelParams);
|
|
22
23
|
const tools = scope.buildTools(definition, {
|
|
23
24
|
exclude: {
|
|
24
|
-
subagents: definition.function?.name
|
|
25
|
-
? [definition.function.name]
|
|
26
|
-
: undefined,
|
|
25
|
+
subagents: definition.function?.name ? [definition.function.name] : undefined,
|
|
27
26
|
},
|
|
28
27
|
});
|
|
29
28
|
const agent = new SdkAgent({
|
|
@@ -39,6 +38,12 @@ export async function createAgent(scope, agentId) {
|
|
|
39
38
|
// 快照后,运行时改动只作用于会话副本,模板保持纯净。
|
|
40
39
|
messages: [...(definition.messages ?? [])],
|
|
41
40
|
tools,
|
|
41
|
+
// 中断相关策略:**显式参数 > `scope.config` > core 默认值**。
|
|
42
|
+
// 中间那一层是「配置即事实」:策略写在 `config.json` 里,各端(CLI / Desktop)
|
|
43
|
+
// 不必自己读配置再转成参数,子 Agent 创建时也能自然继承同一份策略。
|
|
44
|
+
abortedToolRoundStrategy: options.abortedToolRoundStrategy ?? scope.config?.abortedToolRoundStrategy,
|
|
45
|
+
abortedToolRoundReason: options.abortedToolRoundReason,
|
|
46
|
+
abortedMessageStrategy: options.abortedMessageStrategy ?? scope.config?.abortedMessageStrategy,
|
|
42
47
|
});
|
|
43
48
|
return agent;
|
|
44
49
|
}
|
|
@@ -1,21 +1,25 @@
|
|
|
1
1
|
import OpenAI from "openai";
|
|
2
2
|
import type { Scope } from "../scope/Scope.js";
|
|
3
|
+
import type { ModelParams } from "../types/index.js";
|
|
3
4
|
/**
|
|
4
5
|
* Agent 模型装配结果:openai SDK client + 模型名 + 模型参数。
|
|
5
6
|
* Agent 构造时直接消费此结构。
|
|
6
7
|
*/
|
|
7
8
|
export interface AgentModel {
|
|
8
|
-
/** openai
|
|
9
|
+
/** openai SDK 客户端 */
|
|
9
10
|
client: OpenAI;
|
|
10
11
|
/** 发送给 API 的模型名 */
|
|
11
12
|
model: string;
|
|
12
|
-
/**
|
|
13
|
-
modelConfig?:
|
|
13
|
+
/** 模型参数,透传给 API(可含厂商特有字段,如 DeepSeek thinking) */
|
|
14
|
+
modelConfig?: ModelParams;
|
|
14
15
|
}
|
|
15
16
|
/**
|
|
16
17
|
* 模型工厂 — 根据 modelId 和 Scope 装配 openai SDK client。
|
|
17
18
|
*
|
|
18
19
|
* 端点(baseUrl / apiKey)来自 config.endpoints,发送给 API 的模型名 = modelName || id。
|
|
19
20
|
* 任何 OpenAI 兼容端点(OpenAI / 智谱 BigModel / DeepSeek 等)均可通过 baseURL 接入。
|
|
21
|
+
*
|
|
22
|
+
* `overrides` 是 **Agent 级参数覆盖**(`AgentDefinition.modelParams`):
|
|
23
|
+
* 同一个模型可以给不同 Agent 配不同参数,而模型自身的 `defaultParams` 保持不变。
|
|
20
24
|
*/
|
|
21
|
-
export declare function createModel(scope: Scope, modelId: string): AgentModel;
|
|
25
|
+
export declare function createModel(scope: Scope, modelId: string, overrides?: ModelParams): AgentModel;
|
|
@@ -1,20 +1,37 @@
|
|
|
1
1
|
import OpenAI from "openai";
|
|
2
|
+
/**
|
|
3
|
+
* 参数覆盖 —— 浅合并,一行。
|
|
4
|
+
*
|
|
5
|
+
* 这是 SDK 对「模型参数」的唯一处理逻辑:不解释键名、不做档位推导、不知道厂商差异。
|
|
6
|
+
* 需要多层次语义(如「思考档位」)的应用,应该在**写配置时**就把档位展开成具体参数,
|
|
7
|
+
* 存进 `Model.defaultParams` / `AgentDefinition.modelParams`,运行期不再查表。
|
|
8
|
+
*
|
|
9
|
+
* 没有覆盖时返回原对象(保持 `undefined` 语义,避免凭空塞一个空对象)。
|
|
10
|
+
*/
|
|
11
|
+
function mergeParams(base, overrides) {
|
|
12
|
+
if (!overrides || Object.keys(overrides).length === 0)
|
|
13
|
+
return base;
|
|
14
|
+
return { ...base, ...overrides };
|
|
15
|
+
}
|
|
2
16
|
/**
|
|
3
17
|
* 模型工厂 — 根据 modelId 和 Scope 装配 openai SDK client。
|
|
4
18
|
*
|
|
5
19
|
* 端点(baseUrl / apiKey)来自 config.endpoints,发送给 API 的模型名 = modelName || id。
|
|
6
20
|
* 任何 OpenAI 兼容端点(OpenAI / 智谱 BigModel / DeepSeek 等)均可通过 baseURL 接入。
|
|
21
|
+
*
|
|
22
|
+
* `overrides` 是 **Agent 级参数覆盖**(`AgentDefinition.modelParams`):
|
|
23
|
+
* 同一个模型可以给不同 Agent 配不同参数,而模型自身的 `defaultParams` 保持不变。
|
|
7
24
|
*/
|
|
8
|
-
export function createModel(scope, modelId) {
|
|
25
|
+
export function createModel(scope, modelId, overrides) {
|
|
9
26
|
const config = scope.config;
|
|
10
27
|
const modelConfig = config.models.find((m) => m.id === modelId);
|
|
11
28
|
if (!modelConfig)
|
|
12
|
-
throw new Error(
|
|
29
|
+
throw new Error(`Model "${modelId}" not found`);
|
|
13
30
|
const endpointConfig = config.endpoints.find((e) => e.id === modelConfig.endpointId);
|
|
14
31
|
if (!endpointConfig)
|
|
15
|
-
throw new Error(
|
|
32
|
+
throw new Error(`Endpoint "${modelConfig.endpointId}" is not configured`);
|
|
16
33
|
if (!endpointConfig.apiKey) {
|
|
17
|
-
throw new Error(
|
|
34
|
+
throw new Error(`API key for endpoint "${endpointConfig.name}" is not set`);
|
|
18
35
|
}
|
|
19
36
|
const client = new OpenAI({
|
|
20
37
|
apiKey: endpointConfig.apiKey,
|
|
@@ -25,6 +42,6 @@ export function createModel(scope, modelId) {
|
|
|
25
42
|
return {
|
|
26
43
|
client,
|
|
27
44
|
model: apiModelName,
|
|
28
|
-
modelConfig: modelConfig.defaultParams,
|
|
45
|
+
modelConfig: mergeParams(modelConfig.defaultParams, overrides),
|
|
29
46
|
};
|
|
30
47
|
}
|