@h-ai/ai 1.0.0-beta.2 → 1.0.0-beta.21

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.md CHANGED
@@ -4,11 +4,191 @@
4
4
 
5
5
  [框架首页](../../README.md) · 相关模块:[@h-ai/api-contract](../api-contract/README.md) · [@h-ai/core](../core/README.md) · [@h-ai/datapipe](../datapipe/README.md) · [@h-ai/reldb](../reldb/README.md) · [@h-ai/vecdb](../vecdb/README.md)
6
6
 
7
- ## 简介
8
-
9
7
  AI 能力模块,提供统一的 `ai` 服务对象,覆盖 LLM 对话、文生图、工具调用、MCP、Embedding、记忆、检索/RAG、知识库、上下文管理、文件解析、Rerank、语音(ASR/TTS)与 A2A。Node.js 侧通过 `ai.init()` 初始化,浏览器侧通过 API/client 代理访问。
10
8
 
11
- ## 核心功能清单
9
+ ## 快速开始
10
+
11
+ `ai.close()` 等待已开始的初始化完成并清理,合并并发关闭;重初始化先清理旧实例,关闭期间不接受新初始化。
12
+
13
+ ### 开发 LLM-only(零数据库依赖)
14
+
15
+ ```ts
16
+ import { ai } from '@h-ai/ai'
17
+
18
+ const init = await ai.init({
19
+ llm: {
20
+ model: 'gpt-4o-mini',
21
+ apiKey: process.env.HAI_AI_LLM_APIKEY,
22
+ },
23
+ })
24
+ if (!init.success)
25
+ throw new Error(init.error.message)
26
+
27
+ try {
28
+ const result = await ai.llm.chat({
29
+ messages: [
30
+ { role: 'user', content: '你好!' }
31
+ ],
32
+ })
33
+ if (!result.success)
34
+ throw new Error(result.error.message)
35
+ const reply = result.data.choices[0]?.message.content ?? ''
36
+ }
37
+ finally {
38
+ await ai.close()
39
+ }
40
+ ```
41
+
42
+ 开发/显式测试未初始化 reldb/vecdb 时,AI 使用进程内临时 Store;关闭、退出或切换实例后不保留。`NODE_ENV` 或 `HAI_CORE_ENV` 为 production 时,临时 Store、SQLite 或本地向量后端会使初始化失败。生产必须先初始化共享 RelDB 与网络 vecdb,或传入满足同等原子契约的共享 Provider。
43
+
44
+ ## 功能
45
+
46
+ ### 用途、输入与输出
47
+
48
+ 除标明“direct”、AsyncIterable 或 Promise 直接结果的项目外,输出列均指 HaiResult 成功后的 data;先检查 success。表中 request/definition/options 等变量必须按该行真实输入类型在应用提供,不能把类型名当成运行时值。流和显式工具可能抛错,应在消费边界处理。
49
+
50
+ 下表的调用片段复用本页已初始化的服务;命名变量代表应用已提供的请求、Schema、资源定义或配置。完整步骤和失败处理见对应功能示例。`HaiResult` 先判断 `success`,异步项按签名 `await`。
51
+
52
+ | 入口 | 场景 | 输入 | 输出 | 调用片段 |
53
+ | --------------------------------- | -------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
54
+ | `ai.llm.chat` | 单次回答 | `ChatCompletionRequest: messages, model?, signal?, tools?` | `ChatCompletionResponse: choices, model, usage?` | `ai.llm.chat({ messages: [{ role: "user", content: "你好" }] })` |
55
+ | `ai.llm.chatStream` | 逐块回答 | `same ChatCompletionRequest` | `AsyncIterable<ChatCompletionChunk>; iteration may throw` | `ai.llm.chatStream({ messages })` |
56
+ | `ai.llm.ask` | 纯文本问答 | `question: string, AskOptions?` | `string answer` | `ai.llm.ask("解释共享状态")` |
57
+ | `ai.llm.askStream` | 纯文本流 | `question: string, AskOptions?` | `AsyncIterable<string>` | `ai.llm.askStream("解释共享状态")` |
58
+ | `ai.llm.generateObject` | 受 Schema 约束的答案 | `Zod schema, messages, model?, maxRepairs?, signal?` | `schema-inferred T` | `ai.llm.generateObject({ schema: AnswerSchema, messages })` |
59
+ | `ai.llm.listModels` | 查询模型 | `none` | `string[] model IDs` | `ai.llm.listModels()` |
60
+ | `ai.llm.getHistory` | 读取对话历史 | `{ objectId, sessionId }, { limit?, order? }?` | `ChatRecord[]` | `ai.llm.getHistory({ objectId: "u1", sessionId: "s1" })` |
61
+ | `ai.llm.listSessions` | 列出主体会话 | `objectId: string` | `SessionInfo[]` | `ai.llm.listSessions("u1")` |
62
+ | `ai.tools.define` | 定义可授权工具 | `{ name, description, parameters: Zod schema, handler, timeoutMs? }` | `direct Tool<TInput,TOutput>; no init required` | `ai.tools.define(toolDefinition)` |
63
+ | `ai.tools.createRegistry` | 管理工具集合 | `{ authorize? }?` | `direct ToolRegistryOperations; no init required` | `ai.tools.createRegistry({ authorize })` |
64
+ | `ai.stream.createProcessor` | 积累增量文本 | `none` | `direct StreamProcessor` | `ai.stream.createProcessor()` |
65
+ | `ai.stream.collect` | 完整消费聊天流 | `AsyncIterable<ChatCompletionChunk>` | `Promise<StreamResult>; stream failure rejects` | `ai.stream.collect(ai.llm.chatStream({ messages }))` |
66
+ | `ai.stream.createSSEDecoder` | 跨片段解码 SSE | `none` | `direct SSEDecoder with decode/reset` | `ai.stream.createSSEDecoder()` |
67
+ | `ai.stream.encodeSSE` | 编码事件流 | `SSEEvent: data, event?, id?, retry?` | `direct string; invalid metadata throws` | `ai.stream.encodeSSE({ data: "Hello" })` |
68
+ | `ai.embedding.embed` | 通用向量请求 | `EmbeddingRequest with input/model?` | `EmbeddingResponse` | `ai.embedding.embed({ input: "产品说明" })` |
69
+ | `ai.embedding.embedText` | 单段向量 | `text: string` | `number[]` | `ai.embedding.embedText("产品说明")` |
70
+ | `ai.embedding.embedBatch` | 批量向量 | `texts: string[]` | `number[][] in input order` | `ai.embedding.embedBatch(["简介", "部署"])` |
71
+ | `ai.mcp.registerTool` | 注册本进程工具 | `MCPToolDefinition, typed handler` | `void` | `ai.mcp.registerTool(mcpToolDefinition, toolHandler)` |
72
+ | `ai.mcp.registerResource` | 注册资源 | `MCPResource, async content handler` | `void` | `ai.mcp.registerResource(resourceDefinition, readContent)` |
73
+ | `ai.mcp.registerPrompt` | 注册提示词 | `MCPPrompt, args => Promise<MCPPromptMessage[]>` | `void` | `ai.mcp.registerPrompt(promptDefinition, buildMessages)` |
74
+ | `ai.mcp.callTool` | 调用已注册工具 | `name, arguments, MCPContext?` | `unknown tool result` | `ai.mcp.callTool("search", { query: "配置" })` |
75
+ | `ai.mcp.readResource` | 读取资源 | `resource URI` | `MCPResourceContent with exactly text or blob` | `ai.mcp.readResource("docs://intro")` |
76
+ | `ai.mcp.getPrompt` | 构建提示词 | `name, Record<string,string> arguments` | `MCPPromptMessage[]` | `ai.mcp.getPrompt("review", { topic: "API" })` |
77
+ | `ai.retrieval.addSource` | 登记检索源 | `RetrievalSource: id, collection, optional metadata` | `void` | `ai.retrieval.addSource({ id: "docs", collection: "manual" })` |
78
+ | `ai.retrieval.removeSource` | 撤销检索源 | `sourceId: string` | `void` | `ai.retrieval.removeSource("docs")` |
79
+ | `ai.retrieval.listSources` | 列出可用检索源 | `none` | `direct Promise<RetrievalSource[]>` | `ai.retrieval.listSources()` |
80
+ | `ai.retrieval.retrieve` | 向量检索 | `RetrievalRequest: query, sources?, topK?, minScore?, enableRerank?` | `RetrievalResult` | `ai.retrieval.retrieve({ query: "部署" })` |
81
+ | `ai.rag.query` | 带引用回答 | `query: string, RagOptions?` | `RagResult: answer, context, citations, query, model` | `ai.rag.query("如何部署?", { sources: ["docs"] })` |
82
+ | `ai.rag.queryStream` | 带引用流式回答 | `query: string, RagOptions?` | `AsyncIterable<RagStreamEvent>` | `ai.rag.queryStream("如何部署?", { sources: ["docs"] })` |
83
+ | `ai.knowledge.setup` | 准备集合 | `KnowledgeSetupOptions?` | `void; collection ready for ingest` | `ai.knowledge.setup()` |
84
+ | `ai.knowledge.ingest` | 发布文本资料 | `{ documentId, content, title?, collection?, ...metadata }` | `KnowledgeIngestResult with revision/cleanupPending` | `ai.knowledge.ingest({ documentId: "intro", content: "入门正文" })` |
85
+ | `ai.knowledge.ingestFile` | 导入文件 | `KnowledgeIngestFileInput including file bytes and document identity` | `KnowledgeIngestResult` | `ai.knowledge.ingestFile(fileInput)` |
86
+ | `ai.knowledge.ingestBatch` | 批量导入 | `KnowledgeIngestInput[], onProgress?` | `KnowledgeIngestBatchResult with per-document outcomes` | `ai.knowledge.ingestBatch(documentInputs, onProgress)` |
87
+ | `ai.knowledge.retrieve` | 检索发布版本 | `query: string, KnowledgeRetrieveOptions?` | `KnowledgeRetrieveResult` | `ai.knowledge.retrieve("部署说明")` |
88
+ | `ai.knowledge.ask` | 基于知识回答 | `query: string, KnowledgeAskOptions?` | `KnowledgeAskResult` | `ai.knowledge.ask("如何恢复备份?")` |
89
+ | `ai.knowledge.findByEntity` | 按实体找资料 | `entityName: string, EntityQueryOptions?` | `EntityDocumentResult[]` | `ai.knowledge.findByEntity("订单")` |
90
+ | `ai.knowledge.listEntities` | 实体清单 | `EntityListOptions?` | `KnowledgeEntity[]` | `ai.knowledge.listEntities()` |
91
+ | `ai.knowledge.listDocuments` | 文档清单 | `KnowledgeDocumentListOptions?` | `KnowledgeDocumentInfo[]` | `ai.knowledge.listDocuments()` |
92
+ | `ai.knowledge.removeDocument` | 撤销文档 | `documentId, KnowledgeDocumentRemoveOptions?` | `void; may fail after visibility revocation if cleanup fails` | `ai.knowledge.removeDocument("intro")` |
93
+ | `ai.knowledge.repair` | 补偿残留向量 | `{ collection?, offset?, limit? }` | `KnowledgeRepairResult with progress` | `ai.knowledge.repair({ offset: 0, limit: 100 })` |
94
+ | `ai.knowledge.deleteCollection` | 撤销整个集合 | `collection name?` | `void; cleanup tombstone remains` | `ai.knowledge.deleteCollection("retired-manual")` |
95
+ | `ai.memory.scoped` | 绑定可信主体 | `{ objectId: nonempty string, scope? }` | `direct ScopedMemoryOperations; invalid binding throws TypeError` | `ai.memory.scoped({ objectId: "u1", scope: { topicId: "orders" } })` |
96
+ | `ai.memory.extract` | 提取事实记忆 | `ChatMessage[], { objectId, scope?, model?, signal?, ...options }` | `MemoryEntry[]` | `ai.memory.extract(messages, { objectId: "u1" })` |
97
+ | `ai.memory.add` | 保存明确事实 | `MemoryEntryInput: objectId, content, type, scope?` | `MemoryEntry` | `ai.memory.add({ objectId: "u1", content: "偏好中文", type: "preference" })` |
98
+ | `ai.memory.get` | 授权读取记忆 | `memoryId, { objectId, scope? } for untrusted IDs` | `MemoryEntry` | `ai.memory.get(memoryId, { objectId: "u1" })` |
99
+ | `ai.memory.update` | 更新已有事实 | `memoryId, MemoryUpdateInput, trusted access scope` | `MemoryEntry` | `ai.memory.update(memoryId, { content: "偏好日文" }, { objectId: "u1" })` |
100
+ | `ai.memory.remove` | 删除授权记忆 | `memoryId, trusted access scope` | `void` | `ai.memory.remove(memoryId, { objectId: "u1" })` |
101
+ | `ai.memory.recall` | 召回相关事实 | `query, { objectId, scope?, topK?, types?, ...options }` | `MemoryEntry[]` | `ai.memory.recall("语言偏好", { objectId: "u1" })` |
102
+ | `ai.memory.injectMemories` | 补充对话上下文 | `ChatMessage[], { objectId, scope?, topK?, ...options }` | `ChatMessage[]` | `ai.memory.injectMemories(messages, { objectId: "u1" })` |
103
+ | `ai.memory.list` | 读取完整列表 | `MemoryListOptions with objectId/scope filters` | `MemoryEntry[]; incomplete scan fails` | `ai.memory.list({ objectId: "u1" })` |
104
+ | `ai.memory.listPage` | 分页浏览记忆 | `MemoryListPageOptions with objectId/pagination` | `StorePage<MemoryEntry>` | `ai.memory.listPage({ objectId: "u1", offset: 0, limit: 20 })` |
105
+ | `ai.memory.clear` | 清理指定范围 | `nonempty MemoryClearOptions` | `void; empty filters are rejected` | `ai.memory.clear({ objectId: "u1" })` |
106
+ | `ai.memory.admin.clearAll` | 可信管理员全清 | `{ confirm: true }; require host administrator authorization` | `void; destructive across subjects` | `ai.memory.admin.clearAll({ confirm: true })` |
107
+ | `ai.persona.save` | 保存角色 | `PersonaProfileInput: id, name, systemPrompt, objectId?, traits?` | `PersonaProfile` | `ai.persona.save(personaProfile)` |
108
+ | `ai.persona.get` | 读取角色 | `id, { objectId }?; omitted subject selects system profile` | `PersonaProfile` | `ai.persona.get("tutor", { objectId: "u1" })` |
109
+ | `ai.persona.update` | 更新角色 | `id, PersonaProfileUpdate, { objectId }?` | `PersonaProfile` | `ai.persona.update("tutor", updates, { objectId: "u1" })` |
110
+ | `ai.persona.remove` | 删除角色 | `id, { objectId }?` | `void` | `ai.persona.remove("tutor", { objectId: "u1" })` |
111
+ | `ai.persona.list` | 列出主体角色 | `{ objectId }?` | `PersonaProfile[]` | `ai.persona.list({ objectId: "u1" })` |
112
+ | `ai.persona.compose` | 生成系统提示词 | `id, { objectId }?` | `string prompt` | `ai.persona.compose("tutor", { objectId: "u1" })` |
113
+ | `ai.token.estimateText` | 估算单段 Token | `text: string` | `direct number; estimate, not billing usage` | `ai.token.estimateText("Hello 世界")` |
114
+ | `ai.token.estimateMessages` | 估算消息 Token | `ChatMessage[]` | `direct number including protocol overhead` | `ai.token.estimateMessages(messages)` |
115
+ | `ai.summary.generate` | 生成摘要文本 | `ChatMessage[], SummaryOptions?` | `string` | `ai.summary.generate(messages)` |
116
+ | `ai.summary.summarize` | 生成摘要及覆盖信息 | `ChatMessage[], SummaryOptions?` | `{ summary, tokenCount, coveredMessages }` | `ai.summary.summarize(messages)` |
117
+ | `ai.compress.tryCompress` | 按预算压缩 | `ChatMessage[], { strategy?, maxTokens?, preserveLastN?, ...options }` | `CompressResult: messages and original/compressed token counts` | `ai.compress.tryCompress(messages, { maxTokens: 4000 })` |
118
+ | `ai.context.createManager` | 开始多轮对话 | `ContextManagerOptions with scope { objectId, sessionId }` | `ContextManager` | `ai.context.createManager({ scope: { objectId: "u1", sessionId: "s1" } })` |
119
+ | `ai.context.restoreManager` | 恢复对话 | `{ objectId, sessionId }, options?` | `ContextManager` | `ai.context.restoreManager({ objectId: "u1", sessionId: "s1" })` |
120
+ | `ai.context.listSessions` | 列出可恢复会话 | `objectId` | `SessionInfo[]` | `ai.context.listSessions("u1")` |
121
+ | `ai.context.renameSession` | 修改会话标题 | `scope, title` | `void` | `ai.context.renameSession({ objectId: "u1", sessionId: "s1" }, "订单讨论")` |
122
+ | `ai.context.removeSession` | 删除指定会话 | `scope` | `void; tombstone prevents scope reuse` | `ai.context.removeSession({ objectId: "u1", sessionId: "s1" })` |
123
+ | `ai.rerank.rerank` | 重排文档对象 | `RerankRequest: query, documents, model?, topN?` | `RerankResponse with model/results` | `ai.rerank.rerank({ query: "部署", documents: ["配置说明"] })` |
124
+ | `ai.rerank.rerankTexts` | 重排文本候选 | `query, string[] texts, topN?` | `RerankItem[] with index/relevanceScore` | `ai.rerank.rerankTexts("部署", ["配置说明"], 1)` |
125
+ | `ai.file.parse` | 识别文件并提取 | `FileParseRequest with content, filename, options?` | `FileParseResult; extraction is not HTML sanitization` | `ai.file.parse({ content: "<p>正文</p>", filename: "intro.html" })` |
126
+ | `ai.file.parseText` | 直接提取文本 | `Buffer\|string content, filename?` | `string` | `ai.file.parseText("Hello", "intro.txt")` |
127
+ | `ai.reasoning.run` | 多步骤求解 | `query, ReasoningOptions including strategy/tools?` | `ReasoningResult` | `ai.reasoning.run("审查方案", { strategy: "cot" })` |
128
+ | `ai.reasoning.runStream` | 观察推理过程 | `query, ReasoningOptions?` | `AsyncIterable<ReasoningStreamEvent>` | `ai.reasoning.runStream("审查方案", { strategy: "react" })` |
129
+ | `ai.audio.transcribe` | 识别完整音频 | `TranscriptionRequest: audio, language?, model?, signal?` | `TranscriptionResult: text, language?, segments?` | `ai.audio.transcribe({ audio: { data: wavBytes, format: "wav" } })` |
130
+ | `ai.audio.transcribeStream` | 持续语音识别 | `TranscriptionStreamRequest: chunks or complete audio` | `AsyncIterable<TranscriptionEvent>` | `ai.audio.transcribeStream(transcriptionInput)` |
131
+ | `ai.audio.synthesize` | 合成完整语音 | `SynthesisRequest: text, language?, model?, signal?` | `SynthesisResult: audio and duration metadata` | `ai.audio.synthesize({ text: "你好" })` |
132
+ | `ai.audio.synthesizeStream` | 按段合成 | `SynthesisStreamRequest: text segment or async segments` | `AsyncIterable<SynthesisEvent>` | `ai.audio.synthesizeStream(synthesisInput)` |
133
+ | `ai.audio.getCapabilities` | 先检查模型能力 | `{ operation: transcribe\|synthesize, model? }` | `AudioModelCapabilities` | `ai.audio.getCapabilities({ operation: "synthesize" })` |
134
+ | `ai.image.generate` | 生成或参考图片 | `{ prompt, referenceImages?, model?, size?, signal? }` | `{ images: GeneratedImage[] } with bytes/MIME` | `ai.image.generate({ prompt: "一座灯塔" })` |
135
+ | `ai.a2a.registerExecutor` | 注册任务执行器 | `SDK AgentExecutor` | `void` | `ai.a2a.registerExecutor(executor)` |
136
+ | `ai.a2a.getAgentCard` | 提供标准发现文档 | `none; configured a2a card` | `A2AAgentCardDocument (A2A 1.0 ProtoJSON)` | `ai.a2a.getAgentCard()` |
137
+ | `ai.a2a.handleRequest` | 处理认证的协议请求 | `unknown JSON-RPC body, trusted context.agentId?` | `direct Promise<A2AHandleResult>; JSON-RPC/SSE outcome` | `ai.a2a.handleRequest(body, { agentId: trustedAgentId })` |
138
+ | `ai.a2a.listMessages` | 可信管理查询 | `A2ATaskFilter: callerId?, contextId?, since?, pagination?` | `StorePage<A2AMessageRecord>` | `ai.a2a.listMessages(messageFilter)` |
139
+ | `ai.a2a.callRemoteAgent` | 调用获准远端 | `allowlisted HTTPS URL, message, A2ACallOptions?` | `A2ACallResult` | `ai.a2a.callRemoteAgent("https://agent.example.com/a2a", "请分析订单")` |
140
+ | `ai.init` | 准备服务 | `AIConfigInput?, AIInitOptions?` | `HaiResult<void>; validate dependencies before use` | `ai.init({ llm: { apiKey: process.env.HAI_AI_LLM_APIKEY } })` |
141
+ | `ai.close` | 反序释放服务 | `none` | `Promise<void>; wait for cleanup` | `ai.close()` |
142
+ | `ai.config` | 诊断当前配置 | `none` | `redacted AIConfig or null` | `ai.config` |
143
+ | `ai.isInitialized` | 检查生命周期状态 | `none` | `boolean` | `ai.isInitialized` |
144
+ | `ai.llm.models.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.llm.models.list()` |
145
+ | `ai.llm.models.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.llm.models.get("coding")` |
146
+ | `ai.llm.models.register` | 登记数据库定义 | `ModelEntry input (id/model/protocol/credentials/capabilities)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.llm.models.register(modelDefinition)` |
147
+ | `ai.llm.models.update` | 按版本替换定义 | `ModelEntry input (id/model/protocol/credentials/capabilities), expectedVersion?` | `HaiResult<AIResourceEntry>; full replacement, conflict fails` | `ai.llm.models.update(modelDefinition, current.data.version)` |
148
+ | `ai.llm.models.remove` | 删除数据库定义 | `id, expectedVersion?; ACP definitions must have no session references` | `HaiResult<void>; external files/services are retained` | `ai.llm.models.remove("coding", current.data.version)` |
149
+ | `ai.audio.models.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.audio.models.list()` |
150
+ | `ai.audio.models.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.audio.models.get("speech")` |
151
+ | `ai.audio.models.register` | 登记数据库定义 | `AudioModelEntry input (id/provider/model/operations)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.audio.models.register(audioModelDefinition)` |
152
+ | `ai.audio.models.update` | 按版本替换定义 | `AudioModelEntry input (id/provider/model/operations), expectedVersion?` | `HaiResult<AIResourceEntry>; full replacement, conflict fails` | `ai.audio.models.update(audioModelDefinition, current.data.version)` |
153
+ | `ai.audio.models.remove` | 删除数据库定义 | `id, expectedVersion?; ACP definitions must have no session references` | `HaiResult<void>; external files/services are retained` | `ai.audio.models.remove("speech", current.data.version)` |
154
+ | `ai.image.models.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.image.models.list()` |
155
+ | `ai.image.models.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.image.models.get("poster")` |
156
+ | `ai.image.models.register` | 登记数据库定义 | `ImageModelEntry input (id/provider/model)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.image.models.register(imageModelDefinition)` |
157
+ | `ai.image.models.update` | 按版本替换定义 | `ImageModelEntry input (id/provider/model), expectedVersion?` | `HaiResult<AIResourceEntry>; full replacement, conflict fails` | `ai.image.models.update(imageModelDefinition, current.data.version)` |
158
+ | `ai.image.models.remove` | 删除数据库定义 | `id, expectedVersion?; ACP definitions must have no session references` | `HaiResult<void>; external files/services are retained` | `ai.image.models.remove("poster", current.data.version)` |
159
+ | `ai.mcp.servers.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.mcp.servers.list()` |
160
+ | `ai.mcp.servers.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.mcp.servers.get("tools")` |
161
+ | `ai.mcp.servers.register` | 登记数据库定义 | `MCPExternalServer input (id/transport/url or command)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.mcp.servers.register(mcpServerDefinition)` |
162
+ | `ai.mcp.servers.update` | 按版本替换定义 | `MCPExternalServer input (id/transport/url or command), expectedVersion?` | `HaiResult<AIResourceEntry>; full replacement, conflict fails` | `ai.mcp.servers.update(mcpServerDefinition, current.data.version)` |
163
+ | `ai.mcp.servers.remove` | 删除数据库定义 | `id, expectedVersion?; ACP definitions must have no session references` | `HaiResult<void>; external files/services are retained` | `ai.mcp.servers.remove("tools", current.data.version)` |
164
+ | `ai.retrieval.sources.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.retrieval.sources.list()` |
165
+ | `ai.retrieval.sources.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.retrieval.sources.get("docs")` |
166
+ | `ai.retrieval.sources.register` | 登记数据库定义 | `RetrievalSource input (id/collection)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.retrieval.sources.register(sourceDefinition)` |
167
+ | `ai.retrieval.sources.update` | 按版本替换定义 | `RetrievalSource input (id/collection), expectedVersion?` | `HaiResult<AIResourceEntry>; full replacement, conflict fails` | `ai.retrieval.sources.update(sourceDefinition, current.data.version)` |
168
+ | `ai.retrieval.sources.remove` | 删除数据库定义 | `id, expectedVersion?; ACP definitions must have no session references` | `HaiResult<void>; external files/services are retained` | `ai.retrieval.sources.remove("docs", current.data.version)` |
169
+ | `ai.acp.agents.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.acp.agents.list()` |
170
+ | `ai.acp.agents.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.acp.agents.get("coder")` |
171
+ | `ai.acp.agents.register` | 登记数据库定义 | `ACPAgent input (id/mode/adapter/modelIds)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.acp.agents.register(agentDefinition)` |
172
+ | `ai.acp.agents.update` | 按版本替换定义 | `ACPAgent input (id/mode/adapter/modelIds), expectedVersion?` | `HaiResult<AIResourceEntry>; full replacement, conflict fails` | `ai.acp.agents.update(agentDefinition, current.data.version)` |
173
+ | `ai.acp.agents.remove` | 删除数据库定义 | `id, expectedVersion?; ACP definitions must have no session references` | `HaiResult<void>; external files/services are retained` | `ai.acp.agents.remove("coder", current.data.version)` |
174
+ | `ai.acp.workspaces.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.acp.workspaces.list()` |
175
+ | `ai.acp.workspaces.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.acp.workspaces.get("project")` |
176
+ | `ai.acp.workspaces.register` | 登记数据库定义 | `ACPWorkspace input (id/storage/repositories)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.acp.workspaces.register(workspaceDefinition)` |
177
+ | `ai.acp.workspaces.update` | 按版本替换定义 | `ACPWorkspace input (id/storage/repositories), expectedVersion?` | `HaiResult<AIResourceEntry>; full replacement, conflict fails` | `ai.acp.workspaces.update(workspaceDefinition, current.data.version)` |
178
+ | `ai.acp.workspaces.remove` | 删除数据库定义 | `id, expectedVersion?; ACP definitions must have no session references` | `HaiResult<void>; external files/services are retained` | `ai.acp.workspaces.remove("project", current.data.version)` |
179
+ | `ai.acp.agents.initialize` | 预检适配器配置 | `agentId, modelId?` | `HaiResult<{ agentId, mode, modelIds }>; no credentials` | `ai.acp.agents.initialize("coder")` |
180
+ | `ai.acp.agents.check` | 实际连接并握手 | `agentId, { workspaceId?, ...ACPClientOptions }` | `HaiResult<native initialize response>; owned connection is closed` | `ai.acp.agents.check("coder", { workspaceId: "project" })` |
181
+ | `ai.acp.workspaces.prepare` | 准备工作目录 | `workspaceId` | `HaiResult<main absolute path>; dirty content is retained` | `ai.acp.workspaces.prepare("project")` |
182
+ | `ai.acp.workspaces.importFiles` | 导入受控文件 | `workspaceId, { path: relative path, content: string\|Uint8Array }[]` | `HaiResult<{ imported: string[] }>; no overwrite` | `ai.acp.workspaces.importFiles("project", [{ path: "notes.txt", content: "需求" }])` |
183
+ | `ai.acp.sessions.create` | 启动受管开发会话 | `ACPCreateSessionOptions: agentId/workspaceId/newWorktree?` | `HaiResult<managed session handle>` | `ai.acp.sessions.create({ agentId: "coder", workspaceId: "project", newWorktree: true })` |
184
+ | `ai.acp.sessions.get` | 读取会话句柄 | `framework session id` | `HaiResult<managed session handle>; does not resume` | `ai.acp.sessions.get("task-1")` |
185
+ | `ai.acp.sessions.list` | 查询受管会话 | `workspaceId?` | `HaiResult<ACPSessionInfo[]>` | `ai.acp.sessions.list("project")` |
186
+ | `ai.acp.sessions.resume` | 恢复原生会话 | `framework session id, ACPClientOptions?` | `HaiResult<managed session handle>; definition changes may reject` | `ai.acp.sessions.resume("task-1")` |
187
+ | `ai.acp.sessions.close` | 停止拥有的执行环境 | `framework session id` | `HaiResult<void>; source and native history retained` | `ai.acp.sessions.close("task-1")` |
188
+ | `ai.acp.sessions.reclaimWorktree` | 回收干净检出目录 | `closed framework session id; preview stopped and changes saved` | `HaiResult<void>; branch and normal files retained` | `ai.acp.sessions.reclaimWorktree("task-1")` |
189
+ | `ai.acp.sessions.remove` | 移除会话记录 | `closed or failed framework session id` | `HaiResult<void>; worktree and native history retained` | `ai.acp.sessions.remove("task-1")` |
190
+ | `ai.acp.connect` | 接入原生传输 | `ACPTransport: stdio/http/ws, ACPClientOptions?` | `HaiResult<connection handle>` | `ai.acp.connect({ type: "http", url: "https://agent.example.com/acp" })` |
191
+ | `ai.acp.close` | 关闭子系统 | `none; normally call ai.close()` | `Promise<void>; cleanup may throw` | `ai.acp.close()` |
12
192
 
