@ai-zen/agents-sdk 1.0.0-alpha.9 → 1.1.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 +691 -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 +26 -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 +288 -0
- package/dist/runtime/HandoffService.js +538 -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
package/README.md
CHANGED
|
@@ -21,10 +21,10 @@ Desktop ──┘ │
|
|
|
21
21
|
types ← pure types, zero business dependencies (incl. ToolEnv)
|
|
22
22
|
config ← ConfigManager + constants: config.json read/write + directory setup + factory defaults
|
|
23
23
|
crud ← capability-entity CRUD (Agent definitions; conversations/drafts are persisted by each consumer)
|
|
24
|
-
runtime ← model factory + Agent assembly + task migration (createModel / createAgent / SdkAgent /
|
|
24
|
+
runtime ← model factory + Agent assembly + task handoff/migration (cancellable via `AbortSignal`; createModel / createAgent / SdkAgent / HandoffService / HandoffGuardPlugin)
|
|
25
25
|
scope ← Scope orchestration container + ScopePlugin contract + PermissionEvaluator / disclosure + plugins/ (5 self-contained capability sources: discovery + tools + plugin)
|
|
26
26
|
agent-plugins ← Agent plugins (autoMigrate, autoRefreshTools, contextGuard, unknownToolHint)
|
|
27
|
-
shared ← logging, errors
|
|
27
|
+
shared ← content blocks (file → content block transport), entity repository, logging, errors
|
|
28
28
|
```
|
|
29
29
|
|
|
30
30
|
Dependency direction: `agent-plugins → runtime → scope`; `runtime → scope / crud / shared / types`, `scope → types / shared`. Upper layers depend on lower layers.
|
|
@@ -68,8 +68,9 @@ const scope = new Scope({
|
|
|
68
68
|
await scope.init();
|
|
69
69
|
|
|
70
70
|
const agent = await createAgent(scope, "my-agent");
|
|
71
|
-
const
|
|
72
|
-
agent.use(new
|
|
71
|
+
const handoffService = new HandoffService({ handoffDir: "/work/.ai-zen/handoffs", skillDirs });
|
|
72
|
+
agent.use(new ContextGuardPlugin({ guardTokens, isSuspended: () => handoffService.busy }));
|
|
73
|
+
agent.use(new AutoMigratePlugin({ service: handoffService, handoffTokens }));
|
|
73
74
|
agent.use(new AutoRefreshToolsPlugin());
|
|
74
75
|
agent.use(new UnknownToolHintPlugin({ scope }));
|
|
75
76
|
await agent.init();
|
|
@@ -124,15 +125,30 @@ Conditionally injected based on the active model / config:
|
|
|
124
125
|
|
|
125
126
|
Tool output protection: `AppConfig.maxToolOutput` (in characters, default 32768) is the unified ceiling for tool output. Each tool handles overflow itself — `exec` dumps `stdout.log` / `stderr.log` separately (returning head/tail previews per stream), `find_text` / `glob` / `ls` dump `result.json` (returning a head preview), and `read` only warns and suggests batched reads via `range`. Dumps go to `<tmpdir>/ai-zen/tool-output/<tool>-<timestamp>-<random>/`, one directory per call, with no self-cleanup. See [`docs/sdk-design-v1.md` §12](docs/sdk-design-v1.md).
|
|
126
127
|
|
|
128
|
+
Interrupt strategies live in the config: `AppConfig.abortedMessageStrategy` (`keep` / `drop`, factory `keep` — the model can continue the half-sentence after an interrupt) and `AppConfig.abortedToolRoundStrategy` (`fill` / `drop`, factory `fill` — whole rounds go in or out, because `tool_calls` must pair with results). `createAgent()` reads them from `scope.config` when no explicit option is passed, keeping a single source of truth.
|
|
129
|
+
|
|
127
130
|
## Built-in Plugins
|
|
128
131
|
|
|
129
132
|
| Plugin | Description |
|
|
130
133
|
|--------|-------------|
|
|
131
|
-
| `AutoMigratePlugin` | Automatically triggers task migration when
|
|
134
|
+
| `AutoMigratePlugin` | Automatically triggers task migration when `usage.prompt_tokens` exceeds `handoffTokens`; delegates the actual migration to the injected `HandoffService` (history handled per `strategy`: default `omit` keeps it auditable, optional `prune` drops it). `resolveMode` lets the caller pick the handoff executor or skip the round. Steps aside while `service.busy` to avoid the handoff→migrate→handoff recursion |
|
|
132
135
|
| `AutoRefreshToolsPlugin` | Re-scans the file system before each `send()` to refresh the tool list |
|
|
133
|
-
| `ContextGuardPlugin` | Context safety guard — before each request, throws `ContextOverflowError` (interrupting the conversation) when the previous round's `usage.prompt_tokens` exceeds `
|
|
136
|
+
| `ContextGuardPlugin` | Context safety guard — before each request, throws `ContextOverflowError` (interrupting the conversation) when the previous round's `usage.prompt_tokens` exceeds `guardTokens` (an absolute value: no multiplier, no looser tier), preventing context runaway from reading oversized files. `isSuspended()` lets the guard itself step aside for handoff/migration turns |
|
|
134
137
|
| `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`) |
|
|
135
138
|
|
|
139
|
+
## Language
|
|
140
|
+
|
|
141
|
+
The SDK is **English-only**: every model-facing and user-facing string — tool schema descriptions, factory prompts, runtime-injected guidance, tool results, error messages, factory catalog data — is a fixed English literal. There is no locale field, no message catalog, and no runtime language switch. UI language belongs entirely to each consumer (the CLI's `i18n/`, the Desktop's language setting).
|
|
142
|
+
|
|
143
|
+
This is a performance boundary, not a convenience choice — **SDK behaviour and performance must not vary by the user's language**:
|
|
144
|
+
|
|
145
|
+
- **Thresholds are absolute.** `Model.tokenThresholds.handoff` / `guard` and `AppConfig.maxToolOutput` are absolute token / character counts. A localized tool schema is a different token count, so handoff and context-guard would trip at *different amounts of real content* for the same `config.json` — same config, different behaviour per language.
|
|
146
|
+
- **Schema cost is paid every turn.** Description text is re-sent with every request, so a token delta is a standing cost in request size, context usage and spend rather than a one-off.
|
|
147
|
+
- **Cache prefixes stop being comparable.** Prompt caching matches on the prefix; letting language into the SDK multiplies the prefix shapes of one code path and removes the single variable that benchmarks rely on.
|
|
148
|
+
- **Diagnosis needs one shape.** Performance data, bug reproductions and tool-call success rates have to be comparable across users; once behaviour drifts with locale, every conclusion needs a "what language are you on?" qualifier first.
|
|
149
|
+
|
|
150
|
+
Following the user's language is handled by one language-neutral instruction in the factory system prompt — `Always reply in the same language the user writes in.` — which adapts per **message** rather than per installation, and needs no locale plumbing in the SDK. Full rationale: [`docs/sdk-design-v1.md` §1](docs/sdk-design-v1.md).
|
|
151
|
+
|
|
136
152
|
## Design Principles
|
|
137
153
|
|
|
138
154
|
See the project-root [`PRINCIPLES.md`](../../PRINCIPLES.md):
|
package/README.zh.md
CHANGED
|
@@ -20,10 +20,10 @@ Desktop ──┘ │
|
|
|
20
20
|
types ← 纯类型,零业务依赖(含 ToolEnv 工具环境)
|
|
21
21
|
config ← ConfigManager + constants:读写 config.json + 目录初始化 + 出厂默认
|
|
22
22
|
crud ← 能力实体 CRUD(Agent 定义等;会话/草稿已下放给各端自行持久化)
|
|
23
|
-
runtime ← 模型工厂 + Agent 组装 +
|
|
23
|
+
runtime ← 模型工厂 + Agent 组装 + 任务交接/迁移(可 `AbortSignal` 取消;createModel / createAgent / SdkAgent / HandoffService / HandoffGuardPlugin)
|
|
24
24
|
scope ← Scope 编排容器 + ScopePlugin 契约 + PermissionEvaluator / disclosure + plugins/(5 个自包含能力来源:发现 + 工具 + 插件)
|
|
25
25
|
agent-plugins ← Agent 插件(autoMigrate、autoRefreshTools、contextGuard、unknownToolHint)
|
|
26
|
-
shared ←
|
|
26
|
+
shared ← 内容块(文件 → 内容块的传输决策)、实体仓储、日志、错误
|
|
27
27
|
```
|
|
28
28
|
|
|
29
29
|
依赖方向:`agent-plugins → runtime → scope`;`runtime → scope / crud / shared / types`,`scope → types / shared`。上层依赖下层,反之不行。
|
|
@@ -67,8 +67,9 @@ const scope = new Scope({
|
|
|
67
67
|
await scope.init();
|
|
68
68
|
|
|
69
69
|
const agent = await createAgent(scope, "my-agent");
|
|
70
|
-
const
|
|
71
|
-
agent.use(new
|
|
70
|
+
const handoffService = new HandoffService({ handoffDir: "/work/.ai-zen/handoffs", skillDirs });
|
|
71
|
+
agent.use(new ContextGuardPlugin({ guardTokens, isSuspended: () => handoffService.busy }));
|
|
72
|
+
agent.use(new AutoMigratePlugin({ service: handoffService, handoffTokens }));
|
|
72
73
|
agent.use(new AutoRefreshToolsPlugin());
|
|
73
74
|
agent.use(new UnknownToolHintPlugin({ scope }));
|
|
74
75
|
await agent.init();
|
|
@@ -87,7 +88,7 @@ await scope.dispose(); // 断开 MCP、释放插件资源
|
|
|
87
88
|
| `scope` | ✅ 已实现 — Scope + ScopePlugin + 5 个标准插件(builtin / user-tools / skills / mcp / subagents)+ allInOne |
|
|
88
89
|
| `runtime` | ✅ 已实现 — createAgent、MCP 连接管理、任务迁移 |
|
|
89
90
|
| `agent-plugins` | ✅ 已实现 — AutoMigratePlugin / AutoRefreshToolsPlugin / ContextGuardPlugin / UnknownToolHintPlugin |
|
|
90
|
-
| `shared` | ✅ 已实现 — SdkError + 可注入 Logger |
|
|
91
|
+
| `shared` | ✅ 已实现 — 内容块传输决策(`content-blocks`)+ 实体仓储 + SdkError + 可注入 Logger |
|
|
91
92
|
|
|
92
93
|
## 内置工具
|
|
93
94
|
|
|
@@ -123,15 +124,30 @@ await scope.dispose(); // 断开 MCP、释放插件资源
|
|
|
123
124
|
|
|
124
125
|
工具输出保护:`AppConfig.maxToolOutput`(字符数,缺省 32768)是工具输出的统一上限,超限时由各工具自行处置——`exec` 分文件落盘 `stdout.log` / `stderr.log`(返回各流头尾预览),`find_text` / `glob` / `ls` 落盘 `result.json`(返回头部预览),`read` 仅警告并提示用 `range` 分批读取。落盘目录为 `<tmpdir>/ai-zen/tool-output/<工具名>-<时间戳>-<随机串>/`,每次调用独立、不自清理。详见 [`docs/sdk-design-v1.md` §12](docs/sdk-design-v1.md)。
|
|
125
126
|
|
|
127
|
+
中断策略进配置:`AppConfig.abortedMessageStrategy`(`keep` / `drop`,出厂 `keep`——中断后模型能接着半截往下说)与 `AppConfig.abortedToolRoundStrategy`(`fill` / `drop`,出厂 `fill`——整轮进出,`tool_calls` 必须与结果配对)。`createAgent()` 不传参数时直接取 `scope.config`,于是策略只有一个真相源。
|
|
128
|
+
|
|
126
129
|
## 内置插件
|
|
127
130
|
|
|
128
131
|
| 插件 | 说明 |
|
|
129
132
|
|------|------|
|
|
130
|
-
| `AutoMigratePlugin` |
|
|
133
|
+
| `AutoMigratePlugin` | 上下文超限时自动触发任务迁移(历史按 `strategy` 处理:默认 `omit` 标记保留可审计,可选 `prune` 物理剔除),委托注入的 `HandoffService`;`resolveMode` 让调用方决定交接执行者或跳过本轮;`service.busy` 期间让行,避免「交接→迁移→交接」递归 |
|
|
131
134
|
| `AutoRefreshToolsPlugin` | 每次 `send()` 前重新扫描文件系统,刷新工具列表 |
|
|
132
|
-
| `ContextGuardPlugin` | 上下文安全护栏 — 每轮发请求前检测上一轮 `usage.prompt_tokens`,超过 `
|
|
135
|
+
| `ContextGuardPlugin` | 上下文安全护栏 — 每轮发请求前检测上一轮 `usage.prompt_tokens`,超过 `guardTokens`(绝对值:没有倍数、没有放宽档)时抛 `ContextOverflowError` 中断对话,防止读入超大文件导致上下文失控。`isSuspended()` 让护栏自己在交接/迁移回合让行 |
|
|
133
136
|
| `UnknownToolHintPlugin` | 未知工具智能提示 — LLM 调用不存在的工具时,根据 MCP 配置引导使用 `call_mcp_tool` / 提示权限问题(调用方显式 `agent.use` 注册) |
|
|
134
137
|
|
|
138
|
+
## 语言
|
|
139
|
+
|
|
140
|
+
SDK 是 **English-only**:所有面向模型与面向用户的文案(工具 schema 描述、出厂提示词、运行期注入语、工具返回值、错误信息、出厂 catalog 数据)都是**固定英文字面量**。没有 locale 字段、没有语言包、没有运行期切换。界面语言完全属于各端(CLI 的 `i18n/`、Desktop 的语言设置)。
|
|
141
|
+
|
|
142
|
+
这是**性能边界**,不是图省事 —— **SDK 的行为与性能不得随用户语言变化**:
|
|
143
|
+
|
|
144
|
+
- **阈值是绝对量。** `Model.tokenThresholds.handoff` / `guard` 与 `AppConfig.maxToolOutput` 都以 token / 字符的绝对值为判据。工具 schema 换个语言就是另一组 token 数 —— 交接与上下文阻断会在**不同的实际内容量**上触发。同一份 `config.json` 在不同语言下跑出不同行为。
|
|
145
|
+
- **schema 成本每轮都付。** 描述文字随每次请求重发,token 差异是摊在每一轮上的持续开销,会改变请求体积、上下文占用与费用,而不是一次性成本。
|
|
146
|
+
- **缓存前缀不再可比。** prompt 缓存按前缀匹配;语言一旦进入 SDK,同一条代码路径就有了多个前缀形态,基准测试失去单一变量。
|
|
147
|
+
- **基准与排查需要单一形态。** 性能数据、bug 复现、工具调用成功率都要能横向比较;行为若随 locale 漂移,任何结论都得先问「你是什么语言」。
|
|
148
|
+
|
|
149
|
+
「模型跟随用户语言」由一条语言中立的 system prompt 指令承担 —— `Always reply in the same language the user writes in.` —— 按**每条消息**自适应,比按安装实例绑定 locale 更准确,也不需要 SDK 参与。完整论述见 [`docs/sdk-design-v1.md` §1](docs/sdk-design-v1.md)。
|
|
150
|
+
|
|
135
151
|
## 设计原则
|
|
136
152
|
|
|
137
153
|
参见项目根 [`PRINCIPLES.md`](../../PRINCIPLES.md):
|
|
@@ -1,23 +1,49 @@
|
|
|
1
1
|
import type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
|
|
2
|
-
import {
|
|
2
|
+
import type { HandoffMode, HandoffService } from "../runtime/HandoffService.js";
|
|
3
|
+
/** 触发迁移时的用量信息(供执行者选择、确认文案使用) */
|
|
4
|
+
export interface AutoMigrateTriggerInfo {
|
|
5
|
+
/** 当前 prompt token 用量 */
|
|
6
|
+
promptTokens: number;
|
|
7
|
+
/** 交接阈值(当前模型的 tokenThresholds.handoff) */
|
|
8
|
+
handoffTokens: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* 迁移执行者解析器:只负责「用什么方式交接」,不负责「何时迁移」。
|
|
12
|
+
*
|
|
13
|
+
* - 返回 `HandoffMode` → 用该执行者迁移;
|
|
14
|
+
* - 返回 `null` → 跳过本次迁移(例如用户拒绝);
|
|
15
|
+
* - 未提供 → 使用 `HandoffService` 构造时的默认执行者。
|
|
16
|
+
*/
|
|
17
|
+
export type AutoMigrateModeResolver = (info: AutoMigrateTriggerInfo) => HandoffMode | null | Promise<HandoffMode | null>;
|
|
3
18
|
export interface AutoMigrateOptions {
|
|
4
|
-
/**
|
|
5
|
-
service:
|
|
19
|
+
/** 交接服务实例(持有交接前后钩子;编排 handoff / migrate 两条链路) */
|
|
20
|
+
service: HandoffService;
|
|
6
21
|
/** 触发迁移的上下文阈值 */
|
|
7
|
-
|
|
22
|
+
handoffTokens: number;
|
|
23
|
+
/**
|
|
24
|
+
* 执行者解析(可选)。上层可在此弹确认框、读用户偏好,
|
|
25
|
+
* 或直接返回 `null` 表达「本次不迁移」——**无需**再继承本插件。
|
|
26
|
+
*/
|
|
27
|
+
resolveMode?: AutoMigrateModeResolver;
|
|
8
28
|
}
|
|
9
29
|
/**
|
|
10
|
-
* 自动迁移插件
|
|
30
|
+
* 自动迁移插件 —— 只负责「何时触发」,实际迁移统一委托给持有的 `HandoffService`。
|
|
11
31
|
*
|
|
12
|
-
* 当
|
|
13
|
-
* 唯一运行时参数,其余(模型、迁移前后钩子)已由服务在构造时持有。
|
|
32
|
+
* 当 `usage.prompt_tokens` 超过 handoffTokens 时触发迁移:
|
|
14
33
|
*
|
|
15
34
|
* ```ts
|
|
16
35
|
* agent.use(new AutoMigratePlugin({
|
|
17
|
-
* service:
|
|
18
|
-
*
|
|
36
|
+
* service: handoffService,
|
|
37
|
+
* handoffTokens: 250_000,
|
|
38
|
+
* resolveMode: async ({ promptTokens, handoffTokens }) =>
|
|
39
|
+
* (await askUser(promptTokens, handoffTokens)) ? "self" : null,
|
|
19
40
|
* }));
|
|
20
41
|
* ```
|
|
42
|
+
*
|
|
43
|
+
* 两层让行(缺一不可):
|
|
44
|
+
* - `service.busy`:交接回合本身就是一次 `send()`,其 `onAfterSend` 会再次到这里;
|
|
45
|
+
* 不跳过就会「交接触发迁移 → 迁移再交接」无限递归;
|
|
46
|
+
* - 交接回合结束后的用量也仍可能超阈值,故 busy 判断必须覆盖整个交接 + 迁移过程。
|
|
21
47
|
*/
|
|
22
48
|
export declare class AutoMigratePlugin implements AgentPlugin {
|
|
23
49
|
private options;
|
|
@@ -1,17 +1,23 @@
|
|
|
1
|
+
import { HandoffAbortedError } from "../runtime/HandoffService.js";
|
|
1
2
|
import { getLogger } from "../shared/logger.js";
|
|
2
|
-
const log = getLogger();
|
|
3
3
|
/**
|
|
4
|
-
* 自动迁移插件
|
|
4
|
+
* 自动迁移插件 —— 只负责「何时触发」,实际迁移统一委托给持有的 `HandoffService`。
|
|
5
5
|
*
|
|
6
|
-
* 当
|
|
7
|
-
* 唯一运行时参数,其余(模型、迁移前后钩子)已由服务在构造时持有。
|
|
6
|
+
* 当 `usage.prompt_tokens` 超过 handoffTokens 时触发迁移:
|
|
8
7
|
*
|
|
9
8
|
* ```ts
|
|
10
9
|
* agent.use(new AutoMigratePlugin({
|
|
11
|
-
* service:
|
|
12
|
-
*
|
|
10
|
+
* service: handoffService,
|
|
11
|
+
* handoffTokens: 250_000,
|
|
12
|
+
* resolveMode: async ({ promptTokens, handoffTokens }) =>
|
|
13
|
+
* (await askUser(promptTokens, handoffTokens)) ? "self" : null,
|
|
13
14
|
* }));
|
|
14
15
|
* ```
|
|
16
|
+
*
|
|
17
|
+
* 两层让行(缺一不可):
|
|
18
|
+
* - `service.busy`:交接回合本身就是一次 `send()`,其 `onAfterSend` 会再次到这里;
|
|
19
|
+
* 不跳过就会「交接触发迁移 → 迁移再交接」无限递归;
|
|
20
|
+
* - 交接回合结束后的用量也仍可能超阈值,故 busy 判断必须覆盖整个交接 + 迁移过程。
|
|
15
21
|
*/
|
|
16
22
|
export class AutoMigratePlugin {
|
|
17
23
|
options;
|
|
@@ -20,17 +26,27 @@ export class AutoMigratePlugin {
|
|
|
20
26
|
}
|
|
21
27
|
async onAfterSend(ctx) {
|
|
22
28
|
const agent = ctx.agent;
|
|
23
|
-
const { service,
|
|
29
|
+
const { service, handoffTokens, resolveMode } = this.options;
|
|
30
|
+
// 交接/迁移进行中:让行(防递归)
|
|
31
|
+
if (service.busy)
|
|
32
|
+
return;
|
|
24
33
|
const promptTokens = agent.lastUsage?.prompt_tokens;
|
|
25
34
|
if (promptTokens == null)
|
|
26
35
|
return;
|
|
27
|
-
if (promptTokens <=
|
|
36
|
+
if (promptTokens <= handoffTokens)
|
|
28
37
|
return;
|
|
29
38
|
try {
|
|
30
|
-
await
|
|
39
|
+
const mode = resolveMode ? await resolveMode({ promptTokens, handoffTokens }) : undefined;
|
|
40
|
+
if (mode === null)
|
|
41
|
+
return; // 用户选择跳过本次迁移
|
|
42
|
+
await service.migrate({ agent, promptTokens, handoffTokens, mode: mode ?? undefined });
|
|
31
43
|
}
|
|
32
44
|
catch (err) {
|
|
33
|
-
|
|
45
|
+
// 用户主动取消不是失败:服务已把会话退回交接前,这里再报错只会在界面上
|
|
46
|
+
// 凭空多一条「迁移失败」(默认 logger 是 console.error,TUI 下直接撕画面)
|
|
47
|
+
if (err instanceof HandoffAbortedError)
|
|
48
|
+
return;
|
|
49
|
+
getLogger().error(`[autoMigrate] migration failed: ${err?.message ?? err}`);
|
|
34
50
|
}
|
|
35
51
|
}
|
|
36
52
|
}
|
|
@@ -12,9 +12,7 @@ export class AutoRefreshToolsPlugin {
|
|
|
12
12
|
await agent.scope.refresh({ silent: true });
|
|
13
13
|
agent.tools = agent.scope.buildTools(agent.definition, {
|
|
14
14
|
exclude: {
|
|
15
|
-
subagents: agent.definition.function?.name
|
|
16
|
-
? [agent.definition.function.name]
|
|
17
|
-
: undefined,
|
|
15
|
+
subagents: agent.definition.function?.name ? [agent.definition.function.name] : undefined,
|
|
18
16
|
},
|
|
19
17
|
});
|
|
20
18
|
}
|
|
@@ -1,34 +1,46 @@
|
|
|
1
1
|
import type { AgentPlugin, SendContext } from "@ai-zen/agents-core";
|
|
2
2
|
export interface ContextGuardOptions {
|
|
3
|
-
/** 上下文告警阈值(token)。用量超过 maxTokens × ratio 即中断。 */
|
|
4
|
-
maxTokens: number;
|
|
5
3
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* 强行阻断阈值(tokens,绝对值)。
|
|
5
|
+
*
|
|
6
|
+
* 语义只有一条:请求前上一轮用量超过它 → 中断本轮。没有倍数、没有放宽档——
|
|
7
|
+
* 想调松就把它调大,「安全边界写多少就是多少」比「隐式乘以某个系数」可预测得多。
|
|
8
8
|
*/
|
|
9
|
-
|
|
9
|
+
guardTokens: number;
|
|
10
|
+
/**
|
|
11
|
+
* 临时让行:返回 `true` 时本轮不做超限判定(默认 `false`)。
|
|
12
|
+
*
|
|
13
|
+
* 用于交接/迁移回合 —— 那些回合本身就是「上下文已满」时才发起的,若不放宽必定被打回。
|
|
14
|
+
* 语义是「谁做限制谁放宽」:限制在护栏自己身上,放宽也必须由护栏自己表达,
|
|
15
|
+
* 而不是由调用方去改写用量数据。典型接线:`isSuspended: () => handoffService.busy`。
|
|
16
|
+
*/
|
|
17
|
+
isSuspended?: () => boolean;
|
|
10
18
|
}
|
|
11
19
|
/**
|
|
12
20
|
* 上下文安全护栏插件。
|
|
13
21
|
*
|
|
14
|
-
* 在每次内循环**发请求前**检测上一轮用量(usage.prompt_tokens
|
|
15
|
-
*
|
|
16
|
-
* 在请求前抛出 ContextOverflowError,**中断对话**,交由上层向用户报错。
|
|
22
|
+
* 在每次内循环**发请求前**检测上一轮用量(usage.prompt_tokens):超过 `guardTokens`
|
|
23
|
+
* 即抛 `ContextOverflowError` 中断对话,交由上层向用户报错。
|
|
17
24
|
*
|
|
18
25
|
* 与迁移插件职责分离:
|
|
19
|
-
* - ContextGuardPlugin
|
|
20
|
-
* - AutoMigratePlugin
|
|
26
|
+
* - `ContextGuardPlugin`:硬线,只做「严重超限即中断」的安全兜底,绝不继续对话/迁移;
|
|
27
|
+
* - `AutoMigratePlugin`:软线(`tokenThresholds.handoff`),在正常范围内做交接迁移。
|
|
28
|
+
* 两条线都是绝对值,`guard` 应当明显大于 `handoff`,交接回合的额外请求才有余量。
|
|
21
29
|
*
|
|
22
30
|
* ```ts
|
|
23
|
-
*
|
|
24
|
-
* agent.use(
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
31
|
+
* const { handoff, guard } = config.models[i].tokenThresholds;
|
|
32
|
+
* agent.use(
|
|
33
|
+
* new ContextGuardPlugin({
|
|
34
|
+
* guardTokens: guard,
|
|
35
|
+
* isSuspended: () => handoffService.busy, // 交接回合让行
|
|
36
|
+
* }),
|
|
37
|
+
* );
|
|
38
|
+
* agent.use(new AutoMigratePlugin({ service: handoffService, handoffTokens: handoff }));
|
|
28
39
|
* ```
|
|
29
40
|
*/
|
|
30
41
|
export declare class ContextGuardPlugin implements AgentPlugin {
|
|
31
|
-
private
|
|
42
|
+
private readonly guardTokens;
|
|
43
|
+
private readonly isSuspended?;
|
|
32
44
|
constructor(options: ContextGuardOptions);
|
|
33
45
|
onInnerLoopStart(ctx: SendContext): Promise<void>;
|
|
34
46
|
}
|
|
@@ -2,36 +2,42 @@ import { ContextOverflowError } from "../shared/errors.js";
|
|
|
2
2
|
/**
|
|
3
3
|
* 上下文安全护栏插件。
|
|
4
4
|
*
|
|
5
|
-
* 在每次内循环**发请求前**检测上一轮用量(usage.prompt_tokens
|
|
6
|
-
*
|
|
7
|
-
* 在请求前抛出 ContextOverflowError,**中断对话**,交由上层向用户报错。
|
|
5
|
+
* 在每次内循环**发请求前**检测上一轮用量(usage.prompt_tokens):超过 `guardTokens`
|
|
6
|
+
* 即抛 `ContextOverflowError` 中断对话,交由上层向用户报错。
|
|
8
7
|
*
|
|
9
8
|
* 与迁移插件职责分离:
|
|
10
|
-
* - ContextGuardPlugin
|
|
11
|
-
* - AutoMigratePlugin
|
|
9
|
+
* - `ContextGuardPlugin`:硬线,只做「严重超限即中断」的安全兜底,绝不继续对话/迁移;
|
|
10
|
+
* - `AutoMigratePlugin`:软线(`tokenThresholds.handoff`),在正常范围内做交接迁移。
|
|
11
|
+
* 两条线都是绝对值,`guard` 应当明显大于 `handoff`,交接回合的额外请求才有余量。
|
|
12
12
|
*
|
|
13
13
|
* ```ts
|
|
14
|
-
*
|
|
15
|
-
* agent.use(
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
14
|
+
* const { handoff, guard } = config.models[i].tokenThresholds;
|
|
15
|
+
* agent.use(
|
|
16
|
+
* new ContextGuardPlugin({
|
|
17
|
+
* guardTokens: guard,
|
|
18
|
+
* isSuspended: () => handoffService.busy, // 交接回合让行
|
|
19
|
+
* }),
|
|
20
|
+
* );
|
|
21
|
+
* agent.use(new AutoMigratePlugin({ service: handoffService, handoffTokens: handoff }));
|
|
19
22
|
* ```
|
|
20
23
|
*/
|
|
21
24
|
export class ContextGuardPlugin {
|
|
22
|
-
|
|
25
|
+
guardTokens;
|
|
26
|
+
isSuspended;
|
|
23
27
|
constructor(options) {
|
|
24
|
-
this.
|
|
28
|
+
this.guardTokens = options.guardTokens;
|
|
29
|
+
this.isSuspended = options.isSuspended;
|
|
25
30
|
}
|
|
26
31
|
async onInnerLoopStart(ctx) {
|
|
27
|
-
|
|
28
|
-
|
|
32
|
+
// 交接/迁移回合让行(见 `isSuspended`)
|
|
33
|
+
if (this.isSuspended?.())
|
|
34
|
+
return;
|
|
35
|
+
const promptTokens = ctx.agent.lastUsage?.prompt_tokens;
|
|
29
36
|
// 首轮请求前尚无用量数据,跳过(只能在发出首轮请求、拿到 usage 后才有据可查)
|
|
30
|
-
const promptTokens = agent.lastUsage?.prompt_tokens;
|
|
31
37
|
if (promptTokens == null)
|
|
32
38
|
return;
|
|
33
|
-
if (promptTokens >
|
|
34
|
-
throw new ContextOverflowError(promptTokens,
|
|
39
|
+
if (promptTokens > this.guardTokens) {
|
|
40
|
+
throw new ContextOverflowError(promptTokens, this.guardTokens);
|
|
35
41
|
}
|
|
36
42
|
}
|
|
37
43
|
}
|
|
@@ -19,16 +19,16 @@ export class UnknownToolHintPlugin {
|
|
|
19
19
|
this.scope = options.scope;
|
|
20
20
|
}
|
|
21
21
|
onUnknownTool(ctx) {
|
|
22
|
-
const toolName = ctx.toolCall.function?.name ?? "
|
|
22
|
+
const toolName = ctx.toolCall.function?.name ?? "unknown";
|
|
23
23
|
const mcpPlugin = this.scope.getPluginById(McpScopePlugin.ID);
|
|
24
24
|
const hasMcpConfig = mcpPlugin?.hasConfig() ?? false;
|
|
25
25
|
const hasCallMcpTool = ctx.availableTools.some((t) => t.function.name === "call_mcp_tool");
|
|
26
26
|
if (hasMcpConfig && !hasCallMcpTool) {
|
|
27
|
-
return
|
|
27
|
+
return `Tool "${toolName}" does not exist. An MCP server is configured, but the call_mcp_tool permission is disabled — adjust permissions if you need to use MCP tools.`;
|
|
28
28
|
}
|
|
29
29
|
if (hasMcpConfig && hasCallMcpTool) {
|
|
30
|
-
return
|
|
30
|
+
return `Tool "${toolName}" does not exist. To call MCP tools, use call_mcp_tool.`;
|
|
31
31
|
}
|
|
32
|
-
return
|
|
32
|
+
return `Tool "${toolName}" does not exist.`;
|
|
33
33
|
}
|
|
34
34
|
}
|
|
@@ -1,15 +1,23 @@
|
|
|
1
|
-
import type { AppConfig, AgentDefinition } from "../types/index.js";
|
|
1
|
+
import type { AppConfig, AgentDefinition, ReasoningPresets } from "../types/index.js";
|
|
2
2
|
/**
|
|
3
3
|
* 配置管理器 — 负责配置文件的读写、目录初始化、默认实体创建。
|
|
4
4
|
*/
|
|
5
5
|
export declare class ConfigManager {
|
|
6
6
|
readonly configPath: string;
|
|
7
7
|
readonly basePath: string;
|
|
8
|
+
/** 当前配置里的模型 id 集合(bootstrap 时填充,供默认 Agent 校验 modelId) */
|
|
9
|
+
private knownModelIds;
|
|
8
10
|
constructor(configPath: string);
|
|
9
11
|
/**
|
|
10
12
|
* 读取配置。文件不存在时返回出厂默认配置。
|
|
13
|
+
*
|
|
14
|
+
* 读到即**迁移**(`config/migrate.ts`):上层拿到的永远是当前字段形状,
|
|
15
|
+
* 旧字段(`maxContextTokens` / `maxContextChars`)不会漏到调用方。
|
|
16
|
+
* 迁移结果不在这里落盘——落盘只在 `ensureDefaultConfig()` 做一次。
|
|
11
17
|
*/
|
|
12
18
|
read(): Promise<AppConfig>;
|
|
19
|
+
/** 读磁盘原文(不做任何迁移/同步),供 `ensureDefaultConfig()` 对比写盘用 */
|
|
20
|
+
private readRaw;
|
|
13
21
|
write(config: AppConfig): Promise<void>;
|
|
14
22
|
/**
|
|
15
23
|
* 确保基础目录结构存在。
|
|
@@ -28,13 +36,20 @@ export declare class ConfigManager {
|
|
|
28
36
|
/**
|
|
29
37
|
* 确保 basePath/agents/default.json 存在。
|
|
30
38
|
*
|
|
31
|
-
* - default.json 已存在且 custom === true →
|
|
32
|
-
* - default.json 已存在且 custom !== true →
|
|
33
|
-
* 其余字段(name/permissions
|
|
34
|
-
* - agents/ 为空 → 写入默认 Agent
|
|
39
|
+
* - default.json 已存在且 custom === true → 用户声明为自定义,不替换提示词(缺 modelId 仍补)
|
|
40
|
+
* - default.json 已存在且 custom !== true → 同步出厂提示词(messages),
|
|
41
|
+
* 其余字段(name/permissions 等)保留;提示词与 modelId 都一致时不写盘
|
|
42
|
+
* - agents/ 为空 → 写入默认 Agent(含 modelId)
|
|
35
43
|
* - 已有其他 Agent → 返回 null
|
|
44
|
+
*
|
|
45
|
+
* 模型真相源只有 `AgentDefinition.modelId`:这里保证默认 Agent **一定有** modelId,
|
|
46
|
+
* 运行期不再有任何 `config.defaultModel` 兜底。
|
|
47
|
+
*
|
|
48
|
+
* @param legacyDefaultModel 老配置里的 `config.defaultModel`。仅在 Agent **既无 modelId**
|
|
49
|
+
* 且该模型仍在模型清单里时用它补齐,让升级不改变用户实际在用的模型;之后
|
|
50
|
+
* 这个字段就彻底不存在了。
|
|
36
51
|
*/
|
|
37
|
-
ensureDefaultAgent(): Promise<AgentDefinition | null>;
|
|
52
|
+
ensureDefaultAgent(legacyDefaultModel?: string): Promise<AgentDefinition | null>;
|
|
38
53
|
/**
|
|
39
54
|
* 确保 basePath/sub-agents/{DEFAULT_SUBAGENT_ID}.json 存在。
|
|
40
55
|
*
|
|
@@ -52,6 +67,38 @@ export declare class ConfigManager {
|
|
|
52
67
|
agent: AgentDefinition | null;
|
|
53
68
|
subAgent: AgentDefinition | null;
|
|
54
69
|
}>;
|
|
70
|
+
/** 策略表文件路径(与 config.json 同级) */
|
|
71
|
+
get reasoningPresetsPath(): string;
|
|
72
|
+
/**
|
|
73
|
+
* 读取思考策略表。
|
|
74
|
+
*
|
|
75
|
+
* 文件缺失或无法解析时返回出厂种子(内存值,不写盘)——保证调用方永远拿到可用的表:
|
|
76
|
+
* 用户误删文件后客户端仍能正常选档位,下次 `ensureReasoningPresets()` 会重新释放。
|
|
77
|
+
*/
|
|
78
|
+
readReasoningPresets(): Promise<ReasoningPresets>;
|
|
79
|
+
/**
|
|
80
|
+
* 释放 / 同步出厂思考策略。
|
|
81
|
+
*
|
|
82
|
+
* 覆盖策略与 `syncManagedModels` 同构,**按策略逐个判断**(粒度到单个策略):
|
|
83
|
+
* - 文件不存在 → 写入出厂种子;
|
|
84
|
+
* - 某策略标了 `custom: true` → 用户自有,原样保留;
|
|
85
|
+
* - 某策略未标 → 用出厂版覆盖该策略(内容相同则不写盘);
|
|
86
|
+
* - 用户自建的非出厂策略 → 始终保留。
|
|
87
|
+
*
|
|
88
|
+
* @returns 实际写入的策略名列表(未变化 / 用户自有 均不计入)
|
|
89
|
+
*/
|
|
90
|
+
ensureReasoningPresets(): Promise<string[]>;
|
|
91
|
+
/**
|
|
92
|
+
* 释放 / 同步出厂 Skill。
|
|
93
|
+
*
|
|
94
|
+
* 覆盖策略与 `syncManagedModels` 同构:
|
|
95
|
+
* - 磁盘上不存在 → 写入出厂内容;
|
|
96
|
+
* - 存在且 frontmatter 标了 `custom: "true"` → 用户自有,原样保留;
|
|
97
|
+
* - 存在但未标 → 视为出厂托管,同步为当前版本内容(内容相同则不写盘)。
|
|
98
|
+
*
|
|
99
|
+
* @returns 实际写入的 Skill id 列表(内容未变化 / 用户自有 均不计入)
|
|
100
|
+
*/
|
|
101
|
+
ensureFactorySkills(): Promise<string[]>;
|
|
55
102
|
/** mcp.json 路径:{basePath}/mcp.json */
|
|
56
103
|
get mcpPath(): string;
|
|
57
104
|
/**
|
|
@@ -81,10 +128,12 @@ export declare class ConfigManager {
|
|
|
81
128
|
* 规则:
|
|
82
129
|
* - 未标 `custom: true` 的条目 → 由 SDK 托管,从结果中移除,改用 defaults 中的最新定义;
|
|
83
130
|
* - 标了 `custom: true` 的条目 → 用户自有,原样保留;与出厂定义同 id 时用户版本优先;
|
|
84
|
-
* - 默认模型 ID(
|
|
131
|
+
* - 默认模型 ID(defaultImageModel / defaultMigrationModel)
|
|
85
132
|
* 在合并后若已不存在 → 回退到出厂默认,避免悬空引用。
|
|
86
133
|
*
|
|
134
|
+
* 注意 `defaultModel` 已不再存在:模型真相源是 `AgentDefinition.modelId`。
|
|
135
|
+
*
|
|
87
136
|
* 端点(endpoints)不参与托管,始终保持用户配置。
|
|
88
137
|
*/
|
|
89
138
|
export declare function syncManagedModels(config: AppConfig): AppConfig;
|
|
90
|
-
export { DEFAULT_AGENT_ID, DEFAULT_AGENT_DEFINITION, DEFAULT_SUBAGENT_ID, DEFAULT_SUBAGENT_DEFINITION, DEFAULT_APP_CONFIG, DEFAULT_MCP_CONFIG, CONFIG_SUB_DIRS, } from "./constants.js";
|
|
139
|
+
export { DEFAULT_AGENT_ID, DEFAULT_AGENT_DEFINITION, DEFAULT_MODEL_ID, DEFAULT_SUBAGENT_ID, DEFAULT_SUBAGENT_DEFINITION, DEFAULT_APP_CONFIG, DEFAULT_MCP_CONFIG, CONFIG_SUB_DIRS, } from "./constants.js";
|