@ai-zen/agents-sdk 1.2.0-alpha.1 → 2.0.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 +20 -0
- package/README.md +3 -3
- package/README.zh.md +3 -3
- package/dist/agent-plugins/AutoMigratePlugin.d.ts +34 -5
- package/dist/agent-plugins/AutoMigratePlugin.js +56 -7
- package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +8 -5
- package/dist/agent-plugins/AutoRefreshToolsPlugin.js +5 -6
- package/dist/agent-plugins/ContextGuardPlugin.d.ts +15 -3
- package/dist/agent-plugins/ContextGuardPlugin.js +16 -2
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +18 -16
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +16 -14
- package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +12 -3
- package/dist/agent-plugins/UnknownToolHintPlugin.js +16 -4
- package/dist/config/ConfigManager.d.ts +21 -16
- package/dist/config/ConfigManager.js +47 -25
- package/dist/index.d.ts +5 -2
- package/dist/index.js +3 -0
- package/dist/runtime/HandoffGuardPlugin.d.ts +7 -5
- package/dist/runtime/HandoffGuardPlugin.js +8 -6
- package/dist/runtime/HandoffService.d.ts +51 -12
- package/dist/runtime/HandoffService.js +112 -19
- package/dist/runtime/SdkAgent.d.ts +2 -3
- package/dist/runtime/SdkAgent.js +1 -2
- package/dist/scope/Scope.d.ts +35 -8
- package/dist/scope/Scope.js +50 -11
- package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +7 -0
- package/dist/scope/plugins/mcp/McpConnectionManager.js +7 -0
- package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +23 -0
- package/dist/scope/plugins/mcp/McpScopePlugin.js +68 -1
- package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +28 -0
- package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +35 -0
- package/dist/scope/plugins/peers/peerSessionTools.d.ts +122 -0
- package/dist/scope/plugins/peers/peerSessionTools.js +266 -0
- package/dist/scope/plugins/skills/skillTools.d.ts +1 -1
- package/dist/scope/plugins/skills/skillTools.js +6 -2
- package/dist/scope/plugins/subagents/subAgentTools.js +3 -0
- package/dist/shared/errors.d.ts +10 -3
- package/dist/shared/errors.js +10 -3
- package/dist/types/index.d.ts +6 -4
- package/package.json +2 -2
|
@@ -37,9 +37,12 @@ export class ConfigManager {
|
|
|
37
37
|
/**
|
|
38
38
|
* 读磁盘原文(不做任何迁移/同步),供 `ensureDefaultConfig()` 对比写盘用。
|
|
39
39
|
*
|
|
40
|
-
* 文件在但读不成配置(JSON
|
|
41
|
-
*
|
|
42
|
-
* 只返回默认值不落盘,用户每次开客户端都会再撞一次。
|
|
40
|
+
* 文件在但读不成配置(JSON 解析不了、或者解析出来不是对象)就是一档「坏」:先把坏文件
|
|
41
|
+
* 改名留档,再用出厂配置写回磁盘,再回调一次,返回出厂配置。写回是为了让下次启动不再
|
|
42
|
+
* 遇到同一个坏文件 —— 只返回默认值不落盘,用户每次开客户端都会再撞一次。
|
|
43
|
+
*
|
|
44
|
+
* 留档不是为了兜底,是为了数据:`config.json` 一恢复,用户的端点与密钥就全没了,
|
|
45
|
+
* 残骸是唯一能查回「我原来配了什么」的地方。
|
|
43
46
|
*/
|
|
44
47
|
async readRaw() {
|
|
45
48
|
try {
|
|
@@ -58,6 +61,7 @@ export class ConfigManager {
|
|
|
58
61
|
parsed = null;
|
|
59
62
|
}
|
|
60
63
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
64
|
+
await this.archiveBroken(this.configPath);
|
|
61
65
|
await this.write(DEFAULT_APP_CONFIG);
|
|
62
66
|
await this.onRecovered?.(this.configPath);
|
|
63
67
|
return { ...DEFAULT_APP_CONFIG };
|
|
@@ -351,9 +355,15 @@ export class ConfigManager {
|
|
|
351
355
|
return join(this.basePath, "mcp.json");
|
|
352
356
|
}
|
|
353
357
|
/**
|
|
354
|
-
* 确保 basePath/mcp.json
|
|
355
|
-
*
|
|
356
|
-
*
|
|
358
|
+
* 确保 basePath/mcp.json 存在,三种情况分开(与 `config.json` / `host.json` 同一口径):
|
|
359
|
+
*
|
|
360
|
+
* - **不存在** → 写入出厂默认 MCP 配置(含 socket-pty 与 chrome-devtools)。这是正常首启,
|
|
361
|
+
* 不回调;
|
|
362
|
+
* - **存在且解析得成对象** → 原样返回,不动用户的文件(哪怕里面全是用户自己的服务器);
|
|
363
|
+
* - **存在但坏了**(读不了 / 不是 JSON / 不是对象 / 是数组)→ 恢复出厂:先把坏文件改名
|
|
364
|
+
* 留档为 `mcp.json.broken`,再写回出厂默认配置,然后回调一次。
|
|
365
|
+
*
|
|
366
|
+
* @returns 当前生效的 MCP 配置原始内容
|
|
357
367
|
*/
|
|
358
368
|
async ensureDefaultMcpConfig() {
|
|
359
369
|
const mcpPath = this.mcpPath;
|
|
@@ -366,33 +376,45 @@ export class ConfigManager {
|
|
|
366
376
|
await this.writeJson(mcpPath, DEFAULT_MCP_CONFIG);
|
|
367
377
|
return { ...DEFAULT_MCP_CONFIG };
|
|
368
378
|
}
|
|
369
|
-
//
|
|
370
|
-
|
|
371
|
-
}
|
|
372
|
-
/**
|
|
373
|
-
* 读取 basePath/mcp.json,不存在时返回空结构。
|
|
374
|
-
*/
|
|
375
|
-
async readMcpConfig() {
|
|
376
|
-
const mcpPath = this.mcpPath;
|
|
379
|
+
// 存在:读不出来、解析不了、解析出来不是对象(含数组)都是同一档「坏」
|
|
380
|
+
let parsed = null;
|
|
377
381
|
try {
|
|
378
|
-
await fs.
|
|
382
|
+
parsed = JSON.parse(await fs.readFile(mcpPath, "utf-8"));
|
|
379
383
|
}
|
|
380
384
|
catch {
|
|
381
|
-
|
|
382
|
-
}
|
|
383
|
-
try {
|
|
384
|
-
return JSON.parse(await fs.readFile(mcpPath, "utf-8"));
|
|
385
|
+
parsed = null;
|
|
385
386
|
}
|
|
386
|
-
|
|
387
|
-
return
|
|
387
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
388
|
+
return parsed;
|
|
388
389
|
}
|
|
390
|
+
// 恢复出厂:先留一份残骸(用户会问「我原来那些服务器去哪了」),再写回出厂配置
|
|
391
|
+
await this.archiveBroken(mcpPath);
|
|
392
|
+
await this.writeJson(mcpPath, DEFAULT_MCP_CONFIG);
|
|
393
|
+
await this.onRecovered?.(mcpPath);
|
|
394
|
+
return { ...DEFAULT_MCP_CONFIG };
|
|
389
395
|
}
|
|
390
396
|
/**
|
|
391
|
-
*
|
|
397
|
+
* 把坏掉的配置文件改名留档为 `<文件名>.broken`(`config.json` 与 `mcp.json` 同一口径)。
|
|
398
|
+
*
|
|
399
|
+
* 同名残骸已经在就带上时间戳(同一毫秒再撞上就补序号),免得把上一份残骸覆盖掉。
|
|
392
400
|
*/
|
|
393
|
-
async
|
|
394
|
-
|
|
395
|
-
|
|
401
|
+
async archiveBroken(path) {
|
|
402
|
+
const base = `${path}.broken`;
|
|
403
|
+
let target = base;
|
|
404
|
+
for (let index = 0; await this.exists(target); index += 1) {
|
|
405
|
+
target = index === 0 ? `${base}.${Date.now()}` : `${base}.${Date.now()}-${index}`;
|
|
406
|
+
}
|
|
407
|
+
await fs.rename(path, target);
|
|
408
|
+
}
|
|
409
|
+
/** 这个路径在不在(`access` 不抛就是在) */
|
|
410
|
+
async exists(path) {
|
|
411
|
+
try {
|
|
412
|
+
await fs.access(path);
|
|
413
|
+
return true;
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
return false;
|
|
417
|
+
}
|
|
396
418
|
}
|
|
397
419
|
/** 原子写 JSON 文件(先写 .tmp 再 rename,避免半成品)。 */
|
|
398
420
|
async writeJson(path, data) {
|
package/dist/index.d.ts
CHANGED
|
@@ -11,13 +11,16 @@ export { discoverMcpServers } from "./scope/plugins/mcp/discover.js";
|
|
|
11
11
|
export { discoverUserTools, discoverUserToolFiles } from "./scope/plugins/usertools/discover.js";
|
|
12
12
|
export type { UserToolFile } from "./scope/plugins/usertools/discover.js";
|
|
13
13
|
export { Scope } from "./scope/Scope.js";
|
|
14
|
-
export type { FilterOutput, ExcludeOptions, FilterOptions } from "./scope/Scope.js";
|
|
14
|
+
export type { FilterOutput, ExcludeOptions, FilterOptions, ScopeConfigSource, } from "./scope/Scope.js";
|
|
15
15
|
export type { ScopePlugin, ScopeCandidates } from "./scope/ScopePlugin.js";
|
|
16
16
|
export { BuiltinToolsScopePlugin } from "./scope/plugins/builtin/BuiltinToolsScopePlugin.js";
|
|
17
17
|
export { UserToolsScopePlugin } from "./scope/plugins/usertools/UserToolsScopePlugin.js";
|
|
18
18
|
export { SkillsScopePlugin } from "./scope/plugins/skills/SkillsScopePlugin.js";
|
|
19
19
|
export { McpScopePlugin } from "./scope/plugins/mcp/McpScopePlugin.js";
|
|
20
20
|
export { SubAgentsScopePlugin } from "./scope/plugins/subagents/SubAgentsScopePlugin.js";
|
|
21
|
+
export { PeerSessionsScopePlugin } from "./scope/plugins/peers/PeerSessionsScopePlugin.js";
|
|
22
|
+
export { PEER_SESSION_TOOL_NAMES, CREATE_SESSION_TOOL, READ_SESSION_STATUS_TOOL, SEND_TO_SESSION_TOOL, } from "./scope/plugins/peers/peerSessionTools.js";
|
|
23
|
+
export type { PeerSessionPort, PeerSessionCreated, PeerSessionStatus, PeerSessionState, PeerSessionRejectReason, PeerSessionCreateInput, PeerSessionSent, PeerSessionSendInput, PeerSessionSendState, } from "./scope/plugins/peers/peerSessionTools.js";
|
|
21
24
|
export { allInOne } from "./scope/plugins/allInOne.js";
|
|
22
25
|
export type { AllInOneOptions } from "./scope/plugins/allInOne.js";
|
|
23
26
|
export { ConfigManager, DEFAULT_AGENT_ID, DEFAULT_AGENT_DEFINITION, DEFAULT_SUBAGENT_ID, DEFAULT_SUBAGENT_DEFINITION, DEFAULT_APP_CONFIG, DEFAULT_MCP_CONFIG, CONFIG_SUB_DIRS, } from "./config/ConfigManager.js";
|
|
@@ -33,7 +36,7 @@ export type { AgentModel } from "./runtime/createModel.js";
|
|
|
33
36
|
export { completeOnce } from "./runtime/completeOnce.js";
|
|
34
37
|
export type { CompleteOnceInput } from "./runtime/completeOnce.js";
|
|
35
38
|
export { SdkAgent } from "./runtime/SdkAgent.js";
|
|
36
|
-
export type { AgentPlugin,
|
|
39
|
+
export type { AgentPlugin, InnerLoopContext, OuterLoopContext, SubAgentHookContext, ToolHookContext, } from "./runtime/SdkAgent.js";
|
|
37
40
|
export { createAgent } from "./runtime/createAgent.js";
|
|
38
41
|
export type { CreateAgentOptions } from "./runtime/createAgent.js";
|
|
39
42
|
export { resolveModel, resolveModelParams } from "./runtime/resolveModel.js";
|
package/dist/index.js
CHANGED
|
@@ -14,6 +14,9 @@ export { UserToolsScopePlugin } from "./scope/plugins/usertools/UserToolsScopePl
|
|
|
14
14
|
export { SkillsScopePlugin } from "./scope/plugins/skills/SkillsScopePlugin.js";
|
|
15
15
|
export { McpScopePlugin } from "./scope/plugins/mcp/McpScopePlugin.js";
|
|
16
16
|
export { SubAgentsScopePlugin } from "./scope/plugins/subagents/SubAgentsScopePlugin.js";
|
|
17
|
+
// 平级会话:能力来自宿主注入的端口,不给端口就不产出任何工具
|
|
18
|
+
export { PeerSessionsScopePlugin } from "./scope/plugins/peers/PeerSessionsScopePlugin.js";
|
|
19
|
+
export { PEER_SESSION_TOOL_NAMES, CREATE_SESSION_TOOL, READ_SESSION_STATUS_TOOL, SEND_TO_SESSION_TOOL, } from "./scope/plugins/peers/peerSessionTools.js";
|
|
17
20
|
export { allInOne } from "./scope/plugins/allInOne.js";
|
|
18
21
|
// 配置 — ConfigManager
|
|
19
22
|
export { ConfigManager, DEFAULT_AGENT_ID, DEFAULT_AGENT_DEFINITION, DEFAULT_SUBAGENT_ID, DEFAULT_SUBAGENT_DEFINITION, DEFAULT_APP_CONFIG, DEFAULT_MCP_CONFIG, CONFIG_SUB_DIRS, } from "./config/ConfigManager.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AgentPlugin,
|
|
1
|
+
import type { AgentPlugin, ToolHookContext } from "@ai-zen/agents-core";
|
|
2
2
|
/**
|
|
3
3
|
* 交接回合的工具守卫 —— 保证「原 agent 停下手头一切工作」不只是提示词约定。
|
|
4
4
|
*
|
|
@@ -8,13 +8,15 @@ import type { AgentPlugin, ToolCallContext } from "@ai-zen/agents-core";
|
|
|
8
8
|
* - `edit` / `batch_edit` / `rm` / `rename` / `mkdir` / `copy`:一律拒绝;
|
|
9
9
|
* - 读取类工具与其他工具:放行。
|
|
10
10
|
*
|
|
11
|
-
* 拒绝方式是**软拒绝**(返回字符串):core 的 `
|
|
12
|
-
*
|
|
13
|
-
*
|
|
11
|
+
* 拒绝方式是**软拒绝**(返回字符串):core 的 `onToolStart` 语义会把该字符串作为那条
|
|
12
|
+
* tool 消息的正文回给模型并继续下一圈,因此模型能读到引导(「只允许写交接文档」)并转回正题。
|
|
13
|
+
* 反例:抛错会穿到 `start()` 外面把整个循环打死(agent 变成僵尸),整轮交接直接停摆。
|
|
14
14
|
*
|
|
15
15
|
* 边界(必须如实记录,不要误以为是安全边界):
|
|
16
16
|
* - **挡不住 `exec`**:`echo > file`、`cat > file <<EOF` 永远能绕过。本插件降低的是
|
|
17
17
|
* 「顺手改代码」的误操作概率,不是沙箱。
|
|
18
|
+
* - **料不到的参数不算放行**:参数解析失败时 `parsedArgs` 为 `undefined`,`write` 会被
|
|
19
|
+
* 当成「没给路径」而拒绝(宁可让模型重试一次,也不放一个看不清的写操作)。
|
|
18
20
|
* - 一次性:`arm()` 后生效,`disarm()` 后完全让行。`Agent.use()` 没有移除 API,
|
|
19
21
|
* 故用「同一实例 + 开关」而非反复注册,避免插件数组无限增长。
|
|
20
22
|
*/
|
|
@@ -31,5 +33,5 @@ export declare class HandoffGuardPlugin implements AgentPlugin {
|
|
|
31
33
|
disarm(): void;
|
|
32
34
|
/** 是否处于交接回合(供上层/测试观察) */
|
|
33
35
|
get armed(): boolean;
|
|
34
|
-
|
|
36
|
+
onToolStart({ toolCall }: ToolHookContext): string | undefined;
|
|
35
37
|
}
|
|
@@ -8,13 +8,15 @@ import { resolve as resolvePath } from "node:path";
|
|
|
8
8
|
* - `edit` / `batch_edit` / `rm` / `rename` / `mkdir` / `copy`:一律拒绝;
|
|
9
9
|
* - 读取类工具与其他工具:放行。
|
|
10
10
|
*
|
|
11
|
-
* 拒绝方式是**软拒绝**(返回字符串):core 的 `
|
|
12
|
-
*
|
|
13
|
-
*
|
|
11
|
+
* 拒绝方式是**软拒绝**(返回字符串):core 的 `onToolStart` 语义会把该字符串作为那条
|
|
12
|
+
* tool 消息的正文回给模型并继续下一圈,因此模型能读到引导(「只允许写交接文档」)并转回正题。
|
|
13
|
+
* 反例:抛错会穿到 `start()` 外面把整个循环打死(agent 变成僵尸),整轮交接直接停摆。
|
|
14
14
|
*
|
|
15
15
|
* 边界(必须如实记录,不要误以为是安全边界):
|
|
16
16
|
* - **挡不住 `exec`**:`echo > file`、`cat > file <<EOF` 永远能绕过。本插件降低的是
|
|
17
17
|
* 「顺手改代码」的误操作概率,不是沙箱。
|
|
18
|
+
* - **料不到的参数不算放行**:参数解析失败时 `parsedArgs` 为 `undefined`,`write` 会被
|
|
19
|
+
* 当成「没给路径」而拒绝(宁可让模型重试一次,也不放一个看不清的写操作)。
|
|
18
20
|
* - 一次性:`arm()` 后生效,`disarm()` 后完全让行。`Agent.use()` 没有移除 API,
|
|
19
21
|
* 故用「同一实例 + 开关」而非反复注册,避免插件数组无限增长。
|
|
20
22
|
*/
|
|
@@ -45,13 +47,13 @@ export class HandoffGuardPlugin {
|
|
|
45
47
|
get armed() {
|
|
46
48
|
return this.handoffPath !== undefined;
|
|
47
49
|
}
|
|
48
|
-
|
|
50
|
+
onToolStart({ toolCall }) {
|
|
49
51
|
const handoffPath = this.handoffPath;
|
|
50
52
|
if (handoffPath == null)
|
|
51
53
|
return;
|
|
52
|
-
const name =
|
|
54
|
+
const name = toolCall.tool_call?.function?.name ?? "";
|
|
53
55
|
if (name === "write") {
|
|
54
|
-
const raw =
|
|
56
|
+
const raw = toolCall.parsedArgs?.path;
|
|
55
57
|
if (typeof raw === "string" && resolvePath(this.cwd, raw) === handoffPath) {
|
|
56
58
|
return;
|
|
57
59
|
}
|
|
@@ -102,7 +102,7 @@ export interface HandoffParams {
|
|
|
102
102
|
* 两种执行者都要认它:
|
|
103
103
|
* - `summary`:直接作为 `chat.completions.create` 的 RequestOptions 传下去,
|
|
104
104
|
* 请求会真的被中断(否则该请求根本无从取消);
|
|
105
|
-
* - `self
|
|
105
|
+
* - `self`:agent 被 `abort()` 了(`paused`),所以每一轮之后要主动检查取不取消。
|
|
106
106
|
*/
|
|
107
107
|
signal?: AbortSignal;
|
|
108
108
|
}
|
|
@@ -121,9 +121,10 @@ export interface MigrateParams extends HandoffParams {
|
|
|
121
121
|
* 模板的唯一真相源是 `handoff` Skill(`SKILL.md`);代码只负责
|
|
122
122
|
* 「读正文 → 注入 → 校验文件 → 读不到时用兜底模板」,不持有第二份章节清单。
|
|
123
123
|
*
|
|
124
|
-
* 重入:`handoff()` 与 `migrate()` 共用 `busy`
|
|
125
|
-
*
|
|
126
|
-
*
|
|
124
|
+
* 重入:`handoff()` 与 `migrate()` 共用 `busy` 标志。交接回合本身就是「往同一个 agent
|
|
125
|
+
* 里再投一轮」(`push` 一条指令),它跑完后 agent 会再变闲一次 —— 若不在 busy 期间让
|
|
126
|
+
* `AutoMigratePlugin` / `ContextGuardPlugin` 让行,就会「交接触发迁移、迁移再触发交接」
|
|
127
|
+
* 无限递归,或在最满的时刻被护栏直接拒掉。
|
|
127
128
|
*
|
|
128
129
|
* 取消:取消句柄由服务自己持有({@link HandoffService.abort}),而不是只认调用方传进来的
|
|
129
130
|
* `signal` —— 自动迁移由 `AutoMigratePlugin` 直接驱动,调用方根本没有机会把 signal 递进来,
|
|
@@ -187,6 +188,9 @@ export declare class HandoffService {
|
|
|
187
188
|
*
|
|
188
189
|
* 为什么不内联全文:接手方第一次真正需要的是「去哪里取交接」,读一次文件的输入成本
|
|
189
190
|
* 与内联全文相当,但内联会让每条请求都携带全文;路径方案把成本推迟到真正需要时。
|
|
191
|
+
*
|
|
192
|
+
* `source` 必须带(`CORE.md` §3「所有 `role: user` 的消息都必须有 source」):这条不是
|
|
193
|
+
* 用户说的话,是宿主注入的,所以是 `system` + label。
|
|
190
194
|
*/
|
|
191
195
|
static createPostMessages(handoffPath: string): AgentNS.Message[];
|
|
192
196
|
/** 序列化消息为 `[role]: content` 文本(仅 `summary` 模式使用) */
|
|
@@ -195,8 +199,9 @@ export declare class HandoffService {
|
|
|
195
199
|
* 取消进行中的交接/迁移(用户按 Ctrl+C)。没有进行中的交接时是 no-op。
|
|
196
200
|
*
|
|
197
201
|
* 边界:本方法只保证「停下 + 回退」——不再重试、不降级 summary、不迁移,并把会话
|
|
198
|
-
* 退回交接前。**它不负责立刻掐断正在跑的模型请求**:`self`
|
|
199
|
-
* `
|
|
202
|
+
* 退回交接前。**它不负责立刻掐断正在跑的模型请求**:`self` 模式的那一轮是往常驻 agent 里
|
|
203
|
+
* `push()` 的一条指令,调用方通常要同时 `agent.abort()`(TUI 就是这么做的 ——
|
|
204
|
+
* 那一按会让 agent 停在 `paused`,本服务随之把这一轮判成「没跑完」);`summary`
|
|
200
205
|
* 模式的那次请求拿的是本服务合并出的 signal,会被真正中断。
|
|
201
206
|
*/
|
|
202
207
|
abort(): void;
|
|
@@ -255,25 +260,59 @@ export declare class HandoffService {
|
|
|
255
260
|
* 截回原长度之后,转录、历史、用量全都自动复位,不需要第二处补偿。
|
|
256
261
|
*/
|
|
257
262
|
private restoreBeforeHandoff;
|
|
258
|
-
/**
|
|
263
|
+
/**
|
|
264
|
+
* 自交接是否可用:需要 `write` 工具,且 agent 是**常驻**的。
|
|
265
|
+
*
|
|
266
|
+
* 为什么要看 `lifetime`:自交接靠「往同一个会话里投一轮指令」实现,而一次性 agent
|
|
267
|
+
* 开跑即关收(第二次 `push` 抛 `closed`),且跑完就死透(`CORE.md` §1)—— 它根本没
|
|
268
|
+
* 有「再问一轮」这种能力。
|
|
269
|
+
*/
|
|
259
270
|
private supportsSelfHandoff;
|
|
260
271
|
/**
|
|
261
272
|
* 自交接回合:让原 agent 停工、核实、写文档,并校验文件确实落盘。
|
|
262
273
|
*
|
|
263
274
|
* 失败判定(任一成立即视为失败,交由上层单向降级 summary):
|
|
264
275
|
* - 文件不存在 / 小于阈值;
|
|
265
|
-
* -
|
|
276
|
+
* - 模型/工具链抛错(例如没有权限、被护栏拒绝);
|
|
277
|
+
* - 这一轮压根没跑完(agent 被 `abort()` 暂停、或已经被关门/硬杀)。
|
|
266
278
|
*
|
|
267
279
|
* **取消不算失败**:`signal` 已触发时抛 {@link HandoffAbortedError},既不走
|
|
268
|
-
* 「文件没写好→重试一次」也不降级 summary。
|
|
269
|
-
*
|
|
270
|
-
*
|
|
271
|
-
*
|
|
280
|
+
* 「文件没写好→重试一次」也不降级 summary。 这条分支必须显式写:`agent.abort()` 不抛错
|
|
281
|
+
* (core 把在途请求掉、消息标记成 Aborted 然后正常返回),否则「用户按了 Ctrl+C」会被
|
|
282
|
+
* 下面的文件校验误判成「模型没写出文档」,于是重试一轮、再降级一轮 —— 用户以为取消了,
|
|
283
|
+
* 实际多烧了两轮全量输入。
|
|
272
284
|
*
|
|
273
285
|
* 取消的善后(删文档、截消息)不在这里做:交给 {@link runHandoff} 的 catch 一处处理,
|
|
274
286
|
* 因为「文档已写出但还没校验」的取消根本进不到本方法的 catch。
|
|
275
287
|
*/
|
|
276
288
|
private runSelfHandoff;
|
|
289
|
+
/**
|
|
290
|
+
* 往**常驻** agent 里投一条指令,等这一轮真的收完。
|
|
291
|
+
*
|
|
292
|
+
* ## 为什么是「push + 订阅 state」
|
|
293
|
+
*
|
|
294
|
+
* core 重写后没有 `send()` 了(`CORE.md` §1:「常驻会话只 `push`,不看返回值」):
|
|
295
|
+
* 「等」这种动作看不见不由我引起的变化,唯一可靠的替代是**订阅**。于是这里先订阅
|
|
296
|
+
* `state`、再 `push` —— 顺序不能反:push 之后状态已经变了,晚一步就错过「这一轮开始了」
|
|
297
|
+
* 那一拍,随后第一次报闲会被误当成「我这一轮跑完了」。
|
|
298
|
+
*
|
|
299
|
+
* ## `start()`:老 `send()` 隐含的那件事
|
|
300
|
+
*
|
|
301
|
+
* 老的 `send()` 是对「这个 agent」发起的,没起来也能顺手跑一段。新 core 的循环只听
|
|
302
|
+
* `start()`,所以这里先把它叫起来:`start()` 幂等(已起来就返回同一句 promise),
|
|
303
|
+
* **不能 await** —— 它到死才 resolve。宿主正常会话里这一句是空动作。
|
|
304
|
+
*
|
|
305
|
+
* ## 返回「这一轮怎么结束的」而不是「成没成」
|
|
306
|
+
*
|
|
307
|
+
* 三种结束方式对调用方意义不同(`idle` 才能去校验产物),所以分开报:
|
|
308
|
+
* - `idle`:跑完了;
|
|
309
|
+
* - `paused`:被 `abort()` 暂停/掉;
|
|
310
|
+
* - `dead`:关门/硬杀,循环已经结束。
|
|
311
|
+
*
|
|
312
|
+
* 第四种情况不在这里表达:`push` 在关门之后会直接抛 `AgentError("closed")` —— 那是
|
|
313
|
+
* 「调用方违约」(往一个已经没有的会话里塞东西),就该往上抛,不该被归成一种“结束方式”。
|
|
314
|
+
*/
|
|
315
|
+
private pushInstructionRound;
|
|
277
316
|
/** 独立摘要:一次模型调用,用同一份 Skill 正文作为规范 */
|
|
278
317
|
private generateSummary;
|
|
279
318
|
/** 落盘(仅 `summary` 模式需要;`self` 模式由 agent 的 write 工具完成) */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { promises as fs } from "node:fs";
|
|
2
2
|
import { dirname, join, resolve as resolvePath } from "node:path";
|
|
3
|
-
import { Message } from "@ai-zen/agents-core";
|
|
3
|
+
import { AgentError, 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";
|
|
@@ -55,9 +55,10 @@ function mergeSignals(own, external) {
|
|
|
55
55
|
* 模板的唯一真相源是 `handoff` Skill(`SKILL.md`);代码只负责
|
|
56
56
|
* 「读正文 → 注入 → 校验文件 → 读不到时用兜底模板」,不持有第二份章节清单。
|
|
57
57
|
*
|
|
58
|
-
* 重入:`handoff()` 与 `migrate()` 共用 `busy`
|
|
59
|
-
*
|
|
60
|
-
*
|
|
58
|
+
* 重入:`handoff()` 与 `migrate()` 共用 `busy` 标志。交接回合本身就是「往同一个 agent
|
|
59
|
+
* 里再投一轮」(`push` 一条指令),它跑完后 agent 会再变闲一次 —— 若不在 busy 期间让
|
|
60
|
+
* `AutoMigratePlugin` / `ContextGuardPlugin` 让行,就会「交接触发迁移、迁移再触发交接」
|
|
61
|
+
* 无限递归,或在最满的时刻被护栏直接拒掉。
|
|
61
62
|
*
|
|
62
63
|
* 取消:取消句柄由服务自己持有({@link HandoffService.abort}),而不是只认调用方传进来的
|
|
63
64
|
* `signal` —— 自动迁移由 `AutoMigratePlugin` 直接驱动,调用方根本没有机会把 signal 递进来,
|
|
@@ -169,6 +170,9 @@ export class HandoffService {
|
|
|
169
170
|
*
|
|
170
171
|
* 为什么不内联全文:接手方第一次真正需要的是「去哪里取交接」,读一次文件的输入成本
|
|
171
172
|
* 与内联全文相当,但内联会让每条请求都携带全文;路径方案把成本推迟到真正需要时。
|
|
173
|
+
*
|
|
174
|
+
* `source` 必须带(`CORE.md` §3「所有 `role: user` 的消息都必须有 source」):这条不是
|
|
175
|
+
* 用户说的话,是宿主注入的,所以是 `system` + label。
|
|
172
176
|
*/
|
|
173
177
|
static createPostMessages(handoffPath) {
|
|
174
178
|
const content = [
|
|
@@ -177,7 +181,7 @@ export class HandoffService {
|
|
|
177
181
|
"",
|
|
178
182
|
"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.",
|
|
179
183
|
].join("\n");
|
|
180
|
-
return [Message.User(content)];
|
|
184
|
+
return [Message.User(content, { kind: "system", label: "handoff" })];
|
|
181
185
|
}
|
|
182
186
|
/** 序列化消息为 `[role]: content` 文本(仅 `summary` 模式使用) */
|
|
183
187
|
static serializeMessages(messages) {
|
|
@@ -196,8 +200,9 @@ export class HandoffService {
|
|
|
196
200
|
* 取消进行中的交接/迁移(用户按 Ctrl+C)。没有进行中的交接时是 no-op。
|
|
197
201
|
*
|
|
198
202
|
* 边界:本方法只保证「停下 + 回退」——不再重试、不降级 summary、不迁移,并把会话
|
|
199
|
-
* 退回交接前。**它不负责立刻掐断正在跑的模型请求**:`self`
|
|
200
|
-
* `
|
|
203
|
+
* 退回交接前。**它不负责立刻掐断正在跑的模型请求**:`self` 模式的那一轮是往常驻 agent 里
|
|
204
|
+
* `push()` 的一条指令,调用方通常要同时 `agent.abort()`(TUI 就是这么做的 ——
|
|
205
|
+
* 那一按会让 agent 停在 `paused`,本服务随之把这一轮判成「没跑完」);`summary`
|
|
201
206
|
* 模式的那次请求拿的是本服务合并出的 signal,会被真正中断。
|
|
202
207
|
*/
|
|
203
208
|
abort() {
|
|
@@ -346,7 +351,7 @@ export class HandoffService {
|
|
|
346
351
|
let handoffDoc;
|
|
347
352
|
let historyText = "";
|
|
348
353
|
if (mode === "self" && !this.supportsSelfHandoff(agent)) {
|
|
349
|
-
this.logger.warn("[handoff] agent has no write tool or
|
|
354
|
+
this.logger.warn("[handoff] agent has no write tool or is not a resident session, falling back to standalone summary mode");
|
|
350
355
|
mode = "summary";
|
|
351
356
|
}
|
|
352
357
|
if (mode === "self") {
|
|
@@ -401,9 +406,15 @@ export class HandoffService {
|
|
|
401
406
|
agent.messages.splice(messageCountBefore);
|
|
402
407
|
await this.discardPartialFile(handoffPath, existedBefore);
|
|
403
408
|
}
|
|
404
|
-
/**
|
|
409
|
+
/**
|
|
410
|
+
* 自交接是否可用:需要 `write` 工具,且 agent 是**常驻**的。
|
|
411
|
+
*
|
|
412
|
+
* 为什么要看 `lifetime`:自交接靠「往同一个会话里投一轮指令」实现,而一次性 agent
|
|
413
|
+
* 开跑即关收(第二次 `push` 抛 `closed`),且跑完就死透(`CORE.md` §1)—— 它根本没
|
|
414
|
+
* 有「再问一轮」这种能力。
|
|
415
|
+
*/
|
|
405
416
|
supportsSelfHandoff(agent) {
|
|
406
|
-
if (
|
|
417
|
+
if (agent.lifetime === "one-shot")
|
|
407
418
|
return false;
|
|
408
419
|
return Boolean(agent.tools?.some((tool) => tool.function?.name === "write"));
|
|
409
420
|
}
|
|
@@ -412,13 +423,14 @@ export class HandoffService {
|
|
|
412
423
|
*
|
|
413
424
|
* 失败判定(任一成立即视为失败,交由上层单向降级 summary):
|
|
414
425
|
* - 文件不存在 / 小于阈值;
|
|
415
|
-
* -
|
|
426
|
+
* - 模型/工具链抛错(例如没有权限、被护栏拒绝);
|
|
427
|
+
* - 这一轮压根没跑完(agent 被 `abort()` 暂停、或已经被关门/硬杀)。
|
|
416
428
|
*
|
|
417
429
|
* **取消不算失败**:`signal` 已触发时抛 {@link HandoffAbortedError},既不走
|
|
418
|
-
* 「文件没写好→重试一次」也不降级 summary。
|
|
419
|
-
*
|
|
420
|
-
*
|
|
421
|
-
*
|
|
430
|
+
* 「文件没写好→重试一次」也不降级 summary。 这条分支必须显式写:`agent.abort()` 不抛错
|
|
431
|
+
* (core 把在途请求掉、消息标记成 Aborted 然后正常返回),否则「用户按了 Ctrl+C」会被
|
|
432
|
+
* 下面的文件校验误判成「模型没写出文档」,于是重试一轮、再降级一轮 —— 用户以为取消了,
|
|
433
|
+
* 实际多烧了两轮全量输入。
|
|
422
434
|
*
|
|
423
435
|
* 取消的善后(删文档、截消息)不在这里做:交给 {@link runHandoff} 的 catch 一处处理,
|
|
424
436
|
* 因为「文档已写出但还没校验」的取消根本进不到本方法的 catch。
|
|
@@ -435,24 +447,34 @@ export class HandoffService {
|
|
|
435
447
|
*/
|
|
436
448
|
guard.arm(handoffPath, cwd);
|
|
437
449
|
try {
|
|
438
|
-
await
|
|
450
|
+
const first = await this.pushInstructionRound(agent, HandoffService.createHandoffInstruction({
|
|
439
451
|
skillContent,
|
|
440
452
|
handoffPath,
|
|
441
453
|
toolsAvailable: true,
|
|
442
|
-
}));
|
|
454
|
+
}), signal);
|
|
443
455
|
// `agent.abort()` 不抛错,必须主动检查(见方法注释)
|
|
444
456
|
this.throwIfAborted(signal);
|
|
457
|
+
// 这一轮没跑完(暂停 / 关门 / 硬杀):产物没意义,也别再往里投 ——
|
|
458
|
+
// 暂停中不取件,再投只会把一条陈旧指令留在队列里,等 resume 之后突然自己跑起来
|
|
459
|
+
if (first !== "idle")
|
|
460
|
+
return false;
|
|
445
461
|
if (await this.isHandoffFileReady(handoffPath))
|
|
446
462
|
return true;
|
|
447
463
|
this.logger.warn(`[handoff] handoff document missing or too small, retrying once: ${handoffPath}`);
|
|
448
|
-
await
|
|
464
|
+
const second = await this.pushInstructionRound(agent, [
|
|
449
465
|
`The handoff document does not exist or is too small to deliver: ${handoffPath}`,
|
|
450
466
|
"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.",
|
|
451
|
-
].join("\n"));
|
|
467
|
+
].join("\n"), signal);
|
|
452
468
|
this.throwIfAborted(signal);
|
|
469
|
+
if (second !== "idle")
|
|
470
|
+
return false;
|
|
453
471
|
return await this.isHandoffFileReady(handoffPath);
|
|
454
472
|
}
|
|
455
473
|
catch (err) {
|
|
474
|
+
// agent 已经关门:不是「文档没写出来」,是「这个会话已经不在了」。降级 summary 会
|
|
475
|
+
// 为一个死掉的会话白烧一轮全量输入,所以直接把 `closed` 往上交(调用方该知道这件事)
|
|
476
|
+
if (err instanceof AgentError && err.code === "closed")
|
|
477
|
+
throw err;
|
|
456
478
|
if (isAbortError(err, signal))
|
|
457
479
|
throw new HandoffAbortedError();
|
|
458
480
|
this.logger.error(`[handoff] self handoff round failed: ${err?.message ?? err}`);
|
|
@@ -462,6 +484,77 @@ export class HandoffService {
|
|
|
462
484
|
guard.disarm();
|
|
463
485
|
}
|
|
464
486
|
}
|
|
487
|
+
/**
|
|
488
|
+
* 往**常驻** agent 里投一条指令,等这一轮真的收完。
|
|
489
|
+
*
|
|
490
|
+
* ## 为什么是「push + 订阅 state」
|
|
491
|
+
*
|
|
492
|
+
* core 重写后没有 `send()` 了(`CORE.md` §1:「常驻会话只 `push`,不看返回值」):
|
|
493
|
+
* 「等」这种动作看不见不由我引起的变化,唯一可靠的替代是**订阅**。于是这里先订阅
|
|
494
|
+
* `state`、再 `push` —— 顺序不能反:push 之后状态已经变了,晚一步就错过「这一轮开始了」
|
|
495
|
+
* 那一拍,随后第一次报闲会被误当成「我这一轮跑完了」。
|
|
496
|
+
*
|
|
497
|
+
* ## `start()`:老 `send()` 隐含的那件事
|
|
498
|
+
*
|
|
499
|
+
* 老的 `send()` 是对「这个 agent」发起的,没起来也能顺手跑一段。新 core 的循环只听
|
|
500
|
+
* `start()`,所以这里先把它叫起来:`start()` 幂等(已起来就返回同一句 promise),
|
|
501
|
+
* **不能 await** —— 它到死才 resolve。宿主正常会话里这一句是空动作。
|
|
502
|
+
*
|
|
503
|
+
* ## 返回「这一轮怎么结束的」而不是「成没成」
|
|
504
|
+
*
|
|
505
|
+
* 三种结束方式对调用方意义不同(`idle` 才能去校验产物),所以分开报:
|
|
506
|
+
* - `idle`:跑完了;
|
|
507
|
+
* - `paused`:被 `abort()` 暂停/掉;
|
|
508
|
+
* - `dead`:关门/硬杀,循环已经结束。
|
|
509
|
+
*
|
|
510
|
+
* 第四种情况不在这里表达:`push` 在关门之后会直接抛 `AgentError("closed")` —— 那是
|
|
511
|
+
* 「调用方违约」(往一个已经没有的会话里塞东西),就该往上抛,不该被归成一种“结束方式”。
|
|
512
|
+
*/
|
|
513
|
+
async pushInstructionRound(agent, content, signal) {
|
|
514
|
+
// 暂停中不取件:此刻投进去只会排在队列里,等 resume 后突然自己跑起来
|
|
515
|
+
if (agent.state === "paused")
|
|
516
|
+
return "paused";
|
|
517
|
+
// 叫起来(幂等;不 await —— 那句 promise 到死才 resolve)
|
|
518
|
+
void agent.start();
|
|
519
|
+
const ended = new Promise((resolve) => {
|
|
520
|
+
let sawBusy = false;
|
|
521
|
+
const offs = [];
|
|
522
|
+
const finish = (end) => {
|
|
523
|
+
for (const off of offs.splice(0))
|
|
524
|
+
off();
|
|
525
|
+
resolve(end);
|
|
526
|
+
};
|
|
527
|
+
offs.push(agent.on("state", (event) => {
|
|
528
|
+
if (event.to === "busy") {
|
|
529
|
+
sawBusy = true;
|
|
530
|
+
}
|
|
531
|
+
else if (event.to === "idle" && sawBusy) {
|
|
532
|
+
// 只认「忙过之后的闲」:投递之前那一段(队列里还压着别人的货)的闲不是我的
|
|
533
|
+
finish("idle");
|
|
534
|
+
}
|
|
535
|
+
else if (event.to === "paused") {
|
|
536
|
+
finish("paused");
|
|
537
|
+
}
|
|
538
|
+
}));
|
|
539
|
+
offs.push(agent.on("stopped", () => finish("dead")));
|
|
540
|
+
offs.push(agent.on("killed", () => finish("dead")));
|
|
541
|
+
// 取消也要能打断「等闲」(`CORE.md` §5 那个死角:等子 agent 闲同样得能被掐断)
|
|
542
|
+
const onAbort = () => finish("paused");
|
|
543
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
544
|
+
// 正常收尾时把 signal 上的监听一起摘掉:调用方的 signal 可能活得比这一轮长得多
|
|
545
|
+
offs.push(() => signal?.removeEventListener("abort", onAbort));
|
|
546
|
+
});
|
|
547
|
+
agent.push({
|
|
548
|
+
content,
|
|
549
|
+
priority: "low",
|
|
550
|
+
// 这条指令是**宿主侧**(`/handoff` 命令、自动迁移)注入的,不是用户说的话 ——
|
|
551
|
+
// 按「谁注入谁填」给它一个 system 来源(`CORE.md` §3)
|
|
552
|
+
source: { kind: "system", label: "handoff" },
|
|
553
|
+
});
|
|
554
|
+
// 关门之后投递会抛 `AgentError("closed")`(`CORE.md` §1):不接、不归类,
|
|
555
|
+
// 让它往上走到 {@link runSelfHandoff} 的 catch(那里把 closed 原样再往上交)
|
|
556
|
+
return await ended;
|
|
557
|
+
}
|
|
465
558
|
/** 独立摘要:一次模型调用,用同一份 Skill 正文作为规范 */
|
|
466
559
|
async generateSummary(agent, historyText, handoffPath, signal) {
|
|
467
560
|
const client = this.client ?? agent.client;
|
|
@@ -4,7 +4,7 @@ import type { AbortedMessageStrategy, AbortedToolRoundStrategy, AgentNS, Tool }
|
|
|
4
4
|
import type { AgentDefinition } from "../types/index.js";
|
|
5
5
|
import type { Scope } from "../scope/Scope.js";
|
|
6
6
|
import type { ModelLevel } from "./resolveModel.js";
|
|
7
|
-
export type { AgentPlugin,
|
|
7
|
+
export type { AgentPlugin, InnerLoopContext, OuterLoopContext, SubAgentHookContext, ToolHookContext, } from "@ai-zen/agents-core";
|
|
8
8
|
/**
|
|
9
9
|
* SDK Agent — 继承 Core Agent,携带 SDK 层额外信息。
|
|
10
10
|
*
|
|
@@ -16,7 +16,7 @@ export type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
|
|
|
16
16
|
* - modelLevel:这个模型是从哪一级解析出来的(会话 / Agent 定义 / 全局兜底)。
|
|
17
17
|
* 值是 `resolveModel` 的副产品,客户端用它把「当前生效档」标在 `/model` 选择器上。
|
|
18
18
|
*
|
|
19
|
-
* 插件能力(use / init /
|
|
19
|
+
* 插件能力(use / init / 钩子分发)继承自 Core Agent,此处不重复实现。
|
|
20
20
|
* 未知工具的 MCP 智能提示由独立插件 `UnknownToolHintPlugin` 提供(调用方显式 use)。
|
|
21
21
|
* 权限统一从 `definition.permissions` 读取。
|
|
22
22
|
*/
|
|
@@ -36,7 +36,6 @@ export declare class SdkAgent extends Agent {
|
|
|
36
36
|
modelConfig?: Record<string, unknown>;
|
|
37
37
|
messages?: AgentNS.Message[];
|
|
38
38
|
tools?: Tool[];
|
|
39
|
-
allowJsonParseError?: boolean;
|
|
40
39
|
/** 工具轮次被中断时的归一策略(core 默认 `fill`) */
|
|
41
40
|
abortedToolRoundStrategy?: AbortedToolRoundStrategy;
|
|
42
41
|
/** `fill` 策略下未完成工具结果的填充原因 */
|
package/dist/runtime/SdkAgent.js
CHANGED
|
@@ -10,7 +10,7 @@ import { Agent } from "@ai-zen/agents-core";
|
|
|
10
10
|
* - modelLevel:这个模型是从哪一级解析出来的(会话 / Agent 定义 / 全局兜底)。
|
|
11
11
|
* 值是 `resolveModel` 的副产品,客户端用它把「当前生效档」标在 `/model` 选择器上。
|
|
12
12
|
*
|
|
13
|
-
* 插件能力(use / init /
|
|
13
|
+
* 插件能力(use / init / 钩子分发)继承自 Core Agent,此处不重复实现。
|
|
14
14
|
* 未知工具的 MCP 智能提示由独立插件 `UnknownToolHintPlugin` 提供(调用方显式 use)。
|
|
15
15
|
* 权限统一从 `definition.permissions` 读取。
|
|
16
16
|
*/
|
|
@@ -28,7 +28,6 @@ export class SdkAgent extends Agent {
|
|
|
28
28
|
modelConfig: params.modelConfig,
|
|
29
29
|
messages: params.messages,
|
|
30
30
|
tools: params.tools,
|
|
31
|
-
allowJsonParseError: params.allowJsonParseError,
|
|
32
31
|
abortedToolRoundStrategy: params.abortedToolRoundStrategy,
|
|
33
32
|
abortedToolRoundReason: params.abortedToolRoundReason,
|
|
34
33
|
abortedMessageStrategy: params.abortedMessageStrategy,
|