13
193
  - `ai.tools`:工具定义、注册表、批量执行;无需初始化。
14
194
  - `ai.stream`:ChatCompletion 流式 chunk 处理;无需初始化。
@@ -26,7 +206,7 @@ AI 能力模块,提供统一的 `ai` 服务对象,覆盖 LLM 对话、文生
26
206
  - `ai.a2a`:Agent-to-Agent 请求处理与远端调用。
27
207
  - `@h-ai/ai/client`:独立浏览器 Audio WebSocket 客户端。
28
208
 
29
- `@h-ai/ai/client` 仅提供 `createAudioClient({ url, getTicket })` 与 Audio 客户端类型。HTTP 使用 `@h-ai/api-client` 的 typed 领域方法;默认聊天补全非流式,流与 A2A 使用应用自行绑定的 contract。旧字符串路径客户端和重复 SSE helper 已删除,浏览器不导出 Node 单例 `ai`。
209
+ `@h-ai/ai/client` 仅提供 `createAudioClient({ url, getTicket })` 与 Audio 客户端类型。HTTP 使用 `@h-ai/api-client` 的 typed 领域方法;默认聊天补全非流式,流与 A2A 使用应用自行绑定的 contract。浏览器不导出 Node 单例 `ai`。
30
210
 
31
211
  ```ts
32
212
  import { apiClient } from '@h-ai/api-client'
@@ -35,7 +215,11 @@ const ready = await apiClient.init({ baseUrl: 'https://api.example.com/api/v1' }
35
215
  if (!ready.success)
36
216
  throw new Error(ready.error.message)
37
217
  try {
38
- const response = await apiClient.ai.chats.createCompletion({ messages: [{ role: 'user', content: '你好' }] })
218
+ const response = await apiClient.ai.chats.createCompletion({
219
+ messages: [
220
+ { role: 'user', content: '你好' }
221
+ ]
222
+ })
39
223
  if (!response.success)
40
224
  throw new Error(response.error.message)
41
225
  const reply = response.data.choices[0]?.message.content
@@ -49,34 +233,7 @@ finally {
49
233
 
50
234
  更完整的方法清单、错误码与长示例见 [REFERENCE.md](./REFERENCE.md)。
51
235
 
52
- ## 使用入门
53
-
54
- ### 快速开始
55
-
56
- #### 开发 LLM-only(零数据库依赖)
57
-
58
- ```ts
59
- import { ai } from '@h-ai/ai'
60
-
61
- const init = await ai.init({
62
- llm: {
63
- model: 'gpt-4o-mini',
64
- apiKey: process.env.HAI_AI_LLM_APIKEY,
65
- },
66
- })
67
- if (!init.success)
68
- return init
69
-
70
- const result = await ai.llm.chat({
71
- messages: [{ role: 'user', content: '你好!' }],
72
- })
73
-
74
- await ai.close()
75
- ```
76
-
77
- 开发/显式测试未初始化 reldb/vecdb 时,AI 使用进程内临时 Store;关闭、退出或切换实例后不保留。`NODE_ENV` 或 `HAI_CORE_ENV` 为 production 时,临时 Store、SQLite 或本地向量后端会使初始化失败。生产必须先初始化共享 RelDB 与网络 vecdb,或传入满足同等原子契约的共享 Provider。
78
-
79
- #### 持久化 DB Provider(reldb + vecdb)
236
+ ### 持久化 DB Provider(reldb + vecdb)
80
237
 
81
238
  ```ts
