@ai-zen/agents-sdk 1.0.0 → 1.2.0-alpha.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 +40 -0
- package/README.md +5 -17
- package/README.zh.md +5 -17
- package/dist/agent-plugins/AutoMigratePlugin.js +5 -0
- package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +28 -1
- package/dist/agent-plugins/AutoRefreshToolsPlugin.js +29 -8
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +64 -0
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +68 -0
- package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +0 -1
- package/dist/agent-plugins/UnknownToolHintPlugin.js +0 -1
- package/dist/config/ConfigManager.d.ts +11 -7
- package/dist/config/ConfigManager.js +15 -13
- package/dist/config/constants.d.ts +5 -3
- package/dist/config/constants.js +10 -4
- package/dist/config/migrate.d.ts +15 -6
- package/dist/config/migrate.js +16 -12
- package/dist/index.d.ts +12 -4
- package/dist/index.js +9 -4
- package/dist/runtime/HandoffService.d.ts +51 -9
- package/dist/runtime/HandoffService.js +158 -97
- package/dist/runtime/SdkAgent.d.ts +11 -4
- package/dist/runtime/SdkAgent.js +10 -4
- package/dist/runtime/completeOnce.d.ts +43 -0
- package/dist/runtime/completeOnce.js +38 -0
- package/dist/runtime/createAgent.d.ts +27 -1
- package/dist/runtime/createAgent.js +37 -7
- package/dist/runtime/createModel.d.ts +13 -1
- package/dist/runtime/createModel.js +14 -1
- package/dist/runtime/resolveModel.d.ts +93 -0
- package/dist/runtime/resolveModel.js +78 -0
- package/dist/scope/Scope.d.ts +1 -2
- package/dist/scope/Scope.js +1 -1
- package/dist/scope/ScopePlugin.d.ts +1 -1
- package/dist/scope/plugins/allInOne.d.ts +1 -1
- package/dist/scope/plugins/allInOne.js +1 -1
- package/dist/scope/plugins/builtin/ExecTool.js +4 -0
- package/dist/scope/plugins/builtin/SdkCallbackTool.d.ts +1 -2
- package/dist/scope/plugins/builtin/SdkCallbackTool.js +0 -1
- package/dist/scope/plugins/builtin/SpawnTool.js +2 -2
- package/dist/scope/plugins/builtin/ViewImageTool.d.ts +1 -1
- package/dist/scope/plugins/builtin/ViewImageTool.js +1 -1
- package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +1 -1
- package/dist/scope/plugins/mcp/McpScopePlugin.js +1 -1
- package/dist/scope/plugins/mcp/mcpTools.d.ts +1 -1
- package/dist/scope/plugins/mcp/mcpTools.js +4 -4
- package/dist/scope/plugins/skills/SkillsScopePlugin.d.ts +1 -1
- package/dist/scope/plugins/skills/SkillsScopePlugin.js +1 -1
- package/dist/scope/plugins/skills/discover.js +1 -1
- package/dist/scope/plugins/usertools/discover.d.ts +24 -0
- package/dist/scope/plugins/usertools/discover.js +17 -5
- package/dist/shared/content-blocks.d.ts +6 -9
- package/dist/shared/content-blocks.js +38 -58
- package/dist/types/index.d.ts +76 -30
- package/dist/types/index.js +0 -4
- package/package.json +5 -5
|
@@ -4,6 +4,7 @@ import { Message } from "@ai-zen/agents-core";
|
|
|
4
4
|
import { getLogger } from "../shared/logger.js";
|
|
5
5
|
import { readSkill } from "../scope/plugins/skills/discover.js";
|
|
6
6
|
import { FALLBACK_HANDOFF_TEMPLATE, HANDOFF_SKILL_ID } from "../config/factory-skills.js";
|
|
7
|
+
import { completeOnce } from "./completeOnce.js";
|
|
7
8
|
import { HandoffGuardPlugin } from "./HandoffGuardPlugin.js";
|
|
8
9
|
/**
|
|
9
10
|
* 交接被调用方取消(`AbortSignal` 触发)。
|
|
@@ -34,12 +35,22 @@ function isAbortError(err, signal) {
|
|
|
34
35
|
const name = err?.name;
|
|
35
36
|
return name === "AbortError" || name === "APIUserAbortError";
|
|
36
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* 合并两条取消信号:任一触发即视为取消。
|
|
40
|
+
*
|
|
41
|
+
* 服务自身的 `abort()`(见 {@link HandoffService.abort})与调用方传入的 `signal`
|
|
42
|
+
* 都要认:前者是自动迁移唯一的取消入口(那条链路调用方递不进 signal),后者留给
|
|
43
|
+
* 「外层还有自己的超时 / 取消」的调用方。
|
|
44
|
+
*/
|
|
45
|
+
function mergeSignals(own, external) {
|
|
46
|
+
return external ? AbortSignal.any([own, external]) : own;
|
|
47
|
+
}
|
|
37
48
|
/**
|
|
38
49
|
* 任务交接服务。
|
|
39
50
|
*
|
|
40
51
|
* 职责分层(这是本模块唯一的设计主线):
|
|
41
52
|
* - `handoff()`:**只产出交接文档**(停工 → 写文档 → 校验 → 失败降级),不动会话;
|
|
42
|
-
* - `migrate()`:`handoff()`
|
|
53
|
+
* - `migrate()`:`handoff()` 之后清历史并开新会话。
|
|
43
54
|
*
|
|
44
55
|
* 模板的唯一真相源是 `handoff` Skill(`SKILL.md`);代码只负责
|
|
45
56
|
* 「读正文 → 注入 → 校验文件 → 读不到时用兜底模板」,不持有第二份章节清单。
|
|
@@ -47,6 +58,11 @@ function isAbortError(err, signal) {
|
|
|
47
58
|
* 重入:`handoff()` 与 `migrate()` 共用 `busy` 标志。交接回合本身也是一次 `send()`,
|
|
48
59
|
* 若不在 busy 期间让 `AutoMigratePlugin` / `ContextGuardPlugin` 让行,就会「交接触发迁移、
|
|
49
60
|
* 迁移再触发交接」无限递归,或在最满的时刻被护栏直接击杀。
|
|
61
|
+
*
|
|
62
|
+
* 取消:取消句柄由服务自己持有({@link HandoffService.abort}),而不是只认调用方传进来的
|
|
63
|
+
* `signal` —— 自动迁移由 `AutoMigratePlugin` 直接驱动,调用方根本没有机会把 signal 递进来,
|
|
64
|
+
* 只认外部 signal 的后果是「自动迁移期间按 Ctrl+C 会被当成『文档没写出来』,于是重试一轮、
|
|
65
|
+
* 再降级 summary 一轮,最后照样迁移」。取消后一律回到交接前的状态(见 {@link HandoffService.restoreBeforeHandoff})。
|
|
50
66
|
*/
|
|
51
67
|
export class HandoffService {
|
|
52
68
|
/** 交接文档兜底模板(仅在读不到 Skill 时使用) */
|
|
@@ -65,6 +81,13 @@ export class HandoffService {
|
|
|
65
81
|
logger;
|
|
66
82
|
/** 交接/迁移进行中标志(插件据此让行) */
|
|
67
83
|
_busy = false;
|
|
84
|
+
/**
|
|
85
|
+
* 当前这次交接/迁移的取消句柄(`null` = 没有进行中的交接)。
|
|
86
|
+
*
|
|
87
|
+
* 三条链路(`/handoff`、`/migrate`、自动迁移)共用同一个开关:前两条还有调用方能
|
|
88
|
+
* 传 `signal`,自动迁移没有 —— 句柄放在服务里,三者的取消语义才不会各不相同。
|
|
89
|
+
*/
|
|
90
|
+
abortController = null;
|
|
68
91
|
/** 交接回合的工具守卫(同一实例复用 + arm/disarm,避免插件数组无限增长) */
|
|
69
92
|
guard;
|
|
70
93
|
/** 已注册过守卫的 agent(每个 agent 只 use 一次) */
|
|
@@ -169,14 +192,26 @@ export class HandoffService {
|
|
|
169
192
|
// ==================================================================
|
|
170
193
|
// 公开流程
|
|
171
194
|
// ==================================================================
|
|
195
|
+
/**
|
|
196
|
+
* 取消进行中的交接/迁移(用户按 Ctrl+C)。没有进行中的交接时是 no-op。
|
|
197
|
+
*
|
|
198
|
+
* 边界:本方法只保证「停下 + 回退」——不再重试、不降级 summary、不迁移,并把会话
|
|
199
|
+
* 退回交接前。**它不负责立刻掐断正在跑的模型请求**:`self` 模式的回合是
|
|
200
|
+
* `agent.send()`,调用方通常要同时 `agent.abort()`(TUI 就是这么做的);`summary`
|
|
201
|
+
* 模式的那次请求拿的是本服务合并出的 signal,会被真正中断。
|
|
202
|
+
*/
|
|
203
|
+
abort() {
|
|
204
|
+
this.abortController?.abort();
|
|
205
|
+
}
|
|
172
206
|
/**
|
|
173
207
|
* 只产出交接文档,**不改动会话**(`/handoff`)。
|
|
174
208
|
*
|
|
175
209
|
* 不清理历史:交接回合(指令 + 工具调用 + 回执)会留在 `agent.messages` 里,
|
|
176
|
-
* 用户可继续让 agent
|
|
210
|
+
* 用户可继续让 agent 打磨这份文档(重写同一路径即可)。被取消时相反:整个交接
|
|
211
|
+
* 回合从 `agent.messages` 里截掉,本次新建的文档也不留。
|
|
177
212
|
*/
|
|
178
213
|
async handoff(params) {
|
|
179
|
-
return this.withBusy(() => this.
|
|
214
|
+
return this.withBusy((own) => this.runHandoff({ ...params, signal: mergeSignals(own, params.signal) }, false));
|
|
180
215
|
}
|
|
181
216
|
/**
|
|
182
217
|
* 交接 + 开新会话(`/migrate`、自动迁移)。
|
|
@@ -186,8 +221,11 @@ export class HandoffService {
|
|
|
186
221
|
* - `prune`:物理剔除历史,只留 `definition.messages` + 交接断点。
|
|
187
222
|
*/
|
|
188
223
|
async migrate(params) {
|
|
189
|
-
return this.withBusy(async () => {
|
|
190
|
-
|
|
224
|
+
return this.withBusy(async (own) => {
|
|
225
|
+
// 拿到 ctx 即「已提交」:文档已通过校验,取消不再生效(见 runHandoff 末尾的取消点)。
|
|
226
|
+
// 在 prune 之前再拦一次取消会留下第三种状态 ——「用户点了取消,旧会话却已存档、
|
|
227
|
+
// 历史却已剔除」,比让迁移做完更糟
|
|
228
|
+
const ctx = await this.runHandoff({ ...params, signal: mergeSignals(own, params.signal) }, true);
|
|
191
229
|
const { agent } = ctx;
|
|
192
230
|
const strategy = params.strategy ?? this.defaultStrategy;
|
|
193
231
|
const breakpointMessages = HandoffService.createPostMessages(ctx.handoffPath);
|
|
@@ -215,35 +253,25 @@ export class HandoffService {
|
|
|
215
253
|
// ==================================================================
|
|
216
254
|
// 内部
|
|
217
255
|
// ==================================================================
|
|
218
|
-
/**
|
|
256
|
+
/**
|
|
257
|
+
* 串行化 + 防重入:交接与迁移共用同一把锁,也共用同一个取消句柄。
|
|
258
|
+
*
|
|
259
|
+
* 句柄与 `busy` 同寿命:`finally` 里清掉,否则下一次 `abort()` 会往一个已结束的
|
|
260
|
+
* controller 上发出无意义的 abort(看起来「取消成功」,实际什么都没发生)。
|
|
261
|
+
*/
|
|
219
262
|
async withBusy(fn) {
|
|
220
263
|
if (this._busy)
|
|
221
264
|
throw new Error("A handoff is already in progress, wait for it to finish");
|
|
222
265
|
this._busy = true;
|
|
266
|
+
const controller = new AbortController();
|
|
267
|
+
this.abortController = controller;
|
|
223
268
|
try {
|
|
224
|
-
return await fn();
|
|
269
|
+
return await fn(controller.signal);
|
|
225
270
|
}
|
|
226
271
|
finally {
|
|
227
272
|
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;
|
|
273
|
+
if (this.abortController === controller)
|
|
274
|
+
this.abortController = null;
|
|
247
275
|
}
|
|
248
276
|
}
|
|
249
277
|
/** 取消点检查:每跨过一个阶段就确认一次,避免取消后继续往下一步冲 */
|
|
@@ -277,64 +305,101 @@ export class HandoffService {
|
|
|
277
305
|
/* 文件本就没写出来:忽略 */
|
|
278
306
|
}
|
|
279
307
|
}
|
|
308
|
+
/**
|
|
309
|
+
* 跑完一次交接("/handoff" 与 "/migrate" 共用),取消时**由本方法统一回退**。
|
|
310
|
+
*
|
|
311
|
+
* 为什么回退只写在这一处:取消可能从任何一个阶段冒出来(`self` 回合后的主动检查、
|
|
312
|
+
* `summary` 请求被 abort、前置的 `readSkillContent`),分散到各自的 catch 里就会
|
|
313
|
+
* 漏掉「文档已落盘但还没校验通过」这种半成品状态。这里一次拿全三件事:
|
|
314
|
+
* 交接前的消息条数、文档路径、以及「文档本就不存在」这个事实。
|
|
315
|
+
*
|
|
316
|
+
* 取消形态有两类,都要认:{@link HandoffAbortedError}(主动检查)与底层 abort 错误
|
|
317
|
+
* (OpenAI 的 `APIUserAbortError`)。调用方只需要认前者。
|
|
318
|
+
*/
|
|
280
319
|
async runHandoff(params, migrating) {
|
|
281
320
|
const { agent, promptTokens, handoffTokens, signal } = params;
|
|
282
321
|
const requestedMode = params.mode ?? this.defaultMode;
|
|
283
322
|
const handoffPath = join(this.handoffDirPath, HandoffService.createHandoffFileName(new Date()));
|
|
284
323
|
const model = this.model ?? agent.model;
|
|
285
324
|
const messageCountBefore = agent.messages.length;
|
|
286
|
-
//
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
if (!ok) {
|
|
312
|
-
this.logger.warn("[handoff] self handoff failed, falling back to standalone summary mode");
|
|
325
|
+
// 只删「本次新建」的文档:交接文件名含时间戳,正常不会撞已有文件,但调用方也可以
|
|
326
|
+
// 把 `handoffDir` 指向人工目录,不管怎样都不该删掉别人的文件
|
|
327
|
+
const existedBefore = await this.fileExists(handoffPath);
|
|
328
|
+
try {
|
|
329
|
+
// 迁移前上下文(不含文档,语义固定)
|
|
330
|
+
const beforeCtx = {
|
|
331
|
+
agent,
|
|
332
|
+
mode: requestedMode,
|
|
333
|
+
requestedMode,
|
|
334
|
+
handoffPath,
|
|
335
|
+
model,
|
|
336
|
+
promptTokens,
|
|
337
|
+
handoffTokens,
|
|
338
|
+
migrating,
|
|
339
|
+
messageCountBefore,
|
|
340
|
+
historyText: "",
|
|
341
|
+
};
|
|
342
|
+
await this.safeHook(this.onBeforeHandoff, beforeCtx);
|
|
343
|
+
this.throwIfAborted(signal);
|
|
344
|
+
// ---- 执行者:self 优先,失败/不可用则单向降级 summary ----
|
|
345
|
+
let mode = requestedMode;
|
|
346
|
+
let handoffDoc;
|
|
347
|
+
let historyText = "";
|
|
348
|
+
if (mode === "self" && !this.supportsSelfHandoff(agent)) {
|
|
349
|
+
this.logger.warn("[handoff] agent has no write tool or send capability, falling back to standalone summary mode");
|
|
313
350
|
mode = "summary";
|
|
314
351
|
}
|
|
352
|
+
if (mode === "self") {
|
|
353
|
+
const ok = await this.runSelfHandoff(agent, handoffPath, signal);
|
|
354
|
+
if (!ok) {
|
|
355
|
+
this.logger.warn("[handoff] self handoff failed, falling back to standalone summary mode");
|
|
356
|
+
mode = "summary";
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (mode === "summary") {
|
|
360
|
+
historyText = HandoffService.serializeMessages(agent.messages.filter((m) => !m.omit));
|
|
361
|
+
handoffDoc = await this.generateSummary(agent, historyText, handoffPath, signal);
|
|
362
|
+
await this.writeHandoffFile(handoffPath, handoffDoc);
|
|
363
|
+
}
|
|
364
|
+
// 最后一道取消点:即使两步都跑完,只要期间被取消就不能算成功。跨过这一步就是
|
|
365
|
+
// 「已提交」——之后的 `onHandoff` 钩子(存旧会话等)与迁移收尾不再响应取消
|
|
366
|
+
this.throwIfAborted(signal);
|
|
367
|
+
const ctx = {
|
|
368
|
+
agent,
|
|
369
|
+
mode,
|
|
370
|
+
requestedMode,
|
|
371
|
+
handoffPath,
|
|
372
|
+
handoffDoc,
|
|
373
|
+
model,
|
|
374
|
+
promptTokens,
|
|
375
|
+
handoffTokens,
|
|
376
|
+
migrating,
|
|
377
|
+
messageCountBefore,
|
|
378
|
+
historyText,
|
|
379
|
+
};
|
|
380
|
+
await this.safeHook(this.onHandoff, ctx);
|
|
381
|
+
return ctx;
|
|
315
382
|
}
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
await this.
|
|
383
|
+
catch (err) {
|
|
384
|
+
if (!(err instanceof HandoffAbortedError) && !isAbortError(err, signal))
|
|
385
|
+
throw err;
|
|
386
|
+
await this.restoreBeforeHandoff({ agent, messageCountBefore, handoffPath, existedBefore });
|
|
387
|
+
throw new HandoffAbortedError();
|
|
320
388
|
}
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
messageCountBefore
|
|
334
|
-
|
|
335
|
-
};
|
|
336
|
-
await this.safeHook(this.onHandoff, ctx);
|
|
337
|
-
return ctx;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* 取消后回到交接前的状态:把交接回合追加的消息全部截掉,并删掉本次新建的文档。
|
|
392
|
+
*
|
|
393
|
+
* 为什么必须截消息:`self` 模式的交接回合是「一条几 KB 的 Skill 指令 user 消息 +
|
|
394
|
+
* 工具结果 + 回执」,留在 `agent.messages` 里既让用户看到半段无关对话,也让下一次
|
|
395
|
+
* 请求把它当历史再发一遍(`↑` 翻历史还会把它翻出来)。`agent.messages` 是唯一真相源,
|
|
396
|
+
* 截回原长度之后,转录、历史、用量全都自动复位,不需要第二处补偿。
|
|
397
|
+
*/
|
|
398
|
+
async restoreBeforeHandoff(params) {
|
|
399
|
+
const { agent, messageCountBefore, handoffPath, existedBefore } = params;
|
|
400
|
+
if (agent.messages.length > messageCountBefore)
|
|
401
|
+
agent.messages.splice(messageCountBefore);
|
|
402
|
+
await this.discardPartialFile(handoffPath, existedBefore);
|
|
338
403
|
}
|
|
339
404
|
/** 自交接是否可用:需要 `write` 工具 + `send` 能力 */
|
|
340
405
|
supportsSelfHandoff(agent) {
|
|
@@ -354,13 +419,14 @@ export class HandoffService {
|
|
|
354
419
|
* `agent.abort()` 不抛错(core 把消息标记为 Aborted 后正常返回),否则「用户
|
|
355
420
|
* 按了 Ctrl+C」会被下面的文件校验误判成「模型没写出文档」,于是重试一轮、再降级
|
|
356
421
|
* 一轮 —— 用户以为取消了,实际多烧了两轮全量输入。
|
|
422
|
+
*
|
|
423
|
+
* 取消的善后(删文档、截消息)不在这里做:交给 {@link runHandoff} 的 catch 一处处理,
|
|
424
|
+
* 因为「文档已写出但还没校验」的取消根本进不到本方法的 catch。
|
|
357
425
|
*/
|
|
358
426
|
async runSelfHandoff(agent, handoffPath, signal) {
|
|
359
427
|
const guard = this.ensureGuard(agent);
|
|
360
428
|
const skillContent = await this.readSkillContent();
|
|
361
429
|
const cwd = agent.scope?.cwd ?? process.cwd();
|
|
362
|
-
// 取消时只删本次新建的文件,不碰本已存在的同名文件
|
|
363
|
-
const existedBefore = await this.fileExists(handoffPath);
|
|
364
430
|
/*
|
|
365
431
|
* 交接回合的护栏让行由 `ContextGuardPlugin.isSuspended` 负责(接线为
|
|
366
432
|
* `() => handoffService.busy`),这里不再去改写用量数据:
|
|
@@ -387,10 +453,8 @@ export class HandoffService {
|
|
|
387
453
|
return await this.isHandoffFileReady(handoffPath);
|
|
388
454
|
}
|
|
389
455
|
catch (err) {
|
|
390
|
-
if (isAbortError(err, signal))
|
|
391
|
-
await this.discardPartialFile(handoffPath, existedBefore);
|
|
456
|
+
if (isAbortError(err, signal))
|
|
392
457
|
throw new HandoffAbortedError();
|
|
393
|
-
}
|
|
394
458
|
this.logger.error(`[handoff] self handoff round failed: ${err?.message ?? err}`);
|
|
395
459
|
return false;
|
|
396
460
|
}
|
|
@@ -405,25 +469,22 @@ export class HandoffService {
|
|
|
405
469
|
const modelConfig = this.modelConfig ?? agent.modelConfig;
|
|
406
470
|
const skillContent = await this.readSkillContent();
|
|
407
471
|
this.throwIfAborted(signal);
|
|
408
|
-
//
|
|
409
|
-
//
|
|
410
|
-
|
|
472
|
+
// 请求体形状(system + user、modelConfig 展开、signal 走 RequestOptions)的唯一实现在
|
|
473
|
+
// `completeOnce`:会话自动标题那一类「辅助小请求」走同一条路,两边不会一份带 stream、
|
|
474
|
+
// 另一份不带
|
|
475
|
+
const handoffDoc = await completeOnce({
|
|
476
|
+
client,
|
|
411
477
|
model,
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
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()) {
|
|
478
|
+
modelConfig,
|
|
479
|
+
system: HandoffService.createHandoffInstruction({
|
|
480
|
+
skillContent,
|
|
481
|
+
handoffPath,
|
|
482
|
+
toolsAvailable: false,
|
|
483
|
+
}),
|
|
484
|
+
user: historyText,
|
|
485
|
+
signal,
|
|
486
|
+
});
|
|
487
|
+
if (!handoffDoc.trim()) {
|
|
427
488
|
throw new Error("Failed to generate the handoff document");
|
|
428
489
|
}
|
|
429
490
|
return handoffDoc;
|
|
@@ -3,6 +3,7 @@ import { Agent } from "@ai-zen/agents-core";
|
|
|
3
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
|
+
import type { ModelLevel } from "./resolveModel.js";
|
|
6
7
|
export type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
|
|
7
8
|
/**
|
|
8
9
|
* SDK Agent — 继承 Core Agent,携带 SDK 层额外信息。
|
|
@@ -10,20 +11,26 @@ export type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
|
|
|
10
11
|
* Core Agent 不感知权限、文件系统等业务逻辑;
|
|
11
12
|
* SdkAgent 在 Core Agent 基础上增加了 SDK 层需要的元数据:
|
|
12
13
|
* - scope:全局 Scope 实例
|
|
13
|
-
* - definition:Agent
|
|
14
|
+
* - definition:Agent 定义(含权限 permissions)。**模型解析生效之后的那一份**:
|
|
15
|
+
* 会话级覆盖会写进它的 `modelId`(见 `createAgent`),于是「读哪个字段都不会跑偏」;
|
|
16
|
+
* - modelLevel:这个模型是从哪一级解析出来的(会话 / Agent 定义 / 全局兜底)。
|
|
17
|
+
* 值是 `resolveModel` 的副产品,客户端用它把「当前生效档」标在 `/model` 选择器上。
|
|
14
18
|
*
|
|
15
|
-
* 插件能力(use / init / send 钩子分发)继承自 Core Agent
|
|
19
|
+
* 插件能力(use / init / send 钩子分发)继承自 Core Agent,此处不重复实现。
|
|
16
20
|
* 未知工具的 MCP 智能提示由独立插件 `UnknownToolHintPlugin` 提供(调用方显式 use)。
|
|
17
|
-
* 权限统一从 `definition.permissions`
|
|
21
|
+
* 权限统一从 `definition.permissions` 读取。
|
|
18
22
|
*/
|
|
19
23
|
export declare class SdkAgent extends Agent {
|
|
20
24
|
/** 全局 Scope 实例 */
|
|
21
25
|
readonly scope: Scope;
|
|
22
|
-
/** Agent
|
|
26
|
+
/** Agent 定义(模型解析生效之后的那一份:`modelId` 是**实际在用**的模型) */
|
|
23
27
|
readonly definition: AgentDefinition;
|
|
28
|
+
/** 生效模型来自哪一级(三级解析的结果,见 `resolveModel`) */
|
|
29
|
+
readonly modelLevel: ModelLevel;
|
|
24
30
|
constructor(params: {
|
|
25
31
|
scope: Scope;
|
|
26
32
|
definition: AgentDefinition;
|
|
33
|
+
modelLevel: ModelLevel;
|
|
27
34
|
client: OpenAI;
|
|
28
35
|
model: string;
|
|
29
36
|
modelConfig?: Record<string, unknown>;
|
package/dist/runtime/SdkAgent.js
CHANGED
|
@@ -5,17 +5,22 @@ import { Agent } from "@ai-zen/agents-core";
|
|
|
5
5
|
* Core Agent 不感知权限、文件系统等业务逻辑;
|
|
6
6
|
* SdkAgent 在 Core Agent 基础上增加了 SDK 层需要的元数据:
|
|
7
7
|
* - scope:全局 Scope 实例
|
|
8
|
-
* - definition:Agent
|
|
8
|
+
* - definition:Agent 定义(含权限 permissions)。**模型解析生效之后的那一份**:
|
|
9
|
+
* 会话级覆盖会写进它的 `modelId`(见 `createAgent`),于是「读哪个字段都不会跑偏」;
|
|
10
|
+
* - modelLevel:这个模型是从哪一级解析出来的(会话 / Agent 定义 / 全局兜底)。
|
|
11
|
+
* 值是 `resolveModel` 的副产品,客户端用它把「当前生效档」标在 `/model` 选择器上。
|
|
9
12
|
*
|
|
10
|
-
* 插件能力(use / init / send 钩子分发)继承自 Core Agent
|
|
13
|
+
* 插件能力(use / init / send 钩子分发)继承自 Core Agent,此处不重复实现。
|
|
11
14
|
* 未知工具的 MCP 智能提示由独立插件 `UnknownToolHintPlugin` 提供(调用方显式 use)。
|
|
12
|
-
* 权限统一从 `definition.permissions`
|
|
15
|
+
* 权限统一从 `definition.permissions` 读取。
|
|
13
16
|
*/
|
|
14
17
|
export class SdkAgent extends Agent {
|
|
15
18
|
/** 全局 Scope 实例 */
|
|
16
19
|
scope;
|
|
17
|
-
/** Agent
|
|
20
|
+
/** Agent 定义(模型解析生效之后的那一份:`modelId` 是**实际在用**的模型) */
|
|
18
21
|
definition;
|
|
22
|
+
/** 生效模型来自哪一级(三级解析的结果,见 `resolveModel`) */
|
|
23
|
+
modelLevel;
|
|
19
24
|
constructor(params) {
|
|
20
25
|
super({
|
|
21
26
|
client: params.client,
|
|
@@ -30,5 +35,6 @@ export class SdkAgent extends Agent {
|
|
|
30
35
|
});
|
|
31
36
|
this.scope = params.scope;
|
|
32
37
|
this.definition = params.definition;
|
|
38
|
+
this.modelLevel = params.modelLevel;
|
|
33
39
|
}
|
|
34
40
|
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 一次性模型调用 —— 「不流式、不带工具、问一句答一句」的唯一实现。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么要有它
|
|
5
|
+
*
|
|
6
|
+
* 产品里有几处「辅助小请求」:交接文档的 `summary` 模式、会话自动起名。它们的共同点是
|
|
7
|
+
* **不是对话**:没有消息历史要维护、没有工具、不流式、结果用完即弃。如果各自
|
|
8
|
+
* `client.chat.completions.create(...)` 一遍,就会各写一份「要不要 stream / 带不带 tools /
|
|
9
|
+
* modelConfig 怎么摊开 / signal 怎么传」—— 这四件事写错任何一样都不会报错,只会让请求
|
|
10
|
+
* 变成另一种东西(例如带了 `stream: true` 于是拿到的正文永远是空的)。
|
|
11
|
+
*
|
|
12
|
+
* 所以:请求体的形状只在这里拼一次,两处(`HandoffService.generateSummary`、服务端的
|
|
13
|
+
* 自动标题)都从这里走。
|
|
14
|
+
*
|
|
15
|
+
* ## 为什么返回字符串而不是整条 response
|
|
16
|
+
*
|
|
17
|
+
* 调用方要的都是「模型说了什么」。把 response 交出去,每个调用方都会再写一次
|
|
18
|
+
* `choices[0]?.message?.content ?? ""`,而 `?? ""` 与「空正文算失败」是两种不同的态度:
|
|
19
|
+
* 前者交给调用方判(`summary` 模式把空正文当失败并抛错,标题直接留空),本函数不替它们选。
|
|
20
|
+
*
|
|
21
|
+
* ## 为什么取消信号走第二参数
|
|
22
|
+
*
|
|
23
|
+
* 与 `core/Agent.ts` 调用模型时一致:`signal` 属于 `RequestOptions`(HTTP 层),塞进 body
|
|
24
|
+
* 不会被 OpenAI SDK 当成取消信号,请求照样会跑完。
|
|
25
|
+
*/
|
|
26
|
+
import type OpenAI from "openai";
|
|
27
|
+
import type { ModelParams } from "../types/index.js";
|
|
28
|
+
export interface CompleteOnceInput {
|
|
29
|
+
/** 已装配好的客户端(`createModel` / `createModelFromConfig` 的产物) */
|
|
30
|
+
client: OpenAI;
|
|
31
|
+
/** 发给端点的模型名(`modelName || id`) */
|
|
32
|
+
model: string;
|
|
33
|
+
/** 模型参数(同 `model.defaultParams` + 覆盖),展开进 body */
|
|
34
|
+
modelConfig?: ModelParams;
|
|
35
|
+
/** 一次性指令(角色是 system) */
|
|
36
|
+
system: string;
|
|
37
|
+
/** 这一次要处理的输入(角色是 user) */
|
|
38
|
+
user: string;
|
|
39
|
+
/** 取消 / 超时信号;触发后请求真的被中断 */
|
|
40
|
+
signal?: AbortSignal;
|
|
41
|
+
}
|
|
42
|
+
/** 发一次非流式请求,返回正文(模型没给正文时是空串,由调用方判成败) */
|
|
43
|
+
export declare function completeOnce(input: CompleteOnceInput): Promise<string>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 一次性模型调用 —— 「不流式、不带工具、问一句答一句」的唯一实现。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么要有它
|
|
5
|
+
*
|
|
6
|
+
* 产品里有几处「辅助小请求」:交接文档的 `summary` 模式、会话自动起名。它们的共同点是
|
|
7
|
+
* **不是对话**:没有消息历史要维护、没有工具、不流式、结果用完即弃。如果各自
|
|
8
|
+
* `client.chat.completions.create(...)` 一遍,就会各写一份「要不要 stream / 带不带 tools /
|
|
9
|
+
* modelConfig 怎么摊开 / signal 怎么传」—— 这四件事写错任何一样都不会报错,只会让请求
|
|
10
|
+
* 变成另一种东西(例如带了 `stream: true` 于是拿到的正文永远是空的)。
|
|
11
|
+
*
|
|
12
|
+
* 所以:请求体的形状只在这里拼一次,两处(`HandoffService.generateSummary`、服务端的
|
|
13
|
+
* 自动标题)都从这里走。
|
|
14
|
+
*
|
|
15
|
+
* ## 为什么返回字符串而不是整条 response
|
|
16
|
+
*
|
|
17
|
+
* 调用方要的都是「模型说了什么」。把 response 交出去,每个调用方都会再写一次
|
|
18
|
+
* `choices[0]?.message?.content ?? ""`,而 `?? ""` 与「空正文算失败」是两种不同的态度:
|
|
19
|
+
* 前者交给调用方判(`summary` 模式把空正文当失败并抛错,标题直接留空),本函数不替它们选。
|
|
20
|
+
*
|
|
21
|
+
* ## 为什么取消信号走第二参数
|
|
22
|
+
*
|
|
23
|
+
* 与 `core/Agent.ts` 调用模型时一致:`signal` 属于 `RequestOptions`(HTTP 层),塞进 body
|
|
24
|
+
* 不会被 OpenAI SDK 当成取消信号,请求照样会跑完。
|
|
25
|
+
*/
|
|
26
|
+
/** 发一次非流式请求,返回正文(模型没给正文时是空串,由调用方判成败) */
|
|
27
|
+
export async function completeOnce(input) {
|
|
28
|
+
const { client, model, modelConfig, system, user, signal } = input;
|
|
29
|
+
const response = await client.chat.completions.create({
|
|
30
|
+
model,
|
|
31
|
+
...(modelConfig ?? {}),
|
|
32
|
+
messages: [
|
|
33
|
+
{ role: "system", content: system },
|
|
34
|
+
{ role: "user", content: user },
|
|
35
|
+
],
|
|
36
|
+
}, signal ? { signal } : undefined);
|
|
37
|
+
return response.choices?.[0]?.message?.content ?? "";
|
|
38
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { SdkAgent } from "./SdkAgent.js";
|
|
2
2
|
import type { Scope } from "../scope/Scope.js";
|
|
3
|
+
import type { ModelParams } from "../types/index.js";
|
|
3
4
|
import type { AbortedMessageStrategy, AbortedToolRoundStrategy } from "@ai-zen/agents-core";
|
|
4
5
|
/**
|
|
5
6
|
* `createAgent` 的可选行为开关。
|
|
@@ -18,15 +19,40 @@ export interface CreateAgentOptions {
|
|
|
18
19
|
* `keep` 可让模型在下一轮接着半截往下说,而不是忘掉自己说过什么。
|
|
19
20
|
*/
|
|
20
21
|
abortedMessageStrategy?: AbortedMessageStrategy;
|
|
22
|
+
/**
|
|
23
|
+
* **会话级**模型覆盖(三级解析的第一级)。
|
|
24
|
+
*
|
|
25
|
+
* 只有「这一段会话」该换模型时才传(服务端从 `SessionRecord.modelId` 取,`/model`
|
|
26
|
+
* 不带作用级别的写法写的就是它)。不传就落到 Agent 定义,再落到 `config.defaultModel`。
|
|
27
|
+
*
|
|
28
|
+
* 为什么由调用方传、而不是 SDK 自己去读会话存档:本层不认识会话(它只认识 Scope 与
|
|
29
|
+
* Agent 定义),会话存档是服务端的财产。**解析顺序仍只在这里实现**(见 `resolveModel`)。
|
|
30
|
+
*/
|
|
31
|
+
modelId?: string;
|
|
32
|
+
/**
|
|
33
|
+
* **会话级**模型参数覆盖(三级解析里与 `modelId` 同一级的那一份,服务端从会话存档的
|
|
34
|
+
* `modelParams` 取)。
|
|
35
|
+
*
|
|
36
|
+
* 只有 `modelId` 那一级赢了它才会真正生效 —— 取哪一份由 `resolveModelParams` 按档位
|
|
37
|
+
* 决定(同一处规则)。**它不会与 `AgentDefinition.modelParams` 合并**:定义那份是配给
|
|
38
|
+
* 定义绑定的模型的,会话把模型换掉之后把旧参数发给新模型就是端点 400。
|
|
39
|
+
*/
|
|
40
|
+
modelParams?: ModelParams;
|
|
21
41
|
}
|
|
22
42
|
/**
|
|
23
43
|
* 从磁盘创建 Agent。
|
|
24
44
|
*
|
|
25
45
|
* 通过 Scope 获取已发现的能力,读取 Agent 定义,过滤并实例化工具,产出 SdkAgent。
|
|
46
|
+
* 模型按 **会话级覆盖 > Agent 定义 > 全局兜底** 解析(唯一实现:`resolveModel`);
|
|
47
|
+
* **参数取「模型来自哪一级」那一份**、绝不跨级混合(同一处实现:`resolveModelParams`)。
|
|
26
48
|
*
|
|
27
49
|
* ```ts
|
|
28
50
|
* const agent = await createAgent(scope, "my-agent");
|
|
29
|
-
* //
|
|
51
|
+
* // 这一段会话临时换个模型(不动 Agent 定义):模型与参数都取会话级那一份
|
|
52
|
+
* const scoped = await createAgent(scope, "my-agent", {
|
|
53
|
+
* modelId: "gpt-6-astra",
|
|
54
|
+
* modelParams: { reasoning_effort: "high" },
|
|
55
|
+
* });
|
|
30
56
|
* ```
|
|
31
57
|
*/
|
|
32
58
|
export declare function createAgent(scope: Scope, agentId: string, options?: CreateAgentOptions): Promise<SdkAgent>;
|
|
@@ -1,25 +1,53 @@
|
|
|
1
1
|
import { AgentRepository } from "../crud/AgentRepository.js";
|
|
2
2
|
import { SdkAgent } from "./SdkAgent.js";
|
|
3
3
|
import { createModel } from "./createModel.js";
|
|
4
|
+
import { resolveModel, resolveModelParams } from "./resolveModel.js";
|
|
4
5
|
/**
|
|
5
6
|
* 从磁盘创建 Agent。
|
|
6
7
|
*
|
|
7
8
|
* 通过 Scope 获取已发现的能力,读取 Agent 定义,过滤并实例化工具,产出 SdkAgent。
|
|
9
|
+
* 模型按 **会话级覆盖 > Agent 定义 > 全局兜底** 解析(唯一实现:`resolveModel`);
|
|
10
|
+
* **参数取「模型来自哪一级」那一份**、绝不跨级混合(同一处实现:`resolveModelParams`)。
|
|
8
11
|
*
|
|
9
12
|
* ```ts
|
|
10
13
|
* const agent = await createAgent(scope, "my-agent");
|
|
11
|
-
* //
|
|
14
|
+
* // 这一段会话临时换个模型(不动 Agent 定义):模型与参数都取会话级那一份
|
|
15
|
+
* const scoped = await createAgent(scope, "my-agent", {
|
|
16
|
+
* modelId: "gpt-6-astra",
|
|
17
|
+
* modelParams: { reasoning_effort: "high" },
|
|
18
|
+
* });
|
|
12
19
|
* ```
|
|
13
20
|
*/
|
|
14
21
|
export async function createAgent(scope, agentId, options = {}) {
|
|
15
|
-
const
|
|
16
|
-
if (!
|
|
22
|
+
const stored = await new AgentRepository(scope.agentsDir).read(agentId);
|
|
23
|
+
if (!stored)
|
|
17
24
|
throw new Error(`Agent "${agentId}" not found`);
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
25
|
+
const resolved = resolveModel({
|
|
26
|
+
sessionModelId: options.modelId,
|
|
27
|
+
agentModelId: stored.modelId,
|
|
28
|
+
defaultModel: scope.config?.defaultModel,
|
|
29
|
+
});
|
|
30
|
+
// 三级都没有就是**真的没有模型**:不静默挑一个出厂模型顶上 —— 用户会以为自己在用
|
|
31
|
+
// 配置里那个,实际请求(和账单)落在别的模型上。带上 agentId 是因为同一条错误在
|
|
32
|
+
// 服务端日志里必须能指出是哪份定义没绑。
|
|
33
|
+
if (!resolved) {
|
|
34
|
+
throw new Error(`Agent "${agentId}" has no model bound: no session override, no "modelId" in its definition, ` +
|
|
35
|
+
`and no "defaultModel" in the config`);
|
|
21
36
|
}
|
|
22
|
-
|
|
37
|
+
// 生效的模型写进**这一份**(内存里的)定义:运行期所有读 `definition.modelId` 的地方
|
|
38
|
+
// —— 状态栏快照、上下文阈值(`tokenThresholds`)、插件 —— 必须看到同一个模型,否则
|
|
39
|
+
// 就又回到「界面写着 A、请求发给 B」。磁盘上的定义一个字都不动:会话级覆盖只属于这一段
|
|
40
|
+
// 会话,落盘走的是会话存档的 `modelId`(见服务端 `SessionManager.recordOf`)。
|
|
41
|
+
const definition = { ...stored, modelId: resolved.modelId };
|
|
42
|
+
// 参数跟着「模型来自哪一级」走:档位是上面那次解析的产物,这里只按它取那一份
|
|
43
|
+
// (规则只有一处实现,见 `resolveModelParams`)。会话级没设参数、或模型来自全局兜底时
|
|
44
|
+
// 拿到的是 `undefined` —— 那就一个字段都不覆盖,让模型走自己的 `defaultParams`。
|
|
45
|
+
const params = resolveModelParams({
|
|
46
|
+
level: resolved.level,
|
|
47
|
+
sessionModelParams: options.modelParams,
|
|
48
|
+
agentModelParams: definition.modelParams,
|
|
49
|
+
});
|
|
50
|
+
const { client, model, modelConfig } = createModel(scope, resolved.modelId, params);
|
|
23
51
|
const tools = scope.buildTools(definition, {
|
|
24
52
|
exclude: {
|
|
25
53
|
subagents: definition.function?.name ? [definition.function.name] : undefined,
|
|
@@ -31,6 +59,8 @@ export async function createAgent(scope, agentId, options = {}) {
|
|
|
31
59
|
client,
|
|
32
60
|
model,
|
|
33
61
|
modelConfig,
|
|
62
|
+
// 合出来的是哪一级,客户端要把「当前生效档」标在选择器上
|
|
63
|
+
modelLevel: resolved.level,
|
|
34
64
|
// 在 createAgent 层做模板快照(拷贝),隔离 definition.messages 的引用。
|
|
35
65
|
// AgentContext.messages 是 mutable 运行时数组,若直接把 definition.messages
|
|
36
66
|
// 传入,对话期间 append() 会反向污染 Agent 定义模板——definition.messages
|