@ai-zen/agents-sdk 2.0.0-alpha.0 → 2.0.0-alpha.1

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.
Files changed (131) hide show
  1. package/CHANGELOG.md +73 -16
  2. package/README.md +397 -113
  3. package/README.zh.md +314 -112
  4. package/dist/agent-plugins/AssetTransportPlugin.d.ts +51 -0
  5. package/dist/agent-plugins/AssetTransportPlugin.js +145 -0
  6. package/dist/agent-plugins/AutoMigratePlugin.d.ts +35 -14
  7. package/dist/agent-plugins/AutoMigratePlugin.js +36 -36
  8. package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +6 -6
  9. package/dist/agent-plugins/AutoRefreshToolsPlugin.js +2 -2
  10. package/dist/agent-plugins/ContextGuardPlugin.d.ts +20 -24
  11. package/dist/agent-plugins/ContextGuardPlugin.js +25 -24
  12. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +25 -35
  13. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +26 -41
  14. package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +14 -9
  15. package/dist/agent-plugins/UnknownToolHintPlugin.js +15 -13
  16. package/dist/config/ConfigManager.d.ts +13 -5
  17. package/dist/config/ConfigManager.js +58 -39
  18. package/dist/config/constants.d.ts +1 -1
  19. package/dist/config/constants.js +2 -2
  20. package/dist/config/factory-skills.js +2 -2
  21. package/dist/config/normalize.d.ts +93 -0
  22. package/dist/config/normalize.js +158 -0
  23. package/dist/crud/AgentRepository.d.ts +3 -1
  24. package/dist/crud/AgentRepository.js +4 -2
  25. package/dist/index.d.ts +19 -9
  26. package/dist/index.js +14 -7
  27. package/dist/runtime/AgentRuntime.d.ts +293 -0
  28. package/dist/runtime/AgentRuntime.js +457 -0
  29. package/dist/runtime/HandoffGuardPlugin.d.ts +82 -15
  30. package/dist/runtime/HandoffGuardPlugin.js +136 -17
  31. package/dist/runtime/HandoffService.d.ts +244 -119
  32. package/dist/runtime/HandoffService.js +373 -251
  33. package/dist/runtime/RuntimePeerSessions.d.ts +34 -0
  34. package/dist/runtime/RuntimePeerSessions.js +50 -0
  35. package/dist/runtime/Scopes.d.ts +123 -0
  36. package/dist/runtime/Scopes.js +169 -0
  37. package/dist/runtime/SdkAgent.d.ts +19 -8
  38. package/dist/runtime/SdkAgent.js +23 -6
  39. package/dist/runtime/completeOnce.d.ts +3 -3
  40. package/dist/runtime/completeOnce.js +3 -3
  41. package/dist/runtime/createAgent.d.ts +29 -7
  42. package/dist/runtime/createAgent.js +57 -12
  43. package/dist/runtime/createModel.d.ts +4 -4
  44. package/dist/runtime/createModel.js +6 -6
  45. package/dist/runtime/lastPromptTokens.d.ts +18 -0
  46. package/dist/runtime/lastPromptTokens.js +26 -0
  47. package/dist/runtime/resolveModel.d.ts +9 -9
  48. package/dist/runtime/resolveModel.js +8 -8
  49. package/dist/scope/Scope.d.ts +10 -9
  50. package/dist/scope/Scope.js +6 -6
  51. package/dist/scope/ScopePlugin.d.ts +2 -8
  52. package/dist/scope/disclosure.d.ts +1 -1
  53. package/dist/scope/disclosure.js +1 -1
  54. package/dist/scope/plugins/allInOne.d.ts +13 -1
  55. package/dist/scope/plugins/allInOne.js +9 -5
  56. package/dist/scope/plugins/builtin/AsyncExecTool.d.ts +12 -0
  57. package/dist/scope/plugins/builtin/AsyncExecTool.js +103 -0
  58. package/dist/scope/plugins/builtin/AsyncTimeoutTool.d.ts +10 -0
  59. package/dist/scope/plugins/builtin/AsyncTimeoutTool.js +90 -0
  60. package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.d.ts +1 -1
  61. package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.js +1 -1
  62. package/dist/scope/plugins/builtin/DownloadFileTool.js +1 -1
  63. package/dist/scope/plugins/builtin/ExecTool.js +10 -199
  64. package/dist/scope/plugins/builtin/FindTextTool.d.ts +1 -1
  65. package/dist/scope/plugins/builtin/FindTextTool.js +1 -1
  66. package/dist/scope/plugins/builtin/GenerateImageTool.d.ts +1 -4
  67. package/dist/scope/plugins/builtin/GenerateImageTool.js +2 -8
  68. package/dist/scope/plugins/builtin/InspectFileTool.js +1 -1
  69. package/dist/scope/plugins/builtin/SdkCallbackTool.d.ts +4 -4
  70. package/dist/scope/plugins/builtin/SdkCallbackTool.js +3 -3
  71. package/dist/scope/plugins/builtin/SleepTool.js +2 -3
  72. package/dist/scope/plugins/builtin/ViewImageTool.d.ts +2 -4
  73. package/dist/scope/plugins/builtin/ViewImageTool.js +4 -6
  74. package/dist/scope/plugins/builtin/WriteTool.d.ts +7 -0
  75. package/dist/scope/plugins/builtin/WriteTool.js +8 -1
  76. package/dist/scope/plugins/builtin/asyncTasks.d.ts +41 -0
  77. package/dist/scope/plugins/builtin/asyncTasks.js +97 -0
  78. package/dist/scope/plugins/builtin/commandOutput.d.ts +22 -0
  79. package/dist/scope/plugins/builtin/commandOutput.js +55 -0
  80. package/dist/scope/plugins/builtin/commandRun.d.ts +48 -0
  81. package/dist/scope/plugins/builtin/commandRun.js +169 -0
  82. package/dist/scope/plugins/builtin/discover.d.ts +1 -3
  83. package/dist/scope/plugins/builtin/discover.js +1 -3
  84. package/dist/scope/plugins/builtin/index.d.ts +5 -7
  85. package/dist/scope/plugins/builtin/index.js +7 -7
  86. package/dist/scope/plugins/builtin/outputGuard.d.ts +1 -5
  87. package/dist/scope/plugins/builtin/outputGuard.js +1 -5
  88. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +56 -11
  89. package/dist/scope/plugins/mcp/McpConnectionManager.js +169 -74
  90. package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +17 -7
  91. package/dist/scope/plugins/mcp/McpScopePlugin.js +36 -12
  92. package/dist/scope/plugins/mcp/discover.d.ts +9 -2
  93. package/dist/scope/plugins/mcp/discover.js +12 -14
  94. package/dist/scope/plugins/mcp/mcpTaskNotice.d.ts +52 -0
  95. package/dist/scope/plugins/mcp/mcpTaskNotice.js +8 -0
  96. package/dist/scope/plugins/mcp/mcpTools.d.ts +20 -2
  97. package/dist/scope/plugins/mcp/mcpTools.js +220 -39
  98. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +4 -7
  99. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +4 -7
  100. package/dist/scope/plugins/peers/peerSessionTools.d.ts +97 -46
  101. package/dist/scope/plugins/peers/peerSessionTools.js +147 -121
  102. package/dist/scope/plugins/skills/SkillsScopePlugin.d.ts +4 -0
  103. package/dist/scope/plugins/skills/SkillsScopePlugin.js +10 -4
  104. package/dist/scope/plugins/skills/discover.d.ts +15 -8
  105. package/dist/scope/plugins/skills/discover.js +15 -26
  106. package/dist/scope/plugins/skills/skillTools.d.ts +8 -7
  107. package/dist/scope/plugins/skills/skillTools.js +18 -14
  108. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.d.ts +4 -0
  109. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +4 -1
  110. package/dist/scope/plugins/subagents/discover.d.ts +7 -1
  111. package/dist/scope/plugins/subagents/discover.js +7 -3
  112. package/dist/scope/plugins/subagents/subAgentTools.d.ts +0 -1
  113. package/dist/scope/plugins/subagents/subAgentTools.js +11 -1
  114. package/dist/scope/plugins/usertools/UserToolsScopePlugin.d.ts +4 -0
  115. package/dist/scope/plugins/usertools/UserToolsScopePlugin.js +4 -1
  116. package/dist/scope/plugins/usertools/discover.d.ts +7 -8
  117. package/dist/scope/plugins/usertools/discover.js +17 -27
  118. package/dist/shared/EntityRepository.d.ts +22 -5
  119. package/dist/shared/EntityRepository.js +45 -29
  120. package/dist/shared/content-blocks.d.ts +9 -3
  121. package/dist/shared/content-blocks.js +12 -19
  122. package/dist/shared/errors.d.ts +5 -7
  123. package/dist/shared/errors.js +6 -8
  124. package/dist/shared/logger.d.ts +21 -10
  125. package/dist/shared/logger.js +9 -15
  126. package/dist/types/index.d.ts +36 -13
  127. package/package.json +2 -2
  128. package/dist/config/migrate.d.ts +0 -115
  129. package/dist/config/migrate.js +0 -200
  130. package/dist/scope/plugins/builtin/test-helpers.d.ts +0 -3
  131. package/dist/scope/plugins/builtin/test-helpers.js +0 -4