82
239
  import { ai } from '@h-ai/ai'
@@ -97,7 +254,11 @@ try {
97
254
  })
98
255
  if (!initialized.success)
99
256
  throw new Error(initialized.error.message)
100
- const result = await ai.llm.chat({ messages: [{ role: 'user', content: 'Hello!' }] })
257
+ const result = await ai.llm.chat({
258
+ messages: [
259
+ { role: 'user', content: 'Hello!' }
260
+ ]
261
+ })
101
262
  if (!result.success)
102
263
  throw new Error(result.error.message)
103
264
  const reply = result.data.choices[0]?.message.content ?? ''
@@ -119,7 +280,7 @@ if (failures.length)
119
280
 
120
281
  MySQL 首次初始化允许多个节点并发建索引:仅接受 mysql2 明确的 ER_DUP_KEYNAME/1061,并重新核对列及顺序、非唯一完整列、升序可见 BTREE 和无表达式;已有同名错误结构仍失败。账户需要建表和 INDEX 权限,元数据读取、权限或其他 DDL 错误使 ai.init 返回 CONFIGURATION_ERROR。返回前等待全部已启动 DDL 结束;MySQL DDL 不回滚,失败保留已创建结构,修复权限/结构后再重试。逐步检查初始化结果,失败不接收业务请求,并逆序关闭 AI、vecdb、reldb。
