@ai-zen/agents-sdk 0.7.1 → 0.9.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 -3
- package/README.zh.md +4 -3
- package/dist/index.d.ts +1 -1
- package/dist/plugin/AutoMigratePlugin.d.ts +8 -13
- package/dist/plugin/AutoMigratePlugin.js +7 -53
- package/dist/plugin/ContextGuardPlugin.d.ts +1 -1
- package/dist/plugin/ContextGuardPlugin.js +1 -1
- package/dist/runtime/TaskMigrationService.d.ts +112 -8
- package/dist/runtime/TaskMigrationService.js +158 -16
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,45 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.9.0] - 2026-08-28
|
|
4
|
+
|
|
5
|
+
### 🎯 Optimized
|
|
6
|
+
|
|
7
|
+
- **`TaskMigrationService.migrate` gains a `strategy` switch** — controls how history is handled after migration:
|
|
8
|
+
- **`omit` (default)**: history messages are marked `omit: true` (kept in `agent.messages` for audit/replay, but `Agent.formatHistory()` filters them out), and a "conversation breakpoint" message (handoff doc + handover instructions, role=user) is appended as the new context start. The sequence sent to the model becomes `[definition.messages, breakpoint message]`. Reuses Core's existing `omit` mechanism — no Core changes needed.
|
|
9
|
+
- **`prune`**: physically drops history, keeping only `definition.messages` + breakpoint message (the previous replace behavior).
|
|
10
|
+
- The default can be set via `strategy` when constructing `TaskMigrationService`, and overridden per `migrate()` call (`MigrationStrategy` type is exported).
|
|
11
|
+
- `agent.messages` is rebuilt via a **shallow copy** to avoid mutating objects referenced by `definition.messages` (prevents polluting the template).
|
|
12
|
+
- `historyText` (fed to the model to generate the handoff doc) now **filters omitted history**, so repeated migrations don't re-feed old omitted history to the model.
|
|
13
|
+
- `AutoMigratePlugin` still only decides *when* to trigger — no changes needed.
|
|
14
|
+
|
|
15
|
+
### ✅ Tests
|
|
16
|
+
|
|
17
|
+
- `TaskMigrationService` / `AutoMigratePlugin` assertions updated to the omit semantics (history marked omit + trailing breakpoint + system prompt preserved).
|
|
18
|
+
- New case: `historyText` filters already-omitted history.
|
|
19
|
+
- New case: `strategy=prune` (constructor default + `migrate` param override) physically drops history.
|
|
20
|
+
|
|
21
|
+
## [0.8.0] - 2026-08-24
|
|
22
|
+
|
|
23
|
+
### ⚠️ Breaking
|
|
24
|
+
|
|
25
|
+
- **`TaskMigrationService` is now an instantiated, self-contained migration service** — it holds no model call of its own: `migrate()` reuses the passed `agent`'s own `client` / `model` / `modelConfig` to generate the handoff document, so it needs no `Provider` and no standalone "migration Agent" object (and no duplicated `config + modelId` model wiring). `migrate()` is an instance method that serializes history, calls the model to generate the handoff document, and replaces `agent.messages`.
|
|
26
|
+
- `TaskMigrationServiceOptions` = `{ client?, model?, modelConfig?, onBeforeMigrate?, onMigrated?, logger? }` — pass `client`/`model`/`modelConfig` to override the model call used for the handoff; when omitted, `migrate()` falls back to the passed `agent`'s own config
|
|
27
|
+
- `migrate({ agent, promptTokens?, maxTokens? })` — `agent` is the only runtime param (its `client`/`model`/`modelConfig` back the model call); the migration hooks are flat on the service instance (no `hooks` wrapper)
|
|
28
|
+
- **`AutoMigratePlugin` narrowed to a trigger-only role** — constructor takes `{ service, maxTokens }`; it only detects token overflow in `onAfterSend` and delegates to `service.migrate({ agent, promptTokens, maxTokens })`. No hooks on the plugin.
|
|
29
|
+
- **Removed** — `TaskMigrationService.createAgentDefinition` (the service calls the model directly, so a standalone migration Agent definition is unnecessary) and `BuildMigrationAgentOptions`; `MigrationContext` no longer carries `migrationAgent` (records `model` instead).
|
|
30
|
+
- **New exports** — `MigrationContext`, `TaskMigrationServiceOptions`.
|
|
31
|
+
|
|
32
|
+
### 🛠 Optimized
|
|
33
|
+
|
|
34
|
+
- `serializeMessages` moved from `AutoMigratePlugin` private to `TaskMigrationService` public static.
|
|
35
|
+
- The pure-tool statics (`createPrompt` / `createPostMessages` / `serializeMessages`) remain `static`; the instance `migrate()` reuses the passed `agent`'s model client. The "should migrate" check (`promptTokens > maxTokens`) lives in `AutoMigratePlugin` (the trigger side), not on the service.
|
|
36
|
+
- Migration failure still leaves `agent.messages` unchanged (atomic); hook errors are caught and logged, never interrupting the migration flow.
|
|
37
|
+
|
|
38
|
+
### ✅ Tests
|
|
39
|
+
|
|
40
|
+
- `TaskMigrationService`: statics (`createPrompt` / `createPostMessages` / `serializeMessages`) + `migrate` (model call, hook contexts, failure atomicity) — all green.
|
|
41
|
+
- `AutoMigratePlugin`: trigger-only behavior (overflow → `service.migrate`; below threshold / no usage → no model call).
|
|
42
|
+
|
|
3
43
|
## [0.7.1] - 2026-08-25
|
|
4
44
|
|
|
5
45
|
### 🚀 New Features
|
package/README.md
CHANGED
|
@@ -63,7 +63,8 @@ const provider = await Provider.create({
|
|
|
63
63
|
...paths,
|
|
64
64
|
});
|
|
65
65
|
const agent = createAgent(provider, "my-agent");
|
|
66
|
-
|
|
66
|
+
const migrationService = new TaskMigrationService({ onMigrated }); // migrates via the agent's own model client
|
|
67
|
+
agent.use(new AutoMigratePlugin({ service: migrationService, maxTokens }));
|
|
67
68
|
agent.use(new AutoRefreshToolsPlugin());
|
|
68
69
|
await agent.init();
|
|
69
70
|
await agent.send("Hello");
|
|
@@ -80,7 +81,7 @@ await agent.send("Hello");
|
|
|
80
81
|
| `runtime` | ✅ Implemented — Provider, Capabilities, createAgent, MCP connection management, task migration |
|
|
81
82
|
| `plugin` | ✅ Implemented — AutoMigratePlugin / AutoRefreshToolsPlugin / ContextGuardPlugin / UnknownToolHintPlugin |
|
|
82
83
|
| `shared` | ✅ Implemented — SdkError + injectable Logger |
|
|
83
|
-
| Tests | ✅
|
|
84
|
+
| Tests | ✅ 452 passing, 51 files, all green (incl. real-API chat & viewImage e2e) |
|
|
84
85
|
|
|
85
86
|
## Built-in Tools
|
|
86
87
|
|
|
@@ -117,7 +118,7 @@ Conditionally injected based on the active model / config:
|
|
|
117
118
|
|
|
118
119
|
| Plugin | Description |
|
|
119
120
|
|--------|-------------|
|
|
120
|
-
| `AutoMigratePlugin` | Automatically triggers task migration when the context overflows,
|
|
121
|
+
| `AutoMigratePlugin` | Automatically triggers task migration when the context overflows; delegates the actual migration to the injected `TaskMigrationService` instance (history handled per `strategy`: default `omit` keeps it auditable, optional `prune` drops it), which reuses the agent's own model client |
|
|
121
122
|
| `AutoRefreshToolsPlugin` | Re-scans the file system before each `send()` to refresh the tool list |
|
|
122
123
|
| `ContextGuardPlugin` | Context safety guard — before each request, throws `ContextOverflowError` (interrupting the conversation) when the previous round's `usage.prompt_tokens` exceeds `maxTokens × ratio` (default 1.5), preventing context runaway from reading oversized files |
|
|
123
124
|
| `UnknownToolHintPlugin` | Smarter unknown-tool hints — when the LLM calls a nonexistent tool, guides it to `call_mcp_tool` / points out permission issues based on MCP config (opt-in via `agent.use`) |
|
|
@@ -133,3 +134,4 @@ See the project-root [`PRINCIPLES.md`](../../PRINCIPLES.md):
|
|
|
133
134
|
5. Occam's razor
|
|
134
135
|
6. Refactor as you go; keep clean layering
|
|
135
136
|
7. Tests are the foundation
|
|
137
|
+
he foundation
|
package/README.zh.md
CHANGED
|
@@ -62,7 +62,8 @@ const provider = await Provider.create({
|
|
|
62
62
|
...paths,
|
|
63
63
|
});
|
|
64
64
|
const agent = createAgent(provider, "my-agent");
|
|
65
|
-
|
|
65
|
+
const migrationService = new TaskMigrationService({ onMigrated }); // 迁移复用传入 agent 自身的模型调用
|
|
66
|
+
agent.use(new AutoMigratePlugin({ service: migrationService, maxTokens }));
|
|
66
67
|
agent.use(new AutoRefreshToolsPlugin());
|
|
67
68
|
await agent.init();
|
|
68
69
|
await agent.send("你好");
|
|
@@ -79,7 +80,7 @@ await agent.send("你好");
|
|
|
79
80
|
| `runtime` | ✅ 已实现 — Provider、Capabilities、createAgent、MCP 连接管理、任务迁移 |
|
|
80
81
|
| `plugin` | ✅ 已实现 — AutoMigratePlugin / AutoRefreshToolsPlugin / ContextGuardPlugin / UnknownToolHintPlugin |
|
|
81
82
|
| `shared` | ✅ 已实现 — SdkError + 可注入 Logger |
|
|
82
|
-
| 测试 | ✅
|
|
83
|
+
| 测试 | ✅ 452 通过,51 个文件,全绿(含真实 API 聊天与 viewImage e2e) |
|
|
83
84
|
|
|
84
85
|
## 内置工具
|
|
85
86
|
|
|
@@ -116,7 +117,7 @@ await agent.send("你好");
|
|
|
116
117
|
|
|
117
118
|
| 插件 | 说明 |
|
|
118
119
|
|------|------|
|
|
119
|
-
| `AutoMigratePlugin` |
|
|
120
|
+
| `AutoMigratePlugin` | 上下文超限时自动触发任务迁移,生成交接文档并追加对话断点(历史按 `strategy` 处理:默认 `omit` 标记保留可审计,可选 `prune` 物理剔除;委托注入的 `TaskMigrationService`,复用 Agent 自身的模型调用) |
|
|
120
121
|
| `AutoRefreshToolsPlugin` | 每次 `send()` 前重新扫描文件系统,刷新工具列表 |
|
|
121
122
|
| `ContextGuardPlugin` | 上下文安全护栏 — 每轮发请求前检测上一轮 `usage.prompt_tokens`,超过 `maxTokens × ratio`(默认 1.5,即 +50%)时抛 `ContextOverflowError` 中断对话,防止读入超大文件导致上下文失控 |
|
|
122
123
|
| `UnknownToolHintPlugin` | 未知工具智能提示 — LLM 调用不存在的工具时,根据 MCP 配置引导使用 `call_mcp_tool` / 提示权限问题(调用方显式 `agent.use` 注册) |
|
package/dist/index.d.ts
CHANGED
|
@@ -23,7 +23,7 @@ export type { McpConnectOptions } from "./runtime/McpConnectionManager.js";
|
|
|
23
23
|
export { SdkCallbackTool } from "./runtime/SdkCallbackTool.js";
|
|
24
24
|
export type { SdkCallbackToolOptions } from "./runtime/SdkCallbackTool.js";
|
|
25
25
|
export { TaskMigrationService } from "./runtime/TaskMigrationService.js";
|
|
26
|
-
export type {
|
|
26
|
+
export type { MigrationContext, MigrationStrategy, TaskMigrationServiceOptions, } from "./runtime/TaskMigrationService.js";
|
|
27
27
|
export { AutoMigratePlugin } from "./plugin/AutoMigratePlugin.js";
|
|
28
28
|
export type { AutoMigrateOptions } from "./plugin/AutoMigratePlugin.js";
|
|
29
29
|
export { AutoRefreshToolsPlugin } from "./plugin/AutoRefreshToolsPlugin.js";
|
|
@@ -1,24 +1,21 @@
|
|
|
1
1
|
import type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
|
|
2
|
-
import {
|
|
2
|
+
import { TaskMigrationService } from "../runtime/TaskMigrationService.js";
|
|
3
3
|
export interface AutoMigrateOptions {
|
|
4
|
+
/** 迁移服务实例(持有迁移前后钩子;生成交接文档时复用传入 agent 的模型调用) */
|
|
5
|
+
service: TaskMigrationService;
|
|
6
|
+
/** 触发迁移的上下文阈值 */
|
|
4
7
|
maxTokens: number;
|
|
5
|
-
migrationAgent: SdkAgent;
|
|
6
|
-
/** 迁移开始前触发(promptTokens 刚超限时),此时 agent.messages 还是完整旧历史。适用于保存旧对话或向用户展示迁移提示。 */
|
|
7
|
-
onBeforeMigrate?: (promptTokens: number, maxTokens: number, agent: SdkAgent) => void;
|
|
8
|
-
/** 迁移完成后触发,此时交接文档已注入 agent.messages。适用于 UI 更新等后处理。 */
|
|
9
|
-
onMigrated?: (handoffDoc: string, agent: SdkAgent) => void;
|
|
10
8
|
}
|
|
11
9
|
/**
|
|
12
|
-
*
|
|
10
|
+
* 自动迁移插件 — 只负责「触发」,实际迁移逻辑统一委托给持有的 `TaskMigrationService` 实例。
|
|
13
11
|
*
|
|
14
|
-
* 当 token 使用量超过 maxTokens
|
|
15
|
-
*
|
|
12
|
+
* 当 token 使用量超过 maxTokens 时触发迁移。`service.migrate()` 需要 `agent`(当前对话)作为
|
|
13
|
+
* 唯一运行时参数,其余(模型、迁移前后钩子)已由服务在构造时持有。
|
|
16
14
|
*
|
|
17
15
|
* ```ts
|
|
18
16
|
* agent.use(new AutoMigratePlugin({
|
|
17
|
+
* service: new TaskMigrationService({ onMigrated }),
|
|
19
18
|
* maxTokens: 250_000,
|
|
20
|
-
* migrationAgent: anotherAgent,
|
|
21
|
-
* onMigrated: (doc, agent) => { ... },
|
|
22
19
|
* }));
|
|
23
20
|
* ```
|
|
24
21
|
*/
|
|
@@ -26,6 +23,4 @@ export declare class AutoMigratePlugin implements AgentPlugin {
|
|
|
26
23
|
private options;
|
|
27
24
|
constructor(options: AutoMigrateOptions);
|
|
28
25
|
onAfterSend(ctx: SendContext): Promise<void>;
|
|
29
|
-
private serializeMessages;
|
|
30
|
-
private getLastAssistantContent;
|
|
31
26
|
}
|
|
@@ -1,18 +1,15 @@
|
|
|
1
|
-
import { AgentNS } from "@ai-zen/agents-core";
|
|
2
|
-
import { TaskMigrationService } from "../runtime/TaskMigrationService.js";
|
|
3
1
|
import { getLogger } from "../shared/logger.js";
|
|
4
2
|
const log = getLogger();
|
|
5
3
|
/**
|
|
6
|
-
*
|
|
4
|
+
* 自动迁移插件 — 只负责「触发」,实际迁移逻辑统一委托给持有的 `TaskMigrationService` 实例。
|
|
7
5
|
*
|
|
8
|
-
* 当 token 使用量超过 maxTokens
|
|
9
|
-
*
|
|
6
|
+
* 当 token 使用量超过 maxTokens 时触发迁移。`service.migrate()` 需要 `agent`(当前对话)作为
|
|
7
|
+
* 唯一运行时参数,其余(模型、迁移前后钩子)已由服务在构造时持有。
|
|
10
8
|
*
|
|
11
9
|
* ```ts
|
|
12
10
|
* agent.use(new AutoMigratePlugin({
|
|
11
|
+
* service: new TaskMigrationService({ onMigrated }),
|
|
13
12
|
* maxTokens: 250_000,
|
|
14
|
-
* migrationAgent: anotherAgent,
|
|
15
|
-
* onMigrated: (doc, agent) => { ... },
|
|
16
13
|
* }));
|
|
17
14
|
* ```
|
|
18
15
|
*/
|
|
@@ -23,60 +20,17 @@ export class AutoMigratePlugin {
|
|
|
23
20
|
}
|
|
24
21
|
async onAfterSend(ctx) {
|
|
25
22
|
const agent = ctx.agent;
|
|
26
|
-
const {
|
|
23
|
+
const { service, maxTokens } = this.options;
|
|
27
24
|
const promptTokens = agent.lastUsage?.prompt_tokens;
|
|
28
25
|
if (promptTokens == null)
|
|
29
26
|
return;
|
|
30
|
-
if (
|
|
27
|
+
if (promptTokens <= maxTokens)
|
|
31
28
|
return;
|
|
32
|
-
// 迁移前钩子:由上层(CLI)处理用户提示
|
|
33
|
-
if (onBeforeMigrate) {
|
|
34
|
-
try {
|
|
35
|
-
await onBeforeMigrate(promptTokens, maxTokens, agent);
|
|
36
|
-
}
|
|
37
|
-
catch (err) {
|
|
38
|
-
log.error(`[autoMigrate] onBeforeMigrate 回调失败: ${err?.message ?? err}`);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
29
|
try {
|
|
42
|
-
|
|
43
|
-
const migrationResult = await migrationAgent.send(historyText);
|
|
44
|
-
const handoffDoc = this.getLastAssistantContent(migrationResult);
|
|
45
|
-
if (!handoffDoc)
|
|
46
|
-
return;
|
|
47
|
-
// 仅替换消息列表,不重建 agent,保留所有引用和插件绑定
|
|
48
|
-
agent.messages.length = 0;
|
|
49
|
-
agent.messages.push(...agent.definition.messages, ...TaskMigrationService.createPostMessages(handoffDoc));
|
|
50
|
-
if (onMigrated) {
|
|
51
|
-
try {
|
|
52
|
-
await onMigrated(handoffDoc, agent);
|
|
53
|
-
}
|
|
54
|
-
catch (err) {
|
|
55
|
-
log.error(`[autoMigrate] onMigrated 回调失败: ${err?.message ?? err}`);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
30
|
+
await service.migrate({ agent, promptTokens, maxTokens });
|
|
58
31
|
}
|
|
59
32
|
catch (err) {
|
|
60
33
|
log.error(`[autoMigrate] 迁移失败: ${err?.message ?? err}`);
|
|
61
34
|
}
|
|
62
35
|
}
|
|
63
|
-
serializeMessages(messages) {
|
|
64
|
-
return messages
|
|
65
|
-
.map((m) => {
|
|
66
|
-
const role = m.role ?? "unknown";
|
|
67
|
-
const content = typeof m.content === "string" ? m.content : JSON.stringify(m.content);
|
|
68
|
-
return `[${role}]: ${content}`;
|
|
69
|
-
})
|
|
70
|
-
.join("\n\n");
|
|
71
|
-
}
|
|
72
|
-
getLastAssistantContent(messages) {
|
|
73
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
74
|
-
if (messages[i].role === AgentNS.Role.Assistant && messages[i].content) {
|
|
75
|
-
return typeof messages[i].content === "string"
|
|
76
|
-
? messages[i].content
|
|
77
|
-
: null;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
return null;
|
|
81
|
-
}
|
|
82
36
|
}
|
|
@@ -22,8 +22,8 @@ export interface ContextGuardOptions {
|
|
|
22
22
|
* ```ts
|
|
23
23
|
* agent.use(new ContextGuardPlugin({ maxTokens: 250_000 }));
|
|
24
24
|
* agent.use(new AutoMigratePlugin({
|
|
25
|
+
* service: new TaskMigrationService({ onMigrated }),
|
|
25
26
|
* maxTokens: 250_000,
|
|
26
|
-
* migrationAgent,
|
|
27
27
|
* }));
|
|
28
28
|
* ```
|
|
29
29
|
*/
|
|
@@ -13,8 +13,8 @@ import { ContextOverflowError } from "../shared/errors.js";
|
|
|
13
13
|
* ```ts
|
|
14
14
|
* agent.use(new ContextGuardPlugin({ maxTokens: 250_000 }));
|
|
15
15
|
* agent.use(new AutoMigratePlugin({
|
|
16
|
+
* service: new TaskMigrationService({ onMigrated }),
|
|
16
17
|
* maxTokens: 250_000,
|
|
17
|
-
* migrationAgent,
|
|
18
18
|
* }));
|
|
19
19
|
* ```
|
|
20
20
|
*/
|
|
@@ -1,7 +1,70 @@
|
|
|
1
1
|
import { AgentNS } from "@ai-zen/agents-core";
|
|
2
|
-
import type
|
|
2
|
+
import type OpenAI from "openai";
|
|
3
|
+
import { type Logger } from "../shared/logger.js";
|
|
4
|
+
import type { SdkAgent } from "./SdkAgent.js";
|
|
5
|
+
/**
|
|
6
|
+
* 迁移上下文 — 贯穿「迁移前 → 生成交接文档 → 迁移后」的结构化数据。
|
|
7
|
+
*
|
|
8
|
+
* 供 `TaskMigrationService.migrate` 与钩子(`onBeforeMigrate` / `onMigrated`)使用。
|
|
9
|
+
* 手动迁移与自动迁移共用同一上下文结构,保证上层(CLI)行为一致。
|
|
10
|
+
*/
|
|
11
|
+
export interface MigrationContext {
|
|
12
|
+
/** 当前对话 Agent(引用不变,仅替换消息列表) */
|
|
13
|
+
agent: SdkAgent;
|
|
14
|
+
/** 生成交接文档所用模型名 */
|
|
15
|
+
model: string;
|
|
16
|
+
/** 当前 prompt token 用量(自动迁移时由 AutoMigratePlugin 提供;手动迁移可省略) */
|
|
17
|
+
promptTokens?: number;
|
|
18
|
+
/** 上下文阈值(自动迁移时由 AutoMigratePlugin 提供;手动迁移可省略) */
|
|
19
|
+
maxTokens?: number;
|
|
20
|
+
/** 序列化后的完整对话历史(迁移输入) */
|
|
21
|
+
historyText: string;
|
|
22
|
+
/** 迁移前消息总数 */
|
|
23
|
+
messageCountBefore: number;
|
|
24
|
+
/** 生成的交接文档(迁移完成后填充) */
|
|
25
|
+
handoffDoc?: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* 迁移后的历史处理策略。
|
|
29
|
+
*
|
|
30
|
+
* - `omit`(默认):将历史消息标记 `omit: true`,仍保留在 `agent.messages` 可审计/回放,但不再发送给模型;
|
|
31
|
+
* - `prune`:物理剔除历史,只保留 `definition.messages`(系统提示等模板)+ 追加的对话断点。
|
|
32
|
+
*/
|
|
33
|
+
export type MigrationStrategy = "omit" | "prune";
|
|
34
|
+
/**
|
|
35
|
+
* 任务迁移服务构造参数。
|
|
36
|
+
*/
|
|
37
|
+
export interface TaskMigrationServiceOptions {
|
|
38
|
+
/** 生成交接文档所用客户端(可选;未传则 migrate 时回退到 agent.client) */
|
|
39
|
+
client?: OpenAI;
|
|
40
|
+
/** 生成交接文档所用模型名(可选;未传则 migrate 时回退到 agent.model) */
|
|
41
|
+
model?: string;
|
|
42
|
+
/** 生成交接文档所用模型参数(可选;未传则 migrate 时回退到 agent.modelConfig) */
|
|
43
|
+
modelConfig?: Record<string, unknown>;
|
|
44
|
+
/** 迁移后历史处理策略,默认 `omit`(标记历史保留可审计)。可选 `prune`(物理剔除)。 */
|
|
45
|
+
strategy?: MigrationStrategy;
|
|
46
|
+
/** 迁移前钩子(服务持有)。迁移开始前触发,此时 agent.messages 仍为完整旧历史 */
|
|
47
|
+
onBeforeMigrate?: (ctx: MigrationContext) => void | Promise<void>;
|
|
48
|
+
/** 迁移后钩子(服务持有)。迁移完成后触发,交接文档已注入 agent.messages */
|
|
49
|
+
onMigrated?: (ctx: MigrationContext) => void | Promise<void>;
|
|
50
|
+
/** 可注入日志(可选,默认使用全局单例) */
|
|
51
|
+
logger?: Logger;
|
|
52
|
+
}
|
|
3
53
|
/**
|
|
4
54
|
* 任务迁移服务。
|
|
55
|
+
*
|
|
56
|
+
* 一个服务实例对应一次迁移上下文。它**不持有**任何模型调用——生成交接文档时
|
|
57
|
+
* 默认复用传入 `agent`(`SdkAgent`)自身的 `client` / `model` / `modelConfig`,
|
|
58
|
+
* 因此无需 Provider、无需独立「迁移 Agent」对象,也无需自建 OpenAI 客户端。
|
|
59
|
+
* 如需用不同模型生成交接文档,可在构造时显式传入 `client` / `model` / `modelConfig`,
|
|
60
|
+
* 未传则 migrate 时回退到 agent 自带的配置。
|
|
61
|
+
*
|
|
62
|
+
* 职责:
|
|
63
|
+
* 1. 生成交接文档的提示词 / 注入格式(静态纯工具,供上层使用)
|
|
64
|
+
* 2. 执行完整迁移(串行化 → 模型生成 → 按策略处理历史 + 追加对话断点),并暴露迁移前后钩子(实例方法)
|
|
65
|
+
*
|
|
66
|
+
* 设计上,`AutoMigratePlugin` 只负责「何时触发」(检测 token 超限),
|
|
67
|
+
* 实际迁移逻辑统一收敛到本服务,从而让手动迁移与自动迁移复用同一条链路。
|
|
5
68
|
*/
|
|
6
69
|
export declare class TaskMigrationService {
|
|
7
70
|
static readonly HANDOFF_SECTIONS: {
|
|
@@ -12,13 +75,54 @@ export declare class TaskMigrationService {
|
|
|
12
75
|
readonly files: "## 📁 文件索引";
|
|
13
76
|
readonly instructions: "## 🔔 接手指令";
|
|
14
77
|
};
|
|
15
|
-
|
|
78
|
+
private onBeforeMigrate?;
|
|
79
|
+
private onMigrated?;
|
|
80
|
+
private client?;
|
|
81
|
+
private model?;
|
|
82
|
+
private modelConfig?;
|
|
83
|
+
private strategy;
|
|
84
|
+
private logger;
|
|
85
|
+
constructor(options?: TaskMigrationServiceOptions);
|
|
16
86
|
static createPrompt(): string;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
87
|
+
/**
|
|
88
|
+
* 生成迁移后追加的「对话断点」消息(role=user):交接文档 + 接手指令。
|
|
89
|
+
* 该消息是 omit 迁移方案中新上下文的起点,模型看到的序列为
|
|
90
|
+
* `[definition.messages, 断点消息]`(历史消息已被标记 omit,不再发送)。
|
|
91
|
+
*/
|
|
20
92
|
static createPostMessages(handoffDoc: string): AgentNS.Message[];
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
93
|
+
/**
|
|
94
|
+
* 序列化消息为 `[role]: content` 文本,供模型理解完整对话历史。
|
|
95
|
+
*/
|
|
96
|
+
static serializeMessages(messages: AgentNS.Message[]): string;
|
|
97
|
+
/**
|
|
98
|
+
* 生成交接文档:使用指定的 client / model / modelConfig 带交接 prompt 生成结构化文档。
|
|
99
|
+
*/
|
|
100
|
+
private generateHandoff;
|
|
101
|
+
/**
|
|
102
|
+
* 执行完整迁移:序列化历史 → 模型生成交接文档 → 按策略处理历史并追加对话断点 → 触发钩子。
|
|
103
|
+
*
|
|
104
|
+
* 策略(`strategy`,构造函数默认 / 本参数可覆盖):
|
|
105
|
+
* - `omit`(默认):`agent.definition.messages`(模板)保留,其余既有历史标记 `omit: true`(仍存于
|
|
106
|
+
* `agent.messages` 可审计/回放但不再发送给模型),末尾追加「对话断点」消息。因此 `formatHistory()`
|
|
107
|
+
* 发送给模型的是 `[definition.messages, 断点消息]` —— 历史被压缩但并不删除。
|
|
108
|
+
* - `prune`:物理剔除历史,只保留 `definition.messages` + 断点消息(即原先的替换行为)。
|
|
109
|
+
*
|
|
110
|
+
* 设计约束:
|
|
111
|
+
* - 不重建 Agent,保留所有引用与插件绑定(仅重建消息列表)
|
|
112
|
+
* - 钩子(onBeforeMigrate / onMigrated)抛错会被捕获并记录,**不中断**迁移流程
|
|
113
|
+
* - 生成失败 / 未取到交接文档时抛错,此时 `agent.messages` 保持原样(不会被部分修改)
|
|
114
|
+
*
|
|
115
|
+
* @param params.agent 当前对话 Agent
|
|
116
|
+
* @param params.promptTokens 当前 prompt token 用量(可选)
|
|
117
|
+
* @param params.maxTokens 上下文阈值(可选)
|
|
118
|
+
* @param params.strategy 本次迁移的历史处理策略(可选,覆盖构造时的默认值)
|
|
119
|
+
* @returns 完整的迁移上下文(含生成的交接文档)
|
|
120
|
+
*/
|
|
121
|
+
migrate(params: {
|
|
122
|
+
agent: SdkAgent;
|
|
123
|
+
promptTokens?: number;
|
|
124
|
+
maxTokens?: number;
|
|
125
|
+
/** 本次迁移的历史处理策略(可选,覆盖构造时的默认值) */
|
|
126
|
+
strategy?: MigrationStrategy;
|
|
127
|
+
}): Promise<MigrationContext>;
|
|
24
128
|
}
|
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
import { AgentNS } from "@ai-zen/agents-core";
|
|
2
|
+
import { getLogger } from "../shared/logger.js";
|
|
2
3
|
/**
|
|
3
4
|
* 任务迁移服务。
|
|
5
|
+
*
|
|
6
|
+
* 一个服务实例对应一次迁移上下文。它**不持有**任何模型调用——生成交接文档时
|
|
7
|
+
* 默认复用传入 `agent`(`SdkAgent`)自身的 `client` / `model` / `modelConfig`,
|
|
8
|
+
* 因此无需 Provider、无需独立「迁移 Agent」对象,也无需自建 OpenAI 客户端。
|
|
9
|
+
* 如需用不同模型生成交接文档,可在构造时显式传入 `client` / `model` / `modelConfig`,
|
|
10
|
+
* 未传则 migrate 时回退到 agent 自带的配置。
|
|
11
|
+
*
|
|
12
|
+
* 职责:
|
|
13
|
+
* 1. 生成交接文档的提示词 / 注入格式(静态纯工具,供上层使用)
|
|
14
|
+
* 2. 执行完整迁移(串行化 → 模型生成 → 按策略处理历史 + 追加对话断点),并暴露迁移前后钩子(实例方法)
|
|
15
|
+
*
|
|
16
|
+
* 设计上,`AutoMigratePlugin` 只负责「何时触发」(检测 token 超限),
|
|
17
|
+
* 实际迁移逻辑统一收敛到本服务,从而让手动迁移与自动迁移复用同一条链路。
|
|
4
18
|
*/
|
|
5
19
|
export class TaskMigrationService {
|
|
6
20
|
static HANDOFF_SECTIONS = {
|
|
@@ -11,8 +25,22 @@ export class TaskMigrationService {
|
|
|
11
25
|
files: "## 📁 文件索引",
|
|
12
26
|
instructions: "## 🔔 接手指令",
|
|
13
27
|
};
|
|
14
|
-
|
|
15
|
-
|
|
28
|
+
onBeforeMigrate;
|
|
29
|
+
onMigrated;
|
|
30
|
+
client;
|
|
31
|
+
model;
|
|
32
|
+
modelConfig;
|
|
33
|
+
strategy;
|
|
34
|
+
logger;
|
|
35
|
+
constructor(options = {}) {
|
|
36
|
+
const { onBeforeMigrate, onMigrated, logger, client, model, modelConfig, strategy } = options;
|
|
37
|
+
this.onBeforeMigrate = onBeforeMigrate;
|
|
38
|
+
this.onMigrated = onMigrated;
|
|
39
|
+
this.client = client;
|
|
40
|
+
this.model = model;
|
|
41
|
+
this.modelConfig = modelConfig;
|
|
42
|
+
this.strategy = strategy ?? "omit";
|
|
43
|
+
this.logger = logger ?? getLogger();
|
|
16
44
|
}
|
|
17
45
|
static createPrompt() {
|
|
18
46
|
return [
|
|
@@ -38,20 +66,11 @@ export class TaskMigrationService {
|
|
|
38
66
|
`- 接手后建议的操作步骤`,
|
|
39
67
|
].join("\n");
|
|
40
68
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
description: "专用迁移 Agent:分析对话历史并生成结构化交接文档",
|
|
47
|
-
messages: [
|
|
48
|
-
{ role: AgentNS.Role.System, content: TaskMigrationService.createPrompt() },
|
|
49
|
-
],
|
|
50
|
-
modelId: options.modelId,
|
|
51
|
-
createdAt: now,
|
|
52
|
-
updatedAt: now,
|
|
53
|
-
};
|
|
54
|
-
}
|
|
69
|
+
/**
|
|
70
|
+
* 生成迁移后追加的「对话断点」消息(role=user):交接文档 + 接手指令。
|
|
71
|
+
* 该消息是 omit 迁移方案中新上下文的起点,模型看到的序列为
|
|
72
|
+
* `[definition.messages, 断点消息]`(历史消息已被标记 omit,不再发送)。
|
|
73
|
+
*/
|
|
55
74
|
static createPostMessages(handoffDoc) {
|
|
56
75
|
const content = [
|
|
57
76
|
"这是上一轮对话的任务交接文档。请先阅读交接文档,理解上下文后再继续协助用户完成任务。",
|
|
@@ -66,4 +85,127 @@ export class TaskMigrationService {
|
|
|
66
85
|
].join("\n");
|
|
67
86
|
return [{ role: AgentNS.Role.User, content }];
|
|
68
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* 序列化消息为 `[role]: content` 文本,供模型理解完整对话历史。
|
|
90
|
+
*/
|
|
91
|
+
static serializeMessages(messages) {
|
|
92
|
+
return messages
|
|
93
|
+
.map((m) => {
|
|
94
|
+
const role = m.role ?? "unknown";
|
|
95
|
+
const content = typeof m.content === "string" ? m.content : JSON.stringify(m.content);
|
|
96
|
+
return `[${role}]: ${content}`;
|
|
97
|
+
})
|
|
98
|
+
.join("\n\n");
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* 生成交接文档:使用指定的 client / model / modelConfig 带交接 prompt 生成结构化文档。
|
|
102
|
+
*/
|
|
103
|
+
async generateHandoff(client, model, modelConfig, historyText) {
|
|
104
|
+
const response = await client.chat.completions.create({
|
|
105
|
+
model,
|
|
106
|
+
...(modelConfig ?? {}),
|
|
107
|
+
messages: [
|
|
108
|
+
{ role: "system", content: TaskMigrationService.createPrompt() },
|
|
109
|
+
{ role: "user", content: historyText },
|
|
110
|
+
],
|
|
111
|
+
});
|
|
112
|
+
const handoffDoc = response.choices[0]?.message?.content;
|
|
113
|
+
if (!handoffDoc) {
|
|
114
|
+
throw new Error("未能生成任务交接文档");
|
|
115
|
+
}
|
|
116
|
+
return handoffDoc;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* 执行完整迁移:序列化历史 → 模型生成交接文档 → 按策略处理历史并追加对话断点 → 触发钩子。
|
|
120
|
+
*
|
|
121
|
+
* 策略(`strategy`,构造函数默认 / 本参数可覆盖):
|
|
122
|
+
* - `omit`(默认):`agent.definition.messages`(模板)保留,其余既有历史标记 `omit: true`(仍存于
|
|
123
|
+
* `agent.messages` 可审计/回放但不再发送给模型),末尾追加「对话断点」消息。因此 `formatHistory()`
|
|
124
|
+
* 发送给模型的是 `[definition.messages, 断点消息]` —— 历史被压缩但并不删除。
|
|
125
|
+
* - `prune`:物理剔除历史,只保留 `definition.messages` + 断点消息(即原先的替换行为)。
|
|
126
|
+
*
|
|
127
|
+
* 设计约束:
|
|
128
|
+
* - 不重建 Agent,保留所有引用与插件绑定(仅重建消息列表)
|
|
129
|
+
* - 钩子(onBeforeMigrate / onMigrated)抛错会被捕获并记录,**不中断**迁移流程
|
|
130
|
+
* - 生成失败 / 未取到交接文档时抛错,此时 `agent.messages` 保持原样(不会被部分修改)
|
|
131
|
+
*
|
|
132
|
+
* @param params.agent 当前对话 Agent
|
|
133
|
+
* @param params.promptTokens 当前 prompt token 用量(可选)
|
|
134
|
+
* @param params.maxTokens 上下文阈值(可选)
|
|
135
|
+
* @param params.strategy 本次迁移的历史处理策略(可选,覆盖构造时的默认值)
|
|
136
|
+
* @returns 完整的迁移上下文(含生成的交接文档)
|
|
137
|
+
*/
|
|
138
|
+
async migrate(params) {
|
|
139
|
+
const { agent, promptTokens, maxTokens, strategy: overrideStrategy } = params;
|
|
140
|
+
const strategy = overrideStrategy ?? this.strategy;
|
|
141
|
+
// 序列化有效上下文:过滤已标记 omit 的历史,避免重复迁移时把旧省略历史再次喂给模型。
|
|
142
|
+
// historyText 供模型生成交接文档,而 messageCountBefore 仍记录本次迁移前的消息总数。
|
|
143
|
+
const historyText = TaskMigrationService.serializeMessages(agent.messages.filter((m) => !m.omit));
|
|
144
|
+
const messageCountBefore = agent.messages.length;
|
|
145
|
+
// 生成交接文档所用模型调用:优先使用构造时传入的 client/model/modelConfig,
|
|
146
|
+
// 未传则回退到 agent 自带的(无需 Provider / 独立迁移 Agent)。
|
|
147
|
+
const client = this.client ?? agent.client;
|
|
148
|
+
const model = this.model ?? agent.model;
|
|
149
|
+
const modelConfig = this.modelConfig ?? agent.modelConfig;
|
|
150
|
+
// 迁移前上下文(不含 handoffDoc,独立对象,语义固定)
|
|
151
|
+
const beforeCtx = {
|
|
152
|
+
agent,
|
|
153
|
+
model,
|
|
154
|
+
maxTokens,
|
|
155
|
+
promptTokens,
|
|
156
|
+
historyText,
|
|
157
|
+
messageCountBefore,
|
|
158
|
+
};
|
|
159
|
+
// 迁移前钩子(容错,不中断)
|
|
160
|
+
if (this.onBeforeMigrate) {
|
|
161
|
+
try {
|
|
162
|
+
await this.onBeforeMigrate(beforeCtx);
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
this.logger.error(`[migrate] onBeforeMigrate 回调失败: ${err?.message ?? err}`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
// 生成交接文档
|
|
169
|
+
const handoffDoc = await this.generateHandoff(client, model, modelConfig, historyText);
|
|
170
|
+
// 重建消息列表:按策略处理历史(omit 标记保留 / prune 物理剔除),并追加「对话断点」消息。
|
|
171
|
+
// 均用浅拷贝/新数组,避免直接修改 definition.messages 引用的对象(防止污染模板)。
|
|
172
|
+
const breakpointMessages = TaskMigrationService.createPostMessages(handoffDoc);
|
|
173
|
+
let nextMessages;
|
|
174
|
+
if (strategy === "prune") {
|
|
175
|
+
// 物理剔除:只保留模板消息 + 断点
|
|
176
|
+
nextMessages = [...agent.definition.messages, ...breakpointMessages];
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
// omit(默认):以 definition.messages 长度为界保留模板消息,其余历史统一标记 omit
|
|
180
|
+
const preserveCount = Math.min(agent.definition.messages.length, agent.messages.length);
|
|
181
|
+
nextMessages = [
|
|
182
|
+
...agent.messages.map((m, i) => ({
|
|
183
|
+
...m,
|
|
184
|
+
omit: i >= preserveCount ? true : m.omit,
|
|
185
|
+
})),
|
|
186
|
+
...breakpointMessages,
|
|
187
|
+
];
|
|
188
|
+
}
|
|
189
|
+
agent.messages = nextMessages;
|
|
190
|
+
// 迁移后上下文(含 handoffDoc,与迁移前上下文独立)
|
|
191
|
+
const afterCtx = {
|
|
192
|
+
agent,
|
|
193
|
+
model,
|
|
194
|
+
maxTokens,
|
|
195
|
+
promptTokens,
|
|
196
|
+
historyText,
|
|
197
|
+
messageCountBefore,
|
|
198
|
+
handoffDoc,
|
|
199
|
+
};
|
|
200
|
+
// 迁移后钩子(容错,不中断;此时交接文档已注入)
|
|
201
|
+
if (this.onMigrated) {
|
|
202
|
+
try {
|
|
203
|
+
await this.onMigrated(afterCtx);
|
|
204
|
+
}
|
|
205
|
+
catch (err) {
|
|
206
|
+
this.logger.error(`[migrate] onMigrated 回调失败: ${err?.message ?? err}`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return afterCtx;
|
|
210
|
+
}
|
|
69
211
|
}
|