@h-ai/ai 1.0.0-beta.30 → 1.0.0-beta.31

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 (48) hide show
  1. package/README.en.md +11 -1114
  2. package/README.ja.md +10 -1113
  3. package/README.md +11 -1137
  4. package/dist/{ai-acp-types-DuPV5UGi.d.ts → ai-acp-types-C0ab9EBY.d.ts} +4960 -5220
  5. package/dist/ai-file-types-BN7l67hR.d.ts +167 -0
  6. package/dist/ai-file-worker.d.ts +38 -0
  7. package/dist/ai-file-worker.js +85 -0
  8. package/dist/ai-file-worker.js.map +1 -0
  9. package/dist/ai-video-archive-worker.d.ts +32 -0
  10. package/dist/ai-video-archive-worker.js +102 -0
  11. package/dist/ai-video-archive-worker.js.map +1 -0
  12. package/dist/browser.d.ts +5 -2
  13. package/dist/browser.js +4 -3
  14. package/dist/chunk-A357G2JF.js +971 -0
  15. package/dist/chunk-A357G2JF.js.map +1 -0
  16. package/dist/{chunk-NRDLMUSY.js → chunk-C6T3ONVG.js} +4 -8
  17. package/dist/chunk-C6T3ONVG.js.map +1 -0
  18. package/dist/{chunk-LENTVEBE.js → chunk-CYWCDBIC.js} +251 -973
  19. package/dist/chunk-CYWCDBIC.js.map +1 -0
  20. package/dist/chunk-OWR55FRO.js +140 -0
  21. package/dist/chunk-OWR55FRO.js.map +1 -0
  22. package/dist/{chunk-ILUCWONQ.js → chunk-UVBQCI7A.js} +3 -3
  23. package/dist/{chunk-ILUCWONQ.js.map → chunk-UVBQCI7A.js.map} +1 -1
  24. package/dist/client/index.js +2 -2
  25. package/dist/index.d.ts +6 -3
  26. package/dist/index.js +1357 -700
  27. package/dist/index.js.map +1 -1
  28. package/models/agents/README.md +3 -1
  29. package/models/agents/deepseek-harness/Dockerfile +2 -0
  30. package/package.json +10 -10
  31. package/dist/chunk-LENTVEBE.js.map +0 -1
  32. package/dist/chunk-NRDLMUSY.js.map +0 -1
  33. package/tools/.dockerignore +0 -4
  34. package/tools/README.md +0 -111
  35. package/tools/archives.py +0 -56
  36. package/tools/browser/Dockerfile +0 -19
  37. package/tools/browser/operation.py +0 -50
  38. package/tools/browser/render.mjs +0 -40
  39. package/tools/documents/Dockerfile +0 -20
  40. package/tools/documents/operation.py +0 -80
  41. package/tools/ocr/Dockerfile +0 -19
  42. package/tools/ocr/operation.py +0 -18
  43. package/tools/office/Dockerfile +0 -21
  44. package/tools/office/office_job.py +0 -65
  45. package/tools/office/operation.py +0 -43
  46. package/tools/tests/image-smoke.mjs +0 -83
  47. package/tools/tests/test_hai_tool.py +0 -82
  48. package/tools/tool.py +0 -145
