@h-ai/ai 1.0.0-beta.30 → 1.0.0-beta.32
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/README.en.md +11 -1114
- package/README.ja.md +10 -1113
- package/README.md +11 -1137
- package/dist/{ai-acp-types-DuPV5UGi.d.ts → ai-acp-types-cue1ZWUk.d.ts} +4970 -5227
- package/dist/ai-file-types-BN7l67hR.d.ts +167 -0
- package/dist/ai-file-worker.d.ts +38 -0
- package/dist/ai-file-worker.js +85 -0
- package/dist/ai-file-worker.js.map +1 -0
- package/dist/ai-video-archive-worker.d.ts +32 -0
- package/dist/ai-video-archive-worker.js +102 -0
- package/dist/ai-video-archive-worker.js.map +1 -0
- package/dist/browser.d.ts +5 -2
- package/dist/browser.js +4 -3
- package/dist/{chunk-NRDLMUSY.js → chunk-C6T3ONVG.js} +4 -8
- package/dist/chunk-C6T3ONVG.js.map +1 -0
- package/dist/{chunk-LENTVEBE.js → chunk-HZDINADT.js} +254 -973
- package/dist/chunk-HZDINADT.js.map +1 -0
- package/dist/chunk-IVEOIRBO.js +971 -0
- package/dist/chunk-IVEOIRBO.js.map +1 -0
- package/dist/chunk-OWR55FRO.js +140 -0
- package/dist/chunk-OWR55FRO.js.map +1 -0
- package/dist/{chunk-ILUCWONQ.js → chunk-UVBQCI7A.js} +3 -3
- package/dist/{chunk-ILUCWONQ.js.map → chunk-UVBQCI7A.js.map} +1 -1
- package/dist/client/index.js +2 -2
- package/dist/index.d.ts +6 -3
- package/dist/index.js +1492 -743
- package/dist/index.js.map +1 -1
- package/models/agents/README.md +3 -1
- package/models/agents/deepseek-harness/Dockerfile +2 -0
- package/package.json +10 -10
- package/dist/chunk-LENTVEBE.js.map +0 -1
- package/dist/chunk-NRDLMUSY.js.map +0 -1
- package/tools/.dockerignore +0 -4
- package/tools/README.md +0 -111
- package/tools/archives.py +0 -56
- package/tools/browser/Dockerfile +0 -19
- package/tools/browser/operation.py +0 -50
- package/tools/browser/render.mjs +0 -40
- package/tools/documents/Dockerfile +0 -20
- package/tools/documents/operation.py +0 -80
- package/tools/ocr/Dockerfile +0 -19
- package/tools/ocr/operation.py +0 -18
- package/tools/office/Dockerfile +0 -21
- package/tools/office/office_job.py +0 -65
- package/tools/office/operation.py +0 -43
- package/tools/tests/image-smoke.mjs +0 -83
- package/tools/tests/test_hai_tool.py +0 -82
- package/tools/tool.py +0 -145
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { HaiResult } from '@h-ai/core';
|
|
2
|
+
import { Buffer } from 'node:buffer';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @h-ai/ai — File 子功能类型
|
|
6
|
+
*
|
|
7
|
+
* 定义文件解析操作的类型接口。
|
|
8
|
+
* @module ai-file-types
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 文件解析方法
|
|
13
|
+
*
|
|
14
|
+
* - `text` — 直接解码为 UTF-8 文本(txt / md / csv / 等文本格式)
|
|
15
|
+
* - `html` — HTML 标签剥除后提取文本
|
|
16
|
+
* - `pdf` — 使用 pdfjs-dist 解析 PDF(需安装可选依赖)
|
|
17
|
+
* - `docx` — 使用 mammoth 解析 Word 文档(需安装可选依赖)
|
|
18
|
+
* - `ocr` — 通过视觉 LLM 进行 OCR 识别(图片及无原生解析器的格式)
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* import type { FileParseMethod } from '@h-ai/ai'
|
|
23
|
+
*
|
|
24
|
+
* const value: FileParseMethod = 'text'
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
type FileParseMethod = 'text' | 'html' | 'pdf' | 'docx' | 'ocr';
|
|
28
|
+
/**
|
|
29
|
+
* 文件解析输出格式
|
|
30
|
+
* - `text` — 纯文本(默认),适合程序处理
|
|
31
|
+
* - `markdown` — Markdown 格式,保留文档结构(标题、列表、粗斜体等),
|
|
32
|
+
* 适用于 HTML、PDF、DOCX;图片 OCR 会提示模型输出 Markdown
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* import type { OutputFormat } from '@h-ai/ai'
|
|
37
|
+
*
|
|
38
|
+
* const value: OutputFormat = 'markdown'
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
type OutputFormat = 'text' | 'markdown';
|
|
42
|
+
/**
|
|
43
|
+
* 文件解析选项
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* import type { FileParseOptions } from '@h-ai/ai'
|
|
48
|
+
*
|
|
49
|
+
* const value: FileParseOptions = { mimeType: 'text/html', outputFormat: 'markdown' }
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
interface FileParseOptions {
|
|
53
|
+
/** 强制使用指定 MIME 类型(覆盖自动检测) */
|
|
54
|
+
mimeType?: string;
|
|
55
|
+
/** 强制使用 OCR(即使有原生解析器支持) */
|
|
56
|
+
useOcr?: boolean;
|
|
57
|
+
/**
|
|
58
|
+
* OCR 使用的视觉模型(请求级覆盖)
|
|
59
|
+
*
|
|
60
|
+
* 最高优先级,覆盖 `llm.scenarios.ocr` 场景映射。
|
|
61
|
+
* 未指定时通过 `llm.scenarios.ocr` 解析。
|
|
62
|
+
*/
|
|
63
|
+
model?: string;
|
|
64
|
+
/** OCR 系统提示词(覆盖全局 `file.systemPrompt` 配置) */
|
|
65
|
+
systemPrompt?: string;
|
|
66
|
+
/** PDF 最大解析页数(默认解析全部页) */
|
|
67
|
+
maxPages?: number;
|
|
68
|
+
/**
|
|
69
|
+
* 输出格式(默认 `'text'`)
|
|
70
|
+
*/
|
|
71
|
+
outputFormat?: OutputFormat;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* 文件解析请求
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* ```ts
|
|
78
|
+
* import type { FileParseRequest } from '@h-ai/ai'
|
|
79
|
+
*
|
|
80
|
+
* const value: FileParseRequest = { content: '<h1>周报</h1><p>完成索引升级。</p>', filename: 'weekly.html', options: { outputFormat: 'markdown' } }
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
interface FileParseRequest {
|
|
84
|
+
/**
|
|
85
|
+
* 文件内容
|
|
86
|
+
*
|
|
87
|
+
* - `Buffer` — 二进制文件(图片、PDF、DOCX 等)
|
|
88
|
+
* - `string` — 文本内容(直接传入文本格式文件)
|
|
89
|
+
*/
|
|
90
|
+
content: Buffer | string;
|
|
91
|
+
/** 文件名(用于 MIME 类型自动检测,可选) */
|
|
92
|
+
filename?: string;
|
|
93
|
+
/** 解析选项 */
|
|
94
|
+
options?: FileParseOptions;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* 文件解析结果
|
|
98
|
+
*
|
|
99
|
+
* @example
|
|
100
|
+
* ```ts
|
|
101
|
+
* import type { FileParseResult } from '@h-ai/ai'
|
|
102
|
+
*
|
|
103
|
+
* function preview(parsed: FileParseResult): string {
|
|
104
|
+
* return `${parsed.method}: ${parsed.text.slice(0, 160)}`
|
|
105
|
+
* }
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
interface FileParseResult {
|
|
109
|
+
/** 提取的文本内容(当 `outputFormat` 为 `'markdown'` 时为 Markdown 格式);不是可直接执行的可信 HTML。 */
|
|
110
|
+
text: string;
|
|
111
|
+
/** 解析方法 */
|
|
112
|
+
method: FileParseMethod;
|
|
113
|
+
/** 页数(PDF 解析时) */
|
|
114
|
+
pageCount?: number;
|
|
115
|
+
/** 元数据 */
|
|
116
|
+
metadata?: {
|
|
117
|
+
filename?: string;
|
|
118
|
+
mimeType?: string;
|
|
119
|
+
charCount?: number;
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* File 操作接口(通过 `ai.file` 访问)
|
|
124
|
+
*
|
|
125
|
+
* 需要先调用 `ai.init()` 初始化后使用(OCR 功能需要 LLM 配置)。
|
|
126
|
+
*
|
|
127
|
+
* 支持的格式:
|
|
128
|
+
* - 文本格式(txt、md、csv 等):直接解码
|
|
129
|
+
* - HTML:剥除标签后提取文本
|
|
130
|
+
* - PDF:使用 pdfjs-dist(需安装),否则回退到 OCR
|
|
131
|
+
* - DOCX:使用 mammoth(需安装),否则回退到 OCR
|
|
132
|
+
* - 图片(JPEG、PNG、GIF、WebP):通过视觉 LLM OCR 识别
|
|
133
|
+
*
|
|
134
|
+
* @example
|
|
135
|
+
* ```ts
|
|
136
|
+
* import { ai } from '@h-ai/ai'
|
|
137
|
+
*
|
|
138
|
+
* // 应用启动已成功初始化 ai;这里是业务服务函数。
|
|
139
|
+
* async function run() {
|
|
140
|
+
* const result = await ai.file.parse({ content: '会议决定周一发布。', filename: 'minutes.txt' })
|
|
141
|
+
* if (!result.success)
|
|
142
|
+
* return result
|
|
143
|
+
* return result.data.text
|
|
144
|
+
* }
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
interface FileOperations {
|
|
148
|
+
/**
|
|
149
|
+
* 解析文件内容,提取文本
|
|
150
|
+
*
|
|
151
|
+
* 自动检测文件格式,选择最优解析方法。
|
|
152
|
+
*
|
|
153
|
+
* @param request - 文件解析请求
|
|
154
|
+
* @returns 解析结果,包含文本内容、解析方法和元数据
|
|
155
|
+
*/
|
|
156
|
+
parse: (request: FileParseRequest) => Promise<HaiResult<FileParseResult>>;
|
|
157
|
+
/**
|
|
158
|
+
* 便捷方法:直接返回提取的文本字符串
|
|
159
|
+
*
|
|
160
|
+
* @param content - 文件内容(Buffer 或文本字符串)
|
|
161
|
+
* @param filename - 文件名(用于格式检测,可选)
|
|
162
|
+
* @returns 提取的文本内容
|
|
163
|
+
*/
|
|
164
|
+
parseText: (content: Buffer | string, filename?: string) => Promise<HaiResult<string>>;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export type { FileOperations as F, OutputFormat as O, FileParseMethod as a, FileParseOptions as b, FileParseRequest as c, FileParseResult as d };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Locale, HaiResult } from '@h-ai/core';
|
|
2
|
+
import { OutputFormat } from './browser.js';
|
|
3
|
+
import 'node:buffer';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 本地解析任务仅携带文件内容、格式和调用语言。
|
|
7
|
+
* @example 模块内部上下文
|
|
8
|
+
* ```ts
|
|
9
|
+
* const job: FileParseJob = { type: 'html', content: '<p>Report</p>', format: 'text', locale: 'en-US' }
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
type FileParseJob = {
|
|
13
|
+
format: OutputFormat;
|
|
14
|
+
locale: Locale;
|
|
15
|
+
} & ({
|
|
16
|
+
type: 'html';
|
|
17
|
+
content: string | Uint8Array;
|
|
18
|
+
} | {
|
|
19
|
+
type: 'pdf';
|
|
20
|
+
content: Uint8Array;
|
|
21
|
+
maxPages?: number;
|
|
22
|
+
} | {
|
|
23
|
+
type: 'docx';
|
|
24
|
+
content: Uint8Array;
|
|
25
|
+
});
|
|
26
|
+
/**
|
|
27
|
+
* 本地解析成功后附带正文和 PDF 页数。
|
|
28
|
+
* @example 模块内部上下文
|
|
29
|
+
* ```ts
|
|
30
|
+
* const reply: FileParseReply = ok({ text: 'Report', pageCount: 1 })
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
type FileParseReply = HaiResult<{
|
|
34
|
+
text: string;
|
|
35
|
+
pageCount?: number;
|
|
36
|
+
}>;
|
|
37
|
+
|
|
38
|
+
export type { FileParseJob, FileParseReply };
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { parseHtmlFile } from './chunk-OWR55FRO.js';
|
|
2
|
+
import { aiM } from './chunk-HZDINADT.js';
|
|
3
|
+
import { HaiAIError } from './chunk-C6T3ONVG.js';
|
|
4
|
+
import { Buffer } from 'buffer';
|
|
5
|
+
import { parentPort } from 'worker_threads';
|
|
6
|
+
import { core, ok, err } from '@h-ai/core';
|
|
7
|
+
|
|
8
|
+
async function parsePdfContent(content, outputFormat = "text", maxPages) {
|
|
9
|
+
try {
|
|
10
|
+
const pdfjs = await import(
|
|
11
|
+
// @ts-expect-error — pdfjs-dist is an optional peer dependency
|
|
12
|
+
'pdfjs-dist/legacy/build/pdf.mjs'
|
|
13
|
+
);
|
|
14
|
+
const loadingTask = pdfjs.getDocument({ data: content });
|
|
15
|
+
try {
|
|
16
|
+
const pdf = await loadingTask.promise;
|
|
17
|
+
const totalPages = pdf.numPages;
|
|
18
|
+
const pagesToProcess = maxPages ? Math.min(maxPages, totalPages) : totalPages;
|
|
19
|
+
const textParts = [];
|
|
20
|
+
for (let i = 1; i <= pagesToProcess; i++) {
|
|
21
|
+
const page = await pdf.getPage(i);
|
|
22
|
+
const textContent = await page.getTextContent();
|
|
23
|
+
const pageText = textContent.items.map((item) => item.str ?? "").join(" ");
|
|
24
|
+
textParts.push(pageText);
|
|
25
|
+
}
|
|
26
|
+
const separator = outputFormat === "markdown" ? "\n\n---\n\n" : "\n\n";
|
|
27
|
+
return ok({
|
|
28
|
+
text: textParts.join(separator),
|
|
29
|
+
pageCount: totalPages
|
|
30
|
+
});
|
|
31
|
+
} finally {
|
|
32
|
+
await loadingTask.destroy();
|
|
33
|
+
}
|
|
34
|
+
} catch (error) {
|
|
35
|
+
return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
|
|
36
|
+
params: {
|
|
37
|
+
error: String(error)
|
|
38
|
+
}
|
|
39
|
+
}), error);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function parseDocxContent(content, outputFormat = "text") {
|
|
43
|
+
try {
|
|
44
|
+
const mammoth = await import(
|
|
45
|
+
// @ts-expect-error — mammoth is an optional peer dependency
|
|
46
|
+
'mammoth'
|
|
47
|
+
);
|
|
48
|
+
if (outputFormat === "markdown") {
|
|
49
|
+
const result2 = await mammoth.convertToHtml({
|
|
50
|
+
buffer: Buffer.from(content.buffer, content.byteOffset, content.byteLength)
|
|
51
|
+
});
|
|
52
|
+
return ok(parseHtmlFile(result2.value, "markdown"));
|
|
53
|
+
}
|
|
54
|
+
const result = await mammoth.extractRawText({
|
|
55
|
+
buffer: Buffer.from(content.buffer, content.byteOffset, content.byteLength)
|
|
56
|
+
});
|
|
57
|
+
return ok(result.value);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
|
|
60
|
+
params: {
|
|
61
|
+
error: String(error)
|
|
62
|
+
}
|
|
63
|
+
}), error);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// src/file/ai-file-worker.ts
|
|
68
|
+
async function parse(job) {
|
|
69
|
+
if (job.type === "html") {
|
|
70
|
+
const markup = typeof job.content === "string" ? job.content : Buffer.from(job.content.buffer, job.content.byteOffset, job.content.byteLength).toString("utf8");
|
|
71
|
+
return ok({
|
|
72
|
+
text: parseHtmlFile(markup, job.format)
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
if (job.type === "pdf")
|
|
76
|
+
return parsePdfContent(job.content, job.format, job.maxPages);
|
|
77
|
+
const result = await parseDocxContent(job.content, job.format);
|
|
78
|
+
return result.success ? ok({ text: result.data }) : result;
|
|
79
|
+
}
|
|
80
|
+
parentPort?.on("message", async (job) => {
|
|
81
|
+
const result = await core.i18n.runWithLocale(job.locale, () => parse(job));
|
|
82
|
+
parentPort?.postMessage(result);
|
|
83
|
+
});
|
|
84
|
+
//# sourceMappingURL=ai-file-worker.js.map
|
|
85
|
+
//# sourceMappingURL=ai-file-worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/file/ai-file-native.ts","../src/file/ai-file-worker.ts"],"names":["result","Buffer","ok"],"mappings":";;;;;;;AAgBA,eAAsB,eAAA,CAAgB,OAAA,EAAqB,YAAA,GAA6B,MAAA,EAAQ,QAAA,EAA4E;AAC1K,EAAA,IAAI;AACF,IAAA,MAAM,QAAQ,MAAM;AAAA;A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QAAQ,UAAU,CAAA,CAAE,SAAS,MAAM,CAAA;AACnG,IAAA,OAAOC,EAAAA,CAAG;AAAA,MACR,IAAA,EAAM,aAAA,CAAc,MAAA,EAAQ,GAAA,CAAI,MAAM;AAAA,KACvC,CAAA;AAAA,EACH;AACA,EAAA,IAAI,IAAI,IAAA,KAAS,KAAA;AACf,IAAA,OAAO,gBAAgB,GAAA,CAAI,OAAA,EAAS,GAAA,CAAI,MAAA,EAAQ,IAAI,QAAQ,CAAA;AAC9D,EAAA,MAAM,SAAS,MAAM,gBAAA,CAAiB,GAAA,CAAI,OAAA,EAAS,IAAI,MAAM,CAAA;AAC7D,EAAA,OAAO,MAAA,CAAO,UACVA,EAAAA,CAAG,EAAE,MAAM,MAAA,CAAO,IAAA,EAAM,CAAA,GACxB,MAAA;AACN;AAEA,UAAA,EAAY,EAAA,CAAG,SAAA,EAAW,OAAO,GAAA,KAAsB;AACrD,EAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,IAAA,CAAK,aAAA,CAAc,IAAI,MAAA,EAAQ,MAAM,KAAA,CAAM,GAAG,CAAC,CAAA;AACzE,EAAA,UAAA,EAAY,YAAY,MAAM,CAAA;AAChC,CAAC,CAAA","file":"ai-file-worker.js","sourcesContent":["import type { HaiResult } from '@h-ai/core'\nimport type { OutputFormat } from './ai-file-types.js'\nimport { Buffer } from 'node:buffer'\nimport { err, ok } from '@h-ai/core'\nimport { aiM } from '../ai-i18n.js'\nimport { HaiAIError } from '../ai-types.js'\nimport { parseHtmlFile } from './ai-file-html.js'\n\n/**\n * 使用 pdfjs-dist 解析 PDF 内容。\n * @example 模块内部上下文\n * ```ts\n * const pdfResult = await parsePdfContent(new Uint8Array(), 'text', 1)\n * if (pdfResult.success) void pdfResult.data.pageCount\n * ```\n */\nexport async function parsePdfContent(content: Uint8Array, outputFormat: OutputFormat = 'text', maxPages?: number): Promise<HaiResult<{ text: string, pageCount: number }>> {\n try {\n const pdfjs = await import(\n\n // @ts-expect-error — pdfjs-dist is an optional peer dependency\n 'pdfjs-dist/legacy/build/pdf.mjs',\n ) as { getDocument: (...args: unknown[]) => { promise: Promise<unknown>, destroy: () => Promise<void> } }\n const loadingTask = pdfjs.getDocument({ data: content })\n try {\n const pdf = await loadingTask.promise as {\n numPages: number\n getPage: (n: number) => Promise<{ getTextContent: () => Promise<{ items: Array<{ str?: string }> }> }>\n }\n const totalPages = pdf.numPages\n const pagesToProcess = maxPages\n ? Math.min(maxPages, totalPages)\n : totalPages\n const textParts: string[] = []\n\n for (let i = 1; i <= pagesToProcess; i++) {\n const page = await pdf.getPage(i)\n const textContent = await page.getTextContent()\n const pageText = textContent.items\n .map(item => item.str ?? '')\n .join(' ')\n textParts.push(pageText)\n }\n\n // markdown 模式用页分隔线区分每页\n const separator = outputFormat === 'markdown'\n ? '\\n\\n---\\n\\n'\n : '\\n\\n'\n return ok({\n text: textParts.join(separator),\n pageCount: totalPages,\n })\n }\n finally { await loadingTask.destroy() }\n }\n catch (error) {\n return err(HaiAIError.FILE_PARSE_FAILED, aiM('ai_fileParseFailed', {\n params: {\n error: String(error),\n },\n }), error)\n }\n}\n\n/**\n * 使用 mammoth 解析 DOCX 内容\n *\n * - `'text'`:使用 `extractRawText` 提取纯文本\n * - `'markdown'`:使用 `convertToHtml` 后转换为 Markdown\n * @example 模块内部上下文\n * ```ts\n * const docxResult = await parseDocxContent(new Uint8Array(), 'markdown')\n * if (docxResult.success) void docxResult.data\n * ```\n */\nexport async function parseDocxContent(content: Uint8Array, outputFormat: OutputFormat = 'text'): Promise<HaiResult<string>> {\n try {\n const mammoth = await import(\n\n // @ts-expect-error — mammoth is an optional peer dependency\n 'mammoth',\n ) as {\n extractRawText: (options: unknown) => Promise<{ value: string }>\n convertToHtml: (options: unknown) => Promise<{ value: string }>\n }\n if (outputFormat === 'markdown') {\n const result = await mammoth.convertToHtml({\n buffer: Buffer.from(content.buffer, content.byteOffset, content.byteLength),\n })\n return ok(parseHtmlFile(result.value, 'markdown'))\n }\n const result = await mammoth.extractRawText({\n buffer: Buffer.from(content.buffer, content.byteOffset, content.byteLength),\n })\n return ok(result.value)\n }\n catch (error) {\n return err(HaiAIError.FILE_PARSE_FAILED, aiM('ai_fileParseFailed', {\n params: {\n error: String(error),\n },\n }), error)\n }\n}\n","import type { HaiResult, Locale } from '@h-ai/core'\nimport type { OutputFormat } from './ai-file-types.js'\nimport { Buffer } from 'node:buffer'\nimport { parentPort } from 'node:worker_threads'\nimport { core, ok } from '@h-ai/core'\nimport { parseHtmlFile } from './ai-file-html.js'\nimport { parseDocxContent, parsePdfContent } from './ai-file-native.js'\n\n/**\n * 本地解析任务仅携带文件内容、格式和调用语言。\n * @example 模块内部上下文\n * ```ts\n * const job: FileParseJob = { type: 'html', content: '<p>Report</p>', format: 'text', locale: 'en-US' }\n * ```\n */\nexport type FileParseJob = { format: OutputFormat, locale: Locale } & (\n | { type: 'html', content: string | Uint8Array }\n | { type: 'pdf', content: Uint8Array, maxPages?: number }\n | { type: 'docx', content: Uint8Array }\n)\n\n/**\n * 本地解析成功后附带正文和 PDF 页数。\n * @example 模块内部上下文\n * ```ts\n * const reply: FileParseReply = ok({ text: 'Report', pageCount: 1 })\n * ```\n */\nexport type FileParseReply = HaiResult<{ text: string, pageCount?: number }>\n\nasync function parse(job: FileParseJob): Promise<FileParseReply> {\n if (job.type === 'html') {\n const markup = typeof job.content === 'string'\n ? job.content\n : Buffer.from(job.content.buffer, job.content.byteOffset, job.content.byteLength).toString('utf8')\n return ok({\n text: parseHtmlFile(markup, job.format),\n })\n }\n if (job.type === 'pdf')\n return parsePdfContent(job.content, job.format, job.maxPages)\n const result = await parseDocxContent(job.content, job.format)\n return result.success\n ? ok({ text: result.data })\n : result\n}\n\nparentPort?.on('message', async (job: FileParseJob) => {\n const result = await core.i18n.runWithLocale(job.locale, () => parse(job))\n parentPort?.postMessage(result)\n})\n"]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 视频采集包解压或项目打包任务。
|
|
3
|
+
* @example 模块内部上下文
|
|
4
|
+
* ```ts
|
|
5
|
+
* const input: VideoArchiveJob = { type: 'pack', files: { 'story.txt': new Uint8Array([65]) } }
|
|
6
|
+
* ```
|
|
7
|
+
*/
|
|
8
|
+
type VideoArchiveJob = {
|
|
9
|
+
type: 'read';
|
|
10
|
+
bytes: Uint8Array;
|
|
11
|
+
} | {
|
|
12
|
+
type: 'pack';
|
|
13
|
+
files: Record<string, Uint8Array>;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* 数据格式错误在当前任务内结算,便于后续任务复用线程。
|
|
17
|
+
* @example 模块内部上下文
|
|
18
|
+
* ```ts
|
|
19
|
+
* const invalid: VideoArchiveReply = { type: 'invalid' }
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
type VideoArchiveReply = {
|
|
23
|
+
type: 'files';
|
|
24
|
+
files: Record<string, Uint8Array>;
|
|
25
|
+
} | {
|
|
26
|
+
type: 'zip';
|
|
27
|
+
bytes: Uint8Array;
|
|
28
|
+
} | {
|
|
29
|
+
type: 'invalid';
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export type { VideoArchiveJob, VideoArchiveReply };
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { parentPort } from 'worker_threads';
|
|
2
|
+
import { inflateRawSync } from 'zlib';
|
|
3
|
+
import { zipSync, strFromU8 } from 'fflate';
|
|
4
|
+
|
|
5
|
+
// src/tools/ai-video-archive-worker.ts
|
|
6
|
+
function validateArchive(bytes) {
|
|
7
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
8
|
+
let end = -1;
|
|
9
|
+
for (let offset2 = bytes.length - 22; offset2 >= Math.max(0, bytes.length - 65557); offset2--) {
|
|
10
|
+
if (view.getUint32(offset2, true) === 101010256 && offset2 + 22 + view.getUint16(offset2 + 20, true) === bytes.length) {
|
|
11
|
+
end = offset2;
|
|
12
|
+
break;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
if (end < 0 || view.getUint16(end + 4, true) !== 0 || view.getUint16(end + 6, true) !== 0)
|
|
16
|
+
throw new Error("Unsupported archive directory");
|
|
17
|
+
const count = view.getUint16(end + 10, true);
|
|
18
|
+
const directorySize = view.getUint32(end + 12, true);
|
|
19
|
+
let offset = view.getUint32(end + 16, true);
|
|
20
|
+
const directoryStart = offset;
|
|
21
|
+
const directoryEnd = offset + directorySize;
|
|
22
|
+
if (count < 1 || count > 256 || count !== view.getUint16(end + 8, true) || directoryEnd !== end)
|
|
23
|
+
throw new Error("Archive directory exceeds its bound");
|
|
24
|
+
let expanded = 0;
|
|
25
|
+
const names = /* @__PURE__ */ new Set();
|
|
26
|
+
const entries = [];
|
|
27
|
+
const ranges = [];
|
|
28
|
+
for (let index = 0; index < count; index++) {
|
|
29
|
+
if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 33639248)
|
|
30
|
+
throw new Error("Invalid archive directory entry");
|
|
31
|
+
const flags = view.getUint16(offset + 8, true);
|
|
32
|
+
const compression = view.getUint16(offset + 10, true);
|
|
33
|
+
const compressedSize = view.getUint32(offset + 20, true);
|
|
34
|
+
const size = view.getUint32(offset + 24, true);
|
|
35
|
+
const nameLength = view.getUint16(offset + 28, true);
|
|
36
|
+
const entryLength = 46 + nameLength + view.getUint16(offset + 30, true) + view.getUint16(offset + 32, true);
|
|
37
|
+
const mode = view.getUint32(offset + 38, true) >>> 16;
|
|
38
|
+
if (offset + entryLength > directoryEnd || flags & 1 || compression !== 0 && compression !== 8 || compressedSize > 50 * 1024 * 1024 || size > 50 * 1024 * 1024 || (mode & 61440) === 40960 || view.getUint16(offset + 34, true) !== 0) {
|
|
39
|
+
throw new Error("Unsupported archive entry");
|
|
40
|
+
}
|
|
41
|
+
const name = strFromU8(bytes.subarray(offset + 46, offset + 46 + nameLength), !(flags & 2048));
|
|
42
|
+
expanded += size;
|
|
43
|
+
if (expanded > 100 * 1024 * 1024 || names.has(name) || name.startsWith("/") || /\\|\0|(?:^|\/)\.{1,2}(?:\/|$)|^[a-z]:/i.test(name))
|
|
44
|
+
throw new Error("Unsafe archive path or expanded size");
|
|
45
|
+
const local = view.getUint32(offset + 42, true);
|
|
46
|
+
if (local + 30 > directoryStart || view.getUint32(local, true) !== 67324752 || view.getUint16(local + 6, true) !== flags || view.getUint16(local + 8, true) !== compression) {
|
|
47
|
+
throw new Error("Archive local header mismatch");
|
|
48
|
+
}
|
|
49
|
+
const localNameLength = view.getUint16(local + 26, true);
|
|
50
|
+
const start = local + 30 + localNameLength + view.getUint16(local + 28, true);
|
|
51
|
+
const end2 = start + compressedSize;
|
|
52
|
+
if (end2 > directoryStart || strFromU8(bytes.subarray(local + 30, local + 30 + localNameLength), !(flags & 2048)) !== name || compression === 0 && size !== compressedSize || !(flags & 8) && (view.getUint32(local + 18, true) !== compressedSize || view.getUint32(local + 22, true) !== size)) {
|
|
53
|
+
throw new Error("Archive entry length mismatch");
|
|
54
|
+
}
|
|
55
|
+
ranges.push({ start: local, end: end2 });
|
|
56
|
+
entries.push({ name, compression, size, start, end: end2 });
|
|
57
|
+
names.add(name);
|
|
58
|
+
offset += entryLength;
|
|
59
|
+
}
|
|
60
|
+
if (offset !== directoryEnd)
|
|
61
|
+
throw new Error("Archive directory length mismatch");
|
|
62
|
+
ranges.sort((left, right) => left.start - right.start);
|
|
63
|
+
if (ranges.some((range, index) => index > 0 && range.start < ranges[index - 1].end))
|
|
64
|
+
throw new Error("Archive entries overlap");
|
|
65
|
+
return entries;
|
|
66
|
+
}
|
|
67
|
+
function readCapture(bytes) {
|
|
68
|
+
if (bytes.byteLength > 50 * 1024 * 1024)
|
|
69
|
+
throw new Error("Capture archive exceeds its bound");
|
|
70
|
+
const entries = validateArchive(bytes);
|
|
71
|
+
const files = {};
|
|
72
|
+
for (const entry of entries) {
|
|
73
|
+
if (entry.name !== "capture.json" && entry.name !== "extracted/tokens.json" && !/^screenshots\/[\w./-]+\.png$/i.test(entry.name))
|
|
74
|
+
continue;
|
|
75
|
+
const compressed = bytes.subarray(entry.start, entry.end);
|
|
76
|
+
const output = entry.compression === 0 ? compressed.slice() : inflateRawSync(compressed, {
|
|
77
|
+
maxOutputLength: Math.max(1, entry.size)
|
|
78
|
+
});
|
|
79
|
+
if (output.byteLength !== entry.size)
|
|
80
|
+
throw new Error("Archive expanded size mismatch");
|
|
81
|
+
files[entry.name] = output;
|
|
82
|
+
}
|
|
83
|
+
return files;
|
|
84
|
+
}
|
|
85
|
+
parentPort?.on("message", (job) => {
|
|
86
|
+
try {
|
|
87
|
+
if (job.type === "read") {
|
|
88
|
+
const files = readCapture(job.bytes);
|
|
89
|
+
parentPort?.postMessage({ type: "files", files });
|
|
90
|
+
} else {
|
|
91
|
+
const bytes = zipSync(job.files, {
|
|
92
|
+
level: 6,
|
|
93
|
+
mtime: /* @__PURE__ */ new Date("2000-01-01T00:00:00Z")
|
|
94
|
+
});
|
|
95
|
+
parentPort?.postMessage({ type: "zip", bytes }, [bytes.buffer]);
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
parentPort?.postMessage({ type: "invalid" });
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
//# sourceMappingURL=ai-video-archive-worker.js.map
|
|
102
|
+
//# sourceMappingURL=ai-video-archive-worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tools/ai-video-archive-worker.ts"],"names":["offset","end"],"mappings":";;;;;AA4BA,SAAS,gBAAgB,KAAA,EAAsG;AAC7H,EAAA,MAAM,IAAA,GAAO,IAAI,QAAA,CAAS,KAAA,CAAM,QAAQ,KAAA,CAAM,UAAA,EAAY,MAAM,UAAU,CAAA;AAC1E,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,IAASA,OAAAA,GAAS,KAAA,CAAM,MAAA,GAAS,EAAA,EAAIA,OAAAA,IAAU,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,KAAA,CAAM,MAAA,GAAS,KAAK,CAA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vC,CAAA;AACD,MAAA,UAAA,EAAY,WAAA,CAAY,EAAE,IAAA,EAAM,KAAA,EAAO,OAAM,EAA+B,CAAC,KAAA,CAAM,MAAqB,CAAC,CAAA;AAAA,IAC3G;AAAA,EACF,CAAA,CAAA,MACM;AACJ,IAAA,UAAA,EAAY,WAAA,CAAY,EAAE,IAAA,EAAM,SAAA,EAAuC,CAAA;AAAA,EACzE;AACF,CAAC,CAAA","file":"ai-video-archive-worker.js","sourcesContent":["import { parentPort } from 'node:worker_threads'\nimport { inflateRawSync } from 'node:zlib'\nimport { strFromU8, zipSync } from 'fflate'\n\n/**\n * 视频采集包解压或项目打包任务。\n * @example 模块内部上下文\n * ```ts\n * const input: VideoArchiveJob = { type: 'pack', files: { 'story.txt': new Uint8Array([65]) } }\n * ```\n */\nexport type VideoArchiveJob\n = | { type: 'read', bytes: Uint8Array }\n | { type: 'pack', files: Record<string, Uint8Array> }\n\n/**\n * 数据格式错误在当前任务内结算,便于后续任务复用线程。\n * @example 模块内部上下文\n * ```ts\n * const invalid: VideoArchiveReply = { type: 'invalid' }\n * ```\n */\nexport type VideoArchiveReply\n = | { type: 'files', files: Record<string, Uint8Array> }\n | { type: 'zip', bytes: Uint8Array }\n | { type: 'invalid' }\n\n/** 在解压前扫描 ZIP 中央目录,拒绝链接、加密、ZIP64 和越界声明。 */\nfunction validateArchive(bytes: Uint8Array): { name: string, compression: number, size: number, start: number, end: number }[] {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n let end = -1\n for (let offset = bytes.length - 22; offset >= Math.max(0, bytes.length - 65557); offset--) {\n if (view.getUint32(offset, true) === 0x06054B50 && offset + 22 + view.getUint16(offset + 20, true) === bytes.length) {\n end = offset\n break\n }\n }\n if (end < 0 || view.getUint16(end + 4, true) !== 0 || view.getUint16(end + 6, true) !== 0)\n throw new Error('Unsupported archive directory')\n const count = view.getUint16(end + 10, true)\n const directorySize = view.getUint32(end + 12, true)\n let offset = view.getUint32(end + 16, true)\n const directoryStart = offset\n const directoryEnd = offset + directorySize\n if (count < 1 || count > 256 || count !== view.getUint16(end + 8, true) || directoryEnd !== end)\n throw new Error('Archive directory exceeds its bound')\n let expanded = 0\n const names = new Set<string>()\n const entries: { name: string, compression: number, size: number, start: number, end: number }[] = []\n const ranges: { start: number, end: number }[] = []\n for (let index = 0; index < count; index++) {\n if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 0x02014B50)\n throw new Error('Invalid archive directory entry')\n const flags = view.getUint16(offset + 8, true)\n const compression = view.getUint16(offset + 10, true)\n const compressedSize = view.getUint32(offset + 20, true)\n const size = view.getUint32(offset + 24, true)\n const nameLength = view.getUint16(offset + 28, true)\n const entryLength = 46 + nameLength + view.getUint16(offset + 30, true) + view.getUint16(offset + 32, true)\n const mode = view.getUint32(offset + 38, true) >>> 16\n if (offset + entryLength > directoryEnd || flags & 1 || (compression !== 0 && compression !== 8)\n || compressedSize > 50 * 1024 * 1024 || size > 50 * 1024 * 1024 || (mode & 0xF000) === 0xA000 || view.getUint16(offset + 34, true) !== 0) {\n throw new Error('Unsupported archive entry')\n }\n const name = strFromU8(bytes.subarray(offset + 46, offset + 46 + nameLength), !(flags & 0x800))\n expanded += size\n if (expanded > 100 * 1024 * 1024 || names.has(name) || name.startsWith('/') || /\\\\|\\0|(?:^|\\/)\\.{1,2}(?:\\/|$)|^[a-z]:/i.test(name))\n throw new Error('Unsafe archive path or expanded size')\n const local = view.getUint32(offset + 42, true)\n if (local + 30 > directoryStart || view.getUint32(local, true) !== 0x04034B50\n || view.getUint16(local + 6, true) !== flags || view.getUint16(local + 8, true) !== compression) {\n throw new Error('Archive local header mismatch')\n }\n const localNameLength = view.getUint16(local + 26, true)\n const start = local + 30 + localNameLength + view.getUint16(local + 28, true)\n const end = start + compressedSize\n if (end > directoryStart || strFromU8(bytes.subarray(local + 30, local + 30 + localNameLength), !(flags & 0x800)) !== name\n || (compression === 0 && size !== compressedSize)\n || (!(flags & 8) && (view.getUint32(local + 18, true) !== compressedSize || view.getUint32(local + 22, true) !== size))) {\n throw new Error('Archive entry length mismatch')\n }\n ranges.push({ start: local, end })\n entries.push({ name, compression, size, start, end })\n names.add(name)\n offset += entryLength\n }\n if (offset !== directoryEnd)\n throw new Error('Archive directory length mismatch')\n ranges.sort((left, right) => left.start - right.start)\n if (ranges.some((range, index) => index > 0 && range.start < ranges[index - 1].end))\n throw new Error('Archive entries overlap')\n return entries\n}\n\n/** 先核对目录和声明大小,再解压所需 JSON 与截图;不导入网站脚本或样式。 */\nfunction readCapture(bytes: Uint8Array) {\n if (bytes.byteLength > 50 * 1024 * 1024)\n throw new Error('Capture archive exceeds its bound')\n const entries = validateArchive(bytes)\n const files: Record<string, Uint8Array> = {}\n for (const entry of entries) {\n if (entry.name !== 'capture.json' && entry.name !== 'extracted/tokens.json' && !/^screenshots\\/[\\w./-]+\\.png$/i.test(entry.name))\n continue\n const compressed = bytes.subarray(entry.start, entry.end)\n // 原始声明与实际解压长度都受限,不能仅信任 ZIP 头中的 originalSize。\n const output = entry.compression === 0\n ? compressed.slice()\n : inflateRawSync(compressed, {\n maxOutputLength: Math.max(1, entry.size),\n })\n if (output.byteLength !== entry.size)\n throw new Error('Archive expanded size mismatch')\n files[entry.name] = output\n }\n return files\n}\n\nparentPort?.on('message', (job: VideoArchiveJob) => {\n try {\n if (job.type === 'read') {\n const files = readCapture(job.bytes)\n parentPort?.postMessage({ type: 'files', files } satisfies VideoArchiveReply)\n }\n else {\n const bytes = zipSync(job.files, {\n level: 6,\n mtime: new Date('2000-01-01T00:00:00Z'),\n })\n parentPort?.postMessage({ type: 'zip', bytes } satisfies VideoArchiveReply, [bytes.buffer as ArrayBuffer])\n }\n }\n catch {\n parentPort?.postMessage({ type: 'invalid' } satisfies VideoArchiveReply)\n }\n})\n"]}
|
package/dist/browser.d.ts
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
|
-
export { A as A2AAgentCardConfig, a as A2AAgentCardDocument, b as A2AApiKeySecurity, c as A2AAuthenticator, d as A2ACallOptions, e as A2ACallResult, f as A2ACallerIdentity, g as A2AConfig, h as A2AConfigSchema, i as A2AContextInfo, j as A2AHandleResult, k as A2AMessageRecord, l as A2AOperations, m as A2ASecurityConfig, n as A2ASkillConfigSchema, o as A2ATaskFilter, p as ACPAgentAdapter, q as ACPAgentAdapterInput, r as ACPAgentLaunch, s as ACPAgentSchema, t as ACPClientOptions, u as ACPConfig, v as ACPConfigInput, w as ACPConfigSchema, x as ACPCreateSessionOptions, y as ACPGitReport, z as ACPOperations, B as ACPPublishSchema, C as ACPRepositorySchema, D as ACPSessionInfo, E as ACPTransport, F as ACPWorkspaceSchema, G as AIConfig, H as AIConfigInput, I as AIConfigSchema, J as AIFunctions, K as AIInitOptions, L as AIRelStore, M as AIRelStoreCompareAndSwap, N as AIRelStoreOptions, O as AIResourceEntry, P as AIResourceRegistry, Q as AIStoreProvider, R as AIVectorBackend, S as AIVectorStore, T as AIVersionedRecord, U as AUDIO_WS_PATH, V as ApiType, W as ApiTypeSchema, X as AskOptions, Y as AssistantMessage, Z as AudioConfig, _ as AudioConfigSchema, $ as AudioFormatSchema, a0 as AudioModelEntry, a1 as AudioModelEntrySchema, a2 as AudioOperation, a3 as AudioOperationSchema, a4 as AudioOperationsSchema, a5 as AudioProviderName, a6 as AudioProviderSchema, a7 as AudioWsClientMessage, a8 as AudioWsClientMessageSchema, a9 as AudioWsDoneMessage, aa as AudioWsDoneMessageSchema, ab as AudioWsEndMessage, ac as AudioWsErrorMessage, ad as AudioWsSegmentDoneMessage, ae as AudioWsSegmentStartedMessage, af as AudioWsServerMessage, ag as AudioWsSpeechMessage, ah as AudioWsStartMessage, ai as AudioWsStartMessageSchema, aj as AudioWsTextMessage, ak as AudioWsTextMessageSchema, al as AudioWsTranscriptMessage, am as ChatCompletionChoice, an as ChatCompletionChunk, ao as ChatCompletionDelta, ap as ChatCompletionRequest, aq as ChatCompletionResponse, ar as ChatHistoryOptions, as as ChatMessage, at as ChatRecord, au as Citation, av as CommitTurnInput, aw as CompressConfig, ax as CompressConfigSchema, ay as CompressOperations, az as CompressOptions, aA as CompressResult, aB as CompressionStrategy, aC as CompressionStrategySchema, aD as ConsolidateOptions, aE as ConsolidateResult, aF as ContextChatOptions, aG as ContextChatResult, aH as ContextManager, aI as ContextManagerOptions, aJ as ContextOperations, aK as ContextResetOptions, aL as ContextStreamEvent, aM as ConversationTurn, aN as ConversationTurnStatus, aO as
|
|
1
|
+
export { A as A2AAgentCardConfig, a as A2AAgentCardDocument, b as A2AApiKeySecurity, c as A2AAuthenticator, d as A2ACallOptions, e as A2ACallResult, f as A2ACallerIdentity, g as A2AConfig, h as A2AConfigSchema, i as A2AContextInfo, j as A2AHandleResult, k as A2AMessageRecord, l as A2AOperations, m as A2ASecurityConfig, n as A2ASkillConfigSchema, o as A2ATaskFilter, p as ACPAgentAdapter, q as ACPAgentAdapterInput, r as ACPAgentLaunch, s as ACPAgentSchema, t as ACPClientOptions, u as ACPConfig, v as ACPConfigInput, w as ACPConfigSchema, x as ACPCreateSessionOptions, y as ACPGitReport, z as ACPOperations, B as ACPPublishSchema, C as ACPRepositorySchema, D as ACPSessionInfo, E as ACPTransport, F as ACPWorkspaceSchema, G as AIConfig, H as AIConfigInput, I as AIConfigSchema, J as AIFunctions, K as AIInitOptions, L as AIRelStore, M as AIRelStoreCompareAndSwap, N as AIRelStoreOptions, O as AIResourceEntry, P as AIResourceRegistry, Q as AIStoreProvider, R as AIVectorBackend, S as AIVectorStore, T as AIVersionedRecord, U as AUDIO_WS_PATH, V as ApiType, W as ApiTypeSchema, X as AskOptions, Y as AssistantMessage, Z as AudioConfig, _ as AudioConfigSchema, $ as AudioFormatSchema, a0 as AudioModelEntry, a1 as AudioModelEntrySchema, a2 as AudioOperation, a3 as AudioOperationSchema, a4 as AudioOperationsSchema, a5 as AudioProviderName, a6 as AudioProviderSchema, a7 as AudioWsClientMessage, a8 as AudioWsClientMessageSchema, a9 as AudioWsDoneMessage, aa as AudioWsDoneMessageSchema, ab as AudioWsEndMessage, ac as AudioWsErrorMessage, ad as AudioWsSegmentDoneMessage, ae as AudioWsSegmentStartedMessage, af as AudioWsServerMessage, ag as AudioWsSpeechMessage, ah as AudioWsStartMessage, ai as AudioWsStartMessageSchema, aj as AudioWsTextMessage, ak as AudioWsTextMessageSchema, al as AudioWsTranscriptMessage, am as ChatCompletionChoice, an as ChatCompletionChunk, ao as ChatCompletionDelta, ap as ChatCompletionRequest, aq as ChatCompletionResponse, ar as ChatHistoryOptions, as as ChatMessage, at as ChatRecord, au as Citation, av as CommitTurnInput, aw as CompressConfig, ax as CompressConfigSchema, ay as CompressOperations, az as CompressOptions, aA as CompressResult, aB as CompressionStrategy, aC as CompressionStrategySchema, aD as ConsolidateOptions, aE as ConsolidateResult, aF as ContextChatOptions, aG as ContextChatResult, aH as ContextManager, aI as ContextManagerOptions, aJ as ContextOperations, aK as ContextResetOptions, aL as ContextStreamEvent, aM as ConversationTurn, aN as ConversationTurnStatus, aO as DeveloperMessage, aP as EmbeddingConfig, aQ as EmbeddingConfigSchema, aR as EmbeddingItem, aS as EmbeddingOperations, aT as EmbeddingRequest, aU as EmbeddingResponse, aV as EntityDocumentRelation, aW as EntityDocumentResult, aX as EntityListOptions, aY as EntityQueryOptions, aZ as EntityType, a_ as EntityTypeSchema, a$ as FileConfig, b0 as FileConfigSchema, b1 as GenerateImageRequest, b2 as GenerateImageResult, b3 as GenerateObjectRequest, b4 as GeneratedImage, b5 as HaiAIError, b6 as ImageConfig, b7 as ImageConfigSchema, b8 as ImageContent, b9 as ImageModelEntry, ba as ImageModelEntrySchema, bb as ImageOperations, bc as ImageProviderName, bd as ImageProviderSchema, be as ImageSize, bf as InteractionScope, bg as KnowledgeAskOptions, bh as KnowledgeAskResult, bi as KnowledgeConfig, bj as KnowledgeConfigSchema, bk as KnowledgeDocumentInfo, bl as KnowledgeDocumentListOptions, bm as KnowledgeDocumentMetadata, bn as KnowledgeDocumentRemoveOptions, bo as KnowledgeDocumentRevision, bp as KnowledgeEntity, bq as KnowledgeIngestBatchProgress, br as KnowledgeIngestBatchResult, bs as KnowledgeIngestFileInput, bt as KnowledgeIngestInput, bu as KnowledgeIngestResult, bv as KnowledgeOperations, bw as KnowledgeRepairOptions, bx as KnowledgeRepairProgress, by as KnowledgeRepairResult, bz as KnowledgeRetrieveItem, bA as KnowledgeRetrieveOptions, bB as KnowledgeRetrieveResult, bC as KnowledgeSetupOptions, bD as KnowledgeStore, bE as LLMConfig, bF as LLMConfigSchema, bG as LLMOperations, bH as MCPConfig, bI as MCPConfigSchema, bJ as MCPContext, bK as MCPExternalServer, bL as MCPExternalServerSchema, bM as MCPOperations, bN as MCPPrompt, bO as MCPPromptArgument, bP as MCPPromptContent, bQ as MCPPromptMessage, bR as MCPResource, bS as MCPResourceContent, bT as MCPServerCapabilities, bU as MCPServerCapabilitiesSchema, bV as MCPServerConfig, bW as MCPServerConfigSchema, bX as MCPToolDefinition, bY as MCPToolHandler, bZ as ManagedAudioOperations, b_ as ManagedImageOperations, b$ as ManagedLLMOperations, c0 as ManagedMCPOperations, c1 as ManagedRetrievalOperations, c2 as McpServerOptions, c3 as MemoryAccessScope, c4 as MemoryAdminOperations, c5 as MemoryClearAllOptions, c6 as MemoryClearOptions, c7 as MemoryConfig, c8 as MemoryConfigSchema, c9 as MemoryCoreOperations, ca as MemoryEntry, cb as MemoryEntryInput, cc as MemoryExtractOptions, cd as MemoryInjectionOptions, ce as MemoryListOptions, cf as MemoryListPageOptions, cg as MemoryOperations, ch as MemoryRecallOptions, ci as MemoryType, cj as MemoryTypeSchema, ck as MemoryUpdateInput, cl as MessageContent, cm as MessageRole, cn as ModelCapabilitiesSchema, co as ModelEntry, cp as ModelEntrySchema, cq as ModelScenario, cr as ModelScenarioSchema, cs as ObjectRef, ct as OptionalSecretSchema, cu as PersonaOperations, cv as PersonaProfile, cw as PersonaProfileInput, cx as PersonaProfileUpdate, cy as PersonaScopeOptions, cz as RagContextItem, cA as RagOperations, cB as RagOptions, cC as RagResult, cD as RagStreamEvent, cE as ReasoningOperations, cF as ReasoningOptions, cG as ReasoningResult, cH as ReasoningStep, cI as ReasoningStepType, cJ as ReasoningStrategy, cK as ReasoningStreamEvent, cL as ReferenceImage, cM as RerankDocument, cN as RerankItem, cO as RerankOperations, cP as RerankRequest, cQ as RerankResponse, cR as ResolveRequiredModelEntryOptions, cS as ResolvedAudioModel, cT as ResolvedImageModel, cU as ResolvedModelConfig, cV as RetrievalConfig, cW as RetrievalConfigSchema, cX as RetrievalOperations, cY as RetrievalRequest, cZ as RetrievalResult, c_ as RetrievalResultItem, c$ as RetrievalSource, d0 as RetrievalSourceConfig, d1 as RetrievalSourceSchema, d2 as SSEDecoder, d3 as SSEEvent, d4 as ScopedMemoryBinding, d5 as ScopedMemoryOperations, d6 as SessionInfo, d7 as StoreFilter, d8 as StorePage, d9 as StoreScope, da as StreamOperations, db as StreamProcessor, dc as StreamResult, dd as SummaryConfig, de as SummaryConfigSchema, df as SummaryOperations, dg as SummaryOptions, dh as SummaryResult, di as SystemMessage, dj as TempModelConfig, dk as TextContent, dl as TokenConfig, dm as TokenConfigSchema, dn as TokenOperations, dp as TokenUsage, dq as ToolCall, dr as ToolDefinition, ds as ToolMessage, dt as ToolRegistryOperations, du as ToolsOperations, dv as UserMessage, dw as WhereClause, dx as WhereOperator, dy as WhereValue, dz as ensureAudioCredential, dA as resolveAudioModel, dB as resolveImageModel, dC as resolveModelApi, dD as resolveModelEntry, dE as serializePlayableAudio } from './ai-acp-types-cue1ZWUk.js';
|
|
2
2
|
export { A as AudioCapabilitiesRequest, a as AudioContent, b as AudioFormat, c as AudioInputStream, d as AudioModelCapabilities, e as AudioOperations, f as AudioReference, P as PlayableAudio, S as SynthesisEvent, g as SynthesisOptions, h as SynthesisRequest, i as SynthesisResult, j as SynthesisStreamRequest, k as SynthesisTextSegment, T as TranscriptionEvent, l as TranscriptionOptions, m as TranscriptionRequest, n as TranscriptionResult, o as TranscriptionSegment, p as TranscriptionStreamRequest, q as TranscriptionTimestampGranularity, r as TranscriptionWord } from './ai-audio-types-4R5yUAVl.js';
|
|
3
3
|
export { AudioClientConfig, AudioClientOperations, AudioTicketRequest, blobToWav, createAudioClient } from './client/index.js';
|
|
4
|
+
export { F as FileOperations, a as FileParseMethod, b as FileParseOptions, c as FileParseRequest, d as FileParseResult, O as OutputFormat } from './ai-file-types-BN7l67hR.js';
|
|
4
5
|
export { AgentCapabilities, AgentCard, AgentProvider, AgentSkill, Artifact, CancelTaskRequest, GetTaskRequest, Message, Part, SendMessageRequest, StreamResponse, SubscribeToTaskRequest, Task, TaskArtifactUpdateEvent, TaskPushNotificationConfig, TaskState, TaskStatus, TaskStatusUpdateEvent } from '@a2a-js/sdk';
|
|
5
6
|
export { AgentExecutor, ExecutionEventBus } from '@a2a-js/sdk/server';
|
|
6
7
|
import '@h-ai/core';
|
|
7
8
|
import '@h-ai/runner';
|
|
8
9
|
import 'zod';
|
|
9
|
-
import 'node:buffer';
|
|
10
10
|
import '@h-ai/datapipe';
|
|
11
11
|
import 'zod/v4/core';
|
|
12
12
|
import '@agentclientprotocol/sdk';
|
|
13
|
+
import '@h-ai/tools';
|
|
13
14
|
import 'openai';
|
|
15
|
+
import '@h-ai/tools/server';
|
|
14
16
|
import '@modelcontextprotocol/sdk/types.js';
|
|
15
17
|
import 'node:http';
|
|
18
|
+
import 'node:buffer';
|
package/dist/browser.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
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, ensureAudioCredential, resolveAudioModel, resolveImageModel, resolveModelApi, resolveModelEntry, serializePlayableAudio } from './chunk-
|
|
2
|
-
export { blobToWav, createAudioClient } from './chunk-
|
|
3
|
-
|
|
1
|
+
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, ensureAudioCredential, resolveAudioModel, resolveImageModel, resolveModelApi, resolveModelEntry, serializePlayableAudio } from './chunk-IVEOIRBO.js';
|
|
2
|
+
export { blobToWav, createAudioClient } from './chunk-UVBQCI7A.js';
|
|
3
|
+
import './chunk-HZDINADT.js';
|
|
4
|
+
export { HaiAIError } from './chunk-C6T3ONVG.js';
|
|
4
5
|
//# sourceMappingURL=browser.js.map
|
|
5
6
|
//# sourceMappingURL=browser.js.map
|
|
@@ -47,12 +47,8 @@ var AIErrorInfo = {
|
|
|
47
47
|
EMBEDDING_MODEL_NOT_FOUND: "301:404",
|
|
48
48
|
EMBEDDING_INPUT_TOO_LONG: "302:400",
|
|
49
49
|
// 工具 (400-499)
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
TOOL_EXECUTION_FAILED: "402:500",
|
|
53
|
-
TOOL_TIMEOUT: "403:504",
|
|
54
|
-
TOOL_ALREADY_REGISTERED: "404:409",
|
|
55
|
-
TOOL_FORBIDDEN: "405:403",
|
|
50
|
+
TOOL_PROTOCOL_ERROR: "400:400",
|
|
51
|
+
TOOL_RESULT_ERROR: "401:500",
|
|
56
52
|
// Reasoning (500-599)
|
|
57
53
|
REASONING_FAILED: "500:500",
|
|
58
54
|
REASONING_MAX_ROUNDS: "501:400",
|
|
@@ -137,5 +133,5 @@ var AIErrorInfo = {
|
|
|
137
133
|
var HaiAIError = core.error.buildHaiErrorsDef("ai", AIErrorInfo);
|
|
138
134
|
|
|
139
135
|
export { HaiAIError };
|
|
140
|
-
//# sourceMappingURL=chunk-
|
|
141
|
-
//# sourceMappingURL=chunk-
|
|
136
|
+
//# sourceMappingURL=chunk-C6T3ONVG.js.map
|
|
137
|
+
//# sourceMappingURL=chunk-C6T3ONVG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ai-types.ts"],"names":[],"mappings":";;;AAwCA,IAAM,WAAA,GAAc;AAAA;AAAA,EAElB,cAAA,EAAgB,SAAA;AAAA,EAChB,iBAAA,EAAmB,SAAA;AAAA,EACnB,oBAAA,EAAsB,SAAA;AAAA,EACtB,mBAAA,EAAqB,SAAA;AAAA,EACrB,aAAA,EAAe,SAAA;AAAA,EACf,QAAA,EAAU,SAAA;AAAA,EACV,eAAA,EAAiB,SAAA;AAAA,EACjB,aAAA,EAAe,SAAA;AAAA,EACf,WAAA,EAAa,SAAA;AAAA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B,SAAA;AAAA,EACjB,sBAAA,EAAwB,SAAA;AAAA,EACxB,eAAA,EAAiB,SAAA;AAAA,EACjB,aAAA,EAAe,SAAA;AAAA;AAAA,EAGf,kBAAA,EAAoB,SAAA;AAAA,EACpB,kBAAA,EAAoB,SAAA;AAAA,EACpB,iBAAA,EAAmB,SAAA;AAAA,EACnB,gBAAA,EAAkB,SAAA;AAAA,EAClB,yBAAA,EAA2B,SAAA;AAAA;AAAA,EAG3B,uBAAA,EAAyB,SAAA;AAAA,EACzB,wBAAA,EAA0B,SAAA;AAAA,EAC1B,6BAAA,EAA+B,SAAA;AAAA,EAC/B,uBAAA,EAAyB,SAAA;AAAA,EACzB,sBAAA,EAAwB,SAAA;AAAA,EACxB,0BAAA,EAA4B,SAAA;AAAA,EAC5B,YAAA,EAAc,SAAA;AAAA;AAAA,EAGd,YAAA,EAAc,SAAA;AAAA,EACd,mBAAA,EAAqB,SAAA;AAAA;AAAA,EAGrB,iBAAA,EAAmB,SAAA;AAAA,EACnB,cAAA,EAAgB,SAAA;AAAA;AAAA,EAGhB,kBAAA,EAAoB,SAAA;AAAA,EACpB,iBAAA,EAAmB,SAAA;AAAA,EACnB,sBAAA,EAAwB,SAAA;AAAA,EACxB,eAAA,EAAiB,SAAA;AAAA,EACjB,wBAAA,EAA0B;AAC5B,CAAA;AAgBO,IAAM,UAAA,GAAa,IAAA,CAAK,KAAA,CAAM,iBAAA,CAAkB,MAAM,WAAW","file":"chunk-C6T3ONVG.js","sourcesContent":["import type { ErrorInfo, HaiResult } from '@h-ai/core'\nimport type { RunnerFunctions } from '@h-ai/runner'\nimport type { A2AOperations } from './a2a/ai-a2a-types.js'\nimport type { ACPPlatformPolicy } from './acp/ai-acp-platform.js'\nimport type { ACPAgentAdapter, ACPOperations } from './acp/ai-acp-types.js'\n/**\n * @h-ai/ai — 公共类型定义\n *\n * 聚合导出模块根类型和子功能类型,供外部通过 `@h-ai/ai` 一站式引入。\n * @module ai-types\n */\n\nimport type { AIConfig, AIConfigInput } from './ai-config.js'\n\nimport type { CompressOperations } from './compress/ai-compress-types.js'\nimport type { ContextOperations } from './context/ai-context-types.js'\nimport type { EmbeddingOperations } from './embedding/ai-embedding-types.js'\nimport type { FileOperations } from './file/ai-file-types.js'\nimport type { KnowledgeOperations } from './knowledge/ai-knowledge-types.js'\nimport type { StreamOperations, ToolsOperations } from './llm/ai-llm-types.js'\nimport type { MCPJobFiles } from './mcp/ai-mcp-types.js'\nimport type { MemoryOperations } from './memory/ai-memory-types.js'\nimport type { PersonaOperations } from './persona/ai-persona-types.js'\nimport type { RagOperations } from './rag/ai-rag-types.js'\nimport type { ReasoningOperations } from './reasoning/ai-reasoning-types.js'\nimport type { ManagedAudioOperations, ManagedImageOperations, ManagedLLMOperations, ManagedMCPOperations, ManagedRetrievalOperations } from './registry/ai-registry-types.js'\nimport type { RerankOperations } from './rerank/ai-rerank-types.js'\nimport type { AIStoreProvider } from './store/ai-store-types.js'\nimport type { SummaryOperations } from './summary/ai-summary-types.js'\nimport type { TokenOperations } from './token/ai-token-types.js'\nimport { core } from '@h-ai/core'\n\n// ─── 错误定义(照 @h-ai/core 范式) ───\n\n/**\n * AI 错误信息映射(错误码:HTTP状态码)。\n *\n * 错误码采用 3 位数字格式(000-999),HTTP 状态码遵循标准 HTTP 规范。\n * 完整错误码将自动生成为:`hai:ai:NNN`\n */\nconst AIErrorInfo = {\n // 通用 (000-009)\n INTERNAL_ERROR: '000:500',\n ACP_GIT_NOT_FOUND: '070:500',\n ACP_OPERATION_FAILED: '071:500',\n ACP_INVALID_REQUEST: '072:400',\n ACP_NOT_FOUND: '073:404',\n ACP_BUSY: '074:409',\n ACP_UNSUPPORTED: '075:422',\n ACP_CANCELLED: '076:499',\n ACP_TIMEOUT: '077:504',\n ACP_OUTPUT_INVALID: '078:422',\n ACP_CONFLICT: '079:409',\n ACP_PARTIAL_FAILURE: '080:409',\n ACP_CLOSED: '081:409',\n ACP_RUNTIME_UNAVAILABLE: '082:503',\n ACP_MODEL_INCOMPATIBLE: '083:422',\n ACP_CLEANUP_FAILED: '084:500',\n\n // 初始化 (010-019)\n NOT_INITIALIZED: '010:500',\n CONFIGURATION_ERROR: '011:500',\n INIT_IN_PROGRESS: '012:500',\n RERANK_API_ERROR: '020:502',\n RERANK_INVALID_REQUEST: '021:400',\n\n // LLM (100-199)\n API_ERROR: '100:502',\n INVALID_REQUEST: '101:400',\n RATE_LIMITED: '102:429',\n TIMEOUT: '103:504',\n MODEL_NOT_FOUND: '104:404',\n CONTEXT_LENGTH_EXCEEDED: '105:400',\n LLM_RECORD_FAILED: '106:500',\n LLM_HISTORY_FAILED: '107:500',\n\n // MCP (200-299)\n MCP_CONNECTION_ERROR: '200:502',\n MCP_PROTOCOL_ERROR: '201:502',\n MCP_TOOL_ERROR: '202:500',\n MCP_RESOURCE_ERROR: '203:500',\n MCP_SERVER_ERROR: '204:502',\n MCP_TOOL_FORBIDDEN: '205:403',\n MCP_TOOL_CANCELLED: '206:499',\n\n // Embedding (300-399)\n EMBEDDING_API_ERROR: '300:502',\n EMBEDDING_MODEL_NOT_FOUND: '301:404',\n EMBEDDING_INPUT_TOO_LONG: '302:400',\n\n // 工具 (400-499)\n TOOL_PROTOCOL_ERROR: '400:400',\n TOOL_RESULT_ERROR: '401:500',\n\n // Reasoning (500-599)\n REASONING_FAILED: '500:500',\n REASONING_MAX_ROUNDS: '501:400',\n REASONING_STRATEGY_NOT_FOUND: '502:404',\n\n // Retrieval (600-699)\n RETRIEVAL_FAILED: '600:500',\n RETRIEVAL_SOURCE_NOT_FOUND: '601:404',\n\n // RAG (700-799)\n RAG_FAILED: '700:500',\n RAG_CONTEXT_BUILD_FAILED: '701:500',\n\n // Knowledge (800-899)\n KNOWLEDGE_SETUP_FAILED: '800:500',\n KNOWLEDGE_INGEST_FAILED: '801:500',\n KNOWLEDGE_RETRIEVE_FAILED: '802:500',\n KNOWLEDGE_ENTITY_EXTRACT_FAILED: '803:500',\n KNOWLEDGE_NOT_SETUP: '804:500',\n KNOWLEDGE_COLLECTION_NOT_FOUND: '805:404',\n\n // Memory (900-949)\n MEMORY_EXTRACT_FAILED: '900:500',\n MEMORY_STORE_FAILED: '901:500',\n MEMORY_RECALL_FAILED: '902:500',\n MEMORY_NOT_FOUND: '903:404',\n MEMORY_ENRICH_FAILED: '904:500',\n MEMORY_PROMOTE_FAILED: '905:500',\n MEMORY_LIST_INCOMPLETE: '906:422',\n\n // Persona (910-919)\n PERSONA_NOT_FOUND: '910:404',\n PERSONA_SAVE_FAILED: '911:500',\n\n // File (030-049)\n FILE_PARSE_FAILED: '030:500',\n FILE_UNSUPPORTED_FORMAT: '031:400',\n FILE_OCR_FAILED: '032:500',\n FILE_INVALID_CONTENT: '033:400',\n\n // Audio (050-059)\n AUDIO_INVALID_REQUEST: '050:400',\n AUDIO_MODEL_NOT_FOUND: '051:404',\n AUDIO_PROVIDER_NOT_FOUND: '052:404',\n AUDIO_UNSUPPORTED_INPUT: '053:400',\n AUDIO_UPSTREAM_ERROR: '054:502',\n AUDIO_PROTOCOL_ERROR: '055:502',\n AUDIO_CONNECTION_FAILED: '056:502',\n AUDIO_TIMEOUT: '057:504',\n AUDIO_INPUT_TOO_LARGE: '058:413',\n AUDIO_CANCELLED: '059:499',\n\n // Image (060-069)\n IMAGE_INVALID_REQUEST: '060:400',\n IMAGE_MODEL_NOT_FOUND: '061:404',\n IMAGE_PROVIDER_NOT_FOUND: '062:404',\n IMAGE_UPSTREAM_ERROR: '063:502',\n IMAGE_PROTOCOL_ERROR: '064:502',\n IMAGE_CANCELLED: '065:499',\n IMAGE_DOWNLOAD_BLOCKED: '066:502',\n IMAGE_TOO_LARGE: '067:413',\n IMAGE_TIMEOUT: '068:504',\n\n // 可维护资源清单(090-094)\n RESOURCE_READ_ONLY: '090:403',\n RESOURCE_NOT_FOUND: '091:404',\n RESOURCE_CONFLICT: '092:409',\n RESOURCE_INVALID: '093:400',\n RESOURCE_OPERATION_FAILED: '094:500',\n\n // Context (950-999)\n CONTEXT_COMPRESS_FAILED: '950:500',\n CONTEXT_SUMMARIZE_FAILED: '951:500',\n CONTEXT_TOKEN_ESTIMATE_FAILED: '952:500',\n CONTEXT_BUDGET_EXCEEDED: '953:400',\n CONTEXT_TURN_NOT_FOUND: '954:404',\n CONTEXT_TURN_INVALID_STATE: '955:409',\n CONTEXT_BUSY: '956:409',\n\n // Store (960-969)\n STORE_FAILED: '960:500',\n STORE_NOT_AVAILABLE: '961:503',\n\n // Session (970-979)\n SESSION_NOT_FOUND: '970:404',\n SESSION_FAILED: '971:500',\n\n // A2A (980-999)\n A2A_NOT_CONFIGURED: '980:500',\n A2A_HANDLE_FAILED: '981:500',\n A2A_REMOTE_CALL_FAILED: '982:502',\n A2A_AUTH_FAILED: '983:401',\n A2A_LIST_MESSAGES_FAILED: '984:500',\n} as const satisfies ErrorInfo\n\n/**\n * AI 模块标准错误定义。通过错误码比较分支,用户文案由业务边界本地化。\n *\n * @example\n * ```ts\n * import { HaiAIError } from '@h-ai/ai'\n * import { err } from '@h-ai/core'\n * const result = err(HaiAIError.NOT_INITIALIZED, 'AI is not initialized')\n * if (!result.success) {\n * const status = result.error.httpStatus\n * const code = result.error.code\n * }\n * ```\n */\nexport const HaiAIError = core.error.buildHaiErrorsDef('ai', AIErrorInfo)\n\n// ─── 初始化选项 ───\n\n/**\n * AI 初始化运行时选项\n *\n * 用于传入运行时对象(如自定义 StoreProvider),\n * 这些对象无法通过 Zod 配置 Schema 传递。\n *\n * @example\n * ```ts\n * import { ai, type AIConfigInput, type AIInitOptions, type AIStoreProvider } from '@h-ai/ai'\n * async function start(config: AIConfigInput, storeProvider: AIStoreProvider) {\n * const options: AIInitOptions = { storeProvider }\n * const result = await ai.init(config, options)\n * if (!result.success) throw new Error(result.error.message)\n * }\n * ```\n */\nexport interface AIInitOptions {\n /** 由应用初始化和关闭的受管执行实例。 */\n runner?: RunnerFunctions\n /** 应用对受管 ACP 请求执行的可信授权。 */\n acpPolicy?: ACPPlatformPolicy\n /** 在作业领取者上验证文件权限、读入对象和暂存结果。 */\n mcpJobFiles?: MCPJobFiles\n /** 可信服务端扩展:为其他 ACP 智能体生成原生配置。 */\n acpAdapters?: Record<string, ACPAgentAdapter>\n /**\n * 自定义存储 Provider\n *\n * 提供后 AI 模块将使用此 Provider,而不采用自动选择的存储实现。\n * 未提供时:reldb + vecdb 已初始化则使用持久化 DB Provider,否则使用进程内临时 Provider。\n */\n storeProvider?: AIStoreProvider\n}\n\n// ─── AIFunctions 接口 ───\n\n/**\n * AI 服务接口(通过 `ai` 对象访问)\n *\n * 所有 AI 功能的统一入口,需先调用 `init()` 初始化后才能使用 `llm`、`mcp` 操作。\n * `tools` 和 `stream` 为纯函数,无需初始化即可使用。\n *\n * @example\n * ```ts\n * import { ai, type AIConfigInput, type AIInitOptions } from '@h-ai/ai'\n * // 一次性脚本示例;服务应用在启动阶段 init,在停止接入请求后 close。\n * async function run(config: AIConfigInput, options: AIInitOptions) {\n * const ready = await ai.init(config, options)\n * if (!ready.success) throw new Error(ready.error.message)\n * try {\n * const answer = await ai.llm.ask('你好', { objectId: 'user-1' })\n * if (!answer.success) throw new Error(answer.error.message)\n * return answer.data\n * }\n * finally {\n * await ai.close()\n * }\n * }\n * ```\n */\nexport interface AIFunctions {\n /**\n * 初始化 AI 服务\n *\n * 使用 Zod Schema 校验配置,失败返回 `CONFIGURATION_ERROR`。\n * 重复调用会先关闭旧实例再重新初始化。\n *\n * @param config - AI 配置(可选,默认使用空对象并应用 Schema 默认值)\n * @param options - 运行时选项(可选,用于传入自定义 StoreProvider 等运行时对象)\n * @returns 成功返回 `ok(undefined)`;配置校验失败返回 `err(HaiAIError.CONFIGURATION_ERROR)`\n */\n init: (config?: AIConfigInput, options?: AIInitOptions) => Promise<HaiResult<void>>\n /**\n * 关闭 AI 服务,释放内部状态\n *\n * 关闭后 `llm`、`mcp` 操作将返回 `NOT_INITIALIZED` 错误。\n * 重复关闭不会报错。\n */\n close: () => Promise<void>\n /** 当前脱敏后的配置快照(未初始化时为 `null`) */\n readonly config: AIConfig | null\n /** 是否已初始化(`init()` 成功后为 `true`,`close()` 后为 `false`) */\n readonly isInitialized: boolean\n /** LLM 操作(聊天、流式、模型列表),需要先调用 `init()` */\n readonly llm: ManagedLLMOperations\n /** ACP 智能体、工作区与原生会话,需要先调用 `init()`。 */\n readonly acp: ACPOperations\n /** MCP 本地函数注册及配置/数据库外部服务清单,需要先调用 `init()`。 */\n readonly mcp: ManagedMCPOperations\n /** 模型工具协议适配,工具定义和执行复用 @h-ai/tools;无需初始化 */\n readonly tools: ToolsOperations\n /** 流处理操作(流处理器、SSE 编解码),纯函数,无需初始化 */\n readonly stream: StreamOperations\n /** Embedding 操作(向量嵌入),需要先调用 `init()` */\n readonly embedding: EmbeddingOperations\n /** 推理操作(ReAct / CoT / Plan-Execute),需要先调用 `init()` */\n readonly reasoning: ReasoningOperations\n /** 检索操作(向量检索),需要先调用 `init()` */\n readonly retrieval: ManagedRetrievalOperations\n /** RAG 操作(检索增强生成),需要先调用 `init()` */\n readonly rag: RagOperations\n /** Knowledge 操作(知识库管理与检索),需要先调用 `init()` 和 `knowledge.setup()` */\n readonly knowledge: KnowledgeOperations\n /** Memory 操作(记忆提取、存储、检索、注入),需要先调用 `init()` */\n readonly memory: MemoryOperations\n /** Persona 操作(AI 角色人格档案与系统提示词组合),需要先调用 `init()` */\n readonly persona: PersonaOperations\n /** Token 操作(Token 估算),需要先调用 `init()` */\n readonly token: TokenOperations\n /** Summary 操作(消息摘要生成),需要先调用 `init()` */\n readonly summary: SummaryOperations\n /** Compress 操作(上下文压缩),需要先调用 `init()` */\n readonly compress: CompressOperations\n /** Context 操作(有状态上下文管理器,编排 LLM + Memory + RAG + Reasoning),需要先调用 `init()` */\n readonly context: ContextOperations\n /** Rerank 操作(文档重排序),需要先调用 `init()` */\n readonly rerank: RerankOperations\n /** File 操作(文件内容解析),需要先调用 `init()` */\n readonly file: FileOperations\n /** A2A 操作(Agent-to-Agent 协议),需要先调用 `init()` 并配置 `a2a` */\n readonly a2a: A2AOperations\n /** Audio 操作(语音识别 / 语音合成),需要先调用 `init()` 并配置 `audio` */\n readonly audio: ManagedAudioOperations\n /** Image 操作(文生图),需要先调用 `init()` 并配置 `image` */\n readonly image: ManagedImageOperations\n}\n"]}
|