@@ -1,16 +1,23 @@
1
+ import { type LogSink } from "./logger.js";
1
2
  /**
2
3
  * 通用实体仓储 — 对磁盘 JSON 文件的 CRUD 操作。
3
4
  *
4
5
  * 约定:
5
6
  * - 每个实体一个 JSON 文件,文件名 = `${id}.json`
6
7
  * - 目录不存在时自动创建
7
- * - 解析失败的文件会被跳过(list 时)
8
+ * - `read()` 只把「文件不在」答成 `null`;文件在但读不出来(不是 JSON、没权限)照抛
9
+ * - `list()` 跳过读不出来的那**一条**并报一句
8
10
  */
9
11
  export declare class EntityRepository<T extends {
10
12
  id: string;
11
13
  }> {
12
14
  private dir;
13
- constructor(dir: string);
15
+ protected readonly logger: LogSink;
16
+ /**
17
+ * @param dir 实体目录
18
+ * @param logger 日志口(可选):`list()` 跳过读不出来的那一条时从它报一句。缺省 `SILENT_LOG`
19
+ */
20
+ constructor(dir: string, logger?: LogSink);
14
21
  /**
15
22
  * 获取实体的文件路径;`id` 必须落在本仓储目录内,否则抛错。
16
23
  *
@@ -22,12 +29,22 @@ export declare class EntityRepository<T extends {
22
29
  * - 比较 `root + sep` 而不是裸 `startsWith(root)`:`<root>-evil/x` 也以 `<root>` 开头。
23
30
  */
24
31
  protected path(id: string): string;
25
- /** 列出目录下所有实体(跳过解析失败的文件) */
32
+ /**
33
+ * 列出目录下所有实体。
34
+ *
35
+ * 一个坏文件只影响它自己那一行(宿主的「这个模型被哪个助手引用」读的是整张表),所以
36
+ * 这里接住并报一句:跳过的是这一条,不是整张表。
37
+ */
26
38
  list(): Promise<T[]>;
27
- /** 读取单个实体,不存在返回 null */
39
+ /**
40
+ * 读取单个实体:**只有文件不在才回 `null`**。
41
+ *
42
+ * 「没有这一条」与「这一条坏了」(不是 JSON、EACCES、EIO)是两个答案。折叠成一个 `null`
43
+ * 会让读者对坏文件说假话。要把它当成「没有」的调用方自己接住,并在那一处写明为什么。
44
+ */
28
45
  read(id: string): Promise<T | null>;
29
46
  /** 写入实体(创建或更新) */
30
47
  write(entity: T): Promise<void>;
31
- /** 删除实体,不存在时不抛异常 */
48
+ /** 删除实体;本来就不存在算成功,删不掉(权限等)照抛 */
32
49
  delete(id: string): Promise<void>;
33
50
  }