@@ -0,0 +1,971 @@
1
+ import { aiM } from './chunk-CYWCDBIC.js';
2
+ import { HaiAIError } from './chunk-C6T3ONVG.js';
3
+ import { z } from 'zod';
4
+ import process from 'process';
5
+ import { err, ok, core } from '@h-ai/core';
6
+ import { ChunkOptionsSchema, CleanOptionsSchema } from '@h-ai/datapipe';
7
+ import { AUDIO_WS_PATH as AUDIO_WS_PATH$1, AudioFormatSchema as AudioFormatSchema$1, AudioWsClientMessageSchema as AudioWsClientMessageSchema$1, AudioWsDoneMessageSchema as AudioWsDoneMessageSchema$1, AudioWsStartMessageSchema as AudioWsStartMessageSchema$1, AudioWsTextMessageSchema as AudioWsTextMessageSchema$1 } from '@h-ai/api-contract';
8
+
9
+ var id = z.string().min(1).max(100).regex(/^[\w.-]+$/u);
10
+ var ids = z.array(id).max(64);
11
+ var milliseconds = z.number().int().min(1).max(864e5);
12
+ var platformOptionsSchema = z.strictObject({
13
+ /** 已登记模型和适配器支持的覆盖值。 */
14
+ model: z.strictObject({
15
+ /** 已登记的模型 ID。 */
16
+ id: id.optional(),
17
+ /** 模型声明支持的推理级别。 */
18
+ reasoningEffort: id.optional(),
19
+ /** 适配器支持的采样温度。 */
20
+ temperature: z.number().min(0).max(2).optional(),
21
+ /** 模型单次输出 Token 上限。 */
22
+ maxOutputTokens: z.number().int().positive().optional()
23
+ }).optional(),
24
+ /** Worker 模式、环境与资源覆盖。 */
25
+ execution: z.strictObject({
26
+ /** 会话的 Worker 分配模式。 */
27
+ mode: z.enum(["auto", "shared", "user", "task"]).optional(),
28
+ /** 允许使用的已登记环境 ID。 */
29
+ environmentId: id.optional(),
30
+ /** 在环境资源上限内请求的资源。 */
31
+ resources: z.strictObject({
32
+ /** CPU 核心数。 */
33
+ cpu: z.number().positive().max(1024).optional(),
34
+ /** 内存 MiB。 */
35
+ memoryMiB: z.number().int().min(16).optional()
36
+ }).optional()
37
+ }).optional(),
38
+ /** 应用登记的工作区 ID。 */
39
+ workspaceId: id.optional(),
40
+ /** 本次请求引用的业务资料。 */
41
+ context: z.strictObject({
42
+ /** 可授权读取的文件 ID。 */
43
+ fileIds: ids.optional(),
44
+ /** 可授权检索的知识库 ID。 */
45
+ knowledgeBaseIds: ids.optional(),
46
+ /** 登记的技能 ID。 */
47
+ skillIds: ids.optional(),
48
+ /** 记忆读取和写入范围。 */
49
+ memory: z.strictObject({
50
+ /** 记忆的用户或空间范围。 */
51
+ scope: z.enum(["none", "user", "space"]),
52
+ /** 指定共享空间 ID。 */
53
+ spaceId: id.optional(),
54
+ /** 记忆写入策略。 */
55
+ write: z.enum(["none", "confirm", "on-success"]).optional()
56
+ }).refine((value) => value.scope === "space" === !!value.spaceId).optional()
57
+ }).optional(),
58
+ /** 本任务选择的逻辑工具。 */
59
+ tools: z.strictObject({
60
+ /** 允许使用的已登记工具 ID。 */
61
+ allow: ids.optional()
62
+ }).optional(),
63
+ /** 所需的运行环境能力。 */
64
+ capabilities: ids.optional(),
65
+ /** 任务权限范围和审批策略。 */
66
+ permissions: z.strictObject({
67
+ /** 原生权限预设。 */
68
+ profile: z.enum(["read-only", "workspace", "full-access"]).optional(),
69
+ /** 是否允许发起交互审批。 */
70
+ approval: z.enum(["on-request", "never"]).optional(),
71
+ /** 应用可校验的持久授权规则。 */
72
+ ruleIds: ids.optional()
73
+ }).optional(),
74
+ /** 执行、排队、审批和输出上限。 */
75
+ limits: z.strictObject({
76
+ /** 排队等待上限,毫秒。 */
77
+ queueTimeoutMs: milliseconds.optional(),
78
+ /** 单轮执行上限,毫秒。 */
79
+ runTimeoutMs: milliseconds.optional(),
80
+ /** 单次审批等待上限,毫秒。 */
81
+ approvalTimeoutMs: milliseconds.optional(),
82
+ /** 文本输出上限,字节。 */
83
+ maxOutputBytes: z.number().int().min(1).max(8 * 1024 * 1024).optional()
84
+ }).optional(),
85
+ /** 文本或结构化输出。 */
86
+ output: z.strictObject({
87
+ /** 结果格式。 */
88
+ format: z.enum(["text", "json"]),
89
+ /** 用于校验最终 JSON 的 Schema。 */
90
+ schema: z.record(z.string(), z.json()).optional()
91
+ }).refine((value) => !value.schema || value.format === "json").optional(),
92
+ /** 由适配器验证的原生选项。 */
93
+ native: z.strictObject({
94
+ /** 原生适配器 ID。 */
95
+ adapter: id,
96
+ /** 适配器声明支持的原生参数。 */
97
+ options: z.record(z.string(), z.json())
98
+ }).optional(),
99
+ /** 有限的业务标签,不作为身份依据。 */
100
+ metadata: z.record(z.string().regex(/^[\w.-]{1,48}$/u), z.string().max(128)).refine((value) => Object.keys(value).length <= 16 && !Object.keys(value).some((key) => /^(?:owner|tenant|user|role|scope)/i.test(key))).optional()
101
+ });
102
+ var platformRequestSchema = platformOptionsSchema.extend({ agentId: id });
103
+ var platformRunSchema = platformRequestSchema.extend({
104
+ prompt: z.union([
105
+ z.string().min(1),
106
+ z.array(z.record(z.string(), z.json())).min(1).max(256)
107
+ ]),
108
+ idempotencyKey: z.string().min(1).max(160).optional()
109
+ });
110
+ var platformScopeSchema = z.strictObject({ tenantId: id, userId: id });
111
+
112
+ // src/acp/ai-acp-config.ts
113
+ var acpIdSchema = z.string().regex(/^[a-z0-9][\w-]{0,95}$/i);
114
+ var branch = z.string().min(1).max(240).refine(
115
+ (value) => !value.startsWith("-") && !/[\s~^:?*\\[]/.test(value) && !Array.from(value).some((character) => character.charCodeAt(0) < 32) && !value.includes("..") && !value.includes("@{") && !value.endsWith(".lock") && !value.endsWith("/") && !value.startsWith("/")
116
+ );
117
+ var environment = z.record(z.string().regex(/^[A-Z_]\w*$/i), z.string().regex(/^[A-Z_]\w*$/i)).default({});
118
+ var ACPRepositorySchema = z.strictObject({
119
+ /** 清单中的唯一 ID;同时用于受管理目录名。 */
120
+ id: acpIdSchema.refine((value) => !["files", ".state"].includes(value)),
121
+ /** 远程地址,不允许命令选项和换行。 */
122
+ url: z.string().min(1).refine((value) => !value.startsWith("-") && !/[\r\n\0]/.test(value)),
123
+ /** 该工程明确指定的主分支,更新和 merge-main 发布均使用此值。 */
124
+ mainBranch: branch,
125
+ /** Git remote 名,默认 origin。 */
126
+ remote: acpIdSchema.default("origin")
127
+ });
128
+ var ACPWorkspaceSchema = z.strictObject({
129
+ /** 清单中的唯一 ID;同时用于受管理目录名。 */
130
+ id: acpIdSchema,
131
+ /** 持久存储位置;directory 供本机,volume 供托管容器。 */
132
+ storage: z.discriminatedUnion("type", [
133
+ z.strictObject({
134
+ /** 本机目录存储。 */
135
+ type: z.literal("directory"),
136
+ /** 本机绝对或相对目录,运行时归一化为真实绝对路径。 */
137
+ path: z.string().min(1)
138
+ }),
139
+ z.strictObject({
140
+ /** 存储类型判别字段。 */
141
+ type: z.literal("volume"),
142
+ /** 可读名称;volume 时表示持久卷名。 */
143
+ name: acpIdSchema,
144
+ /** auto 优先可用 Podman,再选 Docker;显式选择不自动降级。 */
145
+ engine: z.enum(["auto", "podman", "docker"]).default("auto"),
146
+ /** 已部署的 Agent 镜像,工作区和智能体需使用同一镜像。 */
147
+ image: z.string().min(1).refine((value) => !value.startsWith("-"))
148
+ })
149
+ ]),
150
+ /** 多个 Git 工程;默认空数组,不使用 Git 时仅创建文件目录。 */
151
+ repositories: z.array(ACPRepositorySchema).default([]),
152
+ /** 工作区历史共用变量映射;Agent 专用凭据应配置在 Agent 定义中。 */
153
+ environmentRefs: environment,
154
+ /** 仅供受管 Git 远程操作使用的环境变量引用,值不传给 Agent 或本地提交。 */
155
+ gitEnvironmentRefs: environment
156
+ }).refine(
157
+ (value) => new Set(value.repositories.map((repo) => repo.id)).size === value.repositories.length
158
+ );
159
+ var common = {
160
+ /** 清单中的唯一 ID;同时用于受管理目录名。 */
161
+ id: acpIdSchema,
162
+ /** 智能体的可读名称。 */
163
+ name: z.string().min(1),
164
+ /** 默认启用,禁用后禁止新建和恢复会话。 */
165
+ enabled: z.boolean().default(true),
166
+ /** 原生配置适配器名称,默认 generic。 */
167
+ adapter: z.string().min(1).default("generic"),
168
+ /** 绑定 Hai LLM 模型 ID;默认空数组。 */
169
+ modelIds: z.array(z.string().min(1)).default([]),
170
+ /** 默认选择的模型 ID,必须存在于 modelIds。 */
171
+ defaultModelId: z.string().min(1).optional(),
172
+ /** 目标环境变量名到宿主环境变量名的映射;保存引用而非明文凭据。 */
173
+ environmentRefs: environment,
174
+ /** 可由受管 Runner 使用的已登记环境,首项是默认候选。 */
175
+ environmentIds: z.array(acpIdSchema).max(64).default([]),
176
+ /** 由部署方对已验证的内置只读后端启用共享 Worker。 */
177
+ sharedMode: z.boolean().default(false),
178
+ /** 此 Agent 可选择的能力上限。 */
179
+ allowedCapabilities: z.array(acpIdSchema.or(z.string().regex(/^[\w.-]{1,96}$/u))).max(64).default([]),
180
+ /** 可由每次调用或会话覆盖的受管默认值。 */
181
+ defaults: platformOptionsSchema.optional()
182
+ };
183
+ var launch = {
184
+ /** 可选原生程序覆盖,使用参数数组执行,不经过 shell。 */
185
+ command: z.string().min(1).optional(),
186
+ /** 原生启动参数,省略时由适配器提供默认值。 */
187
+ args: z.array(z.string()).optional()
188
+ };
189
+ var ACPAgentSchema = z.discriminatedUnion("mode", [
190
+ z.strictObject({
191
+ ...common,
192
+ /** 接入模式:自定义远程服务、本机内嵌进程或托管容器。 */
193
+ mode: z.literal("custom-service"),
194
+ /** 智能体原生支持的传输;不自动转换 stdio 和 HTTP/WS。 */
195
+ transport: z.enum(["http", "ws"]),
196
+ /** 远程地址,不允许命令选项和换行。 */
197
+ url: z.url(),
198
+ /** 远程认证 Header 名到宿主变量名的映射。 */
199
+ headerEnv: z.record(z.string(), z.string()).default({}),
200
+ /** 自定义服务显式声明的原生 HTTP/WS 能力。 */
201
+ supportedTransports: z.array(z.enum(["http", "ws"])).min(1)
202
+ }),
203
+ z.strictObject({
204
+ ...common,
205
+ ...launch,
206
+ /** 接入模式:自定义远程服务、本机内嵌进程或托管容器。 */
207
+ mode: z.literal("embedded"),
208
+ /** 智能体原生支持的传输;不自动转换 stdio 和 HTTP/WS。 */
209
+ transport: z.literal("stdio").default("stdio")
210
+ }),
211
+ z.strictObject({
212
+ ...common,
213
+ ...launch,
214
+ /** 接入模式:自定义远程服务、本机内嵌进程或托管容器。 */
215
+ mode: z.literal("builtin-service"),
216
+ /** 智能体原生支持的传输;不自动转换 stdio 和 HTTP/WS。 */
217
+ transport: z.literal("stdio").default("stdio"),
218
+ /** 已部署的 Agent 镜像,工作区和智能体需使用同一镜像。 */
219
+ image: z.string().min(1).refine((value) => !value.startsWith("-")),
220
+ /** auto 优先可用 Podman,再选 Docker;显式选择不自动降级。 */
221
+ engine: z.enum(["auto", "podman", "docker"]).default("auto")
222
+ })
223
+ ]).superRefine((value, ctx) => {
224
+ if (value.defaultModelId && !value.modelIds.includes(value.defaultModelId)) {
225
+ ctx.addIssue({
226
+ code: "custom",
227
+ path: ["defaultModelId"],
228
+ message: "Model binding mismatch"
229
+ });
230
+ }
231
+ if (value.mode === "custom-service") {
232
+ const protocol = new URL(value.url).protocol;
233
+ if (!(value.transport === "http" ? ["http:", "https:"] : ["ws:", "wss:"]).includes(protocol) || !value.supportedTransports.includes(value.transport)) {
234
+ ctx.addIssue({
235
+ code: "custom",
236
+ path: ["transport"],
237
+ message: "Transport mismatch"
238
+ });
239
+ }
240
+ if (value.modelIds.length || value.defaultModelId) {
241
+ ctx.addIssue({
242
+ code: "custom",
243
+ path: ["modelIds"],
244
+ message: "External service owns its model configuration"
245
+ });
246
+ }
247
+ }
248
+ });
249
+ var ACPPublishSchema = z.strictObject({
250
+ /** 发布到登记的主分支,或以同名会话分支推送到各工程。 */
251
+ mode: z.enum(["merge-main", "push-branch"]),
252
+ /** 非空 Git 提交说明。 */
253
+ message: z.string().min(1).max(1e4),
254
+ /** Git 提交身份,由调用方明确提供。 */
255
+ author: z.strictObject({
256
+ /** Git 提交者名称,不允许换行或尖括号。 */
257
+ name: z.string().min(1).refine((value) => !/[\r\n<>]/.test(value)),
258
+ /** Git 提交者邮箱。 */
259
+ email: z.email()
260
+ })
261
+ });
262
+ var sessionIdentitySchema = acpIdSchema;
263
+ var branchNameSchema = branch;
264
+ var ACPConfigSchema = z.strictObject({
265
+ /** 配置文件定义的只读智能体,与数据库记录按 ID 合并。 */
266
+ agents: z.array(ACPAgentSchema).default([]),
267
+ /** 配置文件定义的只读工作区,与数据库记录按 ID 合并。 */
268
+ workspaces: z.array(ACPWorkspaceSchema).default([]),
269
+ /** 握手和控制请求超时,毫秒。 */
270
+ requestTimeout: z.number().int().positive().default(3e4),
271
+ /** 单轮任务超时,毫秒。 */
272
+ promptTimeout: z.number().int().positive().default(6e5),
273
+ /** 取消后等待终态的上限,毫秒。 */
274
+ cancelTimeout: z.number().int().positive().default(5e3),
275
+ /** 单轮输入和累计输出的字节上限。 */
276
+ maxContentBytes: z.number().int().positive().default(8 * 1024 * 1024),
277
+ /** 未消费事件数量上限。 */
278
+ maxPendingEvents: z.number().int().positive().default(1024),
279
+ /** 无在途操作的受管 Worker 空闲回收时限,毫秒。 */
280
+ workerIdleTimeoutMs: z.number().int().min(1e3).max(864e5).default(3e5)
281
+ });
282
+ var CompressionStrategySchema = z.enum(["summary", "sliding-window", "hybrid"]);
283
+ var EntityTypeSchema = z.enum([
284
+ "person",
285
+ "project",
286
+ "concept",
287
+ "organization",
288
+ "location",
289
+ "event",
290
+ "other"
291
+ ]);
292
+ var MemoryTypeSchema = z.enum([
293
+ "fact",
294
+ "preference",
295
+ "event",
296
+ "entity",
297
+ "instruction"
298
+ ]);
299
+ var OptionalSecretSchema = z.string().nullable().transform(
300
+ (value) => value === null || value.trim() === "" ? void 0 : value
301
+ ).optional();
302
+ var ModelScenarioSchema = z.enum([
303
+ "default",
304
+ "chat",
305
+ "reasoning",
306
+ "plan",
307
+ "execute",
308
+ "extraction",
309
+ "summary",
310
+ "embedding",
311
+ "rerank",
312
+ "ocr",
313
+ "fast"
314
+ ]);
315
+ var ApiTypeSchema = z.enum(["chat", "responses", "anthropic"]);
316
+ var ModelCapabilitiesSchema = z.strictObject({
317
+ /** 可用上下文总容量(Token);未知时省略,不由输出预算推断。 */
318
+ contextWindow: z.number().int().positive().optional(),
319
+ /** 模型单次输出能力上限(Token);与默认 maxTokens 预算不同。 */
320
+ maxOutputTokens: z.number().int().positive().optional(),
321
+ /** 已确认支持的输入模态;未知时省略。 */
322
+ inputModalities: z.array(z.enum(["text", "image", "audio", "video"])).min(1).optional(),
323
+ /** 已确认支持的输出模态;仍需调用接口支持。 */
324
+ outputModalities: z.array(z.enum(["text", "image", "audio", "video"])).min(1).optional(),
325
+ /** 模型是否支持函数工具调用;未知时省略。 */
326
+ toolCalling: z.boolean().optional(),
327
+ /** 推理能力元数据,不自动启用推理请求参数。 */
328
+ reasoning: z.strictObject({
329
+ /** 是否支持推理能力。 */
330
+ supported: z.boolean(),
331
+ /** 已确认可选择的推理级别。 */
332
+ efforts: z.array(z.string().min(1)).min(1).optional()
333
+ }).refine((value) => value.supported || !value.efforts, {
334
+ message: aiM("ai_modelCapabilitiesInvalid")
335
+ }).optional()
336
+ }).refine((value) => !value.contextWindow || !value.maxOutputTokens || value.maxOutputTokens <= value.contextWindow, {
337
+ message: aiM("ai_modelCapabilitiesInvalid")
338
+ });
339
+ var ModelEntrySchema = z.strictObject({
340
+ /** 模型唯一标识(用于 ModelResolver 解析) */
341
+ id: z.string(),
342
+ /** 已确认的模型能力,缺省表示未知 */
343
+ capabilities: ModelCapabilitiesSchema.optional(),
344
+ /** 模型名称(传给 API 的实际模型名) */
345
+ model: z.string(),
346
+ /** API 协议(可选,未指定时回退全局 `protocol`,再回退 `chat`;决定走 Chat Completions / Responses / Anthropic) */
347
+ protocol: ApiTypeSchema.optional(),
348
+ /** API Key 覆盖(可选,未提供时使用全局配置) */
349
+ apiKey: OptionalSecretSchema,
350
+ /** Base URL 覆盖(可选) */
351
+ baseUrl: z.url().optional(),
352
+ /** 最大 Token 数覆盖(可选) */
353
+ maxTokens: z.number().positive().optional(),
354
+ /** 温度覆盖(可选) */
355
+ temperature: z.number().min(0).max(2).optional(),
356
+ /** 超时覆盖(可选,毫秒) */
357
+ timeout: z.number().positive().optional()
358
+ });
359
+ var LLMConfigSchema = z.strictObject({
360
+ /** 默认服务密钥;模型项可单独覆盖。未填写时读取 HAI_AI_LLM_APIKEY 或对应供应商密钥变量,真实值只放服务端。 */
361
+ apiKey: OptionalSecretSchema,
362
+ /** 默认模型服务地址;使用代理时填写,模型项可覆盖。未填写时按协议读取环境地址或使用供应商默认地址。 */
363
+ baseUrl: z.url().optional(),
364
+ /** 默认模型名称(默认 `'gpt-4o-mini'`) */
365
+ model: z.string().optional().default("gpt-4o-mini"),
366
+ /** 默认请求格式:chat 为 Chat Completions,responses 为 OpenAI Responses,anthropic 为 Anthropic Messages;模型项可覆盖。 */
367
+ protocol: ApiTypeSchema.optional().default("chat"),
368
+ /** 单次回答最多生成多少 Token,默认 4096;模型项可覆盖,需符合供应商限制。 */
369
+ maxTokens: z.number().positive().optional().default(4096),
370
+ /** 回答的随机程度,0–2,默认 0.7;较低通常更稳定,模型项可覆盖,部分模型不支持自定义。 */
371
+ temperature: z.number().min(0).max(2).optional().default(0.7),
372
+ /** 一次模型请求最多等待多少毫秒,默认 60000;模型项可覆盖。 */
373
+ timeout: z.number().positive().optional().default(6e4),
374
+ /** 临时模型客户端缓存存活时间(毫秒,默认 `600000` = 10 分钟;超时后临时模型客户端实例失效并重建) */
375
+ tempModelCacheTtl: z.number().positive().optional().default(6e5),
376
+ /** 多模型配置列表(各字段可选,未指定时回退到全局默认值) */
377
+ models: z.array(ModelEntrySchema).optional(),
378
+ /** 场景模型映射(场景名 → 模型 ID 或直接模型名称,各场景均可选) */
379
+ scenarios: z.object(Object.fromEntries(ModelScenarioSchema.options.map((k) => [
380
+ k,
381
+ z.string().optional()
382
+ ]))).optional()
383
+ });
384
+ function resolveModelEntry(llmConfig, scenario, explicit, options) {
385
+ let entry;
386
+ let modelName;
387
+ if (explicit) {
388
+ entry = llmConfig.models?.find((m) => m.id === explicit || m.model === explicit);
389
+ modelName = entry?.model ?? explicit;
390
+ } else {
391
+ const modelId = llmConfig.scenarios?.[scenario] ?? llmConfig.scenarios?.default;
392
+ if (modelId) {
393
+ entry = llmConfig.models?.find((m) => m.id === modelId);
394
+ modelName = entry?.model ?? modelId;
395
+ } else {
396
+ modelName = llmConfig.model ?? "gpt-4o-mini";
397
+ }
398
+ }
399
+ const resolved = {
400
+ model: modelName,
401
+ capabilities: entry?.capabilities,
402
+ protocol: entry?.protocol ?? llmConfig.protocol ?? "chat",
403
+ apiKey: entry?.apiKey ?? llmConfig.apiKey ?? (process.env.HAI_AI_LLM_APIKEY?.trim() || process.env.OPENAI_API_KEY),
404
+ baseUrl: entry?.baseUrl ?? llmConfig.baseUrl ?? (process.env.HAI_AI_LLM_BASEURL?.trim() || process.env.OPENAI_BASE_URL) ?? "https://api.openai.com/v1",
405
+ maxTokens: entry?.maxTokens ?? llmConfig.maxTokens ?? 4096,
406
+ temperature: entry?.temperature ?? llmConfig.temperature ?? 0.7,
407
+ timeout: entry?.timeout ?? llmConfig.timeout ?? 6e4
408
+ };
409
+ if (!resolved.apiKey) {
410
+ return err(HaiAIError.CONFIGURATION_ERROR, options?.missingApiKeyMessage ?? aiM("ai_configMissingApiKey", {
411
+ params: { scenario }
412
+ }));
413
+ }
414
+ return ok(resolved);
415
+ }
416
+ function resolveModelApi(llmConfig, explicitModel, tempApi) {
417
+ if (tempApi)
418
+ return tempApi;
419
+ const entry = explicitModel ? llmConfig.models?.find((m) => m.id === explicitModel || m.model === explicitModel) : void 0;
420
+ return entry?.protocol ?? llmConfig.protocol ?? "chat";
421
+ }
422
+ var MCPServerCapabilitiesSchema = z.object({
423
+ /** 是否支持工具调用(默认 `true`) */
424
+ tools: z.boolean().optional().default(true),
425
+ /** 是否支持资源访问(默认 `true`) */
426
+ resources: z.boolean().optional().default(true),
427
+ /** 是否支持提示词模板(默认 `true`) */
428
+ prompts: z.boolean().optional().default(true)
429
+ });
430
+ var MCPServerConfigSchema = z.object({
431
+ /** 服务器名称 */
432
+ name: z.string(),
433
+ /** 服务器版本(默认 `'1.0.0'`) */
434
+ version: z.string().optional().default("1.0.0"),
435
+ /** 服务器能力声明 */
436
+ capabilities: MCPServerCapabilitiesSchema.optional()
437
+ });
438
+ var MCPExternalServerSchema = z.strictObject({
439
+ /** 服务唯一标识。 */
440
+ id: z.string().min(1),
441
+ /** 传给原生 MCP 客户端的服务名。 */
442
+ name: z.string().min(1),
443
+ /** 原生 MCP 传输类型。 */
444
+ transport: z.enum(["stdio", "http", "sse", "job"]),
445
+ /** 固定工具作业环境 ID,仅 job 模式使用。 */
446
+ environmentId: z.string().regex(/^[\w.-]{1,128}$/u).optional(),
447
+ /** stdio 程序路径;仅可信服务端配置。 */
448
+ command: z.string().min(1).optional(),
449
+ /** stdio 参数,不使用 shell 拼接。 */
450
+ args: z.array(z.string()).default([]),
451
+ /** HTTP/SSE 地址。 */
452
+ url: z.url().optional(),
453
+ /** stdio 变量名到宿主凭据变量名的映射。 */
454
+ environmentRefs: z.record(z.string(), z.string()).default({}),
455
+ /** 认证 Header 名到宿主凭据变量名的映射。 */
456
+ headerEnv: z.record(z.string(), z.string()).default({}),
457
+ /** 受管工具入口允许调用的名称;省略时不开放给 ai.mcp.services。 */
458
+ allowedTools: z.array(z.string().min(1).max(128)).min(1).max(256).optional(),
459
+ /** 受管工具连接和调用的总超时,单位毫秒;缺省为 30 秒。 */
460
+ timeoutMs: z.number().int().min(1).max(3e5).optional(),
461
+ /** 集群范围内该服务允许同时领取的作业数量,仅 job 模式使用。 */
462
+ pool: z.strictObject({
463
+ /** 同时执行的实例上限;未配置服务池时默认为 4。 */
464
+ maxRunning: z.number().int().min(1).max(1e3),
465
+ /** 部署预热池期望保留的干净实例数量。 */
466
+ minReady: z.number().int().min(0).max(1e3).optional(),
467
+ /** 集群内预热、启动、运行、销毁中实例的总上限。 */
468
+ maxTotal: z.number().int().min(1).max(1e3).optional()
469
+ }).refine((pool) => pool.maxTotal === void 0 ? pool.minReady === void 0 : pool.maxTotal >= Math.max(pool.minReady ?? 0, pool.maxRunning)).optional()
470
+ }).refine((value) => {
471
+ if (value.transport === "job")
472
+ return Boolean(/^[\w.-]{1,100}$/u.test(value.id) && value.environmentId && value.allowedTools?.length && !value.command && !value.url && !value.args.length && !Object.keys(value.headerEnv).length && !Object.keys(value.environmentRefs).length);
473
+ if (value.environmentId || value.pool)
474
+ return false;
475
+ return value.transport === "stdio" ? Boolean(value.command) : Boolean(value.url && /^https?:/.test(value.url));
476
+ });
477
+ var MCPConfigSchema = z.object({
478
+ /** 外部 MCP 服务只读清单;与数据库记录合并供受管 Agent 使用。 */
479
+ servers: z.array(MCPExternalServerSchema).optional(),
480
+ /** 服务器配置 */
481
+ server: MCPServerConfigSchema.optional()
482
+ });
483
+ var EmbeddingConfigSchema = z.object({
484
+ /** 向量维度(可选,部分模型支持指定维度) */
485
+ dimensions: z.number().int().positive().optional(),
486
+ /** 批量大小(单次请求最多处理的文本数,默认 100) */
487
+ batchSize: z.number().int().positive().default(100)
488
+ });
489
+ var KnowledgeConfigSchema = z.object({
490
+ /** 默认向量集合名(默认 'hai_ai_knowledge') */
491
+ collection: z.string().default("hai_ai_knowledge"),
492
+ /** 向量维度(默认 1536,需与 embedding 模型匹配) */
493
+ dimension: z.number().int().positive().default(1536),
494
+ /** 是否启用实体提取(默认 true) */
495
+ enableEntityExtraction: z.boolean().default(true),
496
+ /**
497
+ * 默认文本清洗选项
498
+ *
499
+ * 字段含义与 @h-ai/datapipe CleanOptionsInput 完全一致,
500
+ * 支持 removeHtml、removeUrls、normalizeWhitespace、customReplacements 等。
501
+ */
502
+ cleanOptions: CleanOptionsSchema.default(CleanOptionsSchema.parse({})),
503
+ /**
504
+ * 默认分块选项
505
+ *
506
+ * 字段含义与 @h-ai/datapipe ChunkOptionsInput 完全一致,
507
+ * 支持 mode、maxSize、overlap、separator、markdownMinLevel 等完整选项。
508
+ * word 按非空白词计量,其余按 Unicode code point;上限包含分隔符及 overlap,且 overlap < maxSize。
509
+ * AI 默认 markdown/1500/200;导入覆盖预算时仍须满足约束,分块失败不会退回整篇文档。
510
+ */
511
+ chunkOptions: ChunkOptionsSchema.default(ChunkOptionsSchema.parse({
512
+ mode: "markdown",
513
+ maxSize: 1500,
514
+ overlap: 200
515
+ })),
516
+ /** 实体查询命中的额外加权系数(默认 0.15,叠加到向量分数上) */
517
+ entityBoostWeight: z.number().min(0).max(1).default(0.15),
518
+ /** 自定义实体类型列表(不指定时使用内置默认类型) */
519
+ entityTypes: z.array(z.string()).optional(),
520
+ /** 自定义实体提取系统提示词(不指定时使用内置默认提示词) */
521
+ systemPrompt: z.string().optional()
522
+ });
523
+ var MemoryConfigSchema = z.object({
524
+ /** 记忆后端:native 使用框架原生存储与批量合并;mem0 将框架提取结果以 Mem0 数据格式写入 Qdrant */
525
+ provider: z.enum(["native", "mem0"]).default("native"),
526
+ /** 原生记忆向量命名空间,首次初始化后与关系库绑定。 */
527
+ vectorNamespace: z.string().regex(/^[a-z](?:[a-z0-9_-]{0,18}[a-z0-9])?$/, aiM("ai_memoryVectorNamespaceInvalid")).default("default"),
528
+ /**
529
+ * 是否允许在配置了持久化向量后端但 mem0 无法映射时退回内存存储(默认 false)
530
+ *
531
+ * 仅影响 `provider='mem0'`:当前框架适配仅映射 qdrant;其它持久化后端使用 native Provider。底层 vecdb 是
532
+ * lancedb / chroma / 未知后端时,默认 fail-fast(初始化失败),避免服务重启后记忆静默丢失;
533
+ * 仅当显式设为 true 时才在开发或明确 E2E 环境退回内存存储(数据不持久)。
534
+ * 生产始终要求实际持久化连接,不能通过此开关绕过共享状态要求。
535
+ */
536
+ allowEphemeralFallback: z.boolean().default(false),
537
+ /**
538
+ * 单个主体(objectId)的最大记忆条数(默认 1000)
539
+ *
540
+ * native 淘汰按 objectId 分区触发:某个主体写入超过此上限时,只淘汰该主体自身
541
+ * 最低优先级的条目,不会波及其他主体的记忆。
542
+ */
543
+ maxEntriesPerObject: z.number().int().positive().default(1e3),
544
+ /**
545
+ * 全局最大记忆条数(默认 100000)
546
+ *
547
+ * 跨所有主体的总量上限,作为整体保护阈值;超过时淘汰全局最低优先级条目。
548
+ */
549
+ maxEntriesGlobal: z.number().int().positive().default(1e5),
550
+ /** 自定义记忆提取 systemPrompt(可选,覆盖内置默认提示词) */
551
+ systemPrompt: z.string().optional(),
552
+ /** 时间衰减系数(默认 0.95,每次检索乘以此系数调整 recency 权重) */
553
+ recencyDecay: z.number().min(0).max(1).default(0.95),
554
+ /** 是否启用向量检索(默认 true,关闭则仅使用关键词匹配) */
555
+ embeddingEnabled: z.boolean().default(true),
556
+ /** 检索时默认返回数量(默认 10) */
557
+ defaultTopK: z.number().int().positive().default(10),
558
+ /**
559
+ * 候选池倍数(默认 5)
560
+ *
561
+ * 检索时先从向量后端取回 `topK × candidateMultiplier` 条候选,再按 scope / 重要性等
562
+ * 条件在内存中过滤,最后截取 topK。用于修正「向量后端仅返回 topK,随后被 scope 过滤
563
+ * 掉大部分、导致同一主体下特定主题/角色记忆漏召回」的问题:候选池越大,scope 命中越充分。
564
+ *
565
+ * native provider 会对全部候选评分,故此值仅影响向量预取宽度;mem0 provider 无法下推
566
+ * scope,必须依赖更大的候选池才能保证 scope 内记忆被召回。
567
+ */
568
+ candidateMultiplier: z.number().int().positive().default(5),
569
+ /** 写回 / 合并时检索相关记忆的数量(仅 native,默认 20) */
570
+ writebackRelatedTopK: z.number().int().positive().default(20)
571
+ });
572
+ var TokenConfigSchema = z.object({
573
+ /** Token 估算每字符系数(默认 0.25,即 4 字符 ≈ 1 token) */
574
+ tokenRatio: z.number().positive().default(0.25)
575
+ });
576
+ var SummaryConfigSchema = z.object({
577
+ /** 自定义摘要 systemPrompt(可选,覆盖内置默认提示词) */
578
+ systemPrompt: z.string().optional()
579
+ });
580
+ var CompressConfigSchema = z.object({
581
+ /** 默认压缩策略(默认 'hybrid') */
582
+ defaultStrategy: CompressionStrategySchema.default("hybrid"),
583
+ /** 默认 Token 预算(默认 0 表示取模型上限的 80%) */
584
+ defaultMaxTokens: z.number().int().min(0).default(0),
585
+ /** 默认保留最近消息数(默认 4) */
586
+ preserveLastN: z.number().int().min(0).default(4)
587
+ });
588
+ var FileConfigSchema = z.object({
589
+ /** OCR 系统提示词(可选,覆盖内置默认提示词) */
590
+ systemPrompt: z.string().optional()
591
+ });
592
+ var RetrievalSourceSchema = z.object({
593
+ /** 来源唯一标识 */
594
+ id: z.string(),
595
+ /** vecdb collection 名称 */
596
+ collection: z.string(),
597
+ /** 信源显示名 */
598
+ name: z.string().optional(),
599
+ /** 信源 URL / 路径 */
600
+ url: z.string().optional(),
601
+ /** 最大返回条数(默认 5) */
602
+ topK: z.number().int().positive().optional(),
603
+ /** 最低相似度 0~1(低于此值的结果被过滤) */
604
+ minScore: z.number().min(0).max(1).optional(),
605
+ /** 元数据过滤条件 */
606
+ filter: z.record(z.string(), z.unknown()).optional()
607
+ });
608
+ var RetrievalConfigSchema = z.object({
609
+ /** 预注册检索源列表 */
610
+ sources: z.array(RetrievalSourceSchema).optional()
611
+ });
612
+ var A2ASkillConfigSchema = z.object({
613
+ /** 技能 ID */
614
+ id: z.string(),
615
+ /** 技能名称 */
616
+ name: z.string(),
617
+ /** 技能描述 */
618
+ description: z.string().optional(),
619
+ /** 标签列表 */
620
+ tags: z.array(z.string()).optional()
621
+ });
622
+ var A2AConfigSchema = z.object({
623
+ /** 共享执行预算;最终提交同时受数据库租约与绝对执行期限约束。 */
624
+ execution: z.object({
625
+ /** 活跃执行租约毫秒数,默认30秒,范围1秒至1天。 */
626
+ leaseMs: z.number().int().min(1e3).max(864e5).default(3e4),
627
+ /** 共享事件/状态订阅轮询间隔毫秒数,默认250。 */
628
+ pollIntervalMs: z.number().int().min(10).max(5e3).default(250),
629
+ /** 单次执行绝对上限毫秒数,默认5分钟;超时标中断,不自动重放。 */
630
+ maxExecutionMs: z.number().int().min(1e3).max(864e5).default(3e5)
631
+ }).prefault({}),
632
+ /** Agent Card 配置 */
633
+ agentCard: z.object({
634
+ /** Agent 名称 */
635
+ name: z.string(),
636
+ /** Agent 描述 */
637
+ description: z.string().optional(),
638
+ /** Agent 对外 URL */
639
+ url: z.string(),
640
+ /** Agent 版本 */
641
+ version: z.string().optional(),
642
+ /** Agent 技能列表 */
643
+ skills: z.array(A2ASkillConfigSchema).optional()
644
+ }),
645
+ /** A2A 安全认证配置 */
646
+ security: z.object({
647
+ /** API Key 认证(通过 IAM apiKey.verifyApiKey 验证) */
648
+ apiKey: z.object({
649
+ /** API Key 的传递位置(默认 header) */
650
+ in: z.enum(["header", "query"]).default("header"),
651
+ /** 参数名(默认 x-api-key) */
652
+ name: z.string().default("x-api-key")
653
+ }).optional()
654
+ }).optional()
655
+ });
656
+ var AudioProviderSchema = z.enum([
657
+ "openai",
658
+ "mimo",
659
+ "qwen",
660
+ "doubao",
661
+ "whisper",
662
+ "indextts"
663
+ ]);
664
+ var AudioOperationSchema = z.enum(["transcribe", "synthesize"]);
665
+ var AudioOperationsSchema = z.array(AudioOperationSchema).min(1).refine((operations) => new Set(operations).size === operations.length, {
666
+ message: "audio model operations must be unique"
667
+ });
668
+ var AudioModelEntrySchema = z.object({
669
+ /** 模型唯一标识(用于场景解析与请求显式指定) */
670
+ id: z.string(),
671
+ /** 所属语音平台 */
672
+ provider: AudioProviderSchema,
673
+ /** 厂商模型名(传给厂商 API 的实际模型名) */
674
+ model: z.string(),
675
+ /** 模型允许执行的操作;解析模型时会在调用厂商前校验 */
676
+ operations: AudioOperationsSchema,
677
+ /** API Key 覆盖(未提供时可按 Audio 配置继承 LLM 密钥,最后回退对应平台环境变量) */
678
+ apiKey: OptionalSecretSchema,
679
+ /** HTTP / WebSocket 端点覆盖(`whisper` / `indextts` 无默认端点,必须显式配置) */
680
+ baseUrl: z.string().optional(),
681
+ /** 火山引擎 App Key(`X-Api-App-Key`,旧版控制台 ASR 需要) */
682
+ appKey: OptionalSecretSchema,
683
+ /** 火山引擎 Access Key(`X-Api-Access-Key`,旧版控制台 ASR 需要) */
684
+ accessKey: OptionalSecretSchema,
685
+ /** 火山引擎资源 ID(`X-Api-Resource-Id`;未提供时使用平台默认资源 ID) */
686
+ resourceId: z.string().optional(),
687
+ /** 阿里云百炼业务空间 ID(`X-DashScope-WorkSpace`,可选) */
688
+ workspaceId: z.string().optional(),
689
+ /** 请求超时(毫秒,默认 60000) */
690
+ timeout: z.number().positive().optional()
691
+ });
692
+ var AudioConfigSchema = z.object({
693
+ /** 注册的语音模型列表 */
694
+ models: z.array(AudioModelEntrySchema).optional(),
695
+ /** 是否允许未单独配置密钥的语音模型继承 LLM 全局密钥;跨供应商部署应保持关闭。 */
696
+ inheritLlmApiKey: z.boolean().default(false),
697
+ /** 默认识别模型 ID(`ai.audio.transcribe*` 未指定 model 时使用) */
698
+ transcribeModel: z.string().optional(),
699
+ /** 默认合成模型 ID(`ai.audio.synthesize*` 未指定 model 时使用) */
700
+ synthesizeModel: z.string().optional(),
701
+ /** 单次音频字节上限(默认 10 MiB,防止资源耗尽) */
702
+ maxAudioBytes: z.number().int().positive().default(10 * 1024 * 1024),
703
+ /** 实时连接最长持续时间(毫秒,默认 5 分钟) */
704
+ maxStreamDurationMs: z.number().int().positive().default(5 * 60 * 1e3)
705
+ });
706
+ var AUDIO_PROVIDER_DEFAULT_BASE_URL = {
707
+ openai: "https://api.openai.com/v1",
708
+ mimo: "https://api.xiaomimimo.com/v1",
709
+ qwen: "wss://dashscope.aliyuncs.com/api-ws/v1/realtime",
710
+ doubao: "wss://openspeech.bytedance.com"
711
+ };
712
+ var AUDIO_PROVIDER_CREDENTIAL_OPTIONAL = /* @__PURE__ */ new Set(["whisper", "indextts"]);
713
+ function doubaoDefaultResourceId(operation) {
714
+ return operation === "transcribe" ? "volc.bigasr.sauc.duration" : "seed-tts-2.0";
715
+ }
716
+ function audioProviderEnvApiKey(provider) {
717
+ switch (provider) {
718
+ case "openai":
719
+ return process.env.HAI_AI_AUDIO_OPENAI_APIKEY?.trim() || process.env.OPENAI_API_KEY;
720
+ case "mimo":
721
+ return process.env.HAI_AI_AUDIO_MIMO_APIKEY?.trim() || process.env.MIMO_API_KEY;
722
+ case "qwen":
723
+ return process.env.HAI_AI_AUDIO_QWEN_APIKEY?.trim() || process.env.DASHSCOPE_API_KEY;
724
+ case "doubao":
725
+ return process.env.HAI_AI_AUDIO_DOUBAO_APIKEY?.trim() || process.env.VOLC_API_KEY;
726
+ case "whisper":
727
+ return process.env.HAI_AI_AUDIO_WHISPER_APIKEY;
728
+ case "indextts":
729
+ return process.env.HAI_AI_AUDIO_INDEXTTS_APIKEY;
730
+ }
731
+ }
732
+ function resolveAudioModel(audioConfig, operation, explicit, llmApiKey) {
733
+ const targetId = explicit ?? (operation === "transcribe" ? audioConfig.transcribeModel : audioConfig.synthesizeModel);
734
+ if (!targetId) {
735
+ return err(HaiAIError.AUDIO_MODEL_NOT_FOUND, aiM("ai_audioModelNotFound", {
736
+ params: { model: `<${operation}>` }
737
+ }));
738
+ }
739
+ const entry = audioConfig.models?.find((m) => m.id === targetId || m.model === targetId);
740
+ if (!entry) {
741
+ return err(HaiAIError.AUDIO_MODEL_NOT_FOUND, aiM("ai_audioModelNotFound", {
742
+ params: { model: targetId }
743
+ }));
744
+ }
745
+ const operations = entry.operations;
746
+ if (!operations.includes(operation)) {
747
+ return err(
748
+ HaiAIError.AUDIO_UNSUPPORTED_INPUT,
749
+ aiM("ai_audioUnsupportedInput", {
750
+ params: { provider: entry.provider, reason: `model ${entry.id} does not support ${operation}` }
751
+ })
752
+ );
753
+ }
754
+ const apiKey = entry.apiKey ?? (audioConfig.inheritLlmApiKey ? llmApiKey : void 0) ?? audioProviderEnvApiKey(entry.provider);
755
+ const baseUrl = entry.baseUrl ?? AUDIO_PROVIDER_DEFAULT_BASE_URL[entry.provider];
756
+ if (!baseUrl) {
757
+ return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_audioMissingBaseUrl", {
758
+ params: { provider: entry.provider }
759
+ }));
760
+ }
761
+ return ok({
762
+ id: entry.id,
763
+ provider: entry.provider,
764
+ model: entry.model,
765
+ apiKey,
766
+ baseUrl,
767
+ appKey: entry.appKey ?? process.env.VOLC_APP_KEY,
768
+ accessKey: entry.accessKey ?? process.env.VOLC_ACCESS_KEY,
769
+ resourceId: entry.resourceId ?? (entry.provider === "doubao" ? doubaoDefaultResourceId(operation) : ""),
770
+ workspaceId: entry.workspaceId,
771
+ timeout: entry.timeout ?? 6e4
772
+ });
773
+ }
774
+ function ensureAudioCredential(model) {
775
+ if (AUDIO_PROVIDER_CREDENTIAL_OPTIONAL.has(model.provider))
776
+ return null;
777
+ const hasDoubaoLegacy = model.provider === "doubao" && Boolean(model.appKey && model.accessKey);
778
+ if (model.apiKey || hasDoubaoLegacy)
779
+ return null;
780
+ return core.error.buildHaiErrorInst(HaiAIError.CONFIGURATION_ERROR, aiM("ai_audioMissingApiKey", {
781
+ params: { provider: model.provider }
782
+ }));
783
+ }
784
+ var ImageProviderSchema = z.enum([
785
+ "openai",
786
+ "google",
787
+ "qwen",
788
+ "seedream",
789
+ "pollinations"
790
+ ]);
791
+ var ImageModelEntrySchema = z.object({
792
+ /** 模型唯一标识(供请求选择) */
793
+ id: z.string(),
794
+ /** 所属文生图平台 */
795
+ provider: ImageProviderSchema,
796
+ /** 厂商模型名 */
797
+ model: z.string(),
798
+ /** API Key 覆盖;未提供时回退厂商环境变量 */
799
+ apiKey: OptionalSecretSchema,
800
+ /** API 基础 URL 覆盖 */
801
+ baseUrl: z.url().optional(),
802
+ /** 阿里云百炼业务空间 ID(可选) */
803
+ workspaceId: z.string().optional(),
804
+ /** 整次图片生成与下载超时(毫秒,1–2147483647,默认 120000) */
805
+ timeout: z.number().int().positive().max(2147483647).default(12e4)
806
+ });
807
+ var ImageConfigSchema = z.object({
808
+ /** 单张图片或参考图的字节上限,默认 20 MiB;JSON 上限为 max(64 KiB, 两倍图片上限)。 */
809
+ maxImageBytes: z.number().int().positive().max(100 * 1024 * 1024).default(20 * 1024 * 1024),
810
+ /** 单次生成/参考图数量上限,默认 4,最大 16;临时 URL 串行下载。 */
811
+ maxImages: z.number().int().positive().max(16).default(4),
812
+ /** 注册的文生图模型 */
813
+ models: z.array(ImageModelEntrySchema).optional(),
814
+ /** 默认文生图模型 ID */
815
+ generateModel: z.string().optional()
816
+ });
817
+ var IMAGE_PROVIDER_DEFAULT_BASE_URL = {
818
+ openai: "https://api.openai.com/v1",
819
+ google: "https://generativelanguage.googleapis.com",
820
+ qwen: "https://dashscope.aliyuncs.com/api/v1",
821
+ seedream: "https://ark.cn-beijing.volces.com/api/v3",
822
+ pollinations: "https://gen.pollinations.ai"
823
+ };
824
+ function imageProviderEnvApiKey(provider) {
825
+ switch (provider) {
826
+ case "openai":
827
+ return process.env.HAI_AI_IMAGE_OPENAI_APIKEY?.trim() || process.env.OPENAI_API_KEY;
828
+ case "google":
829
+ return process.env.HAI_AI_IMAGE_GOOGLE_APIKEY?.trim() || process.env.GEMINI_API_KEY;
830
+ case "qwen":
831
+ return process.env.HAI_AI_IMAGE_QWEN_APIKEY?.trim() || process.env.DASHSCOPE_API_KEY;
832
+ case "seedream":
833
+ return (process.env.HAI_AI_IMAGE_SEEDREAM_APIKEY?.trim() || process.env.ARK_API_KEY) ?? process.env.VOLC_API_KEY;
834
+ case "pollinations":
835
+ return process.env.HAI_AI_IMAGE_POLLINATIONS_APIKEY?.trim() || process.env.POLLINATIONS_API_KEY;
836
+ }
837
+ }
838
+ function resolveImageModel(imageConfig, explicit) {
839
+ const target = explicit ?? imageConfig.generateModel;
840
+ if (!target) {
841
+ return err(HaiAIError.IMAGE_MODEL_NOT_FOUND, aiM("ai_imageModelNotFound", {
842
+ params: { model: "<generate>" }
843
+ }));
844
+ }
845
+ const entry = imageConfig.models?.find((model) => model.id === target || model.model === target);
846
+ if (!entry) {
847
+ return err(HaiAIError.IMAGE_MODEL_NOT_FOUND, aiM("ai_imageModelNotFound", {
848
+ params: { model: target }
849
+ }));
850
+ }
851
+ const apiKey = entry.apiKey ?? imageProviderEnvApiKey(entry.provider);
852
+ if (!apiKey) {
853
+ return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_imageMissingApiKey", {
854
+ params: { provider: entry.provider }
855
+ }));
856
+ }
857
+ const configuredUrl = entry.baseUrl ?? IMAGE_PROVIDER_DEFAULT_BASE_URL[entry.provider];
858
+ let urlEnd = configuredUrl.length;
859
+ while (urlEnd > 0 && configuredUrl[urlEnd - 1] === "/")
860
+ urlEnd--;
861
+ return ok({
862
+ id: entry.id,
863
+ provider: entry.provider,
864
+ model: entry.model,
865
+ apiKey,
866
+ baseUrl: configuredUrl.slice(0, urlEnd),
867
+ workspaceId: entry.workspaceId,
868
+ timeout: entry.timeout
869
+ });
870
+ }
871
+ var AIConfigSchema = z.object({
872
+ /** ACP 会话与执行限制(仅 Node 服务端)。 */
873
+ acp: ACPConfigSchema.optional(),
874
+ /** LLM 配置(可选,所有字段有默认值) */
875
+ llm: LLMConfigSchema.default({
876
+ model: "gpt-4o-mini",
877
+ protocol: "chat",
878
+ maxTokens: 4096,
879
+ temperature: 0.7,
880
+ timeout: 6e4,
881
+ tempModelCacheTtl: 6e5
882
+ }),
883
+ /** MCP 配置 */
884
+ mcp: MCPConfigSchema.optional(),
885
+ /** Embedding 配置 */
886
+ embedding: EmbeddingConfigSchema.optional(),
887
+ /** Knowledge 配置 */
888
+ knowledge: KnowledgeConfigSchema.optional(),
889
+ /** Memory 配置 */
890
+ memory: MemoryConfigSchema.optional(),
891
+ /** Token 配置 */
892
+ token: TokenConfigSchema.optional(),
893
+ /** Summary 配置 */
894
+ summary: SummaryConfigSchema.optional(),
895
+ /** Compress 配置 */
896
+ compress: CompressConfigSchema.optional(),
897
+ /** Retrieval 配置(预注册检索源) */
898
+ retrieval: RetrievalConfigSchema.optional(),
899
+ /** File 解析配置 */
900
+ file: FileConfigSchema.optional(),
901
+ /** A2A 配置(Agent-to-Agent 协议) */
902
+ a2a: A2AConfigSchema.optional(),
903
+ /** Audio 配置(语音识别 / 语音合成) */
904
+ audio: AudioConfigSchema.optional(),
905
+ /** Image 配置(文生图) */
906
+ image: ImageConfigSchema.optional()
907
+ });
908
+ function serializePlayableAudio(audio) {
909
+ if (audio.format === "wav") {
910
+ return ok({
911
+ audioBase64: toBase64(audio.data),
912
+ format: "wav",
913
+ mimeType: "audio/wav"
914
+ });
915
+ }
916
+ if (audio.format === "mp3") {
917
+ return ok({
918
+ audioBase64: toBase64(audio.data),
919
+ format: "mp3",
920
+ mimeType: "audio/mpeg"
921
+ });
922
+ }
923
+ if (audio.format !== "pcm16")
924
+ return err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, `Unsupported playable audio format: ${audio.format}`);
925
+ const sampleRate = audio.sampleRate;
926
+ const channels = audio.channels ?? 1;
927
+ if (sampleRate === void 0 || !Number.isInteger(sampleRate) || sampleRate <= 0 || channels !== 1 && channels !== 2 || audio.data.byteLength % (channels * 2) !== 0)
928
+ return err(HaiAIError.AUDIO_INVALID_REQUEST, "PCM16 audio metadata is invalid");
929
+ const wav = new Uint8Array(44 + audio.data.byteLength);
930
+ const view = new DataView(wav.buffer);
931
+ writeAscii(wav, 0, "RIFF");
932
+ view.setUint32(4, wav.byteLength - 8, true);
933
+ writeAscii(wav, 8, "WAVE");
934
+ writeAscii(wav, 12, "fmt ");
935
+ view.setUint32(16, 16, true);
936
+ view.setUint16(20, 1, true);
937
+ view.setUint16(22, channels, true);
938
+ view.setUint32(24, sampleRate, true);
939
+ view.setUint32(28, sampleRate * channels * 2, true);
940
+ view.setUint16(32, channels * 2, true);
941
+ view.setUint16(34, 16, true);
942
+ writeAscii(wav, 36, "data");
943
+ view.setUint32(40, audio.data.byteLength, true);
944
+ wav.set(audio.data, 44);
945
+ return ok({
946
+ audioBase64: toBase64(wav),
947
+ format: "wav",
948
+ mimeType: "audio/wav"
949
+ });
950
+ }
951
+ function writeAscii(target, offset, value) {
952
+ for (let index = 0; index < value.length; index++)
953
+ target[offset + index] = value.charCodeAt(index);
954
+ }
955
+ function toBase64(data) {
956
+ let binary = "";
957
+ const chunkSize = 32768;
958
+ for (let offset = 0; offset < data.length; offset += chunkSize)
959
+ binary += String.fromCharCode(...data.subarray(offset, offset + chunkSize));
960
+ return btoa(binary);
961
+ }
962
+ var AUDIO_WS_PATH = AUDIO_WS_PATH$1;
963
+ var AudioFormatSchema = AudioFormatSchema$1;
964
+ var AudioWsStartMessageSchema = AudioWsStartMessageSchema$1;
965
+ var AudioWsTextMessageSchema = AudioWsTextMessageSchema$1;
966
+ var AudioWsDoneMessageSchema = AudioWsDoneMessageSchema$1;
967
+ var AudioWsClientMessageSchema = AudioWsClientMessageSchema$1;
968
+
969
+ export { A2AConfigSchema, A2ASkillConfigSchema, ACPAgentSchema, ACPConfigSchema, ACPPublishSchema, ACPRepositorySchema, ACPWorkspaceSchema, AIConfigSchema, AUDIO_WS_PATH, ApiTypeSchema, AudioConfigSchema, AudioFormatSchema, AudioModelEntrySchema, AudioOperationSchema, AudioOperationsSchema, AudioProviderSchema, AudioWsClientMessageSchema, AudioWsDoneMessageSchema, AudioWsStartMessageSchema, AudioWsTextMessageSchema, CompressConfigSchema, CompressionStrategySchema, EmbeddingConfigSchema, EntityTypeSchema, FileConfigSchema, ImageConfigSchema, ImageModelEntrySchema, ImageProviderSchema, KnowledgeConfigSchema, LLMConfigSchema, MCPConfigSchema, MCPExternalServerSchema, MCPServerCapabilitiesSchema, MCPServerConfigSchema, MemoryConfigSchema, MemoryTypeSchema, ModelCapabilitiesSchema, ModelEntrySchema, ModelScenarioSchema, OptionalSecretSchema, RetrievalConfigSchema, RetrievalSourceSchema, SummaryConfigSchema, TokenConfigSchema, branchNameSchema, ensureAudioCredential, platformOptionsSchema, platformRequestSchema, platformRunSchema, platformScopeSchema, resolveAudioModel, resolveImageModel, resolveModelApi, resolveModelEntry, serializePlayableAudio, sessionIdentitySchema };
970
+ //# sourceMappingURL=chunk-A357G2JF.js.map
971
+ //# sourceMappingURL=chunk-A357G2JF.js.map