121
282
 
122
- #### 自定义 StoreProvider
283
+ ### 自定义 StoreProvider
123
284
 
124
285
  ```ts
125
286
  import type { AIStoreProvider } from '@h-ai/ai'
@@ -128,7 +289,9 @@ import { ai } from '@h-ai/ai'
128
289
  const storeProvider: AIStoreProvider = createMyStoreProvider()
129
290
 
130
291
  await ai.init(
131
- { llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY } },
292
+ {
293
+ llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY }
294
+ },
132
295
  { storeProvider },
133
296
  )
134
297
 
@@ -163,17 +326,17 @@ const controller = new AbortController()
163
326
  const cancellable = ai.llm.chat({ messages, signal: controller.signal })
164
327
  // controller.abort()
165
328
 
166
- // 多协议:模型的 api 决定底层走 Chat Completions / Responses / Anthropic,公共请求响应形状不变
329
+ // 多协议:模型的 protocol 决定底层走 Chat Completions / Responses / Anthropic,公共请求响应形状不变
167
330
  // - chat(默认):OpenAI Chat Completions(兼容绝大多数厂商)
168
331
  // - responses:OpenAI Responses API(/v1/responses)
169
332
  // - anthropic:Anthropic Messages API(Claude 原生协议,环境变量 ANTHROPIC_API_KEY / ANTHROPIC_BASE_URL)
170
- const claude = await ai.llm.chat({ messages, model: 'claude' }) // 该模型配置 api: anthropic
333
+ const claude = await ai.llm.chat({ messages, model: 'claude' }) // 该模型配置 protocol: anthropic
171
334
 
172
335
  // 临时模型:单次请求绕过配置注册模型,直接指定端点与凭据(chat/chatStream/ask/askStream 均支持)
173
336
  // 临时客户端按 TTL 缓存(llm.tempModelCacheTtl,默认 10 分钟),与常驻模型客户端隔离
174
337
  const temp = await ai.llm.chat({
175
338
  messages,
176
- tempModel: { model: 'claude-3-5-sonnet', api: 'anthropic', apiKey: 'sk-temp' },
339
+ tempModel: { model: 'claude-3-5-sonnet', protocol: 'anthropic', apiKey: process.env.TEMP_LLM_API_KEY },
177
340
  })
178
341
  ```
179
342
 