@@ -1,17 +1,25 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import { resolve, sep } from "node:path";
3
+ import { SILENT_LOG } from "./logger.js";
3
4
  /**
4
5
  * 通用实体仓储 — 对磁盘 JSON 文件的 CRUD 操作。
5
6
  *
6
7
  * 约定:
7
8
  * - 每个实体一个 JSON 文件,文件名 = `${id}.json`
8
9
  * - 目录不存在时自动创建
9
- * - 解析失败的文件会被跳过(list 时)
10
+ * - `read()` 只把「文件不在」答成 `null`;文件在但读不出来(不是 JSON、没权限)照抛
11
+ * - `list()` 跳过读不出来的那**一条**并报一句
10
12
  */
11
13
  export class EntityRepository {
12
14
  dir;
13
- constructor(dir) {
15
+ logger;
16
+ /**
17
+ * @param dir 实体目录
18
+ * @param logger 日志口(可选):`list()` 跳过读不出来的那一条时从它报一句。缺省 `SILENT_LOG`
19
+ */
20
+ constructor(dir, logger = SILENT_LOG) {
14
21
  this.dir = dir;
22
+ this.logger = logger;
15
23
  }
16
24
  /**
17
25
  * 获取实体的文件路径;`id` 必须落在本仓储目录内,否则抛错。
@@ -31,7 +39,12 @@ export class EntityRepository {
31
39
  }
32
40
  return target;
33
41
  }
34
- /** 列出目录下所有实体(跳过解析失败的文件) */
42
+ /**
43
+ * 列出目录下所有实体。
44
+ *
45
+ * 一个坏文件只影响它自己那一行(宿主的「这个模型被哪个助手引用」读的是整张表),所以
46
+ * 这里接住并报一句:跳过的是这一条,不是整张表。
47
+ */
35
48
  async list() {
36
49
  try {
37
50
  await fs.access(this.dir);
@@ -43,48 +56,51 @@ export class EntityRepository {
43
56
  const ids = entries.filter((f) => f.endsWith(".json")).map((f) => f.replace(/\.json$/, ""));
44
57
  const entities = [];
45
58
  for (const id of ids) {
46
- const entity = await this.read(id);
47
- if (entity)
48
- entities.push(entity);
59
+ try {
60
+ const entity = await this.read(id);
61
+ if (entity !== null)
62
+ entities.push(entity);
63
+ }
64
+ catch (error) {
65
+ this.logger.warn(`[entity] 读不出来,列表里跳过这一条:${this.path(id)}(${String(error)})`);
66
+ }
49
67
  }
50
68
  return entities;
51
69
  }
52
- /** 读取单个实体,不存在返回 null */
70
+ /**
71
+ * 读取单个实体:**只有文件不在才回 `null`**。
72
+ *
73
+ * 「没有这一条」与「这一条坏了」(不是 JSON、EACCES、EIO)是两个答案。折叠成一个 `null`
74
+ * 会让读者对坏文件说假话。要把它当成「没有」的调用方自己接住,并在那一处写明为什么。
75
+ */
53
76
  async read(id) {
77
+ // `path()` 留在 try 外面:id 逃出目录是调用方的错,该抛,不该被当成「没有这一条」
54
78
  const p = this.path(id);
55
79
  try {
56
- await fs.access(p);
57
- }
58
- catch {
59
- return null;
60
- }
61
- try {
62
- const raw = await fs.readFile(p, "utf-8");
63
- return JSON.parse(raw);
80
+ return JSON.parse(await fs.readFile(p, "utf-8"));
64
81
  }
65
- catch {
66
- return null;
82
+ catch (error) {
83
+ if (error.code === "ENOENT")
84
+ return null;
85
+ throw error;
67
86
  }
68
87
  }
69
88
  /** 写入实体(创建或更新) */
70
89
  async write(entity) {
71
- try {
72
- await fs.access(this.dir);
73
- }
74
- catch {
75
- await fs.mkdir(this.dir, { recursive: true });
76
- }
90
+ // `mkdir(recursive)` 幂等,不必先探测目录在不在
91
+ await fs.mkdir(this.dir, { recursive: true });
77
92
  await fs.writeFile(this.path(entity.id), JSON.stringify(entity, null, 2), "utf-8");
78
93
  }
79
- /** 删除实体,不存在时不抛异常 */
94
+ /** 删除实体;本来就不存在算成功,删不掉(权限等)照抛 */
80
95
  async delete(id) {
81
- const p = this.path(id);
82
96
  try {
83
- await fs.access(p);
84
- await fs.unlink(p);
97
+ await fs.unlink(this.path(id));
85
98
  }
86
- catch {
87
- // 文件不存在,忽略
99
+ catch (error) {
100
+ // 只有 ENOENT 可以当「已经没有了」;EACCES / EPERM / EISDIR 必须报 ——
101
+ // 吞了它们,调用方会把「没删掉」当成「删掉了」(宿主那边就会回 `removed: true`)
102
+ if (error.code !== "ENOENT")
103
+ throw error;
88
104
  }
89
105
  }
90
106
  }
@@ -6,10 +6,10 @@
6
6
  * | 条件 | 结果 |
7
7
  * |------|------|
8
8
  * | http(s) URL | 直接 `image_url`(不上传、不内联) |
9
- * | 端点声明 `capabilities.filesApi` | 上传 Files API → `file` 块(`file_id`),失败降级为内联 |
9
+ * | 端点声明 `capabilities.filesApi` 且有 `apiKey` | 上传 Files API → `file` 块(`file_id`);上传失败即抛,不换传输方式 |
10
10
  * | 其余端点 + 图片 | `image_url` + base64 data URL |
11
11
  * | 其余端点 + 非图片 | `file` 块 + `file_data`(base64 data URL) |
12
- * | 模型明确不支持视觉(`vision === false`)且是图片 | 退化为 `text`,只给路径提示 |
12
+ * | 图片且模型不是视觉模型(`vision !== true`) | 退化为 `text`,只给路径提示 |
13
13
  * | 内联体积超过上限且无法上传 | 抛错(不静默塞进请求体) |
14
14
  *
15
15
  * 本模块只负责**选路**与**上传这一个 HTTP 动作**:需要 `file_id` 时每次调用都真上传,
@@ -69,7 +69,11 @@ export interface FileToSectionResult {
69
69
  transport: ContentTransport;
70
70
  /** 实际处理的字节数(URL 来源为 0) */
71
71
  bytes: number;
72
- /** 降级 / 退化时的人类可读说明,供上层拼提示 */
72
+ /**
73
+ * 退化为文本提示时的人类可读说明,供上层拼提示。
74
+ *
75
+ * 唯一产生者是下面「模型看不见图 → 退化为文本」那一支(上传失败直接抛错,不走这里)。
76
+ */
73
77
  warning?: string;
74
78
  }
75
79
  /**
@@ -93,6 +97,8 @@ export declare function contentHash(bytes: Uint8Array): string;
93
97
  * 抛错场景(均由调用方决定如何呈现给模型):
94
98
  * - `source.url` 不是 http(s)(本地 URL 服务商访问不到)
95
99
  * - 本地文件不存在 / 不是文件 / 扩展名不支持
100
+ * - 端点声明了 Files API 但上传失败(HTTP 非 2xx、网络错误、取消):不换成 base64 内联,
101
+ * 原错误原样抛——换传输方式是调用方该知道的事,不该在这里静默发生
96
102
  * - 需要内联但体积超过上限,且端点不支持上传
97
103
  */
98
104
  export declare function fileToContentSection(input: FileToSectionInput): Promise<FileToSectionResult>;
@@ -6,10 +6,10 @@
6
6
  * | 条件 | 结果 |
7
7
  * |------|------|
8
8
  * | http(s) URL | 直接 `image_url`(不上传、不内联) |
9
- * | 端点声明 `capabilities.filesApi` | 上传 Files API → `file` 块(`file_id`),失败降级为内联 |
9
+ * | 端点声明 `capabilities.filesApi` 且有 `apiKey` | 上传 Files API → `file` 块(`file_id`);上传失败即抛,不换传输方式 |
10
10
  * | 其余端点 + 图片 | `image_url` + base64 data URL |
11
11
  * | 其余端点 + 非图片 | `file` 块 + `file_data`(base64 data URL) |
12
- * | 模型明确不支持视觉(`vision === false`)且是图片 | 退化为 `text`,只给路径提示 |
12
+ * | 图片且模型不是视觉模型(`vision !== true`) | 退化为 `text`,只给路径提示 |
13
13
  * | 内联体积超过上限且无法上传 | 抛错(不静默塞进请求体) |
14
14
  *
15
15
  * 本模块只负责**选路**与**上传这一个 HTTP 动作**:需要 `file_id` 时每次调用都真上传,
@@ -125,6 +125,8 @@ function textSection(text) {
125
125
  * 抛错场景(均由调用方决定如何呈现给模型):
126
126
  * - `source.url` 不是 http(s)(本地 URL 服务商访问不到)
127
127
  * - 本地文件不存在 / 不是文件 / 扩展名不支持
128
+ * - 端点声明了 Files API 但上传失败(HTTP 非 2xx、网络错误、取消):不换成 base64 内联,
129
+ * 原错误原样抛——换传输方式是调用方该知道的事,不该在这里静默发生
128
130
  * - 需要内联但体积超过上限,且端点不支持上传
129
131
  */
130
132
  export async function fileToContentSection(input) {
@@ -196,23 +198,15 @@ export async function fileToContentSection(input) {
196
198
  warning: "The current model does not support image input; degraded to a text hint",
197
199
  };
198
200
  }
199
- // ---- 4. 端点支持 Files API:上传(每次调用都真上传),失败降级内联 ----
200
- let warning;
201
+ // ---- 4. 端点支持 Files API:上传(每次调用都真上传),失败原样抛 ----
201
202
  if (supportsFilesApi(endpoint) && endpoint?.apiKey) {
202
- try {
203
- const upload = input.deps?.upload ?? defaultUpload;
204
- const fileId = await upload({ endpoint, data: ensureBytes(), filename, signal });
205
- return {
206
- section: { type: "file", file_id: fileId },
207
- transport: "files-api",
208
- bytes: byteLength,
209
- };
210
- }
211
- catch (error) {
212
- if (signal?.aborted)
213
- throw error;
214
- warning = `Files API upload failed, falling back to base64 inline: ${error?.message ?? error}`;
215
- }
203
+ const upload = input.deps?.upload ?? defaultUpload;
204
+ const fileId = await upload({ endpoint, data: ensureBytes(), filename, signal });
205
+ return {
206
+ section: { type: "file", file_id: fileId },
207
+ transport: "files-api",
208
+ bytes: byteLength,
209
+ };
216
210
  }
217
211
  // ---- 5. 内联(base64 data URL)----
218
212
  if (byteLength > maxInline) {
@@ -228,6 +222,5 @@ export async function fileToContentSection(input) {
228
222
  : { type: "file", file_data: dataUrl, filename },
229
223
  transport: "inline",
230
224
  bytes: byteLength,
231
- warning,
232
225
  };
233
226
  }
@@ -7,16 +7,14 @@ export declare class SdkError extends Error {
7
7
  constructor(code: string, message: string, cause?: Error);
8
8
  }
9
9
  /**
10
- * 上下文超限错误。由 ContextGuardPlugin 在请求前**用来拼拒绝理由**。
10
+ * 上下文超限错误。由 ContextGuardPlugin 在请求前**用来拼拒绝理由**(返回它的 `message`)。
11
11
  *
12
- * 注意:它现在不再被抛出。core 重写之后,钩子里的异常会穿到 `start()` 外面把整个循环
13
- * 打死(agent 变成僵尸),所以护栏改成「返回字符串 = 拒这一圈」(`onInnerLoopStart`),
14
- * 理由那句文案就来自这个类的 `message`。结构化字段(用量 / 阈值)**没有通道交出去**——
15
- * 拒绝理由只有字符串这一种形状;宿主若必须按数字渲染文案,需要 core 提供带结构载荷的
16
- * `denied`。
12
+ * 它自己不被抛出:钩子里抛错会穿到 `start()` 外面把整个循环打死(agent 变成僵尸),所以
13
+ * 护栏改成「返回字符串 = 拒这一次请求」(`onInnerLoopStart`)。拒绝理由只有字符串这一种
14
+ * 形状,用量 / 阈值这两个字段便于就地拼文案。
17
15
  *
18
16
  * 触发条件通常是上下文 token 用量超过硬线(如读入超大文件),
19
- * 继续对话已无意义且会持续放大费用/延迟,故由上层向用户显式报错。
17
+ * 继续会话已无意义且会持续放大费用/延迟。
20
18
  */
21
19
  export declare class ContextOverflowError extends Error {
22
20
  /** 触发拦截时的用量(usage.prompt_tokens) */
@@ -14,16 +14,14 @@ export class SdkError extends Error {
14
14
  }
15
15
  }
16
16
  /**
17
- * 上下文超限错误。由 ContextGuardPlugin 在请求前**用来拼拒绝理由**。
17
+ * 上下文超限错误。由 ContextGuardPlugin 在请求前**用来拼拒绝理由**(返回它的 `message`)。
18
18
  *
19
- * 注意:它现在不再被抛出。core 重写之后,钩子里的异常会穿到 `start()` 外面把整个循环
20
- * 打死(agent 变成僵尸),所以护栏改成「返回字符串 = 拒这一圈」(`onInnerLoopStart`),
21
- * 理由那句文案就来自这个类的 `message`。结构化字段(用量 / 阈值)**没有通道交出去**——
22
- * 拒绝理由只有字符串这一种形状;宿主若必须按数字渲染文案,需要 core 提供带结构载荷的
23
- * `denied`。
19
+ * 它自己不被抛出:钩子里抛错会穿到 `start()` 外面把整个循环打死(agent 变成僵尸),所以
20
+ * 护栏改成「返回字符串 = 拒这一次请求」(`onInnerLoopStart`)。拒绝理由只有字符串这一种
21
+ * 形状,用量 / 阈值这两个字段便于就地拼文案。
24
22
  *
25
23
  * 触发条件通常是上下文 token 用量超过硬线(如读入超大文件),
26
- * 继续对话已无意义且会持续放大费用/延迟,故由上层向用户显式报错。
24
+ * 继续会话已无意义且会持续放大费用/延迟。
27
25
  */
28
26
  export class ContextOverflowError extends Error {
29
27
  /** 触发拦截时的用量(usage.prompt_tokens) */
@@ -32,7 +30,7 @@ export class ContextOverflowError extends Error {
32
30
  guardTokens;
33
31
  constructor(promptTokens, guardTokens) {
34
32
  super(`🛑 Context critically over the limit: ${promptTokens} tokens used, above the blocking threshold of ${guardTokens}.` +
35
- ` The conversation may have run away after reading an oversized file, so it has been interrupted — please inspect and start over.` +
33
+ ` The session may have run away after reading an oversized file, so it has been interrupted — please inspect and start over.` +
36
34
  ` (If you really need a longer context, raise tokenThresholds.guard for this model in config.json.)`);
37
35
  this.name = "ContextOverflowError";
38
36
  this.promptTokens = promptTokens;
@@ -1,14 +1,25 @@
1
- export interface LogFunctions {
2
- info: (message: string) => void;
3
- warn: (message: string) => void;
4
- error: (message: string) => void;
5
- }
6
- export type Logger = LogFunctions;
7
1
  /**
8
- * 获取全局 Logger 实例。
2
+ * 日志口:一个三方法的结构类型 + 一份什么都不做的缺省实现。
3
+ *
4
+ * 库**不持有**日志出口:这里没有模块级的可变单例。谁要打日志,谁就从自己的参数里收一个
5
+ * {@link LogSink} 往下传;不注入就什么都不写({@link SILENT_LOG})。
6
+ *
7
+ * 为什么不在这里放一份「缺省写 stdout」的实现:库默认往标准输出写,等于把「日志落到哪里」
8
+ * 这件属于进程的事替调用方定了 —— 宿主被拉起时 stdout / stderr 归谁、落到哪个文件,只有
9
+ * 进程自己知道。库缺省沉默,嵌入方(宿主 / 命令行)把自己那一份注入进来。
10
+ *
11
+ * 与 `@ai-zen/agents-logger` 的同名类型**结构相容**,但本包不依赖那个包:「三方法」不值得
12
+ * 让库去认下一个文件日志包。
9
13
  */
10
- export declare function getLogger(): Logger;
14
+ export interface LogSink {
15
+ info(message: string, detail?: unknown): void;
16
+ warn(message: string, detail?: unknown): void;
17
+ error(message: string, detail?: unknown): void;
18
+ }
11
19
  /**
12
- * 设置全局 Logger 实例,替换默认的 console 输出。
20
+ * 什么都不做的 {@link LogSink}:所有「可选日志」参数的缺省值。
21
+ *
22
+ * 一份实例、一处定义:缺省值在构造里写成 `logger ?? SILENT_LOG`,不在每个调用点现拼一个
23
+ * 空对象 —— 那样每一处都是新的一份,且「不注入日志时会发生什么」得读遍调用点才能答上来。
13
24
  */
14
- export declare function setLogger(log: Logger): void;
25
+ export declare const SILENT_LOG: LogSink;
@@ -1,17 +1,11 @@
1
- let currentLogger = {
2
- info: console.log,
3
- warn: console.warn,
4
- error: console.error,
5
- };
6
- /**
7
- * 获取全局 Logger 实例。
8
- */
9
- export function getLogger() {
10
- return currentLogger;
11
- }
12
1
  /**
13
- * 设置全局 Logger 实例,替换默认的 console 输出。
2
+ * 什么都不做的 {@link LogSink}:所有「可选日志」参数的缺省值。
3
+ *
4
+ * 一份实例、一处定义:缺省值在构造里写成 `logger ?? SILENT_LOG`,不在每个调用点现拼一个
5
+ * 空对象 —— 那样每一处都是新的一份,且「不注入日志时会发生什么」得读遍调用点才能答上来。
14
6
  */
15
- export function setLogger(log) {
16
- currentLogger = log;
17
- }
7
+ export const SILENT_LOG = {
8
+ info: () => undefined,
9
+ warn: () => undefined,
10
+ error: () => undefined,
11
+ };
@@ -1,5 +1,6 @@
1
1
  import type { AgentNS, AbortedMessageStrategy, AbortedToolRoundStrategy } from "@ai-zen/agents-core";
2
2
  import type { AutoRefreshWhen } from "../agent-plugins/AutoRefreshToolsPlugin.js";
3
+ import type { LogSink } from "../shared/logger.js";
3
4
  /** 工具刷新的三个档位(`off` = 不装插件,由装配方判) */
4
5
  export type AutoRefreshToolsWhen = AutoRefreshWhen | "off";
5
6
  /** 单维度权限策略:allow 或 deny 互斥 */
@@ -84,8 +85,8 @@ export interface Endpoint {
84
85
  * 两个阈值语义不同,消费方也不同:
85
86
  * - `handoff`:软线。`AutoMigratePlugin` 在 agent 闲下来之后拿 `usage.prompt_tokens` 比它,
86
87
  * 超过即触发任务交接(交接本身还要再发 1~2 次请求,所以这条线必须留足余量)。
87
- * - `guard`:硬线。`ContextGuardPlugin` 在**每次请求前**比它,超过即**拒这一圈**
88
- * (`onInnerLoopStart` 返回理由 → core 报 `denied`,这一轮压根没发出去)——
88
+ * - `guard`:硬线。`ContextGuardPlugin` 在**每次请求前**比它,超过即**拒这一次请求**
89
+ * (`onInnerLoopStart` 返回理由 → core 报 `denied`,这一次请求压根没发出去)——
89
90
  * 这是最后一道保护,宁可报错也不要发出必然失败的请求。
90
91
  *
91
92
  * 建议 `guard ≈ handoff × 1.5`,给交接留出缓冲;两者都是绝对值,配置里写多少就是多少,
@@ -94,7 +95,7 @@ export interface Endpoint {
94
95
  export interface TokenThresholds {
95
96
  /** 交接阈值(软线):prompt_tokens 超过它 → 触发任务交接 */
96
97
  handoff: number;
97
- /** 强行阻断阈值(硬线):请求前用量超过它 → 中断本轮并报错 */
98
+ /** 强行阻断阈值(硬线):请求前用量超过它 → 中断这一次请求并报错 */
98
99
  guard: number;
99
100
  }
100
101
  /** 模型配置,绑定一个 Endpoint */
@@ -133,7 +134,7 @@ export interface AgentDefinition {
133
134
  id: string;
134
135
  name: string;
135
136
  description?: string;
136
- /** 预设对话(至少一条 system) */
137
+ /** 预设消息(至少一条 system) */
137
138
  messages: AgentNS.Message[];
138
139
  /**
139
140
  * 绑定模型 id —— 三级解析的**第二级**(`createAgent` 里唯一一处实现):
@@ -211,17 +212,20 @@ export interface AppConfig {
211
212
  /** 默认迁移模型 ID */
212
213
  defaultMigrationModel?: string;
213
214
  /**
214
- * 给新对话自动取名的模型 ID(缺省回落到 `defaultModel`)。
215
+ * 给新会话自动取名的模型 ID(缺省回落到 `defaultModel`)。
215
216
  *
216
217
  * 起名是一次性、不流式、不带工具的调用,用小模型就够;与「迁移模型」
217
218
  * 分开是因为两者要求不同:迁移要能处理长上下文,起名只要几十个 token。
218
219
  */
219
220
  namingModel?: string;
220
221
  /**
221
- * 缺省语言(`hello` 没有声明语言时用的那一种)。
222
+ * 宿主那一份语言:用户可见的文本在产生那一刻就按它渲染。
222
223
  *
223
- * 语言本身挂在连接上、断开即忘,所以这里存的是「没声明时算哪一种」,不是「用户现在用哪一种」。
224
- * 取值与客户端支持的语言一致(`en` / `zh`);缺省(不写)由消费方按 `en` 处理。
224
+ * 语言是用户的属性,不是连接的属性(这个项目是单用户):宿主只有这一份,任何一端连上来看到的
225
+ * 都是同一种语言。客户端自己那份(界面用哪一种是它自己的事)与这一格无关。
226
+ *
227
+ * 取值 `en` / `zh`;缺省(不写)由消费方按 `en` 处理 —— 不在这里补一个值写进文件,补了就有
228
+ * 两处定义默认值。
225
229
  */
226
230
  language?: "en" | "zh";
227
231
  /**
@@ -246,9 +250,9 @@ export interface AppConfig {
246
250
  /**
247
251
  * 被中断的 assistant 消息(已输出的思考 / 正文)如何处置。
248
252
  *
249
- * - `keep`:保留已输出的部分(恢复为 `Completed`)—— 模型下一轮能接着半截往下说,
253
+ * - `keep`:保留已输出的部分(恢复为 `Completed`)—— 模型下一次请求能接着半截往下说,
250
254
  * 不会「失忆重来」。**出厂默认**。
251
- * - `drop`:丢弃(保持 `Aborted`,不进下一轮上下文)。core 的库级默认。
255
+ * - `drop`:丢弃(保持 `Aborted`,不进下一次请求的上下文)。core 的库级默认。
252
256
  *
253
257
  * 只管**不带工具调用**的消息;工具轮次由 {@link abortedToolRoundStrategy} 决定。
254
258
  * 缺省时由 `createAgent()` 回落 core 默认值(`drop`),出厂配置已写 `keep`。
@@ -265,12 +269,12 @@ export interface AppConfig {
265
269
  */
266
270
  abortedToolRoundStrategy?: AbortedToolRoundStrategy;
267
271
  /**
268
- * 每轮刷新工具清单(MCP server / skill / 用户工具)的时机。
272
+ * 刷新工具清单(MCP server / skill / 用户工具)的时机。
269
273
  *
270
274
  * - `inner-loop-start`:`onInnerLoopStart`,**每次请求前**刷(每次工具回合都能看见新装的
271
275
  * 能力)。**出厂默认**;
272
- * - `outer-loop-start`:`onOuterLoopStart`,每一批事件开头刷一次(一圈一次),
273
- * 要等下一轮才生效,开销最小;
276
+ * - `outer-loop-start`:`onOuterLoopStart`,每一批事件开头刷一次(一批一次),
277
+ * 要等下一次被叫起来才生效,开销最小;
274
278
  * - `off`:不刷,只靠 `/reload`。
275
279
  *
276
280
  * 缺省(`undefined`)按 `inner-loop-start` 算 —— 装配方读它时不要写「undefined 就不装」。
@@ -322,6 +326,18 @@ export interface ToolEnvDeps {
322
326
  upload?: UploadFn;
323
327
  /** 调用端点生成图片,默认 `client.images.generate` */
324
328
  generateImage?: GenerateImageFn;
329
+ /**
330
+ * 按 id 取一份素材的字节。素材库是宿主的财产,SDK 不认识它;这一格是「发出去之前按当前模型
331
+ * 重建内容段」唯一需要外部给的东西。
332
+ *
333
+ * 取不到(那份素材已经不在)就回 `undefined`,**不要抛**:发送前的那一步要把它换成一句
334
+ * 「附件已不在」的文本,而不是让整次请求失败。
335
+ */
336
+ readAsset?: (assetId: string) => {
337
+ bytes: Uint8Array;
338
+ mime: string;
339
+ name?: string;
340
+ } | undefined;
325
341
  }
326
342
  /**
327
343
  * 工具环境 — Scope 的能力插件在实例化内置工具时注入的环境信息。
@@ -336,6 +352,13 @@ export interface ToolEnv {
336
352
  config: AppConfig;
337
353
  /** 外部依赖注入点(默认全部走真实 OpenAI SDK) */
338
354
  deps?: ToolEnvDeps;
355
+ /**
356
+ * 日志口(可选)。后台任务的结果投不回去时,那一行从这里记;不注入就什么都不写。
357
+ *
358
+ * 这类失败没有别的去处:发起任务的工具调用当场就返回了,等结果回来时也没有任何一个
359
+ * 调用点可以接住它。
360
+ */
361
+ log?: LogSink;
339
362
  }
340
363
  /** MCP 连接状态 */
341
364
  export type McpConnectionState = "disconnected" | "connecting" | "connected" | "error";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-zen/agents-sdk",
3
- "version": "2.0.0-alpha.0",
3
+ "version": "2.0.0-alpha.1",
4
4
  "description": "AI-Zen Agents SDK — shared business logic for CLI and Desktop",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -25,7 +25,7 @@
25
25
  "author": "LZQCN",
26
26
  "license": "MIT",
27
27
  "dependencies": {
28
- "@ai-zen/agents-core": "^5.0.0-alpha.0",
28
+ "@ai-zen/agents-core": "^5.0.0-alpha.2",
29
29
  "@modelcontextprotocol/sdk": "^1.29.0",
30
30
  "openai": "^7.5.0"
31
31
  },
@@ -1,115 +0,0 @@
1
- /**
2
- * 配置字段迁移 —— 历史形状升级到当前形状
3
- *
4
- * 三条遗留字段被淘汰:
5
- *
6
- * 1. `Model.maxContextTokens` / `Model.maxContextChars` → **`Model.tokenThresholds`**
7
- * 旧名字一直在误导:它既不是「模型的真实上下文窗口」,也不是单一概念。现在拆成两条线:
8
- * `handoff`(交接阈值,软线)与 `guard`(强行阻断阈值,硬线)。
9
- * `maxContextChars` 是 token 口径之前的历史遗留,按 `floor(chars / 4)` 折成 tokens
10
- * (与旧代码的回退算法一致)后并入 `handoff`。
11
- * 2. **`Model.reasoning` → `Model.reasoningPreset`**
12
- * 老配置用 `reasoning: { efforts, disable? }` 在模型上声明思考能力,现在是
13
- * 「引用策略表里的名字」。未标 `custom` 的模型会被出厂定义整块覆盖,但**标了 `custom`
14
- * 的模型会原地保留**,于是留下一个无人认识的 `reasoning` 死字段,同时因为缺
15
- * `reasoningPreset` 而默默失去调档能力。这里删掉旧字段,并按**同 id 的出厂模型**
16
- * 补上正确的策略名(同一 id 即同一厂商型号,协议能力不会因用户改过参数而变)。
17
- *
18
- * 另有一类「缺省值缺位」的迁移:`Endpoint.capabilities`(见 `normalizeEndpointCapabilities`)。
19
- *
20
- * ## `defaultModel` 是**反例**:它不需要迁移,也绝不能清
21
- *
22
- * 模型解析是三级(`会话级覆盖 > Agent 定义 > 本字段`,唯一实现在
23
- * `runtime/resolveModel.ts`),`defaultModel` 就是**全局兜底层**。字段名从未变过,
24
- * 所以这里**什么都不用搬**:老配置里写着的原样保留、继续生效。绝对不能再清 ——
25
- * 清掉等于用户升级一次就静默丢一次自己配的兜底模型,而这属于「默认值缺位」里最坏的
26
- * 一种:丢的是用户明确填过的值。
27
- *
28
- * 迁移时机:`ConfigManager.read()` 读出即迁(内存里永远是当前形状);
29
- * 落盘由 `ensureDefaultConfig()` 负责 —— 它比较迁移结果与磁盘原文,不同才写回,
30
- * 因此迁移只发生一次,且不会在每次启动时无谓地改写文件。
31
- */
32
- import type { AppConfig, Model } from "../types/index.js";
33
- /** 当前字段名 */
34
- export declare const TOKEN_THRESHOLDS_KEY = "tokenThresholds";
35
- /** 已淘汰的旧字段名(仅迁移代码认识它们) */
36
- export declare const LEGACY_TOKEN_FIELD = "maxContextTokens";
37
- export declare const LEGACY_CHARS_FIELD = "maxContextChars";
38
- export declare const LEGACY_REASONING_FIELD = "reasoning";
39
- /**
40
- * 旧数据缺失阈值时的交接阈值兜底。
41
- *
42
- * 与 CLI 新建模型的默认值一致;宁可给一个保守值,也不要让模型缺阈值——
43
- * 缺阈值意味着既没有交接触发、也没有阻断保护。
44
- */
45
- export declare const DEFAULT_HANDOFF_THRESHOLD = 128000;
46
- /**
47
- * 迁移单个模型条目。
48
- *
49
- * 优先级:已有 `tokenThresholds` 的成员 > 旧 tokens 字段 > 旧 chars 字段折算 > 兜底默认。
50
- * 旧字段一律删除(连同一份数据里残留的脏值),保证迁移后的形状唯一。
51
- * 已有 `handoff` 但缺 `guard` 时按 1.5 倍补齐。
52
- */
53
- export declare function migrateModelThresholds(model: Model): {
54
- model: Model;
55
- changed: boolean;
56
- };
57
- /**
58
- * 迁移单个模型的思考能力声明:`reasoning` → `reasoningPreset`。
59
- *
60
- * 只处理「旧字段存在」这一种情况:字段一旦落盘消失,用户后续主动删掉
61
- * `reasoningPreset`(表示「这个模型我不想调档」)就不会被反复补回来。
62
- */
63
- export declare function migrateModelReasoning(model: Model): {
64
- model: Model;
65
- changed: boolean;
66
- };
67
- /**
68
- * 迁移整个配置。只处理对话模型(`models`)——
69
- * 图片模型(`imageModels`)既没有上下文阈值、也没有思考概念。
70
- *
71
- * 同时做两件字段级收敛:
72
- * - **保留** `defaultModel`(三级解析的全局兜底层,见文件头):它不在这里被删、
73
- * 也不在这里被补 —— 用户没配就没有兜底层,`createAgent` 会给出明确报错;
74
- * - 补齐中断策略(`abortedMessageStrategy` / `abortedToolRoundStrategy`):把缺失或
75
- * 非法值写成出厂默认。这样「配置即事实」——文件里写着的就是运行时用的,不再需要
76
- * 使用方各自 `?? "keep"` 地兵分两路兜底。
77
- */
78
- export declare function migrateConfig(config: AppConfig): {
79
- config: AppConfig;
80
- changed: boolean;
81
- };
82
- /** 合法的中断策略取值(与 core 的枚举一致) */
83
- export declare const ABORTED_MESSAGE_STRATEGIES: readonly ["keep", "drop"];
84
- export declare const ABORTED_TOOL_ROUND_STRATEGIES: readonly ["fill", "drop"];
85
- /** 缺失 / 非法 → 出厂默认;返回是否有改动(直接改写传入对象) */
86
- export declare function normalizeAbortStrategies(config: AppConfig): boolean;
87
- /**
88
- * 补齐端点**缺失**的能力位声明(`Endpoint.capabilities`)。
89
- *
90
- * ## 为什么要补
91
- *
92
- * `capabilities.filesApi` 是后来才引入的能力位 —— 它把 `view_image` 的判定从「端点 id
93
- * 是不是 `deepseek`」改成「看这一位」,而出厂只有 deepseek 打了 `true`。
94
- * 但端点**不参与出厂托管**(`ConfigManager.syncManagedModels` 明写「保持用户配置」),
95
- * 迁移此前也完全不碰 `endpoints` —— 于是在这之前就已写下的配置,其 deepseek
96
- * 端点永远缺 `capabilities`,`supportsFilesApi()` 恒为 `false`:
97
- *
98
- * · 出厂承诺的「deepseek 走 Files API」对这些用户从未生效;
99
- * · 而且**全程静默** —— 「未声明能力位」和「缺 apiKey」两个分支都不发 warning,
100
- * 图片 / `view_image` / MCP 媒体就悄悄退化成 base64 内联,请求体随历史膨胀。
101
- *
102
- * 这是「默认值缺位」,不是「用户选择」,所以由迁移补 —— 与模型清单不同,端点本身仍然
103
- * 归用户所有,我们只往**空位**里放出厂默认。
104
- *
105
- * ## 边界:只补整体缺失,绝不覆盖
106
- *
107
- * - `capabilities` **整体缺失** → 按**同 id 的出厂端点**补上整块;
108
- * - `capabilities` 已存在(哪怕是 `{}`、哪怕写着 `filesApi: false`)→ 一个字段都不动:
109
- * 用户已经表过态,`false` 就是「我不走 Files API」;
110
- * - 端点 id 不在出厂清单(用户自建)→ 不动:我们不知道它是否真有 `/files`,
111
- * 猜错会把上传请求打到不存在的接口上。
112
- *
113
- * @returns 是否有改动(直接改写传入对象)
114
- */
115
- export declare function normalizeEndpointCapabilities(config: AppConfig): boolean;