@h-ai/ai 1.0.0-beta.3 → 1.0.0-beta.30
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 +567 -69
- package/README.ja.md +568 -70
- package/README.md +569 -71
- package/dist/{ai-audio-ws-protocol-1VhScfis.d.ts → ai-acp-types-DuPV5UGi.d.ts} +4922 -333
- package/dist/browser.d.ts +8 -5
- package/dist/browser.js +3 -3
- package/dist/{chunk-GMQFIWND.js → chunk-ILUCWONQ.js} +101 -13
- package/dist/chunk-ILUCWONQ.js.map +1 -0
- package/dist/{chunk-GAC5RLAG.js → chunk-LENTVEBE.js} +566 -45
- package/dist/chunk-LENTVEBE.js.map +1 -0
- package/dist/{chunk-HYMP57AC.js → chunk-NRDLMUSY.js} +25 -2
- package/dist/chunk-NRDLMUSY.js.map +1 -0
- package/dist/client/index.d.ts +28 -2
- package/dist/client/index.js +2 -2
- package/dist/index.d.ts +9 -13
- package/dist/index.js +10537 -1966
- package/dist/index.js.map +1 -1
- package/models/agents/README.md +119 -0
- package/models/agents/build.mjs +177 -0
- package/models/agents/codex-acp/Dockerfile +21 -0
- package/models/agents/codex-acp/agent.json +16 -0
- package/models/agents/deepseek-harness/Dockerfile +18 -0
- package/models/agents/deepseek-harness/agent.json +14 -0
- package/models/agents/goose/Dockerfile +29 -0
- package/models/agents/goose/agent.json +14 -0
- package/package.json +27 -31
- package/tools/.dockerignore +4 -0
- package/tools/README.md +111 -0
- package/tools/archives.py +56 -0
- package/tools/browser/Dockerfile +19 -0
- package/tools/browser/operation.py +50 -0
- package/tools/browser/render.mjs +40 -0
- package/tools/documents/Dockerfile +20 -0
- package/tools/documents/operation.py +80 -0
- package/tools/ocr/Dockerfile +19 -0
- package/tools/ocr/operation.py +18 -0
- package/tools/office/Dockerfile +21 -0
- package/tools/office/office_job.py +65 -0
- package/tools/office/operation.py +43 -0
- package/tools/tests/image-smoke.mjs +83 -0
- package/tools/tests/test_hai_tool.py +82 -0
- package/tools/tool.py +145 -0
- package/dist/chunk-GAC5RLAG.js.map +0 -1
- package/dist/chunk-GMQFIWND.js.map +0 -1
- package/dist/chunk-HYMP57AC.js.map +0 -1
package/README.md
CHANGED
|
@@ -4,11 +4,193 @@
|
|
|
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?, responseFormat?, 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.mcp.services.invoke` | 调用授权的远程工具 | 请求、认证主体和授权函数 | `HaiResult<CallToolResult>` | `ai.mcp.services.invoke(request, authorization)` |
|
|
78
|
+
| `ai.mcp.services.createBroker` | 为 ACP 会话挂载工具入口 | 固定 URL 和实时授权函数 | `HaiResult<MCPServiceBroker>` | `ai.mcp.services.createBroker(brokerOptions)` |
|
|
79
|
+
| `ai.retrieval.addSource` | 登记检索源 | `RetrievalSource: id, collection, optional metadata` | `void` | `ai.retrieval.addSource({ id: "docs", collection: "manual" })` |
|
|
80
|
+
| `ai.retrieval.removeSource` | 撤销检索源 | `sourceId: string` | `void` | `ai.retrieval.removeSource("docs")` |
|
|
81
|
+
| `ai.retrieval.listSources` | 列出可用检索源 | `none` | `direct Promise<RetrievalSource[]>` | `ai.retrieval.listSources()` |
|
|
82
|
+
| `ai.retrieval.retrieve` | 向量检索 | `RetrievalRequest: query, sources?, topK?, minScore?, enableRerank?` | `RetrievalResult` | `ai.retrieval.retrieve({ query: "部署" })` |
|
|
83
|
+
| `ai.rag.query` | 带引用回答 | `query: string, RagOptions?` | `RagResult: answer, context, citations, query, model` | `ai.rag.query("如何部署?", { sources: ["docs"] })` |
|
|
84
|
+
| `ai.rag.queryStream` | 带引用流式回答 | `query: string, RagOptions?` | `AsyncIterable<RagStreamEvent>` | `ai.rag.queryStream("如何部署?", { sources: ["docs"] })` |
|
|
85
|
+
| `ai.knowledge.setup` | 准备集合 | `KnowledgeSetupOptions?` | `void; collection ready for ingest` | `ai.knowledge.setup()` |
|
|
86
|
+
| `ai.knowledge.ingest` | 发布文本资料 | `{ documentId, content, title?, collection?, ...metadata }` | `KnowledgeIngestResult with revision/cleanupPending` | `ai.knowledge.ingest({ documentId: "intro", content: "入门正文" })` |
|
|
87
|
+
| `ai.knowledge.ingestFile` | 导入文件 | `KnowledgeIngestFileInput including file bytes and document identity` | `KnowledgeIngestResult` | `ai.knowledge.ingestFile(fileInput)` |
|
|
88
|
+
| `ai.knowledge.ingestBatch` | 批量导入 | `KnowledgeIngestInput[], onProgress?` | `KnowledgeIngestBatchResult with per-document outcomes` | `ai.knowledge.ingestBatch(documentInputs, onProgress)` |
|
|
89
|
+
| `ai.knowledge.retrieve` | 检索发布版本 | `query: string, KnowledgeRetrieveOptions?` | `KnowledgeRetrieveResult` | `ai.knowledge.retrieve("部署说明")` |
|
|
90
|
+
| `ai.knowledge.ask` | 基于知识回答 | `query: string, KnowledgeAskOptions?` | `KnowledgeAskResult` | `ai.knowledge.ask("如何恢复备份?")` |
|
|
91
|
+
| `ai.knowledge.findByEntity` | 按实体找资料 | `entityName: string, EntityQueryOptions?` | `EntityDocumentResult[]` | `ai.knowledge.findByEntity("订单")` |
|
|
92
|
+
| `ai.knowledge.listEntities` | 实体清单 | `EntityListOptions?` | `KnowledgeEntity[]` | `ai.knowledge.listEntities()` |
|
|
93
|
+
| `ai.knowledge.listDocuments` | 文档清单 | `KnowledgeDocumentListOptions?` | `KnowledgeDocumentInfo[]` | `ai.knowledge.listDocuments()` |
|
|
94
|
+
| `ai.knowledge.removeDocument` | 撤销文档 | `documentId, KnowledgeDocumentRemoveOptions?` | `void; may fail after visibility revocation if cleanup fails` | `ai.knowledge.removeDocument("intro")` |
|
|
95
|
+
| `ai.knowledge.repair` | 补偿残留向量 | `{ collection?, offset?, limit? }` | `KnowledgeRepairResult with progress` | `ai.knowledge.repair({ offset: 0, limit: 100 })` |
|
|
96
|
+
| `ai.knowledge.deleteCollection` | 撤销整个集合 | `collection name?` | `void; cleanup tombstone remains` | `ai.knowledge.deleteCollection("retired-manual")` |
|
|
97
|
+
| `ai.memory.scoped` | 绑定可信主体 | `{ objectId: nonempty string, scope? }` | `direct ScopedMemoryOperations; invalid binding throws TypeError` | `ai.memory.scoped({ objectId: "u1", scope: { topicId: "orders" } })` |
|
|
98
|
+
| `ai.memory.extract` | 提取事实记忆 | `ChatMessage[], { objectId, scope?, model?, signal?, ...options }` | `MemoryEntry[]` | `ai.memory.extract(messages, { objectId: "u1" })` |
|
|
99
|
+
| `ai.memory.add` | 保存明确事实 | `MemoryEntryInput: objectId, content, type, scope?` | `MemoryEntry` | `ai.memory.add({ objectId: "u1", content: "偏好中文", type: "preference" })` |
|
|
100
|
+
| `ai.memory.get` | 授权读取记忆 | `memoryId, { objectId, scope? } for untrusted IDs` | `MemoryEntry` | `ai.memory.get(memoryId, { objectId: "u1" })` |
|
|
101
|
+
| `ai.memory.update` | 更新已有事实 | `memoryId, MemoryUpdateInput, trusted access scope` | `MemoryEntry` | `ai.memory.update(memoryId, { content: "偏好日文" }, { objectId: "u1" })` |
|
|
102
|
+
| `ai.memory.remove` | 删除授权记忆 | `memoryId, trusted access scope` | `void` | `ai.memory.remove(memoryId, { objectId: "u1" })` |
|
|
103
|
+
| `ai.memory.recall` | 召回相关事实 | `query, { objectId, scope?, topK?, types?, ...options }` | `MemoryEntry[]` | `ai.memory.recall("语言偏好", { objectId: "u1" })` |
|
|
104
|
+
| `ai.memory.injectMemories` | 补充对话上下文 | `ChatMessage[], { objectId, scope?, topK?, ...options }` | `ChatMessage[]` | `ai.memory.injectMemories(messages, { objectId: "u1" })` |
|
|
105
|
+
| `ai.memory.list` | 读取完整列表 | `MemoryListOptions with objectId/scope filters` | `MemoryEntry[]; incomplete scan fails` | `ai.memory.list({ objectId: "u1" })` |
|
|
106
|
+
| `ai.memory.listPage` | 分页浏览记忆 | `MemoryListPageOptions with objectId/pagination` | `StorePage<MemoryEntry>` | `ai.memory.listPage({ objectId: "u1", offset: 0, limit: 20 })` |
|
|
107
|
+
| `ai.memory.clear` | 清理指定范围 | `nonempty MemoryClearOptions` | `void; empty filters are rejected` | `ai.memory.clear({ objectId: "u1" })` |
|
|
108
|
+
| `ai.memory.admin.clearAll` | 可信管理员全清 | `{ confirm: true }; require host administrator authorization` | `void; destructive across subjects` | `ai.memory.admin.clearAll({ confirm: true })` |
|
|
109
|
+
| `ai.persona.save` | 保存角色 | `PersonaProfileInput: id, name, systemPrompt, objectId?, traits?` | `PersonaProfile` | `ai.persona.save(personaProfile)` |
|
|
110
|
+
| `ai.persona.get` | 读取角色 | `id, { objectId }?; omitted subject selects system profile` | `PersonaProfile` | `ai.persona.get("tutor", { objectId: "u1" })` |
|
|
111
|
+
| `ai.persona.update` | 更新角色 | `id, PersonaProfileUpdate, { objectId }?` | `PersonaProfile` | `ai.persona.update("tutor", updates, { objectId: "u1" })` |
|
|
112
|
+
| `ai.persona.remove` | 删除角色 | `id, { objectId }?` | `void` | `ai.persona.remove("tutor", { objectId: "u1" })` |
|
|
113
|
+
| `ai.persona.list` | 列出主体角色 | `{ objectId }?` | `PersonaProfile[]` | `ai.persona.list({ objectId: "u1" })` |
|
|
114
|
+
| `ai.persona.compose` | 生成系统提示词 | `id, { objectId }?` | `string prompt` | `ai.persona.compose("tutor", { objectId: "u1" })` |
|
|
115
|
+
| `ai.token.estimateText` | 估算单段 Token | `text: string` | `direct number; estimate, not billing usage` | `ai.token.estimateText("Hello 世界")` |
|
|
116
|
+
| `ai.token.estimateMessages` | 估算消息 Token | `ChatMessage[]` | `direct number including protocol overhead` | `ai.token.estimateMessages(messages)` |
|
|
117
|
+
| `ai.summary.generate` | 生成摘要文本 | `ChatMessage[], SummaryOptions?` | `string` | `ai.summary.generate(messages)` |
|
|
118
|
+
| `ai.summary.summarize` | 生成摘要及覆盖信息 | `ChatMessage[], SummaryOptions?` | `{ summary, tokenCount, coveredMessages }` | `ai.summary.summarize(messages)` |
|
|
119
|
+
| `ai.compress.tryCompress` | 按预算压缩 | `ChatMessage[], { strategy?, maxTokens?, preserveLastN?, ...options }` | `CompressResult: messages and original/compressed token counts` | `ai.compress.tryCompress(messages, { maxTokens: 4000 })` |
|
|
120
|
+
| `ai.context.createManager` | 开始多轮对话 | `ContextManagerOptions with scope { objectId, sessionId }` | `ContextManager` | `ai.context.createManager({ scope: { objectId: "u1", sessionId: "s1" } })` |
|
|
121
|
+
| `ai.context.restoreManager` | 恢复对话 | `{ objectId, sessionId }, options?` | `ContextManager` | `ai.context.restoreManager({ objectId: "u1", sessionId: "s1" })` |
|
|
122
|
+
| `ai.context.listSessions` | 列出可恢复会话 | `objectId` | `SessionInfo[]` | `ai.context.listSessions("u1")` |
|
|
123
|
+
| `ai.context.renameSession` | 修改会话标题 | `scope, title` | `void` | `ai.context.renameSession({ objectId: "u1", sessionId: "s1" }, "订单讨论")` |
|
|
124
|
+
| `ai.context.removeSession` | 删除指定会话 | `scope` | `void; tombstone prevents scope reuse` | `ai.context.removeSession({ objectId: "u1", sessionId: "s1" })` |
|
|
125
|
+
| `ai.rerank.rerank` | 重排文档对象 | `RerankRequest: query, documents, model?, topN?` | `RerankResponse with model/results` | `ai.rerank.rerank({ query: "部署", documents: ["配置说明"] })` |
|
|
126
|
+
| `ai.rerank.rerankTexts` | 重排文本候选 | `query, string[] texts, topN?` | `RerankItem[] with index/relevanceScore` | `ai.rerank.rerankTexts("部署", ["配置说明"], 1)` |
|
|
127
|
+
| `ai.file.parse` | 识别文件并提取 | `FileParseRequest with content, filename, options?` | `FileParseResult; extraction is not HTML sanitization` | `ai.file.parse({ content: "<p>正文</p>", filename: "intro.html" })` |
|
|
128
|
+
| `ai.file.parseText` | 直接提取文本 | `Buffer\|string content, filename?` | `string` | `ai.file.parseText("Hello", "intro.txt")` |
|
|
129
|
+
| `ai.reasoning.run` | 多步骤求解 | `query, ReasoningOptions including strategy/tools?` | `ReasoningResult` | `ai.reasoning.run("审查方案", { strategy: "cot" })` |
|
|
130
|
+
| `ai.reasoning.runStream` | 观察推理过程 | `query, ReasoningOptions?` | `AsyncIterable<ReasoningStreamEvent>` | `ai.reasoning.runStream("审查方案", { strategy: "react" })` |
|
|
131
|
+
| `ai.audio.transcribe` | 识别完整音频 | `TranscriptionRequest: audio, language?, model?, signal?` | `TranscriptionResult: text, language?, segments?` | `ai.audio.transcribe({ audio: { data: wavBytes, format: "wav" } })` |
|
|
132
|
+
| `ai.audio.transcribeStream` | 持续语音识别 | `TranscriptionStreamRequest: chunks or complete audio` | `AsyncIterable<TranscriptionEvent>` | `ai.audio.transcribeStream(transcriptionInput)` |
|
|
133
|
+
| `ai.audio.synthesize` | 合成完整语音 | `SynthesisRequest: text, language?, model?, signal?` | `SynthesisResult: audio and duration metadata` | `ai.audio.synthesize({ text: "你好" })` |
|
|
134
|
+
| `ai.audio.synthesizeStream` | 按段合成 | `SynthesisStreamRequest: text segment or async segments` | `AsyncIterable<SynthesisEvent>` | `ai.audio.synthesizeStream(synthesisInput)` |
|
|
135
|
+
| `ai.audio.getCapabilities` | 先检查模型能力 | `{ operation: transcribe\|synthesize, model? }` | `AudioModelCapabilities` | `ai.audio.getCapabilities({ operation: "synthesize" })` |
|
|
136
|
+
| `ai.image.generate` | 生成或参考图片 | `{ prompt, referenceImages?, model?, size?, signal? }` | `{ images: GeneratedImage[] } with bytes/MIME` | `ai.image.generate({ prompt: "一座灯塔" })` |
|
|
137
|
+
| `ai.a2a.registerExecutor` | 注册任务执行器 | `SDK AgentExecutor` | `void` | `ai.a2a.registerExecutor(executor)` |
|
|
138
|
+
| `ai.a2a.getAgentCard` | 提供标准发现文档 | `none; configured a2a card` | `A2AAgentCardDocument (A2A 1.0 ProtoJSON)` | `ai.a2a.getAgentCard()` |
|
|
139
|
+
| `ai.a2a.handleRequest` | 处理认证的协议请求 | `unknown JSON-RPC body, trusted context.agentId?` | `direct Promise<A2AHandleResult>; JSON-RPC/SSE outcome` | `ai.a2a.handleRequest(body, { agentId: trustedAgentId })` |
|
|
140
|
+
| `ai.a2a.listMessages` | 可信管理查询 | `A2ATaskFilter: callerId?, contextId?, since?, pagination?` | `StorePage<A2AMessageRecord>` | `ai.a2a.listMessages(messageFilter)` |
|
|
141
|
+
| `ai.a2a.callRemoteAgent` | 调用获准远端 | `allowlisted HTTPS URL, message, A2ACallOptions?` | `A2ACallResult` | `ai.a2a.callRemoteAgent("https://agent.example.com/a2a", "请分析订单")` |
|
|
142
|
+
| `ai.init` | 准备服务 | `AIConfigInput?, AIInitOptions?` | `HaiResult<void>; validate dependencies before use` | `ai.init({ llm: { apiKey: process.env.HAI_AI_LLM_APIKEY } })` |
|
|
143
|
+
| `ai.close` | 反序释放服务 | `none` | `Promise<void>; wait for cleanup` | `ai.close()` |
|
|
144
|
+
| `ai.config` | 诊断当前配置 | `none` | `redacted AIConfig or null` | `ai.config` |
|
|
145
|
+
| `ai.isInitialized` | 检查生命周期状态 | `none` | `boolean` | `ai.isInitialized` |
|
|
146
|
+
| `ai.llm.models.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.llm.models.list()` |
|
|
147
|
+
| `ai.llm.models.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.llm.models.get("coding")` |
|
|
148
|
+
| `ai.llm.models.register` | 登记数据库定义 | `ModelEntry input (id/model/protocol/credentials/capabilities)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.llm.models.register(modelDefinition)` |
|
|
149
|
+
| `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)` |
|
|
150
|
+
| `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)` |
|
|
151
|
+
| `ai.audio.models.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.audio.models.list()` |
|
|
152
|
+
| `ai.audio.models.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.audio.models.get("speech")` |
|
|
153
|
+
| `ai.audio.models.register` | 登记数据库定义 | `AudioModelEntry input (id/provider/model/operations)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.audio.models.register(audioModelDefinition)` |
|
|
154
|
+
| `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)` |
|
|
155
|
+
| `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)` |
|
|
156
|
+
| `ai.image.models.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.image.models.list()` |
|
|
157
|
+
| `ai.image.models.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.image.models.get("poster")` |
|
|
158
|
+
| `ai.image.models.register` | 登记数据库定义 | `ImageModelEntry input (id/provider/model)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.image.models.register(imageModelDefinition)` |
|
|
159
|
+
| `ai.image.models.update` | 按版本替换定义 | `ImageModelEntry input (id/provider/model), expectedVersion?` | `HaiResult<AIResourceEntry>; full replacement, conflict fails` | `ai.image.models.update(imageModelDefinition, current.data.version)` |
|
|
160
|
+
| `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)` |
|
|
161
|
+
| `ai.mcp.servers.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.mcp.servers.list()` |
|
|
162
|
+
| `ai.mcp.servers.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.mcp.servers.get("tools")` |
|
|
163
|
+
| `ai.mcp.servers.register` | 登记数据库定义 | `MCPExternalServer input (id/transport/url or command)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.mcp.servers.register(mcpServerDefinition)` |
|
|
164
|
+
| `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)` |
|
|
165
|
+
| `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)` |
|
|
166
|
+
| `ai.retrieval.sources.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.retrieval.sources.list()` |
|
|
167
|
+
| `ai.retrieval.sources.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.retrieval.sources.get("docs")` |
|
|
168
|
+
| `ai.retrieval.sources.register` | 登记数据库定义 | `RetrievalSource input (id/collection)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.retrieval.sources.register(sourceDefinition)` |
|
|
169
|
+
| `ai.retrieval.sources.update` | 按版本替换定义 | `RetrievalSource input (id/collection), expectedVersion?` | `HaiResult<AIResourceEntry>; full replacement, conflict fails` | `ai.retrieval.sources.update(sourceDefinition, current.data.version)` |
|
|
170
|
+
| `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)` |
|
|
171
|
+
| `ai.acp.agents.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.acp.agents.list()` |
|
|
172
|
+
| `ai.acp.agents.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.acp.agents.get("coder")` |
|
|
173
|
+
| `ai.acp.agents.register` | 登记数据库定义 | `ACPAgent input (id/mode/adapter/modelIds)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.acp.agents.register(agentDefinition)` |
|
|
174
|
+
| `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)` |
|
|
175
|
+
| `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)` |
|
|
176
|
+
| `ai.acp.workspaces.list` | 列出合并清单 | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.acp.workspaces.list()` |
|
|
177
|
+
| `ai.acp.workspaces.get` | 读取来源和版本 | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.acp.workspaces.get("project")` |
|
|
178
|
+
| `ai.acp.workspaces.register` | 登记数据库定义 | `ACPWorkspace input (id/storage/repositories)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.acp.workspaces.register(workspaceDefinition)` |
|
|
179
|
+
| `ai.acp.workspaces.update` | 按版本替换定义 | `ACPWorkspace input (id/storage/repositories), expectedVersion?` | `HaiResult<AIResourceEntry>; full replacement, conflict fails` | `ai.acp.workspaces.update(workspaceDefinition, current.data.version)` |
|
|
180
|
+
| `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)` |
|
|
181
|
+
| `ai.acp.agents.initialize` | 预检适配器配置 | `agentId, modelId?` | `HaiResult<{ agentId, mode, modelIds }>; no credentials` | `ai.acp.agents.initialize("coder")` |
|
|
182
|
+
| `ai.acp.agents.check` | 实际连接并握手 | `agentId, { workspaceId?, ...ACPClientOptions }` | `HaiResult<native initialize response>; owned connection is closed` | `ai.acp.agents.check("coder", { workspaceId: "project" })` |
|
|
183
|
+
| `ai.acp.workspaces.prepare` | 准备工作目录 | `workspaceId` | `HaiResult<main absolute path>; dirty content is retained` | `ai.acp.workspaces.prepare("project")` |
|
|
184
|
+
| `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: "需求" }])` |
|
|
185
|
+
| `ai.acp.sessions.create` | 启动受管开发会话 | `ACPCreateSessionOptions: agentId/workspaceId/newWorktree?` | `HaiResult<managed session handle>` | `ai.acp.sessions.create({ agentId: "coder", workspaceId: "project", newWorktree: true })` |
|
|
186
|
+
| `ai.acp.sessions.get` | 读取会话句柄 | `framework session id` | `HaiResult<managed session handle>; does not resume` | `ai.acp.sessions.get("task-1")` |
|
|
187
|
+
| `ai.acp.sessions.list` | 查询受管会话 | `workspaceId?` | `HaiResult<ACPSessionInfo[]>` | `ai.acp.sessions.list("project")` |
|
|
188
|
+
| `ai.acp.sessions.resume` | 恢复原生会话 | `framework session id, ACPClientOptions?` | `HaiResult<managed session handle>; definition changes may reject` | `ai.acp.sessions.resume("task-1")` |
|
|
189
|
+
| `ai.acp.sessions.close` | 停止拥有的执行环境 | `framework session id` | `HaiResult<void>; source and native history retained` | `ai.acp.sessions.close("task-1")` |
|
|
190
|
+
| `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")` |
|
|
191
|
+
| `ai.acp.sessions.remove` | 移除会话记录 | `closed or failed framework session id` | `HaiResult<void>; worktree and native history retained` | `ai.acp.sessions.remove("task-1")` |
|
|
192
|
+
| `ai.acp.connect` | 接入原生传输 | `ACPTransport: stdio/http/ws, ACPClientOptions?` | `HaiResult<connection handle>` | `ai.acp.connect({ type: "http", url: "https://agent.example.com/acp" })` |
|
|
193
|
+
| `ai.acp.close` | 关闭子系统 | `none; normally call ai.close()` | `Promise<void>; cleanup may throw` | `ai.acp.close()` |
|
|
12
194
|
|
|
13
195
|
- `ai.tools`:工具定义、注册表、批量执行;无需初始化。
|
|
14
196
|
- `ai.stream`:ChatCompletion 流式 chunk 处理;无需初始化。
|
|
@@ -26,7 +208,7 @@ AI 能力模块,提供统一的 `ai` 服务对象,覆盖 LLM 对话、文生
|
|
|
26
208
|
- `ai.a2a`:Agent-to-Agent 请求处理与远端调用。
|
|
27
209
|
- `@h-ai/ai/client`:独立浏览器 Audio WebSocket 客户端。
|
|
28
210
|
|
|
29
|
-
`@h-ai/ai/client` 仅提供 `createAudioClient({ url, getTicket })` 与 Audio 客户端类型。HTTP 使用 `@h-ai/api-client` 的 typed 领域方法;默认聊天补全非流式,流与 A2A 使用应用自行绑定的 contract
|
|
211
|
+
`@h-ai/ai/client` 仅提供 `createAudioClient({ url, getTicket })` 与 Audio 客户端类型。HTTP 使用 `@h-ai/api-client` 的 typed 领域方法;默认聊天补全非流式,流与 A2A 使用应用自行绑定的 contract。浏览器不导出 Node 单例 `ai`。
|
|
30
212
|
|
|
31
213
|
```ts
|
|
32
214
|
import { apiClient } from '@h-ai/api-client'
|
|
@@ -35,7 +217,11 @@ const ready = await apiClient.init({ baseUrl: 'https://api.example.com/api/v1' }
|
|
|
35
217
|
if (!ready.success)
|
|
36
218
|
throw new Error(ready.error.message)
|
|
37
219
|
try {
|
|
38
|
-
const response = await apiClient.ai.chats.createCompletion({
|
|
220
|
+
const response = await apiClient.ai.chats.createCompletion({
|
|
221
|
+
messages: [
|
|
222
|
+
{ role: 'user', content: '你好' }
|
|
223
|
+
]
|
|
224
|
+
})
|
|
39
225
|
if (!response.success)
|
|
40
226
|
throw new Error(response.error.message)
|
|
41
227
|
const reply = response.data.choices[0]?.message.content
|
|
@@ -49,34 +235,7 @@ finally {
|
|
|
49
235
|
|
|
50
236
|
更完整的方法清单、错误码与长示例见 [REFERENCE.md](./REFERENCE.md)。
|
|
51
237
|
|
|
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)
|
|
238
|
+
### 持久化 DB Provider(reldb + vecdb)
|
|
80
239
|
|
|
81
240
|
```ts
|
|
82
241
|
import { ai } from '@h-ai/ai'
|
|
@@ -97,7 +256,11 @@ try {
|
|
|
97
256
|
})
|
|
98
257
|
if (!initialized.success)
|
|
99
258
|
throw new Error(initialized.error.message)
|
|
100
|
-
const result = await ai.llm.chat({
|
|
259
|
+
const result = await ai.llm.chat({
|
|
260
|
+
messages: [
|
|
261
|
+
{ role: 'user', content: 'Hello!' }
|
|
262
|
+
]
|
|
263
|
+
})
|
|
101
264
|
if (!result.success)
|
|
102
265
|
throw new Error(result.error.message)
|
|
103
266
|
const reply = result.data.choices[0]?.message.content ?? ''
|
|
@@ -117,9 +280,11 @@ if (failures.length)
|
|
|
117
280
|
throw new AggregateError(failures, 'AI operation or cleanup failed')
|
|
118
281
|
```
|
|
119
282
|
|
|
283
|
+
默认 PostgreSQL Store 支持空库首次部署和旧库升级时并发调用 `ai.init`。各节点通过事务级 advisory lock 排队准备表、索引和写入门闩。结构变更失败时回滚,修正权限或结构后可重试。已有索引直接复用。向量重建在事务提交后异步执行,节点失联后由其他节点接续。
|
|
284
|
+
|
|
120
285
|
MySQL 首次初始化允许多个节点并发建索引:仅接受 mysql2 明确的 ER_DUP_KEYNAME/1061,并重新核对列及顺序、非唯一完整列、升序可见 BTREE 和无表达式;已有同名错误结构仍失败。账户需要建表和 INDEX 权限,元数据读取、权限或其他 DDL 错误使 ai.init 返回 CONFIGURATION_ERROR。返回前等待全部已启动 DDL 结束;MySQL DDL 不回滚,失败保留已创建结构,修复权限/结构后再重试。逐步检查初始化结果,失败不接收业务请求,并逆序关闭 AI、vecdb、reldb。
|
|
121
286
|
|
|
122
|
-
|
|
287
|
+
### 自定义 StoreProvider
|
|
123
288
|
|
|
124
289
|
```ts
|
|
125
290
|
import type { AIStoreProvider } from '@h-ai/ai'
|
|
@@ -128,7 +293,9 @@ import { ai } from '@h-ai/ai'
|
|
|
128
293
|
const storeProvider: AIStoreProvider = createMyStoreProvider()
|
|
129
294
|
|
|
130
295
|
await ai.init(
|
|
131
|
-
{
|
|
296
|
+
{
|
|
297
|
+
llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY }
|
|
298
|
+
},
|
|
132
299
|
{ storeProvider },
|
|
133
300
|
)
|
|
134
301
|
|
|
@@ -173,12 +340,35 @@ const claude = await ai.llm.chat({ messages, model: 'claude' }) // 该模型配
|
|
|
173
340
|
// 临时客户端按 TTL 缓存(llm.tempModelCacheTtl,默认 10 分钟),与常驻模型客户端隔离
|
|
174
341
|
const temp = await ai.llm.chat({
|
|
175
342
|
messages,
|
|
176
|
-
tempModel: { model: 'claude-3-5-sonnet', protocol: 'anthropic', apiKey:
|
|
343
|
+
tempModel: { model: 'claude-3-5-sonnet', protocol: 'anthropic', apiKey: process.env.TEMP_LLM_API_KEY },
|
|
177
344
|
})
|
|
178
345
|
```
|
|
179
346
|
|
|
180
347
|
SSE 文本解码遵循 [WHATWG 事件流规则](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation):LF/CRLF/CR 跨片、多行 data、仅去冒号后一个空格、继承有效 id/retry;空或缺省 event 按 message,EOF 不补空行派发残余事件。encodeSSE 规范化 data 换行,并对 id/event 换行、id 的 NUL 或无效 retry 显式抛错。Anthropic/MiMo 共用内部 UTF-8 流读取;消费方退出、取消、协议结束和失败均取消正文并释放 reader,不自动重连或重放业务。Anthropic timeout 覆盖正文,MiMo 保留每个 HTTP 请求的独立 timeout。
|
|
181
348
|
|
|
349
|
+
##### 结构化输出:`ai.llm.generateObject`
|
|
350
|
+
|
|
351
|
+
按模型或网关的响应能力选择 `responseFormat`。默认 `json_schema` 向上游发送严格 JSON Schema,`schemaName` 只用于此模式,默认 `result`。仅支持通用 JSON 的 Chat 网关使用 `json_object`,框架将 Schema 放入提示词。两种模式都在本地用同一个 Zod Schema 校验,解析或校验失败时可按 `maxRepairs` 修复,默认一次。
|
|
352
|
+
|
|
353
|
+
```ts
|
|
354
|
+
import { ai } from '@h-ai/ai'
|
|
355
|
+
import { z } from 'zod'
|
|
356
|
+
|
|
357
|
+
// 已初始化 AI,llm 使用支持通用 JSON 模式的文本模型。
|
|
358
|
+
const result = await ai.llm.generateObject({
|
|
359
|
+
schema: z.object({
|
|
360
|
+
title: z.string()
|
|
361
|
+
}), // 要求返回含 title 字符串的对象。
|
|
362
|
+
messages: [
|
|
363
|
+
{ role: 'user', content: '为发布检查表生成标题。' }
|
|
364
|
+
], // 本次输入。
|
|
365
|
+
responseFormat: 'json_object', // 请求通用 JSON,仍会执行本地 Zod 校验。
|
|
366
|
+
maxRepairs: 1, // 解析或校验失败时允许再请求一次。
|
|
367
|
+
})
|
|
368
|
+
if (result.success)
|
|
369
|
+
process.stdout.write(result.data.title) // 例如:发布检查表。
|
|
370
|
+
```
|
|
371
|
+
|
|
182
372
|
#### 工具调用
|
|
183
373
|
|
|
184
374
|
```ts
|
|
@@ -191,7 +381,9 @@ const registry = ai.tools.createRegistry({
|
|
|
191
381
|
const registered = registry.register(ai.tools.define({
|
|
192
382
|
name: 'get_weather',
|
|
193
383
|
description: '获取天气',
|
|
194
|
-
parameters: z.object({
|
|
384
|
+
parameters: z.object({
|
|
385
|
+
city: z.string()
|
|
386
|
+
}),
|
|
195
387
|
// handler 第二参为执行上下文:可响应取消(打断/超时)、感知截止时间与交互主体
|
|
196
388
|
handler: async ({ city }, { signal }) => {
|
|
197
389
|
const res = await fetch(`https://api.example.com/weather?city=${city}`, { signal })
|
|
@@ -208,12 +400,109 @@ const result = await registry.execute(toolCall, { signal: controller.signal, obj
|
|
|
208
400
|
// 批量调用默认串行,避免副作用工具并发启动;纯读取且确认安全时才显式并行
|
|
209
401
|
const batch = await registry.executeAll(toolCalls)
|
|
210
402
|
|
|
211
|
-
const chat = await ai.llm.chat({
|
|
403
|
+
const chat = await ai.llm.chat({
|
|
404
|
+
messages,
|
|
405
|
+
tools: registry.getDefinitions()
|
|
406
|
+
})
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
#### ACP 智能体、工作区和会话
|
|
410
|
+
|
|
411
|
+
`ai.acp` 在 Node 服务端接入原生 ACP 智能体:`embedded` 本机进程、`builtin-service` Podman/Docker 容器(自动选择优先 Podman)、`custom-service` 已有 HTTP/WS 服务。Codex/dsh 当前使用 stdio;不自动转换不支持的传输。
|
|
412
|
+
|
|
413
|
+
Podman 关闭远程服务代理变量的自动继承;代理通过 Agent/workspace 的 `environmentRefs` 显式配置,并使用容器可达的地址。
|
|
414
|
+
|
|
415
|
+
Goose 1.57.0 镜像提供原生 `goose serve` HTTP/WS `/acp` 服务,通过 custom-service 和 `X-Secret-Key` 接入。模型由 Goose 服务维护,工作区与状态卷由部署方挂载;真实远程 E2E 按握手能力验收恢复。
|
|
416
|
+
|
|
417
|
+
- `agents.register/get/list/update/remove/initialize/check` 维护智能体。`codex`、`deepseek-harness` 适配器引用 `llm.models`;其他原生程序用 `generic` 或可信 `AIInitOptions.acpAdapters`。自定义服务自行管理模型。
|
|
418
|
+
- `workspaces.register/prepare/importFiles` 管理目录或持久 volume、多 Git 工程和普通文件;每个 Git 明确 `mainBranch`。prepare 不覆盖脏目录。
|
|
419
|
+
- 私有仓库用 workspace 的 `gitEnvironmentRefs` 将凭据仅提供给远程 Git;Agent 专用变量放在 agent 的 `environmentRefs`。旧 workspace 的 `environmentRefs` 仍共用。
|
|
420
|
+
- `sessions.create/resume/get/list/close` 管理会话;`newWorktree: true` 从各本地主分支建同名 worktree。可用 `repositoryId` 从指定仓库根目录启动与恢复,让 Agent 按该仓库发现规则和技能。prompt/stream/strict promptStructured、权限回调、MCP、模式配置、取消和能力检查沿用 ACP。
|
|
421
|
+
- `session.info().data.workspace` 在成功时提供本机或同节点卷的工作树位置,可在 Agent 关闭后用于预览。先停止预览并保存改动,再用 `sessions.reclaimWorktree(id)` 定向回收干净工作树,保留分支、普通文件、原生历史和卷。
|
|
422
|
+
- `session.updateMain()` 只 fetch/ff-only 更新明确主分支;`publish({ mode: 'merge-main' | 'push-branch', message, author })` 仅发布受管隔离 session,逐仓库报告部分失败,不强推。操作前停止执行环境,继续任务显式 resume。
|
|
423
|
+
|
|
424
|
+
模型容量、模态和推理能力填 `llm.models[].capabilities`,未知不猜。Codex 要求原生 Responses;Hai 现有转换不是反向服务网关。关闭后保留代码/状态卷,确认拥有的进程停止才释放 CAS 占用;worktree 不是安全沙箱。
|
|
425
|
+
|
|
426
|
+
DeepSeek Harness 直连官方 DeepSeek Chat 时,在模型条目中设置 `protocol: 'chat'` 和 `baseUrl: 'https://api.deepseek.com'`。内部中继可保留官方模型名 `deepseek-flash` 或 `deepseek-v4-pro` 以启用相同的兼容设置。Harness 用 `system` 发送指令,按 DeepSeek 格式发送输出上限,并在工具结果回传时保留 `reasoning_content`。 [DeepSeek Chat API](https://api-docs.deepseek.com/api/create-chat-completion/)
|
|
427
|
+
|
|
428
|
+
接入示例与限制见 [ACP 指南](../cli/templates/skills/hai-ai/acp.md)。构建 Agent 时可选 `minimal`、`documents`、`office`、`browser`、`developer`,默认精简镜像含 Git、Node 和原生 Agent,Codex 还含 bubblewrap。运行环境可登记镜像 ID 或远程清单 digest。[Agent 镜像](models/agents/README.md) 普通 API 返回 HaiResult,stream 失败抛出,ACP 运行入口位于 Node 服务端。
|
|
429
|
+
|
|
430
|
+
托管 Git 遇到子模块或 Git LFS 属性时明确返回 ACP_UNSUPPORTED,避免将不完整工程报告为就绪。
|
|
431
|
+
|
|
432
|
+
##### 按用户运行受管 ACP
|
|
433
|
+
|
|
434
|
+
服务启动时先初始化 RelDB 和 [Runner](../runner/README.md),再将已启动的实例传给 `ai.init(config, { runner, acpPolicy })`。在 `acp.agents` 注册 Agent,并用 `environmentIds` 绑定 Runner 的固定镜像环境,用 `modelIds` 绑定 `llm.models` 的模型。Codex 需要 Responses 网关。API 和执行节点使用共享数据库与相同环境定义。关闭服务时先关闭 AI,再关闭 Runner 和数据库。
|
|
435
|
+
|
|
436
|
+
`task` 为本次会话启动独占 Worker,`user` 可在同一主体与启动配置下复用。`auto` 先检查共享条件,再按应用策略决定能否复用个人 Worker,其余使用独占 Worker。`shared` 只允许使用只读会话,且限于无需私有上下文、工作区或工具的请求。固定版本 DeepSeek Harness 0.2.1-rc.5 可显式启用 `sharedMode`。内置 Codex 和 Goose 使用个人或独占模式。配置示例见 [ACP 配置](../../docs/usage/configuration/ai.md#acp-接入与模型能力)。
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
import type { RunnerScope } from '@h-ai/runner' // tenantId 和 userId 来自已认证的应用会话。
|
|
440
|
+
import { ai } from '@h-ai/ai' // 使用已注入 Runner 的服务端实例。
|
|
441
|
+
|
|
442
|
+
async function summarize(identity: RunnerScope, requestId: string) {
|
|
443
|
+
const agent = ai.acp.scoped(identity) // 将后续任务、会话和权限访问绑定到此主体。
|
|
444
|
+
const options = {
|
|
445
|
+
agentId: 'assistant',
|
|
446
|
+
execution: { mode: 'auto' as const }
|
|
447
|
+
} // assistant 是已登记的 Agent。
|
|
448
|
+
const plan = await agent.plan(options) // 返回实际模式、环境、模型和资源设置,不领取容器。
|
|
449
|
+
if (!plan.success)
|
|
450
|
+
return plan // 环境或权限不满足时不提交。
|
|
451
|
+
const result = await agent.run({ ...options, prompt: '列出三条发布检查项', idempotencyKey: requestId }) // 返回 taskId、output 和生效选项。
|
|
452
|
+
if (!result.success)
|
|
453
|
+
return result // 提交、执行或清理失败时返回 HaiResult 错误。
|
|
454
|
+
const events = await agent.tasks.events(result.data.taskId, 0, 20) // 读取前 20 个持久事件,空页为 []。
|
|
455
|
+
if (!events.success)
|
|
456
|
+
return events
|
|
457
|
+
return { result: result.data, events: events.data } // 例如 output.text 是模型回答,events 含按序号排列的事件。
|
|
458
|
+
}
|
|
212
459
|
```
|
|
213
460
|
|
|
461
|
+
```ts
|
|
462
|
+
import type { RunnerScope } from '@h-ai/runner' // 服务端认证主体。
|
|
463
|
+
import { ai } from '@h-ai/ai' // assistant 已登记,并允许在同一用户内复用 Worker。
|
|
464
|
+
|
|
465
|
+
async function continueWork(identity: RunnerScope) {
|
|
466
|
+
const agent = ai.acp.scoped(identity) // 成功访问只限当前主体的资源。
|
|
467
|
+
const created = await agent.sessions.create({
|
|
468
|
+
agentId: 'assistant',
|
|
469
|
+
execution: { mode: 'user' }
|
|
470
|
+
}) // 成功得到含 id 的会话句柄。
|
|
471
|
+
if (!created.success)
|
|
472
|
+
return created
|
|
473
|
+
const session = created.data // 句柄提供 prompt、stream、changeExecution 和 close。
|
|
474
|
+
const run = async () => {
|
|
475
|
+
const first = await session.prompt('记下验收目标') // 返回这一轮的 taskId、output 与生效选项。
|
|
476
|
+
if (!first.success)
|
|
477
|
+
return first
|
|
478
|
+
const switched = await session.changeExecution({ mode: 'task', acceptNewSession: true }) // 保留业务 id,建立新的原生会话。
|
|
479
|
+
if (!switched.success)
|
|
480
|
+
return switched
|
|
481
|
+
return await session.prompt('给出独立验收清单') // 模型回答位于成功结果的 data.output。
|
|
482
|
+
}
|
|
483
|
+
return run().finally(async () => {
|
|
484
|
+
const closed = await session.close() // 成功的 data 为 undefined,释放会话或独占任务环境。
|
|
485
|
+
if (!closed.success)
|
|
486
|
+
throw new Error(closed.error.message)
|
|
487
|
+
})
|
|
488
|
+
}
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
使用 `agents.describe(agentId)` 查询内置适配器的能力,`sessions.get(id)` 由同一主体在其他 API 节点取得句柄,`session.stream(prompt, options)` 迭代持久事件并在失败时抛错。`tasks.get(taskId)` 返回执行回执,`tasks.cancel(taskId)` 接受取消并返回当前状态。可在 `run` 或 `prompt` 的 `onEvent` 中取得 `accepted` 事件的 `taskId`,然后用另一请求查看或取消。
|
|
492
|
+
|
|
493
|
+
`acpPolicy` 负责 `workspaceId` 快照、知识库、记忆、文件、Skills 和工具的业务授权。`allowTools` 与 `bindTools` 可接入下文的 MCP 入口。应用取得 `approval` 事件中的 `approvalId` 后,从同一主体调用 `approvals.respond(id, 'allow-once' | 'allow-session' | 'always-allow' | 'deny')`,成功返回 `undefined`。`approvals.rules(offset, limit)` 分页返回仍可用的规则和 `expiresAt`,`approvals.revoke(ruleId)` 撤销当前主体的规则。`full-access` 需要应用明确允许且使用 `task`。`session.submit({ prompt, idempotencyKey, context })` 返回可续读的任务回执。浏览器带 `taskId` 和已读序号调用 `tasks.events`。`session.status()` 可发现空闲回收的会话,创建新会话时可带入用户确认的 `historySummary`。`workspaces.readGitSnapshot` 为独占环境读取普通文件树,成功后可保存改动补丁,并在用户确认后调用 `workspaces.publishSnapshot` 发布独立任务分支。更多示例见 [Agent 工作台](../../apps/agent/README.md) 和 [受管调用](../../docs/usage/development/ai-acp.md#多用户应用的受管调用)。
|
|
494
|
+
|
|
495
|
+
#### 配置与数据库资源清单
|
|
496
|
+
|
|
497
|
+
`llm.models`、`audio.models`、`image.models`、`mcp.servers`、`retrieval.sources`、`acp.agents/workspaces` 合并配置和数据库。配置同 ID 优先且只读,数据库支持 list/get/register/update/remove;条目返回 value/source/version,更新可检查版本。异步调用读取最新定义,音频同步能力查询使用最近刷新快照。资源错误为 090–094。管理定义可能含模型密钥,仅在可信服务端使用。
|
|
498
|
+
|
|
499
|
+
[Resource catalogs](../cli/templates/skills/hai-ai/resources.md) · [ACP](../cli/templates/skills/hai-ai/acp.md)
|
|
500
|
+
|
|
214
501
|
#### A2A 协议边界
|
|
215
502
|
|
|
216
|
-
|
|
503
|
+
远端调用的自定义请求头按名称大小写不敏感地覆盖。固定 JSON-RPC 地址拒绝 HTTP 重定向,认证头不会被转发到重定向目标。
|
|
504
|
+
|
|
505
|
+
`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
506
|
|
|
218
507
|
A2A 的 journal、context 归属与消息表在 `ai.init()` 阶段初始化。任务按可信 `agentId` 隔离(含获取、取消和续接);匿名请求共享匿名主体,生产应在可信传输层认证。`listMessages` 是服务端管理接口,支持 `callerId`、`contextId`、`since`,不能向未授权客户端暴露。
|
|
219
508
|
|
|
@@ -234,15 +523,102 @@ import { z } from 'zod'
|
|
|
234
523
|
const server = createMcpServer({ name: 'my-server', version: '1.0.0' })
|
|
235
524
|
server.registerTool('search', {
|
|
236
525
|
description: '搜索',
|
|
237
|
-
inputSchema: {
|
|
526
|
+
inputSchema: {
|
|
527
|
+
query: z.string()
|
|
528
|
+
},
|
|
238
529
|
}, async ({ query }) => ({
|
|
239
|
-
content: [
|
|
530
|
+
content: [
|
|
531
|
+
{ type: 'text', text: `Results for ${query}` }
|
|
532
|
+
],
|
|
533
|
+
}))
|
|
534
|
+
await server.connect(new StreamableHTTPServerTransport({
|
|
535
|
+
sessionIdGenerator: () => globalThis.crypto.randomUUID()
|
|
240
536
|
}))
|
|
241
|
-
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
##### 调用远程 MCP 和独立工具作业
|
|
540
|
+
|
|
541
|
+
在 `mcp.servers` 的 `transport: http` 条目中登记第三方 Streamable HTTP 地址和 `allowedTools`。需要认证时用 `headerEnv` 引用服务器环境变量。`transport: job` 可用同一套调用接口运行离线文档、Office 和 OCR 工具。为作业配置 `environmentId`、允许操作和可选 `pool`,将 Runner 与 `mcpJobFiles` 传给 `ai.init`。作业请求只传已授权的 `fileId`,执行节点再次检查文件权限,产物以对象 ID 返回。浏览器镜像由部署方单独运行。详见 [MCP 配置](../../docs/usage/configuration/ai.md#mcp和a2a) 与 [工具镜像](tools/README.md)。
|
|
542
|
+
|
|
543
|
+
```ts
|
|
544
|
+
import type { MCPServiceAuthorization } from '@h-ai/ai' // 应用从 IAM 构造主体和按实际参数复核权限的回调。
|
|
545
|
+
import { ai } from '@h-ai/ai' // 服务端已初始化,并登记了 manual 与 office 服务。
|
|
546
|
+
|
|
547
|
+
async function searchManual(access: MCPServiceAuthorization, query: string) {
|
|
548
|
+
const result = await ai.mcp.services.invoke({
|
|
549
|
+
serviceId: 'manual',
|
|
550
|
+
tool: 'search_manual',
|
|
551
|
+
arguments: { query }
|
|
552
|
+
}, access) // 目录和授权通过后得到标准 MCP 工具结果。
|
|
553
|
+
if (!result.success)
|
|
554
|
+
return result // 权限拒绝或上游失败时保留错误。
|
|
555
|
+
return result.data.content // 例如 [{ type: 'text', text: '...' }]。
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
async function convertDocument(access: MCPServiceAuthorization, fileId: string) {
|
|
559
|
+
const result = await ai.mcp.services.invoke({
|
|
560
|
+
serviceId: 'office',
|
|
561
|
+
tool: 'office.convert',
|
|
562
|
+
arguments: { fileId }
|
|
563
|
+
}, access) // 用授权对象 ID 提交离线转换。
|
|
564
|
+
if (!result.success)
|
|
565
|
+
return result
|
|
566
|
+
return result.data.structuredContent // 成功示例 { fileId: 'pdf-123', name: 'result.pdf' },下载需再次验权。
|
|
567
|
+
}
|
|
568
|
+
```
|
|
569
|
+
|
|
570
|
+
```ts
|
|
571
|
+
import type { MCPServiceAuthorization, MCPServiceBrokerOptions } from '@h-ai/ai' // url 由部署方指定,authorize 每次检查当前主体、任务和参数。
|
|
572
|
+
import { createServer } from 'node:http' // 提供示例 HTTP 请求入口。
|
|
573
|
+
import { ai } from '@h-ai/ai' // 服务端已初始化,并登记了 manual 服务。
|
|
574
|
+
|
|
575
|
+
function mountTools(options: MCPServiceBrokerOptions) {
|
|
576
|
+
const result = ai.mcp.services.createBroker(options) // 成功返回 bind、handleRequest 和 close。
|
|
577
|
+
if (!result.success)
|
|
578
|
+
throw new Error(result.error.message)
|
|
579
|
+
const broker = result.data // 每个执行节点创建自己的入口。
|
|
580
|
+
const server = createServer((req, res) => {
|
|
581
|
+
void broker.handleRequest(req, res)
|
|
582
|
+
}) // 处理绑定地址上的 MCP 请求。
|
|
583
|
+
return { broker, server } // 宿主监听固定地址并负责传输保护,关闭时调用 broker.close() 和 server.close()。
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
async function bindManual(broker: ReturnType<typeof mountTools>['broker'], principal: MCPServiceAuthorization['principal'], sessionId: string, signal: AbortSignal) {
|
|
587
|
+
const result = await broker.bind({
|
|
588
|
+
principal,
|
|
589
|
+
taskId: sessionId,
|
|
590
|
+
signal,
|
|
591
|
+
tools: [
|
|
592
|
+
{
|
|
593
|
+
id: 'manual_search',
|
|
594
|
+
serviceId: 'manual',
|
|
595
|
+
tool: 'search_manual', // 模型可见名称与清单名称分开配置。
|
|
596
|
+
description: 'Search authorized manuals', // 提供给模型的说明。
|
|
597
|
+
inputSchema: {
|
|
598
|
+
type: 'object',
|
|
599
|
+
properties: {
|
|
600
|
+
query: { type: 'string' }
|
|
601
|
+
},
|
|
602
|
+
required: ['query'],
|
|
603
|
+
additionalProperties: false
|
|
604
|
+
}, // 调用时校验工具参数。
|
|
605
|
+
}
|
|
606
|
+
]
|
|
607
|
+
}) // 成功为 { servers, revoke },servers 含当前会话的短期 Bearer。
|
|
608
|
+
if (!result.success)
|
|
609
|
+
throw new Error(result.error.message)
|
|
610
|
+
return result.data // 可从 ACPPlatformPolicy.bindTools 返回;会话结束时撤销凭据。
|
|
611
|
+
}
|
|
242
612
|
```
|
|
243
613
|
|
|
244
614
|
#### Memory / RAG / Knowledge
|
|
245
615
|
|
|
616
|
+
默认数据库 Store 在同一事务提交原生记忆和待同步向量操作。新增、更新、删除及清理成功表示关系数据已经生效,向量索引可稍后追平。向量库故障时读取仍以关系记录为准。任一共享同一关系库和向量库的节点都可以分批重试,进程重启后接续。
|
|
617
|
+
|
|
618
|
+
在 `ai.init({ memory: { vectorNamespace: 'orders-prod' } })` 中设置原生记忆向量命名空间,默认 `default`。独立关系库在共用 Qdrant 时仍会得到不同的物理集合。同一应用各节点使用同一个关系库、命名空间和向量后端。首次升级从关系库保存的向量后台重建索引,既有记忆可继续检索。旧共享集合保持原样。巡检只清理专用集合中的过时向量,每页保存共享进度,迟到写入和重启后可继续回收。 [升级步骤](../../docs/usage/configuration/ai.md#从旧共享集合升级)
|
|
619
|
+
|
|
620
|
+
`ai.memory.scoped({ objectId })` 要求非空且非纯空白的主体 ID,否则工厂立即抛 `TypeError`,不会创建未绑定实例。公共 `clear({ scope: {} })` 等空范围返回失败;跨主体全清必须调用显式管理员入口。原生记忆的访问统计与更新使用版本 CAS,迟到读取不会复活已删除记录;关系事务失败通过 HaiResult 返回。向量同步会自动重试,调用方无需重新提交业务操作。
|
|
621
|
+
|
|
246
622
|
Knowledge 每次导入生成唯一 `revision` 和分块 ID,先完整准备分块、向量及实体,再持久化暂存清单、写入向量,最后通过共享 Store CAS 一次发布正文、实体和元数据。相同文档并发重建只允许一个写入者;失败时保留完整旧版,缩短文档不会留下可见旧尾块。检索只接受当前发布版本,并在发布穿插时重试,持续冲突返回错误供调用方重试。向量候选可能按需扩大,清理积压会增加查询成本。
|
|
247
623
|
|
|
248
624
|
`ingest` 成功结果包含 `revision` 与 `cleanupPending`:后者为 true 表示新版本已经发布,但旧向量删除仍待补偿。调用 `repair({ collection, offset, limit })` 分页重试;`setup` 自动检查前 100 份清单,生产环境应定期扫描全部页。暂存期限为存储端时钟的 5 分钟,超时写入者不能发布;故障暂存的永久墓碑用于反复删除迟到的外部写入,不能随日志保留期删除。SQL 与 vecdb 不组成跨库事务,恢复依赖持久清单和持续补偿。`removeDocument` / `deleteCollection` 先撤销可见性,清理失败返回错误;集合删除保留空向量集合及代际墓碑以支持补偿,重新 setup 不显示上一代内容。
|
|
@@ -260,15 +636,23 @@ if (!enriched.success) {
|
|
|
260
636
|
}
|
|
261
637
|
|
|
262
638
|
// 多租户推荐入口:scoped() 绑定主体与作用域,所有操作自动携带 objectId / scope(含归属校验),杜绝「忘记传 objectId」越权
|
|
263
|
-
const memory = ai.memory.scoped({
|
|
639
|
+
const memory = ai.memory.scoped({
|
|
640
|
+
objectId: 'user-001',
|
|
641
|
+
scope: { topicId: 't-1', personaId: 'p-1' }
|
|
642
|
+
})
|
|
264
643
|
await memory.add({ content: '用户偏好中文', type: 'preference' })
|
|
265
644
|
const recalled = await memory.recall('语言偏好')
|
|
266
645
|
|
|
267
646
|
// clear 拒绝空过滤(防误清全局);全局清空只能显式走管理接口
|
|
268
|
-
await memory.clear({
|
|
647
|
+
await memory.clear({
|
|
648
|
+
types: ['event']
|
|
649
|
+
}) // 仅清该作用域内的 event
|
|
269
650
|
await ai.memory.admin.clearAll({ confirm: true }) // 危险:清空整个记忆后端,需显式确认
|
|
270
651
|
|
|
271
|
-
const rag = await ai.rag.query('核心架构是什么?', {
|
|
652
|
+
const rag = await ai.rag.query('核心架构是什么?', {
|
|
653
|
+
sources: ['docs'],
|
|
654
|
+
topK: 5
|
|
655
|
+
})
|
|
272
656
|
|
|
273
657
|
const setup = await ai.knowledge.setup()
|
|
274
658
|
if (setup.success) {
|
|
@@ -299,11 +683,33 @@ await ai.init({
|
|
|
299
683
|
audio: {
|
|
300
684
|
inheritLlmApiKey: true,
|
|
301
685
|
models: [
|
|
302
|
-
{
|
|
303
|
-
|
|
686
|
+
{
|
|
687
|
+
id: 'asr',
|
|
688
|
+
provider: 'qwen',
|
|
689
|
+
model: 'qwen3-asr-flash-realtime',
|
|
690
|
+
operations: ['transcribe']
|
|
691
|
+
},
|
|
692
|
+
{
|
|
693
|
+
id: 'tts',
|
|
694
|
+
provider: 'qwen',
|
|
695
|
+
model: 'qwen3-tts-flash-realtime',
|
|
696
|
+
operations: ['synthesize']
|
|
697
|
+
},
|
|
304
698
|
// 自托管:whisper / indextts 必须显式配置 baseUrl
|
|
305
|
-
{
|
|
306
|
-
|
|
699
|
+
{
|
|
700
|
+
id: 'whisper',
|
|
701
|
+
provider: 'whisper',
|
|
702
|
+
model: 'faster-whisper-large-v3',
|
|
703
|
+
operations: ['transcribe'],
|
|
704
|
+
baseUrl: 'http://127.0.0.1:8101/v1'
|
|
705
|
+
},
|
|
706
|
+
{
|
|
707
|
+
id: 'indextts',
|
|
708
|
+
provider: 'indextts',
|
|
709
|
+
model: 'indextts-2.5',
|
|
710
|
+
operations: ['synthesize'],
|
|
711
|
+
baseUrl: 'http://127.0.0.1:8102/v1'
|
|
712
|
+
},
|
|
307
713
|
],
|
|
308
714
|
transcribeModel: 'asr',
|
|
309
715
|
synthesizeModel: 'tts',
|
|
@@ -430,6 +836,12 @@ if (result.success) {
|
|
|
430
836
|
|
|
431
837
|
`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
838
|
|
|
839
|
+
#### 文件解析(File)
|
|
840
|
+
|
|
841
|
+
向 `ai.file.parse({ content, filename, options: { outputFormat: 'markdown' } })` 传入业务文件内容和名称;先检查 `success`,再读取 `data.text`,纯文本输出选择 `outputFormat: 'text'`。HTML 使用 parse5 解析结构并迭代提取,忽略 script/style,保留标题、列表、链接、图片、引用、代码和表格等常见 Markdown 结构,不以截断正常文档规避畸形标签的正则回溯。
|
|
842
|
+
|
|
843
|
+
结果是文本或 Markdown,不是可信 HTML;界面使用文本绑定或框架的 `MarkdownRenderer`,不要直接交给 `{@html}`。配置、调用参数和错误码保持原有契约。
|
|
844
|
+
|
|
433
845
|
#### Context 管理器
|
|
434
846
|
|
|
435
847
|
自动记忆提取在本节点后台运行;`pendingMemoryTasks=0` 不代表全部成功。`flush()` 等待本批任务,异常和失败 HaiResult 都返回 `MEMORY_EXTRACT_FAILED`(含失败数量),同轮并发观察者共享结果。返回即确认该批报告,后续只观察新任务,不自动重放可能部分完成的提取。`save()`、`reset({ waitForMemoryTasks: true })`、`consolidate()` 遇到该失败立即返回,不继续后续状态或记忆写入。进程崩溃后的外部效果仍须人工核对。
|
|
@@ -468,7 +880,10 @@ if (manager.success) {
|
|
|
468
880
|
`chatStream` 在**调用上游模型前**就登记轮次并产出 `turn_started`(事件序列 `turn_started → delta* → done`,中途取消时 `turn_started → delta* → cancelled`)。因此即使生成到一半被 `AbortSignal` 取消,也能拿到 `turnId` 与已生成文本,用真实内容提交:
|
|
469
881
|
|
|
470
882
|
```ts
|
|
471
|
-
const created = ai.context.createManager({
|
|
883
|
+
const created = ai.context.createManager({
|
|
884
|
+
scope: { objectId: 'user-001', sessionId: 'sess-001' },
|
|
885
|
+
turnCommit: 'manual'
|
|
886
|
+
})
|
|
472
887
|
if (!created.success)
|
|
473
888
|
return created
|
|
474
889
|
const m = created.data
|
|
@@ -506,7 +921,14 @@ const turns = m.getTurns()
|
|
|
506
921
|
|
|
507
922
|
```ts
|
|
508
923
|
// 会话结束时固化:整合摘要 → 提取长期记忆(写入不含 sessionId 的持久作用域)
|
|
509
|
-
const
|
|
924
|
+
const created = ai.context.createManager({
|
|
925
|
+
scope: { objectId: 'user-001', sessionId: 'sess-001' }
|
|
926
|
+
})
|
|
927
|
+
if (!created.success)
|
|
928
|
+
return created
|
|
929
|
+
const result = await created.data.consolidate({
|
|
930
|
+
scope: { userId: 'user-001', personaId: 'xiaoq' }
|
|
931
|
+
})
|
|
510
932
|
if (result.success) {
|
|
511
933
|
// result.data.summary —— 本次会话整合摘要
|
|
512
934
|
// result.data.memories —— 固化到长期记忆的条目
|
|
@@ -528,18 +950,101 @@ await ai.persona.save({
|
|
|
528
950
|
|
|
529
951
|
// 组合出可直接喂给 ContextManager 的系统提示词(systemPrompt + traits)
|
|
530
952
|
const composed = await ai.persona.compose('xiaoq')
|
|
953
|
+
if (!composed.success)
|
|
954
|
+
return composed
|
|
531
955
|
const manager = ai.context.createManager({
|
|
532
956
|
scope: { objectId: 'user-001', sessionId: 'persona-session' },
|
|
533
957
|
systemPrompt: composed.data,
|
|
534
|
-
memory: {
|
|
958
|
+
memory: {
|
|
959
|
+
enable: true,
|
|
960
|
+
enableExtract: true,
|
|
961
|
+
scope: { personaId: 'xiaoq' }
|
|
962
|
+
},
|
|
535
963
|
})
|
|
536
964
|
```
|
|
537
965
|
|
|
538
|
-
`ai.persona` 提供 `save` / `get` / `update` / `remove` / `list` / `compose
|
|
966
|
+
`ai.persona` 提供 `save` / `get` / `update` / `remove` / `list` / `compose`,按 `[objectId, id]` 隔离角色。保存时传 `objectId`,其余操作传 `{ objectId }`;省略时访问 `system` 平台角色。租户业务应绑定可信认证主体,不能把客户端传入的角色 ID 当作授权。
|
|
539
967
|
|
|
540
|
-
###
|
|
968
|
+
### 安全边界
|
|
969
|
+
|
|
970
|
+
- Prompt、检索文档和模型输出都按不可信输入处理;不要把用户内容拼进不可覆盖的系统规则。
|
|
971
|
+
- Zod 只校验工具参数形状,不代表调用者有权限。高权限工具必须在 handler 内再次校验身份、租户、资源归属与配额,并只把允许自动执行的工具注册给模型。
|
|
972
|
+
- `callRemoteAgent()` 是独立客户端能力,只依赖 `ai.init()`,不要求配置 Agent Card 或注册本地 executor。它拒绝非 HTTP(S) 和 URL 内嵌凭据,但应用仍必须对远端 origin 配置白名单,并在出口代理处限制 DNS 重绑定、重定向到私网和云元数据地址。
|
|
973
|
+
- 不记录完整 Prompt、工具参数、A2A headers、临时模型凭据或带 query 的远端 URL;确需审计时仅保存脱敏摘要。
|
|
541
974
|
|
|
542
|
-
|
|
975
|
+
### 返回句柄的用法
|
|
976
|
+
|
|
977
|
+
`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 覆盖。
|
|
978
|
+
|
|
979
|
+
| 入口 | 场景 | 输入 | 输出 | 调用片段 |
|
|
980
|
+
| -------------------------- | ------------------ | ---------------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------- |
|
|
981
|
+
| `registry.register` | 登记单个工具 | `Tool` | `HaiResult<void>; duplicate rejected` | `registry.register(tool)` |
|
|
982
|
+
| `registry.registerMany` | 批量登记工具 | `Tool[]` | `HaiResult<void>` | `registry.registerMany(tools)` |
|
|
983
|
+
| `registry.replace` | 显式替换工具 | `Tool with existing name` | `HaiResult<void>` | `registry.replace(tool)` |
|
|
984
|
+
| `registry.unregister` | 移除工具 | `tool name` | `boolean` | `registry.unregister("search")` |
|
|
985
|
+
| `registry.get` | 读取工具定义 | `tool name` | `Tool or undefined` | `registry.get("search")` |
|
|
986
|
+
| `registry.has` | 检查工具存在 | `tool name` | `boolean` | `registry.has("search")` |
|
|
987
|
+
| `registry.getNames` | 工具名称 | `none` | `string[]` | `registry.getNames()` |
|
|
988
|
+
| `registry.getDefinitions` | 传给模型的定义 | `none` | `ToolDefinition[]` | `registry.getDefinitions()` |
|
|
989
|
+
| `registry.execute` | 授权后执行工具 | `ToolCall, ToolExecutionOptions?` | `Promise<HaiResult<ToolMessage>>` | `registry.execute(toolCall, { objectId: "u1" })` |
|
|
990
|
+
| `registry.executeAll` | 逐个或显式并行执行 | `ToolCall[], { parallel?, ...executionOptions }` | `Promise<HaiResult<ToolMessage[]>>` | `registry.executeAll(toolCalls)` |
|
|
991
|
+
| `registry.clear` | 清理本地工具 | `none` | `void` | `registry.clear()` |
|
|
992
|
+
| `registry.size` | 工具数量 | `none` | `number` | `registry.size` |
|
|
993
|
+
| `manager.addMessage` | 补充对话消息 | `ChatMessage` | `Promise<HaiResult<void>>` | `manager.addMessage({ role: "user", content: "你好" })` |
|
|
994
|
+
| `manager.getMessages` | 读取对话快照 | `none` | `HaiResult<ChatMessage[]>` | `manager.getMessages()` |
|
|
995
|
+
| `manager.reload` | 刷新共享快照 | `none` | `Promise<HaiResult<void>>` | `manager.reload()` |
|
|
996
|
+
| `manager.getTokenUsage` | 观察上下文预算 | `none` | `HaiResult<{ current, budget }>` | `manager.getTokenUsage()` |
|
|
997
|
+
| `manager.getSummaries` | 读取摘要 | `none` | `HaiResult<SummaryResult[]>` | `manager.getSummaries()` |
|
|
998
|
+
| `manager.save` | 持久保存 | `none` | `Promise<HaiResult<void>>` | `manager.save()` |
|
|
999
|
+
| `manager.flush` | 等待后台记忆写入 | `none` | `Promise<HaiResult<void>>` | `manager.flush()` |
|
|
1000
|
+
| `manager.reset` | 终止并重置对话 | `ContextResetOptions?` | `Promise<HaiResult<void>>` | `manager.reset({ preserveSystemPrompt: true })` |
|
|
1001
|
+
| `manager.getTurns` | 读取真实轮次 | `none` | `HaiResult<ConversationTurn[]>` | `manager.getTurns()` |
|
|
1002
|
+
| `manager.markTurnSpeaking` | 记录开始播放 | `turnId` | `Promise<HaiResult<void>>` | `manager.markTurnSpeaking(turnId)` |
|
|
1003
|
+
| `manager.commitTurn` | 提交已表达内容 | `turnId, { text? }` | `Promise<HaiResult<void>>` | `manager.commitTurn(turnId, { text: spokenText })` |
|
|
1004
|
+
| `manager.interruptTurn` | 提交打断前内容 | `turnId, { text? }` | `Promise<HaiResult<void>>` | `manager.interruptTurn(turnId, { text: spokenText })` |
|
|
1005
|
+
| `manager.consolidate` | 固化长期记忆 | `ConsolidateOptions?` | `Promise<HaiResult<{ summary, memories }>>` | `manager.consolidate({ scope: { personaId: "tutor" } })` |
|
|
1006
|
+
| `manager.chat` | 多轮回答 | `message: string, ContextChatOptions?` | `Promise<HaiResult<ContextChatResult>>` | `manager.chat("请继续")` |
|
|
1007
|
+
| `manager.chatStream` | 多轮流式回答 | `message: string, ContextChatOptions?` | `AsyncIterable<ContextStreamEvent>` | `manager.chatStream("请继续")` |
|
|
1008
|
+
| `session.info` | 读取受管会话 | `none` | `Promise<HaiResult<ACPSessionInfo>>` | `session.info()` |
|
|
1009
|
+
| `session.prompt` | 执行一轮开发 | `ContentBlock[], AbortSignal?` | `Promise<HaiResult<{ text, stopReason, events }>>` | `session.prompt([{ type: "text", text: "检查工程" }])` |
|
|
1010
|
+
| `session.promptStructured` | 校验一份 JSON | `ContentBlock[], Zod schema, AbortSignal?` | `Promise<HaiResult<schema-inferred T>>` | `session.promptStructured(content, OutputSchema)` |
|
|
1011
|
+
| `session.stream` | 观察原生事件 | `ContentBlock[], AbortSignal?` | `AsyncIterable<SessionNotification>; failure throws` | `session.stream([{ type: "text", text: "检查工程" }])` |
|
|
1012
|
+
| `session.cancel` | 取消当前轮次 | `none` | `Promise<HaiResult<void>>` | `session.cancel()` |
|
|
1013
|
+
| `session.setMode` | 选择已公布模式 | `native mode ID` | `Promise<HaiResult<native mode response>>` | `session.setMode("code")` |
|
|
1014
|
+
| `session.setConfigOption` | 设置已公布选项 | `native option key and allowed value` | `Promise<HaiResult<native config response>>` | `session.setConfigOption("model", "coding")` |
|
|
1015
|
+
| `session.updateMain` | 仅快进更新主分支 | `none; execution and preview must be stopped` | `Promise<HaiResult<ACPGitReport[]>>; partial failure reports in cause` | `session.updateMain()` |
|
|
1016
|
+
| `session.publish` | 提交并推送 | `{ mode, message, author }; managed isolated session only` | `Promise<HaiResult<ACPGitReport[]>>` | `session.publish(publishOptions)` |
|
|
1017
|
+
| `session.close` | 停止执行保留状态 | `none` | `Promise<HaiResult<void>>` | `session.close()` |
|
|
1018
|
+
| `connection.authenticate` | 原生认证 | `advertised authentication method ID` | `Promise<HaiResult<native auth response>>` | `connection.authenticate("api-key")` |
|
|
1019
|
+
| `connection.createSession` | 创建低层原生会话 | `absolute remote cwd, McpServer[]?` | `Promise<HaiResult<{ id, prompt, cancel }>>` | `connection.createSession("/workspace/project", [])` |
|
|
1020
|
+
| `connection.listSessions` | 原生分页会话 | `cursor?` | `Promise<HaiResult<native paginated response>>` | `connection.listSessions()` |
|
|
1021
|
+
| `connection.deleteSession` | 删除原生会话 | `native session ID` | `Promise<HaiResult<native delete response>>` | `connection.deleteSession(nativeId)` |
|
|
1022
|
+
| `connection.close` | 关闭低层连接 | `none` | `Promise<HaiResult<void>>` | `connection.close()` |
|
|
1023
|
+
|
|
1024
|
+
## 配置
|
|
1025
|
+
|
|
1026
|
+
### 按场景选择配置入口
|
|
1027
|
+
|
|
1028
|
+
| 配置入口 | 场景 | 输入 | 生效结果 | 示例 |
|
|
1029
|
+
| ----------- | ------------------ | -------------------------------------------------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
1030
|
+
| `llm` | 模型连接与请求协议 | model, protocol, apiKey/baseUrl, timeout, models/scenarios | chat/Responses/Anthropic selection; normalized model requests | `{ llm: { model: "gpt-4o-mini", timeout: 60000 } }` |
|
|
1031
|
+
| `embedding` | 检索向量 | model?, dimensions?, batchSize? | consistent vector dimensions for the target collection | `{ embedding: { dimensions: 1536, batchSize: 100 } }` |
|
|
1032
|
+
| `mcp` | 外部工具服务 | servers with transport/endpoints or commands | registered server definitions; application authorizes tool execution | `{ mcp: { servers: [] } }` |
|
|
1033
|
+
| `retrieval` | 默认信源 | sources: { id, collection, topK?, minScore?, filter? }[] | queryable source definitions; does not import documents | `{ retrieval: { sources: [{ id: "docs", collection: "manual", topK: 5 }] } }` |
|
|
1034
|
+
| `knowledge` | 文档发布与分块 | collection, dimension, cleanOptions, chunkOptions | versioned document/vector publication and bounded chunks | `{ knowledge: { collection: "manual", dimension: 1536, chunkOptions: { maxSize: 1500, overlap: 200 } } }` |
|
|
1035
|
+
| `memory` | 主体记忆后端和预算 | provider, quotas, recencyDecay, defaultTopK, candidateMultiplier | native or Mem0-format behavior with explicit persistence limits | `{ memory: { provider: "native", defaultTopK: 10 } }` |
|
|
1036
|
+
| `token` | Token 估算 | tokenRatio > 0; default 0.25 | local token budget estimates; not provider billing usage | `{ token: { tokenRatio: 0.25 } }` |
|
|
1037
|
+
| `summary` | 摘要规则 | systemPrompt? | prompt used by summary generation; model from llm.scenarios | `{ summary: { systemPrompt: "保留已确认决策和待办" } }` |
|
|
1038
|
+
| `compress` | 上下文压缩预算 | defaultStrategy, defaultMaxTokens, preserveLastN | compression defaults; 0 budget derives from model limit | `{ compress: { defaultStrategy: "hybrid", defaultMaxTokens: 4000, preserveLastN: 4 } }` |
|
|
1039
|
+
| `file` | OCR 提取规则 | systemPrompt?; model via llm.scenarios.ocr | text extraction instructions; not HTML sanitization | `{ file: { systemPrompt: "只提取可见文字" } }` |
|
|
1040
|
+
| `audio` | 语音模型与容量 | models, transcribeModel/synthesizeModel, maxAudioBytes/maxStreamDurationMs | provider capability/operation selection and bounded input/stream | `see Audio examples` |
|
|
1041
|
+
| `image` | 图像模型与下载预算 | models, generateModel, maxImageBytes, maxImages; timeout per model | generated bytes with MIME; unsafe downloads rejected | `see Image examples` |
|
|
1042
|
+
| `a2a` | 代理发现与执行租约 | agentCard and execution lease/poll/deadline options | ProtoJSON discovery and shared task journal | `see A2A protocol section` |
|
|
1043
|
+
| `acp` | 智能体执行约束 | agents/workspaces and execution content/event limits | validated definitions and managed native sessions | `see ACP guide` |
|
|
1044
|
+
|
|
1045
|
+
Rerank 继承全局 LLM timeout,模型条目可覆盖;同一预算覆盖请求及响应正文,超时返回 RERANK_API_ERROR。
|
|
1046
|
+
|
|
1047
|
+
模型请求协议通过 `llm.protocol`、`llm.models[].protocol` 或单次 `tempModel.protocol` 指定,支持 `chat | responses | anthropic`。环境变量为 `HAI_AI_LLM_PROTOCOL`、`HAI_AI_LLM_MODELS_0_PROTOCOL`(模型项按索引递增);凭据通过 `apiKey` 或相应私有环境提供。
|
|
543
1048
|
|
|
544
1049
|
```yaml
|
|
545
1050
|
llm:
|
|
@@ -587,7 +1092,7 @@ memory:
|
|
|
587
1092
|
通过 `core.config.load('ai', ...)` 加载时,约定环境变量优先于 YAML;
|
|
588
1093
|
例如 `HAI_AI_LLM_APIKEY`、`HAI_AI_LLM_BASEURL`、`HAI_AI_LLM_MODEL`。
|
|
589
1094
|
|
|
590
|
-
启用
|
|
1095
|
+
启用 Mem0 数据格式适配:
|
|
591
1096
|
|
|
592
1097
|
```yaml
|
|
593
1098
|
memory:
|
|
@@ -596,17 +1101,15 @@ memory:
|
|
|
596
1101
|
```
|
|
597
1102
|
|
|
598
1103
|
- **`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 退回内存匹配,结果一致)。
|
|
599
|
-
- **`mem0
|
|
600
|
-
|
|
601
|
-
两个 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 })`。
|
|
1104
|
+
- **`mem0`(数据格式适配)**:框架负责提取与 Embedding,通过原生 HTTP 读写 Qdrant 的 Mem0 UUID/payload 格式,可读取既有数据;不运行完整上游引擎、遥测或历史数据库。仅映射带完整连接参数的 Qdrant。生产(`NODE_ENV` 或 `HAI_CORE_ENV=production`)拒绝临时回退;开发或明确 E2E 可显式使用 `memory.allowEphemeralFallback: true`。其它持久化后端选择 `native`。
|
|
602
1105
|
|
|
603
|
-
|
|
1106
|
+
两个 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 })`。
|
|
604
1107
|
|
|
605
|
-
|
|
1108
|
+
Mem0 格式存储与 VecDB 的 Qdrant Provider 均使用原生 HTTP,无需额外 SDK。固定 REST 请求使用 `query`,路径段编码;30 秒超时覆盖完整响应体,响应超过 16 MiB 明确失败。写入和删除等待 `wait=true` 的实际完成回执。列表和条件清理最多核对每主体 1000 条原始候选(包括过期项),超限返回 `MEMORY_LIST_INCOMPLETE`,不执行部分条件删除;仅按主体清理不受此列表上限限制。
|
|
606
1109
|
|
|
607
|
-
|
|
1110
|
+
Qdrant 格式后端要求 1.19 或更新版本,并拒绝 HTTP 重定向。更新使用服务端 `update_only` 与主体/版本条件,同一次原子写入拒绝已删除或已被其它写入更新的条目;迟到更新不会复活删除记录。写后版本核对失败仍需按已有回执核对实际效果。
|
|
608
1111
|
|
|
609
|
-
`add` / `extract`
|
|
1112
|
+
`add` / `extract` 的写入回执不含完整业务字段,框架写后读取权威记录再返回;并发提取等待全部在途写入结束。若写入或写后读失败,`error.ext.requiresEffectReconciliation=true`,`memoryIds` 保存已知写入 ID(回执丢失时可能为空)。应按主体核对实际记忆后决定恢复,不能盲目重做 add/extract;框架不自动重放。
|
|
610
1113
|
|
|
611
1114
|
**候选池与 scope 漏召回**:`scope` 过滤在内存中完成,若先按 `topK` 截断再过滤,同一主体下相关度较高的其它主题/角色记忆会把目标 scope 的记忆挤出候选池,导致「明明有却召回 0 条」。为此 `recall` / `injectMemories` 先取回 `topK × candidateMultiplier`(默认 5)条候选,过滤后再截取 `topK`。scope 隔离越细(如按 `topicId` + `personaId`),可将 `candidateMultiplier` 调大:
|
|
612
1115
|
|
|
@@ -621,14 +1124,9 @@ const memories = await ai.memory.recall('经济发展', {
|
|
|
621
1124
|
|
|
622
1125
|
`ai.config` 返回脱敏后的配置快照;`apiKey`、`privateKey`、URL 内嵌凭证等敏感字段不会原样暴露。
|
|
623
1126
|
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
- Prompt、检索文档和模型输出都按不可信输入处理;不要把用户内容拼进不可覆盖的系统规则。
|
|
627
|
-
- Zod 只校验工具参数形状,不代表调用者有权限。高权限工具必须在 handler 内再次校验身份、租户、资源归属与配额,并只把允许自动执行的工具注册给模型。
|
|
628
|
-
- `callRemoteAgent()` 是独立客户端能力,只依赖 `ai.init()`,不要求配置 Agent Card 或注册本地 executor。它拒绝非 HTTP(S) 和 URL 内嵌凭据,但应用仍必须对远端 origin 配置白名单,并在出口代理处限制 DNS 重绑定、重定向到私网和云元数据地址。
|
|
629
|
-
- 不记录完整 Prompt、工具参数、A2A headers、临时模型凭据或带 query 的远端 URL;确需审计时仅保存脱敏摘要。
|
|
1127
|
+
原生记忆新增使用共享关系库事务串行检查主体与全局配额。淘汰每次最多读取最旧 64 条候选并按重要性和时效评分。旧库超过配额时,新写入会先回收一批,直到有余量。自定义共享 Store 可实现 `AIRelStore.withWriteLock` 提供同样的跨节点保证。
|
|
630
1128
|
|
|
631
|
-
|
|
1129
|
+
## 错误处理
|
|
632
1130
|
|
|
633
1131
|
```ts
|
|
634
1132
|
const result = await ai.llm.chat({ messages })
|