@@ -191,7 +354,9 @@ const registry = ai.tools.createRegistry({
191
354
  const registered = registry.register(ai.tools.define({
192
355
  name: 'get_weather',
193
356
  description: '获取天气',
194
- parameters: z.object({ city: z.string() }),
357
+ parameters: z.object({
358
+ city: z.string()
359
+ }),
195
360
  // handler 第二参为执行上下文:可响应取消(打断/超时)、感知截止时间与交互主体
196
361
  handler: async ({ city }, { signal }) => {
197
362
  const res = await fetch(`https://api.example.com/weather?city=${city}`, { signal })
@@ -208,12 +373,44 @@ const result = await registry.execute(toolCall, { signal: controller.signal, obj
208
373
  // 批量调用默认串行,避免副作用工具并发启动;纯读取且确认安全时才显式并行
209
374
  const batch = await registry.executeAll(toolCalls)
210
375
 
211
- const chat = await ai.llm.chat({ messages, tools: registry.getDefinitions() })
376
+ const chat = await ai.llm.chat({
377
+ messages,
378
+ tools: registry.getDefinitions()
379
+ })
212
380
  ```
213
381
 
382
+ #### ACP 智能体、工作区和会话
383
+
384
+ `ai.acp` 在 Node 服务端接入原生 ACP 智能体:`embedded` 本机进程、`builtin-service` Podman/Docker 容器(自动选择优先 Podman)、`custom-service` 已有 HTTP/WS 服务。Codex/dsh 当前使用 stdio;不自动转换不支持的传输。
385
+
386
+ Podman 关闭远程服务代理变量的自动继承;代理通过 Agent/workspace 的 `environmentRefs` 显式配置,并使用容器可达的地址。
387
+
388
+ Goose 1.57.0 镜像提供原生 `goose serve` HTTP/WS `/acp` 服务,通过 custom-service 和 `X-Secret-Key` 接入。模型由 Goose 服务维护,工作区与状态卷由部署方挂载;真实远程 E2E 按握手能力验收恢复。
389
+
390
+ - `agents.register/get/list/update/remove/initialize/check` 维护智能体。`codex`、`deepseek-harness` 适配器引用 `llm.models`;其他原生程序用 `generic` 或可信 `AIInitOptions.acpAdapters`。自定义服务自行管理模型。
391
+ - `workspaces.register/prepare/importFiles` 管理目录或持久 volume、多 Git 工程和普通文件;每个 Git 明确 `mainBranch`。prepare 不覆盖脏目录。
392
+ - 私有仓库用 workspace 的 `gitEnvironmentRefs` 将凭据仅提供给远程 Git;Agent 专用变量放在 agent 的 `environmentRefs`。旧 workspace 的 `environmentRefs` 仍共用。
393
+ - `sessions.create/resume/get/list/close` 管理会话;`newWorktree: true` 从各本地主分支建同名 worktree。可用 `repositoryId` 从指定仓库根目录启动与恢复,让 Agent 按该仓库发现规则和技能。prompt/stream/strict promptStructured、权限回调、MCP、模式配置、取消和能力检查沿用 ACP。
394
+ - `session.info().data.workspace` 在成功时提供本机或同节点卷的工作树位置,可在 Agent 关闭后用于预览。先停止预览并保存改动,再用 `sessions.reclaimWorktree(id)` 定向回收干净工作树,保留分支、普通文件、原生历史和卷。
395
+ - `session.updateMain()` 只 fetch/ff-only 更新明确主分支;`publish({ mode: 'merge-main' | 'push-branch', message, author })` 仅发布受管隔离 session,逐仓库报告部分失败,不强推。操作前停止执行环境,继续任务显式 resume。
396
+
397
+ 模型容量、模态和推理能力填 `llm.models[].capabilities`,未知不猜。Codex 要求原生 Responses;Hai 现有转换不是反向服务网关。关闭后保留代码/状态卷,确认拥有的进程停止才释放 CAS 占用;worktree 不是安全沙箱。
398
+
399
+ 接入示例与限制见 [ACP 指南](../cli/templates/skills/hai-ai/acp.md)。[Agent 镜像](models/agents/README.md) 包含 Git/Node/Python,可选 Java/Rust/Go;Codex 镜像同时含 codex-acp 和 codex。错误码为 `hai:ai:070`–`084`。普通 API 返回 HaiResult,stream 失败抛出;Node 以外不启动 Agent。
400
+
401
+ 托管 Git 遇到子模块或 Git LFS 属性时明确返回 ACP_UNSUPPORTED,避免将不完整工程报告为就绪。
402
+
403
+ #### 配置与数据库资源清单
404
+
405
+ `llm.models`、`audio.models`、`image.models`、`mcp.servers`、`retrieval.sources`、`acp.agents/workspaces` 合并配置和数据库。配置同 ID 优先且只读,数据库支持 list/get/register/update/remove;条目返回 value/source/version,更新可检查版本。异步调用读取最新定义,音频同步能力查询使用最近刷新快照。资源错误为 090–094。管理定义可能含模型密钥,仅在可信服务端使用。
406
+
407
+ [Resource catalogs](../cli/templates/skills/hai-ai/resources.md) · [ACP](../cli/templates/skills/hai-ai/acp.md)
408
+
214
409
  #### A2A 协议边界
215
410
 
216
- `ai.a2a.getAgentCard()` 返回完整 A2A 0.3 Agent Card,含 `protocolVersion`、MIME 和 streaming 能力;Kit 默认发现路径为 `/.well-known/agent-card.json`。`handleRequest()` 始终返回 JSON-RPC/SSE 处理结果,未初始化返回 JSON-RPC 错误。可信 HTTP 认证上下文的 `agentId` 映射为 executor 的 `context.user.userName`。当前支持 JSON-RPC/SSE,不声明 push notifications、gRPC 或 REST 支持;业务资源授权仍由应用负责。
411
+ 远端调用的自定义请求头按名称大小写不敏感地覆盖。固定 JSON-RPC 地址拒绝 HTTP 重定向,认证头不会被转发到重定向目标。
412
+
413
+ `ai.a2a.getAgentCard()` 返回可直接用于 HTTP 发现响应的标准 A2A 1.0 ProtoJSON,含 `supportedInterfaces`、MIME 和 streaming 能力;Kit 默认发现路径为 `/.well-known/agent-card.json`。`handleRequest()` 始终返回 JSON-RPC/SSE 处理结果,未初始化返回 JSON-RPC 错误。可信 HTTP 认证上下文的 `agentId` 映射为 executor 的 `context.user.userName`。当前支持 JSON-RPC/SSE,不声明 push notifications、gRPC 或 REST 支持;业务资源授权仍由应用负责。
217
414
 
218
415
  A2A 的 journal、context 归属与消息表在 `ai.init()` 阶段初始化。任务按可信 `agentId` 隔离(含获取、取消和续接);匿名请求共享匿名主体,生产应在可信传输层认证。`listMessages` 是服务端管理接口,支持 `callerId`、`contextId`、`since`,不能向未授权客户端暴露。
219
416
 
@@ -234,15 +431,25 @@ import { z } from 'zod'
234
431
  const server = createMcpServer({ name: 'my-server', version: '1.0.0' })
235
432
  server.registerTool('search', {
236
433
  description: '搜索',
237
- inputSchema: { query: z.string() },
434
+ inputSchema: {
435
+ query: z.string()
436
+ },
238
437
  }, async ({ query }) => ({
239
- content: [{ type: 'text', text: `Results for ${query}` }],
438
+ content: [
439
+ { type: 'text', text: `Results for ${query}` }
440
+ ],
441
+ }))
442
+ await server.connect(new StreamableHTTPServerTransport({
443
+ sessionIdGenerator: () => globalThis.crypto.randomUUID()
240
444
  }))
241
- await server.connect(new StreamableHTTPServerTransport({ sessionIdGenerator: () => globalThis.crypto.randomUUID() }))
242
445
  ```
243
446
 
244
447
  #### Memory / RAG / Knowledge
245
448
 
449
+ 原生记忆删除(包括管理员全清)先清向量,再删除权威记录;向量清理失败时记录保留以便重试。SQL 与向量后端不共享事务,后一步失败仍需核对当前状态。
450
+
451
+ `ai.memory.scoped({ objectId })` 要求非空且非纯空白的主体 ID,否则工厂立即抛 `TypeError`,不会创建未绑定实例。公共 `clear({ scope: {} })` 等空范围返回失败;跨主体全清必须调用显式管理员入口。原生记忆的访问统计与更新使用版本 CAS,迟到读取不会复活已删除记录;数据库或向量清理失败通过 HaiResult 返回,不能当作成功。
452
+
246
453
  Knowledge 每次导入生成唯一 `revision` 和分块 ID,先完整准备分块、向量及实体,再持久化暂存清单、写入向量,最后通过共享 Store CAS 一次发布正文、实体和元数据。相同文档并发重建只允许一个写入者;失败时保留完整旧版,缩短文档不会留下可见旧尾块。检索只接受当前发布版本,并在发布穿插时重试,持续冲突返回错误供调用方重试。向量候选可能按需扩大,清理积压会增加查询成本。
247
454
 
248
455
  `ingest` 成功结果包含 `revision` 与 `cleanupPending`:后者为 true 表示新版本已经发布,但旧向量删除仍待补偿。调用 `repair({ collection, offset, limit })` 分页重试;`setup` 自动检查前 100 份清单,生产环境应定期扫描全部页。暂存期限为存储端时钟的 5 分钟,超时写入者不能发布;故障暂存的永久墓碑用于反复删除迟到的外部写入,不能随日志保留期删除。SQL 与 vecdb 不组成跨库事务,恢复依赖持久清单和持续补偿。`removeDocument` / `deleteCollection` 先撤销可见性,清理失败返回错误;集合删除保留空向量集合及代际墓碑以支持补偿,重新 setup 不显示上一代内容。
@@ -260,15 +467,23 @@ if (!enriched.success) {
260
467
  }
261
468
 
262
469
  // 多租户推荐入口:scoped() 绑定主体与作用域,所有操作自动携带 objectId / scope(含归属校验),杜绝「忘记传 objectId」越权
263
- const memory = ai.memory.scoped({ objectId: 'user-001', scope: { topicId: 't-1', personaId: 'p-1' } })
470
+ const memory = ai.memory.scoped({
471
+ objectId: 'user-001',
472
+ scope: { topicId: 't-1', personaId: 'p-1' }
473
+ })
264
474
  await memory.add({ content: '用户偏好中文', type: 'preference' })
265
475
  const recalled = await memory.recall('语言偏好')
266
476
 
267
477
  // clear 拒绝空过滤(防误清全局);全局清空只能显式走管理接口
268
- await memory.clear({ types: ['event'] }) // 仅清该作用域内的 event
478
+ await memory.clear({
479
+ types: ['event']
480
+ }) // 仅清该作用域内的 event
269
481
  await ai.memory.admin.clearAll({ confirm: true }) // 危险:清空整个记忆后端,需显式确认
270
482
 
271
- const rag = await ai.rag.query('核心架构是什么?', { sources: ['docs'], topK: 5 })
483
+ const rag = await ai.rag.query('核心架构是什么?', {
484
+ sources: ['docs'],
485
+ topK: 5
486
+ })
272
487
 
273
488
  const setup = await ai.knowledge.setup()
274
489
  if (setup.success) {
@@ -299,11 +514,33 @@ await ai.init({
299
514
  audio: {
300
515
  inheritLlmApiKey: true,
301
516
  models: [
302
- { id: 'asr', provider: 'qwen', model: 'qwen3-asr-flash-realtime', operations: ['transcribe'] },
303
- { id: 'tts', provider: 'qwen', model: 'qwen3-tts-flash-realtime', operations: ['synthesize'] },
517
+ {
518
+ id: 'asr',
519
+ provider: 'qwen',
520
+ model: 'qwen3-asr-flash-realtime',
521
+ operations: ['transcribe']
522
+ },
523
+ {
524
+ id: 'tts',
525
+ provider: 'qwen',
526
+ model: 'qwen3-tts-flash-realtime',
527
+ operations: ['synthesize']
528
+ },
304
529
  // 自托管:whisper / indextts 必须显式配置 baseUrl
305
- { id: 'whisper', provider: 'whisper', model: 'faster-whisper-large-v3', operations: ['transcribe'], baseUrl: 'http://127.0.0.1:8101/v1' },
306
- { id: 'indextts', provider: 'indextts', model: 'indextts-2.5', operations: ['synthesize'], baseUrl: 'http://127.0.0.1:8102/v1' },
530
+ {
531
+ id: 'whisper',
532
+ provider: 'whisper',
533
+ model: 'faster-whisper-large-v3',
534
+ operations: ['transcribe'],
535
+ baseUrl: 'http://127.0.0.1:8101/v1'
536
+ },
537
+ {
538
+ id: 'indextts',
539
+ provider: 'indextts',
540
+ model: 'indextts-2.5',
541
+ operations: ['synthesize'],
542
+ baseUrl: 'http://127.0.0.1:8102/v1'
543
+ },
307
544
  ],
308
545
  transcribeModel: 'asr',
309
546
  synthesizeModel: 'tts',
@@ -430,6 +667,12 @@ if (result.success) {
430
667
 
431
668
  `image.maxImageBytes` 默认 20971520(20 MiB,最大 100 MiB),限制单张输出和参考图;`image.maxImages` 默认 4(最大 16),限制输出与参考图数量,临时 URL 串行下载。实际读取(含解压后)超过上限立即取消;JSON 响应最多 `max(64 KiB, 2 × maxImageBytes)`,错误正文最多 64 KiB。模型 `timeout` 默认 120000ms,覆盖厂商请求、重定向和全部下载;`signal` 可取消整个过程。输出仅支持 PNG/JPEG/GIF/WebP 的 MIME 与魔数匹配,拒绝 SVG;魔数校验不等于完整图片解码或尺寸核验。拒绝地址、超限、超时分别返回 `IMAGE_DOWNLOAD_BLOCKED`、`IMAGE_TOO_LARGE`、`IMAGE_TIMEOUT`,调用方须先检查 success。
432
669
 
670
+ #### 文件解析(File)
671
+
672
+ 向 `ai.file.parse({ content, filename, options: { outputFormat: 'markdown' } })` 传入业务文件内容和名称;先检查 `success`,再读取 `data.text`,纯文本输出选择 `outputFormat: 'text'`。HTML 使用 parse5 解析结构并迭代提取,忽略 script/style,保留标题、列表、链接、图片、引用、代码和表格等常见 Markdown 结构,不以截断正常文档规避畸形标签的正则回溯。
673
+
674
+ 结果是文本或 Markdown,不是可信 HTML;界面使用文本绑定或框架的 `MarkdownRenderer`,不要直接交给 `{@html}`。配置、调用参数和错误码保持原有契约。
675
+
433
676
  #### Context 管理器
434
677
 
435
678
  自动记忆提取在本节点后台运行;`pendingMemoryTasks=0` 不代表全部成功。`flush()` 等待本批任务,异常和失败 HaiResult 都返回 `MEMORY_EXTRACT_FAILED`(含失败数量),同轮并发观察者共享结果。返回即确认该批报告,后续只观察新任务,不自动重放可能部分完成的提取。`save()`、`reset({ waitForMemoryTasks: true })`、`consolidate()` 遇到该失败立即返回,不继续后续状态或记忆写入。进程崩溃后的外部效果仍须人工核对。
@@ -468,7 +711,10 @@ if (manager.success) {
468
711
  `chatStream` 在**调用上游模型前**就登记轮次并产出 `turn_started`(事件序列 `turn_started → delta* → done`,中途取消时 `turn_started → delta* → cancelled`)。因此即使生成到一半被 `AbortSignal` 取消,也能拿到 `turnId` 与已生成文本,用真实内容提交:
469
712
 
470
713
  ```ts
471
- const created = ai.context.createManager({ scope: { objectId: 'user-001', sessionId: 'sess-001' }, turnCommit: 'manual' })
714
+ const created = ai.context.createManager({
715
+ scope: { objectId: 'user-001', sessionId: 'sess-001' },
716
+ turnCommit: 'manual'
717
+ })
472
718
  if (!created.success)
473
719
  return created
474
720
  const m = created.data
@@ -506,7 +752,14 @@ const turns = m.getTurns()
506
752
 
507
753
  ```ts
508
754
  // 会话结束时固化:整合摘要 → 提取长期记忆(写入不含 sessionId 的持久作用域)
509
- const result = await manager.consolidate({ scope: { userId: 'user-001', personaId: 'xiaoq' } })
755
+ const created = ai.context.createManager({
756
+ scope: { objectId: 'user-001', sessionId: 'sess-001' }
757
+ })
758
+ if (!created.success)
759
+ return created
760
+ const result = await created.data.consolidate({
761
+ scope: { userId: 'user-001', personaId: 'xiaoq' }
762
+ })
510
763
  if (result.success) {
511
764
  // result.data.summary —— 本次会话整合摘要
512
765
  // result.data.memories —— 固化到长期记忆的条目
@@ -528,29 +781,114 @@ await ai.persona.save({
528
781
 
529
782
  // 组合出可直接喂给 ContextManager 的系统提示词(systemPrompt + traits)
530
783
  const composed = await ai.persona.compose('xiaoq')
784
+ if (!composed.success)
785
+ return composed
531
786
  const manager = ai.context.createManager({
532
787
  scope: { objectId: 'user-001', sessionId: 'persona-session' },
533
788
  systemPrompt: composed.data,
534
- memory: { enable: true, enableExtract: true, scope: { personaId: 'xiaoq' } },
789
+ memory: {
790
+ enable: true,
791
+ enableExtract: true,
792
+ scope: { personaId: 'xiaoq' }
793
+ },
535
794
  })
536
795
  ```
537
796
 
538
- `ai.persona` 提供 `save` / `get` / `update` / `remove` / `list` / `compose`;角色档案全局共享(不按 `objectId` 隔离)。
797
+ `ai.persona` 提供 `save` / `get` / `update` / `remove` / `list` / `compose`,按 `[objectId, id]` 隔离角色。保存时传 `objectId`,其余操作传 `{ objectId }`;省略时访问 `system` 平台角色。租户业务应绑定可信认证主体,不能把客户端传入的角色 ID 当作授权。
539
798
 
540
- ### 配置
799
+ ### 安全边界
800
+
801
+ - Prompt、检索文档和模型输出都按不可信输入处理;不要把用户内容拼进不可覆盖的系统规则。
802
+ - Zod 只校验工具参数形状,不代表调用者有权限。高权限工具必须在 handler 内再次校验身份、租户、资源归属与配额,并只把允许自动执行的工具注册给模型。
803
+ - `callRemoteAgent()` 是独立客户端能力,只依赖 `ai.init()`,不要求配置 Agent Card 或注册本地 executor。它拒绝非 HTTP(S) 和 URL 内嵌凭据,但应用仍必须对远端 origin 配置白名单,并在出口代理处限制 DNS 重绑定、重定向到私网和云元数据地址。
804
+ - 不记录完整 Prompt、工具参数、A2A headers、临时模型凭据或带 query 的远端 URL;确需审计时仅保存脱敏摘要。
805
+
806
+ ### 返回句柄的用法
807
+
808
+ `registry` 来自 `ai.tools.createRegistry()`;`manager` 来自 `ai.context.createManager/restoreManager` 成功后的 data;`session` 来自受管 ACP sessions.create/get/resume 的 data,`connection` 来自 `ai.acp.connect` 的 data。每种句柄只在自己的生命周期及授权范围内使用。scoped Memory 的十个方法与上表同名,主体/作用域已由工厂绑定,不再接受 objectId/scope 覆盖。
809
+
810
+ | 入口 | 场景 | 输入 | 输出 | 调用片段 |
811
+ | -------------------------- | ------------------ | ---------------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------- |
812
+ | `registry.register` | 登记单个工具 | `Tool` | `HaiResult<void>; duplicate rejected` | `registry.register(tool)` |
813
+ | `registry.registerMany` | 批量登记工具 | `Tool[]` | `HaiResult<void>` | `registry.registerMany(tools)` |
814
+ | `registry.replace` | 显式替换工具 | `Tool with existing name` | `HaiResult<void>` | `registry.replace(tool)` |
815
+ | `registry.unregister` | 移除工具 | `tool name` | `boolean` | `registry.unregister("search")` |
816
+ | `registry.get` | 读取工具定义 | `tool name` | `Tool or undefined` | `registry.get("search")` |
817
+ | `registry.has` | 检查工具存在 | `tool name` | `boolean` | `registry.has("search")` |
818
+ | `registry.getNames` | 工具名称 | `none` | `string[]` | `registry.getNames()` |
819
+ | `registry.getDefinitions` | 传给模型的定义 | `none` | `ToolDefinition[]` | `registry.getDefinitions()` |
820
+ | `registry.execute` | 授权后执行工具 | `ToolCall, ToolExecutionOptions?` | `Promise<HaiResult<ToolMessage>>` | `registry.execute(toolCall, { objectId: "u1" })` |
821
+ | `registry.executeAll` | 逐个或显式并行执行 | `ToolCall[], { parallel?, ...executionOptions }` | `Promise<HaiResult<ToolMessage[]>>` | `registry.executeAll(toolCalls)` |
822
+ | `registry.clear` | 清理本地工具 | `none` | `void` | `registry.clear()` |
823
+ | `registry.size` | 工具数量 | `none` | `number` | `registry.size` |
824
+ | `manager.addMessage` | 补充对话消息 | `ChatMessage` | `Promise<HaiResult<void>>` | `manager.addMessage({ role: "user", content: "你好" })` |
825
+ | `manager.getMessages` | 读取对话快照 | `none` | `HaiResult<ChatMessage[]>` | `manager.getMessages()` |
826
+ | `manager.reload` | 刷新共享快照 | `none` | `Promise<HaiResult<void>>` | `manager.reload()` |
827
+ | `manager.getTokenUsage` | 观察上下文预算 | `none` | `HaiResult<{ current, budget }>` | `manager.getTokenUsage()` |
828
+ | `manager.getSummaries` | 读取摘要 | `none` | `HaiResult<SummaryResult[]>` | `manager.getSummaries()` |
829
+ | `manager.save` | 持久保存 | `none` | `Promise<HaiResult<void>>` | `manager.save()` |
830
+ | `manager.flush` | 等待后台记忆写入 | `none` | `Promise<HaiResult<void>>` | `manager.flush()` |
831
+ | `manager.reset` | 终止并重置对话 | `ContextResetOptions?` | `Promise<HaiResult<void>>` | `manager.reset({ preserveSystemPrompt: true })` |
832
+ | `manager.getTurns` | 读取真实轮次 | `none` | `HaiResult<ConversationTurn[]>` | `manager.getTurns()` |
833
+ | `manager.markTurnSpeaking` | 记录开始播放 | `turnId` | `Promise<HaiResult<void>>` | `manager.markTurnSpeaking(turnId)` |
834
+ | `manager.commitTurn` | 提交已表达内容 | `turnId, { text? }` | `Promise<HaiResult<void>>` | `manager.commitTurn(turnId, { text: spokenText })` |
835
+ | `manager.interruptTurn` | 提交打断前内容 | `turnId, { text? }` | `Promise<HaiResult<void>>` | `manager.interruptTurn(turnId, { text: spokenText })` |
836
+ | `manager.consolidate` | 固化长期记忆 | `ConsolidateOptions?` | `Promise<HaiResult<{ summary, memories }>>` | `manager.consolidate({ scope: { personaId: "tutor" } })` |
837
+ | `manager.chat` | 多轮回答 | `message: string, ContextChatOptions?` | `Promise<HaiResult<ContextChatResult>>` | `manager.chat("请继续")` |
838
+ | `manager.chatStream` | 多轮流式回答 | `message: string, ContextChatOptions?` | `AsyncIterable<ContextStreamEvent>` | `manager.chatStream("请继续")` |
839
+ | `session.info` | 读取受管会话 | `none` | `Promise<HaiResult<ACPSessionInfo>>` | `session.info()` |
840
+ | `session.prompt` | 执行一轮开发 | `ContentBlock[], AbortSignal?` | `Promise<HaiResult<{ text, stopReason, events }>>` | `session.prompt([{ type: "text", text: "检查工程" }])` |
841
+ | `session.promptStructured` | 校验一份 JSON | `ContentBlock[], Zod schema, AbortSignal?` | `Promise<HaiResult<schema-inferred T>>` | `session.promptStructured(content, OutputSchema)` |
842
+ | `session.stream` | 观察原生事件 | `ContentBlock[], AbortSignal?` | `AsyncIterable<SessionNotification>; failure throws` | `session.stream([{ type: "text", text: "检查工程" }])` |
843
+ | `session.cancel` | 取消当前轮次 | `none` | `Promise<HaiResult<void>>` | `session.cancel()` |
844
+ | `session.setMode` | 选择已公布模式 | `native mode ID` | `Promise<HaiResult<native mode response>>` | `session.setMode("code")` |
845
+ | `session.setConfigOption` | 设置已公布选项 | `native option key and allowed value` | `Promise<HaiResult<native config response>>` | `session.setConfigOption("model", "coding")` |
846
+ | `session.updateMain` | 仅快进更新主分支 | `none; execution and preview must be stopped` | `Promise<HaiResult<ACPGitReport[]>>; partial failure reports in cause` | `session.updateMain()` |
847
+ | `session.publish` | 提交并推送 | `{ mode, message, author }; managed isolated session only` | `Promise<HaiResult<ACPGitReport[]>>` | `session.publish(publishOptions)` |
848
+ | `session.close` | 停止执行保留状态 | `none` | `Promise<HaiResult<void>>` | `session.close()` |
849
+ | `connection.authenticate` | 原生认证 | `advertised authentication method ID` | `Promise<HaiResult<native auth response>>` | `connection.authenticate("api-key")` |
850
+ | `connection.createSession` | 创建低层原生会话 | `absolute remote cwd, McpServer[]?` | `Promise<HaiResult<{ id, prompt, cancel }>>` | `connection.createSession("/workspace/project", [])` |
851
+ | `connection.listSessions` | 原生分页会话 | `cursor?` | `Promise<HaiResult<native paginated response>>` | `connection.listSessions()` |
852
+ | `connection.deleteSession` | 删除原生会话 | `native session ID` | `Promise<HaiResult<native delete response>>` | `connection.deleteSession(nativeId)` |
853
+ | `connection.close` | 关闭低层连接 | `none` | `Promise<HaiResult<void>>` | `connection.close()` |
854
+
855
+ ## 配置
856
+
857
+ ### 按场景选择配置入口
858
+
859
+ | 配置入口 | 场景 | 输入 | 生效结果 | 示例 |
860
+ | ----------- | ------------------ | -------------------------------------------------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
861
+ | `llm` | 模型连接与请求协议 | model, protocol, apiKey/baseUrl, timeout, models/scenarios | chat/Responses/Anthropic selection; normalized model requests | `{ llm: { model: "gpt-4o-mini", timeout: 60000 } }` |
862
+ | `embedding` | 检索向量 | model?, dimensions?, batchSize? | consistent vector dimensions for the target collection | `{ embedding: { dimensions: 1536, batchSize: 100 } }` |
863
+ | `mcp` | 外部工具服务 | servers with transport/endpoints or commands | registered server definitions; application authorizes tool execution | `{ mcp: { servers: [] } }` |
864
+ | `retrieval` | 默认信源 | sources: { id, collection, topK?, minScore?, filter? }[] | queryable source definitions; does not import documents | `{ retrieval: { sources: [{ id: "docs", collection: "manual", topK: 5 }] } }` |
865
+ | `knowledge` | 文档发布与分块 | collection, dimension, cleanOptions, chunkOptions | versioned document/vector publication and bounded chunks | `{ knowledge: { collection: "manual", dimension: 1536, chunkOptions: { maxSize: 1500, overlap: 200 } } }` |
866
+ | `memory` | 主体记忆后端和预算 | provider, quotas, recencyDecay, defaultTopK, candidateMultiplier | native or Mem0-format behavior with explicit persistence limits | `{ memory: { provider: "native", defaultTopK: 10 } }` |
867
+ | `token` | Token 估算 | tokenRatio > 0; default 0.25 | local token budget estimates; not provider billing usage | `{ token: { tokenRatio: 0.25 } }` |
868
+ | `summary` | 摘要规则 | systemPrompt? | prompt used by summary generation; model from llm.scenarios | `{ summary: { systemPrompt: "保留已确认决策和待办" } }` |
869
+ | `compress` | 上下文压缩预算 | defaultStrategy, defaultMaxTokens, preserveLastN | compression defaults; 0 budget derives from model limit | `{ compress: { defaultStrategy: "hybrid", defaultMaxTokens: 4000, preserveLastN: 4 } }` |
870
+ | `file` | OCR 提取规则 | systemPrompt?; model via llm.scenarios.ocr | text extraction instructions; not HTML sanitization | `{ file: { systemPrompt: "只提取可见文字" } }` |
871
+ | `audio` | 语音模型与容量 | models, transcribeModel/synthesizeModel, maxAudioBytes/maxStreamDurationMs | provider capability/operation selection and bounded input/stream | `see Audio examples` |
872
+ | `image` | 图像模型与下载预算 | models, generateModel, maxImageBytes, maxImages; timeout per model | generated bytes with MIME; unsafe downloads rejected | `see Image examples` |
873
+ | `a2a` | 代理发现与执行租约 | agentCard and execution lease/poll/deadline options | ProtoJSON discovery and shared task journal | `see A2A protocol section` |
874
+ | `acp` | 智能体执行约束 | agents/workspaces and execution content/event limits | validated definitions and managed native sessions | `see ACP guide` |
875
+
876
+ Rerank 继承全局 LLM timeout,模型条目可覆盖;同一预算覆盖请求及响应正文,超时返回 RERANK_API_ERROR。
877
+
878
+ 模型请求协议通过 `llm.protocol`、`llm.models[].protocol` 或单次 `tempModel.protocol` 指定,支持 `chat | responses | anthropic`。环境变量为 `HAI_AI_LLM_PROTOCOL`、`HAI_AI_LLM_MODELS_0_PROTOCOL`(模型项按索引递增);凭据通过 `apiKey` 或相应私有环境提供。
541
879
 
542
880
  ```yaml
543
881
  llm:
544
882
  apiKey: ''
545
883
  baseUrl: https://api.openai.com/v1
546
884
  model: gpt-4o-mini
547
- api: chat # chat(默认)| responses | anthropic —— 底层 API 协议,对使用方透明
885
+ protocol: chat # chat(默认)| responses | anthropic —— 底层 API 协议,对使用方透明
548
886
  timeout: 60000
549
887
  tempModelCacheTtl: 600000 # 临时模型客户端缓存 TTL(毫秒,默认 10 分钟)
550
888
  models: # 可为每个模型单独指定协议
551
889
  - {id: fast, model: gpt-4o-mini}
552
- - {id: strong, model: gpt-4.1, api: responses}
553
- - {id: claude, model: claude-3-5-sonnet-latest, api: anthropic}
890
+ - {id: strong, model: gpt-4.1, protocol: responses}
891
+ - {id: claude, model: claude-3-5-sonnet-latest, protocol: anthropic}
554
892
  scenarios:
555
893
  chat: fast
556
894
  reasoning: strong
@@ -585,7 +923,7 @@ memory:
585
923
  通过 `core.config.load('ai', ...)` 加载时,约定环境变量优先于 YAML;
586
924
  例如 `HAI_AI_LLM_APIKEY`、`HAI_AI_LLM_BASEURL`、`HAI_AI_LLM_MODEL`。
587
925
 
588
- 启用 mem0(真·嵌入式 mem0ai/oss 引擎):
926
+ 启用 Mem0 数据格式适配:
589
927
 
590
928
  ```yaml
591
929
  memory:
@@ -594,17 +932,15 @@ memory:
594
932
  ```
595
933
 
596
934
  - **`native`(默认,推荐)**:HAI 原生引擎,复用同一套 vecdb(向量库)、reldb(关系库)、LLM 与 Embedding。`extract` 采用 **Mem0 式批量合并**——一次 LLM 调用对整批抽取事实与相关既有记忆做 ADD / UPDATE / DELETE / NONE 决策,实现增量更新、跨条去重与矛盾删除,并支持 `category` 主题标签。`maxEntriesPerObject`、`maxEntriesGlobal`、`recencyDecay`、`embeddingEnabled`、`writebackRelatedTopK` 均作用于此后端;淘汰按 `objectId` 分区触发,不会因某一主体写入过多而淘汰其他主体的记忆。native 后端的 `scope` 过滤:候选集已被 `objectId` 索引收窄(≤ `maxEntriesPerObject`),PostgreSQL 上还会把 scope 下推为 `data @> '{"scope":...}'::jsonb` 包含查询并命中 JSONB **GIN 索引**(SQLite / MySQL 退回内存匹配,结果一致)。
597
- - **`mem0`(真·mem0ai/oss)**:直接使用 `mem0ai/oss` 的 `Memory` 引擎(嵌入式,无云服务)。LLM / Embedder 从 `llm` 配置提取;`qdrant` 可复用底层 vecdb。当前适配仅映射带完整连接参数的 `qdrant`;生产环境(`NODE_ENV` 或 `HAI_CORE_ENV` 为 `production`)即使设置 `memory.allowEphemeralFallback: true` 也拒绝实际内存回退。临时回退仅限开发或明确的 `HAI_E2E=1` / `HAI_E2E_MOCK=1`;缺少后端同样不能在生产启动。历史记录默认禁用。
598
-
599
- 两个 Provider 对外 `ai.memory.*` API 完全一致(`extract` / `recall` / `injectMemories` / `add` / `update` / `get` / `remove` / `list` / `listPage` / `clear`),均支持 `objectId`(主体隔离)与 `scope`(业务作用域 key-value 过滤,如 `{ topicId, personaId }`)。`recall` / `list` / `listPage` / `clear` 均按 `scope` 严格过滤,`clear` 在传入 `types` / `scope` 时仅删除同时匹配项(避免误删)。mem0 后端的 `extract` 在框架层用统一提取器完成分类与打分(honor `types` / `model` / `minImportance` / `systemPrompt`)后以 `infer:false` 写入,保留 `hai_type` / `hai_importance`;`recall` 同样支持 `types` 过滤与 `recencyWeight` 时间衰减——二者行为与 native 一致。Mem0 的 `update` 使用 SDK 原地修改文本与元数据,保持 `id` 和创建时间。SDK 查询使用 `filters.user_id`,写入和整主体删除使用 `userId`。SDK 无列表游标:`list` / `listPage` / 条件 `clear` 最多支持每主体 1000 条原始候选(含过期条目),多取一条探测完整性;超限返回 `MEMORY_LIST_INCOMPLETE`(906),不会伪造 total 或执行部分条件删除。候选完整时按 UTC 日期剔除过期项,再按类型/scope 过滤和分页;仅 `objectId` 的清理使用 SDK `deleteAll`,不受列表上限限制。公共空条件清理被拒绝;跨主体全清仅限受信管理员显式 `admin.clearAll({ confirm: true })`。
935
+ - **`mem0`(数据格式适配)**:框架负责提取与 Embedding,通过原生 HTTP 读写 Qdrant 的 Mem0 UUID/payload 格式,可读取既有数据;不运行完整上游引擎、遥测或历史数据库。仅映射带完整连接参数的 Qdrant。生产(`NODE_ENV` 或 `HAI_CORE_ENV=production`)拒绝临时回退;开发或明确 E2E 可显式使用 `memory.allowEphemeralFallback: true`。其它持久化后端选择 `native`。
600
936
 
601
- Mem0 3.3.1 的 Qdrant 适配仍依赖 `QdrantClient.search`;项目将 `@qdrant/js-client-rest` 精确锁定为受测的 `1.18.0`,AI 的可选 peer 也声明此版本。启动会检查该公开方法,缺失时明确配置失败;不要覆盖为已移除此方法的 1.19。
937
+ 两个 Provider 对外 `ai.memory.*` API 完全一致(`extract` / `recall` / `injectMemories` / `add` / `update` / `get` / `remove` / `list` / `listPage` / `clear`),均支持 `objectId`(主体隔离)与 `scope`(业务作用域 key-value 过滤,如 `{ topicId, personaId }`)。`recall` / `list` / `listPage` / `clear` 均按 `scope` 严格过滤,`clear` 在传入 `types` / `scope` 时仅删除同时匹配项(避免误删)。mem0 后端的 `extract` 在框架层用统一提取器完成分类与打分(honor `types` / `model` / `minImportance` / `systemPrompt`)后直接写入格式存储,保留 `hai_type` / `hai_importance`;`recall` 同样支持 `types` 过滤与 `recencyWeight` 时间衰减——二者行为与 native 一致。Mem0 的 `update` 原地修改文本与元数据,保持 `id` 和创建时间。候选扫描有界:`list` / `listPage` / 条件 `clear` 最多支持每主体 1000 条原始候选(含过期条目),多取一条探测完整性;超限返回 `MEMORY_LIST_INCOMPLETE`(906),不会伪造 total 或执行部分条件删除。候选完整时按 UTC 日期剔除过期项,再按类型/scope 过滤和分页;仅 `objectId` 的清理使用后端过滤删除,不受列表上限限制。公共空条件清理被拒绝;跨主体全清仅限受信管理员显式 `admin.clearAll({ confirm: true })`。
602
938
 
603
- 适配器通过 SDK 公开的 `client` 配置注入独享客户端;Mem0 的 Qdrant 写入与删除均使用 `wait: true`,等待服务端应用完成后才继续写后读或分批清理。
939
+ Mem0 格式存储与 VecDB 的 Qdrant Provider 均使用原生 HTTP,无需额外 SDK。固定 REST 请求使用 `query`,路径段编码;30 秒超时覆盖完整响应体,响应超过 16 MiB 明确失败。写入和删除等待 `wait=true` 的实际完成回执。列表和条件清理最多核对每主体 1000 条原始候选(包括过期项),超限返回 `MEMORY_LIST_INCOMPLETE`,不执行部分条件删除;仅按主体清理不受此列表上限限制。
604
940
 
605
- Mem0 的 pgvector 组合在所有环境拒绝启动:当前 SDK 将 PostgreSQL 连接保存在私有对象中,未提供公开关闭入口,框架无法履行资源清理契约。需要 pgvector 时选择 `memory.provider: native`;该原生后端保持支持。`disableHistory: true` 使用 SDK 无资源的历史占位实现,不创建历史 SQLite 文件。工厂通过公开的一条有界只读查询等待实际后端 ready 后才发布成功。
941
+ Qdrant 格式后端要求 1.19 或更新版本,并拒绝 HTTP 重定向。更新使用服务端 `update_only` 与主体/版本条件,同一次原子写入拒绝已删除或已被其它写入更新的条目;迟到更新不会复活删除记录。写后版本核对失败仍需按已有回执核对实际效果。
606
942
 
607
- `add` / `extract` 的 SDK 回执不含完整业务字段,框架写后读取权威记录再返回;并发提取等待全部在途写入结束。若写入或写后读失败,`error.ext.requiresEffectReconciliation=true`,`memoryIds` 保存已知写入 ID(回执丢失时可能为空)。应按主体核对实际记忆后决定恢复,不能盲目重做 add/extract;框架不自动重放。
943
+ `add` / `extract` 的写入回执不含完整业务字段,框架写后读取权威记录再返回;并发提取等待全部在途写入结束。若写入或写后读失败,`error.ext.requiresEffectReconciliation=true`,`memoryIds` 保存已知写入 ID(回执丢失时可能为空)。应按主体核对实际记忆后决定恢复,不能盲目重做 add/extract;框架不自动重放。
608
944
 
609
945
  **候选池与 scope 漏召回**:`scope` 过滤在内存中完成,若先按 `topK` 截断再过滤,同一主体下相关度较高的其它主题/角色记忆会把目标 scope 的记忆挤出候选池,导致「明明有却召回 0 条」。为此 `recall` / `injectMemories` 先取回 `topK × candidateMultiplier`(默认 5)条候选,过滤后再截取 `topK`。scope 隔离越细(如按 `topicId` + `personaId`),可将 `candidateMultiplier` 调大:
610
946
 
@@ -619,14 +955,7 @@ const memories = await ai.memory.recall('经济发展', {
619
955
 
620
956
  `ai.config` 返回脱敏后的配置快照;`apiKey`、`privateKey`、URL 内嵌凭证等敏感字段不会原样暴露。
621
957
 
622
- ### 安全边界
623
-
624
- - Prompt、检索文档和模型输出都按不可信输入处理;不要把用户内容拼进不可覆盖的系统规则。
625
- - Zod 只校验工具参数形状,不代表调用者有权限。高权限工具必须在 handler 内再次校验身份、租户、资源归属与配额,并只把允许自动执行的工具注册给模型。
626
- - `callRemoteAgent()` 是独立客户端能力,只依赖 `ai.init()`,不要求配置 Agent Card 或注册本地 executor。它拒绝非 HTTP(S) 和 URL 内嵌凭据,但应用仍必须对远端 origin 配置白名单,并在出口代理处限制 DNS 重绑定、重定向到私网和云元数据地址。
627
- - 不记录完整 Prompt、工具参数、A2A headers、临时模型凭据或带 query 的远端 URL;确需审计时仅保存脱敏摘要。
628
-
629
- ### 错误处理
958
+ ## 错误处理
630
959
 
631
960
  ```ts
632
961
  const result = await ai.llm.chat({ messages })