@h-ai/ai 1.0.0-beta.23 → 1.0.0-beta.25
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 +308 -141
- package/README.ja.md +308 -141
- package/README.md +306 -141
- package/dist/{ai-acp-types-BNeA1j0P.d.ts → ai-acp-types-Bwp6PcL8.d.ts} +2265 -230
- package/dist/browser.d.ts +3 -1
- package/dist/browser.js +3 -3
- package/dist/{chunk-WSH2246H.js → chunk-3R5SMLSJ.js} +3 -3
- package/dist/{chunk-WSH2246H.js.map → chunk-3R5SMLSJ.js.map} +1 -1
- package/dist/{chunk-M77C3VAP.js → chunk-NRDLMUSY.js} +4 -2
- package/dist/chunk-NRDLMUSY.js.map +1 -0
- package/dist/{chunk-CCXG2S7O.js → chunk-VEWBD2J4.js} +157 -9
- package/dist/chunk-VEWBD2J4.js.map +1 -0
- package/dist/client/index.js +2 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +3088 -879
- package/dist/index.js.map +1 -1
- package/models/agents/README.md +30 -18
- package/models/agents/build.mjs +158 -55
- package/models/agents/codex-acp/Dockerfile +8 -13
- package/models/agents/deepseek-harness/Dockerfile +8 -13
- package/models/agents/goose/Dockerfile +8 -13
- package/models/agents/goose/agent.json +1 -1
- package/package.json +11 -8
- 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-CCXG2S7O.js.map +0 -1
- package/dist/chunk-M77C3VAP.js.map +0 -1
package/README.md
CHANGED
|
@@ -49,146 +49,148 @@ finally {
|
|
|
49
49
|
|
|
50
50
|
下表的调用片段复用本页已初始化的服务;命名变量代表应用已提供的请求、Schema、资源定义或配置。完整步骤和失败处理见对应功能示例。`HaiResult` 先判断 `success`,异步项按签名 `await`。
|
|
51
51
|
|
|
52
|
-
| 入口 | 场景
|
|
53
|
-
| --------------------------------- |
|
|
54
|
-
| `ai.llm.chat` | 单次回答
|
|
55
|
-
| `ai.llm.chatStream` | 逐块回答
|
|
56
|
-
| `ai.llm.ask` | 纯文本问答
|
|
57
|
-
| `ai.llm.askStream` | 纯文本流
|
|
58
|
-
| `ai.llm.generateObject` | 受 Schema 约束的答案
|
|
59
|
-
| `ai.llm.listModels` | 查询模型
|
|
60
|
-
| `ai.llm.getHistory` | 读取对话历史
|
|
61
|
-
| `ai.llm.listSessions` | 列出主体会话
|
|
62
|
-
| `ai.tools.define` | 定义可授权工具
|
|
63
|
-
| `ai.tools.createRegistry` | 管理工具集合
|
|
64
|
-
| `ai.stream.createProcessor` | 积累增量文本
|
|
65
|
-
| `ai.stream.collect` | 完整消费聊天流
|
|
66
|
-
| `ai.stream.createSSEDecoder` | 跨片段解码 SSE
|
|
67
|
-
| `ai.stream.encodeSSE` | 编码事件流
|
|
68
|
-
| `ai.embedding.embed` | 通用向量请求
|
|
69
|
-
| `ai.embedding.embedText` | 单段向量
|
|
70
|
-
| `ai.embedding.embedBatch` | 批量向量
|
|
71
|
-
| `ai.mcp.registerTool` | 注册本进程工具
|
|
72
|
-
| `ai.mcp.registerResource` | 注册资源
|
|
73
|
-
| `ai.mcp.registerPrompt` | 注册提示词
|
|
74
|
-
| `ai.mcp.callTool` | 调用已注册工具
|
|
75
|
-
| `ai.mcp.readResource` | 读取资源
|
|
76
|
-
| `ai.mcp.getPrompt` | 构建提示词
|
|
77
|
-
| `ai.
|
|
78
|
-
| `ai.
|
|
79
|
-
| `ai.retrieval.
|
|
80
|
-
| `ai.retrieval.
|
|
81
|
-
| `ai.
|
|
82
|
-
| `ai.
|
|
83
|
-
| `ai.
|
|
84
|
-
| `ai.
|
|
85
|
-
| `ai.knowledge.
|
|
86
|
-
| `ai.knowledge.
|
|
87
|
-
| `ai.knowledge.
|
|
88
|
-
| `ai.knowledge.
|
|
89
|
-
| `ai.knowledge.
|
|
90
|
-
| `ai.knowledge.
|
|
91
|
-
| `ai.knowledge.
|
|
92
|
-
| `ai.knowledge.
|
|
93
|
-
| `ai.knowledge.
|
|
94
|
-
| `ai.knowledge.
|
|
95
|
-
| `ai.
|
|
96
|
-
| `ai.
|
|
97
|
-
| `ai.memory.
|
|
98
|
-
| `ai.memory.
|
|
99
|
-
| `ai.memory.
|
|
100
|
-
| `ai.memory.
|
|
101
|
-
| `ai.memory.
|
|
102
|
-
| `ai.memory.
|
|
103
|
-
| `ai.memory.
|
|
104
|
-
| `ai.memory.
|
|
105
|
-
| `ai.memory.
|
|
106
|
-
| `ai.memory.
|
|
107
|
-
| `ai.
|
|
108
|
-
| `ai.
|
|
109
|
-
| `ai.persona.
|
|
110
|
-
| `ai.persona.
|
|
111
|
-
| `ai.persona.
|
|
112
|
-
| `ai.persona.
|
|
113
|
-
| `ai.
|
|
114
|
-
| `ai.
|
|
115
|
-
| `ai.
|
|
116
|
-
| `ai.
|
|
117
|
-
| `ai.
|
|
118
|
-
| `ai.
|
|
119
|
-
| `ai.
|
|
120
|
-
| `ai.context.
|
|
121
|
-
| `ai.context.
|
|
122
|
-
| `ai.context.
|
|
123
|
-
| `ai.
|
|
124
|
-
| `ai.
|
|
125
|
-
| `ai.
|
|
126
|
-
| `ai.
|
|
127
|
-
| `ai.
|
|
128
|
-
| `ai.
|
|
129
|
-
| `ai.
|
|
130
|
-
| `ai.
|
|
131
|
-
| `ai.audio.
|
|
132
|
-
| `ai.audio.
|
|
133
|
-
| `ai.audio.
|
|
134
|
-
| `ai.
|
|
135
|
-
| `ai.
|
|
136
|
-
| `ai.
|
|
137
|
-
| `ai.a2a.
|
|
138
|
-
| `ai.a2a.
|
|
139
|
-
| `ai.a2a.
|
|
140
|
-
| `ai.
|
|
141
|
-
| `ai.
|
|
142
|
-
| `ai.
|
|
143
|
-
| `ai.
|
|
144
|
-
| `ai.
|
|
145
|
-
| `ai.
|
|
146
|
-
| `ai.llm.models.
|
|
147
|
-
| `ai.llm.models.
|
|
148
|
-
| `ai.llm.models.
|
|
149
|
-
| `ai.
|
|
150
|
-
| `ai.
|
|
151
|
-
| `ai.audio.models.
|
|
152
|
-
| `ai.audio.models.
|
|
153
|
-
| `ai.audio.models.
|
|
154
|
-
| `ai.
|
|
155
|
-
| `ai.
|
|
156
|
-
| `ai.image.models.
|
|
157
|
-
| `ai.image.models.
|
|
158
|
-
| `ai.image.models.
|
|
159
|
-
| `ai.
|
|
160
|
-
| `ai.
|
|
161
|
-
| `ai.mcp.servers.
|
|
162
|
-
| `ai.mcp.servers.
|
|
163
|
-
| `ai.mcp.servers.
|
|
164
|
-
| `ai.
|
|
165
|
-
| `ai.
|
|
166
|
-
| `ai.retrieval.sources.
|
|
167
|
-
| `ai.retrieval.sources.
|
|
168
|
-
| `ai.retrieval.sources.
|
|
169
|
-
| `ai.
|
|
170
|
-
| `ai.
|
|
171
|
-
| `ai.acp.agents.
|
|
172
|
-
| `ai.acp.agents.
|
|
173
|
-
| `ai.acp.agents.
|
|
174
|
-
| `ai.acp.
|
|
175
|
-
| `ai.acp.
|
|
176
|
-
| `ai.acp.workspaces.
|
|
177
|
-
| `ai.acp.workspaces.
|
|
178
|
-
| `ai.acp.workspaces.
|
|
179
|
-
| `ai.acp.
|
|
180
|
-
| `ai.acp.
|
|
181
|
-
| `ai.acp.
|
|
182
|
-
| `ai.acp.
|
|
183
|
-
| `ai.acp.
|
|
184
|
-
| `ai.acp.
|
|
185
|
-
| `ai.acp.sessions.
|
|
186
|
-
| `ai.acp.sessions.
|
|
187
|
-
| `ai.acp.sessions.
|
|
188
|
-
| `ai.acp.sessions.
|
|
189
|
-
| `ai.acp.sessions.
|
|
190
|
-
| `ai.acp.
|
|
191
|
-
| `ai.acp.
|
|
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()` |
|
|
192
194
|
|
|
193
195
|
- `ai.tools`:工具定义、注册表、批量执行;无需初始化。
|
|
194
196
|
- `ai.stream`:ChatCompletion 流式 chunk 处理;无需初始化。
|
|
@@ -342,6 +344,29 @@ const temp = await ai.llm.chat({
|
|
|
342
344
|
|
|
343
345
|
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。
|
|
344
346
|
|
|
347
|
+
##### 结构化输出:`ai.llm.generateObject`
|
|
348
|
+
|
|
349
|
+
按模型或网关的响应能力选择 `responseFormat`。默认 `json_schema` 向上游发送严格 JSON Schema,`schemaName` 只用于此模式,默认 `result`。仅支持通用 JSON 的 Chat 网关使用 `json_object`,框架将 Schema 放入提示词。两种模式都在本地用同一个 Zod Schema 校验,解析或校验失败时可按 `maxRepairs` 修复,默认一次。
|
|
350
|
+
|
|
351
|
+
```ts
|
|
352
|
+
import { ai } from '@h-ai/ai'
|
|
353
|
+
import { z } from 'zod'
|
|
354
|
+
|
|
355
|
+
// 已初始化 AI,llm 使用支持通用 JSON 模式的文本模型。
|
|
356
|
+
const result = await ai.llm.generateObject({
|
|
357
|
+
schema: z.object({
|
|
358
|
+
title: z.string()
|
|
359
|
+
}), // 要求返回含 title 字符串的对象。
|
|
360
|
+
messages: [
|
|
361
|
+
{ role: 'user', content: '为发布检查表生成标题。' }
|
|
362
|
+
], // 本次输入。
|
|
363
|
+
responseFormat: 'json_object', // 请求通用 JSON,仍会执行本地 Zod 校验。
|
|
364
|
+
maxRepairs: 1, // 解析或校验失败时允许再请求一次。
|
|
365
|
+
})
|
|
366
|
+
if (result.success)
|
|
367
|
+
process.stdout.write(result.data.title) // 例如:发布检查表。
|
|
368
|
+
```
|
|
369
|
+
|
|
345
370
|
#### 工具调用
|
|
346
371
|
|
|
347
372
|
```ts
|
|
@@ -396,10 +421,73 @@ Goose 1.57.0 镜像提供原生 `goose serve` HTTP/WS `/acp` 服务,通过 cus
|
|
|
396
421
|
|
|
397
422
|
模型容量、模态和推理能力填 `llm.models[].capabilities`,未知不猜。Codex 要求原生 Responses;Hai 现有转换不是反向服务网关。关闭后保留代码/状态卷,确认拥有的进程停止才释放 CAS 占用;worktree 不是安全沙箱。
|
|
398
423
|
|
|
399
|
-
接入示例与限制见 [ACP 指南](../cli/templates/skills/hai-ai/acp.md)。[Agent 镜像](models/agents/README.md)
|
|
424
|
+
接入示例与限制见 [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 服务端。
|
|
400
425
|
|
|
401
426
|
托管 Git 遇到子模块或 Git LFS 属性时明确返回 ACP_UNSUPPORTED,避免将不完整工程报告为就绪。
|
|
402
427
|
|
|
428
|
+
##### 按用户运行受管 ACP
|
|
429
|
+
|
|
430
|
+
服务启动时先初始化 RelDB 和 [Runner](../runner/README.md),再将已启动的实例传给 `ai.init(config, { runner, acpPolicy })`。在 `acp.agents` 注册 Agent,并用 `environmentIds` 绑定 Runner 的固定镜像环境,用 `modelIds` 绑定 `llm.models` 的模型。Codex 需要 Responses 网关。API 和执行节点使用共享数据库与相同环境定义。关闭服务时先关闭 AI,再关闭 Runner 和数据库。
|
|
431
|
+
|
|
432
|
+
`task` 为本次会话启动独占 Worker,`user` 可在同一主体与启动配置下复用。`auto` 按策略选择。`shared` 只适用于明确支持共享的只读适配器,且会话不能申请私有上下文、工作区或工具,内置 Codex、DeepSeek Harness 和 Goose 仍使用独立模式。配置示例见 [ACP 配置](../../docs/usage/configuration/ai.md#acp-接入与模型能力)。
|
|
433
|
+
|
|
434
|
+
```ts
|
|
435
|
+
import type { RunnerScope } from '@h-ai/runner' // tenantId 和 userId 来自已认证的应用会话。
|
|
436
|
+
import { ai } from '@h-ai/ai' // 使用已注入 Runner 的服务端实例。
|
|
437
|
+
|
|
438
|
+
async function summarize(identity: RunnerScope, requestId: string) {
|
|
439
|
+
const agent = ai.acp.scoped(identity) // 将后续任务、会话和权限访问绑定到此主体。
|
|
440
|
+
const options = {
|
|
441
|
+
agentId: 'assistant',
|
|
442
|
+
execution: { mode: 'auto' as const }
|
|
443
|
+
} // assistant 是已登记的 Agent。
|
|
444
|
+
const plan = await agent.plan(options) // 返回实际模式、环境、模型和资源设置,不领取容器。
|
|
445
|
+
if (!plan.success)
|
|
446
|
+
return plan // 环境或权限不满足时不提交。
|
|
447
|
+
const result = await agent.run({ ...options, prompt: '列出三条发布检查项', idempotencyKey: requestId }) // 返回 taskId、output 和生效选项。
|
|
448
|
+
if (!result.success)
|
|
449
|
+
return result // 提交、执行或清理失败时返回 HaiResult 错误。
|
|
450
|
+
const events = await agent.tasks.events(result.data.taskId, 0, 20) // 读取前 20 个持久事件,空页为 []。
|
|
451
|
+
if (!events.success)
|
|
452
|
+
return events
|
|
453
|
+
return { result: result.data, events: events.data } // 例如 output.text 是模型回答,events 含按序号排列的事件。
|
|
454
|
+
}
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
```ts
|
|
458
|
+
import type { RunnerScope } from '@h-ai/runner' // 服务端认证主体。
|
|
459
|
+
import { ai } from '@h-ai/ai' // assistant 已登记,并允许在同一用户内复用 Worker。
|
|
460
|
+
|
|
461
|
+
async function continueWork(identity: RunnerScope) {
|
|
462
|
+
const agent = ai.acp.scoped(identity) // 成功访问只限当前主体的资源。
|
|
463
|
+
const created = await agent.sessions.create({
|
|
464
|
+
agentId: 'assistant',
|
|
465
|
+
execution: { mode: 'user' }
|
|
466
|
+
}) // 成功得到含 id 的会话句柄。
|
|
467
|
+
if (!created.success)
|
|
468
|
+
return created
|
|
469
|
+
const session = created.data // 句柄提供 prompt、stream、changeExecution 和 close。
|
|
470
|
+
const run = async () => {
|
|
471
|
+
const first = await session.prompt('记下验收目标') // 返回这一轮的 taskId、output 与生效选项。
|
|
472
|
+
if (!first.success)
|
|
473
|
+
return first
|
|
474
|
+
const switched = await session.changeExecution({ mode: 'task', acceptNewSession: true }) // 保留业务 id,建立新的原生会话。
|
|
475
|
+
if (!switched.success)
|
|
476
|
+
return switched
|
|
477
|
+
return await session.prompt('给出独立验收清单') // 模型回答位于成功结果的 data.output。
|
|
478
|
+
}
|
|
479
|
+
return run().finally(async () => {
|
|
480
|
+
const closed = await session.close() // 成功的 data 为 undefined,释放会话或独占任务环境。
|
|
481
|
+
if (!closed.success)
|
|
482
|
+
throw new Error(closed.error.message)
|
|
483
|
+
})
|
|
484
|
+
}
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
使用 `agents.describe(agentId)` 查询内置适配器的能力,`sessions.get(id)` 由同一主体在其他 API 节点取得句柄,`session.stream(prompt, options)` 迭代持久事件并在失败时抛错。`tasks.get(taskId)` 返回执行回执,`tasks.cancel(taskId)` 接受取消并返回当前状态。可在 `run` 或 `prompt` 的 `onEvent` 中取得 `accepted` 事件的 `taskId`,然后用另一请求查看或取消。
|
|
488
|
+
|
|
489
|
+
`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`。工作区提供只读快照,切换后可按需带入用户确认的 `historySummary`。更多示例见 [受管调用](../../docs/usage/development/ai-acp.md#多用户应用的受管调用)。
|
|
490
|
+
|
|
403
491
|
#### 配置与数据库资源清单
|
|
404
492
|
|
|
405
493
|
`llm.models`、`audio.models`、`image.models`、`mcp.servers`、`retrieval.sources`、`acp.agents/workspaces` 合并配置和数据库。配置同 ID 优先且只读,数据库支持 list/get/register/update/remove;条目返回 value/source/version,更新可检查版本。异步调用读取最新定义,音频同步能力查询使用最近刷新快照。资源错误为 090–094。管理定义可能含模型密钥,仅在可信服务端使用。
|
|
@@ -444,6 +532,81 @@ await server.connect(new StreamableHTTPServerTransport({
|
|
|
444
532
|
}))
|
|
445
533
|
```
|
|
446
534
|
|
|
535
|
+
##### 调用远程 MCP 和独立工具作业
|
|
536
|
+
|
|
537
|
+
在 `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)。
|
|
538
|
+
|
|
539
|
+
```ts
|
|
540
|
+
import type { MCPServiceAuthorization } from '@h-ai/ai' // 应用从 IAM 构造主体和按实际参数复核权限的回调。
|
|
541
|
+
import { ai } from '@h-ai/ai' // 服务端已初始化,并登记了 manual 与 office 服务。
|
|
542
|
+
|
|
543
|
+
async function searchManual(access: MCPServiceAuthorization, query: string) {
|
|
544
|
+
const result = await ai.mcp.services.invoke({
|
|
545
|
+
serviceId: 'manual',
|
|
546
|
+
tool: 'search_manual',
|
|
547
|
+
arguments: { query }
|
|
548
|
+
}, access) // 目录和授权通过后得到标准 MCP 工具结果。
|
|
549
|
+
if (!result.success)
|
|
550
|
+
return result // 权限拒绝或上游失败时保留错误。
|
|
551
|
+
return result.data.content // 例如 [{ type: 'text', text: '...' }]。
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
async function convertDocument(access: MCPServiceAuthorization, fileId: string) {
|
|
555
|
+
const result = await ai.mcp.services.invoke({
|
|
556
|
+
serviceId: 'office',
|
|
557
|
+
tool: 'office.convert',
|
|
558
|
+
arguments: { fileId }
|
|
559
|
+
}, access) // 用授权对象 ID 提交离线转换。
|
|
560
|
+
if (!result.success)
|
|
561
|
+
return result
|
|
562
|
+
return result.data.structuredContent // 成功示例 { fileId: 'pdf-123', name: 'result.pdf' },下载需再次验权。
|
|
563
|
+
}
|
|
564
|
+
```
|
|
565
|
+
|
|
566
|
+
```ts
|
|
567
|
+
import type { MCPServiceAuthorization, MCPServiceBrokerOptions } from '@h-ai/ai' // url 由部署方指定,authorize 每次检查当前主体、任务和参数。
|
|
568
|
+
import { createServer } from 'node:http' // 提供示例 HTTP 请求入口。
|
|
569
|
+
import { ai } from '@h-ai/ai' // 服务端已初始化,并登记了 manual 服务。
|
|
570
|
+
|
|
571
|
+
function mountTools(options: MCPServiceBrokerOptions) {
|
|
572
|
+
const result = ai.mcp.services.createBroker(options) // 成功返回 bind、handleRequest 和 close。
|
|
573
|
+
if (!result.success)
|
|
574
|
+
throw new Error(result.error.message)
|
|
575
|
+
const broker = result.data // 每个执行节点创建自己的入口。
|
|
576
|
+
const server = createServer((req, res) => {
|
|
577
|
+
void broker.handleRequest(req, res)
|
|
578
|
+
}) // 处理绑定地址上的 MCP 请求。
|
|
579
|
+
return { broker, server } // 宿主监听固定地址并负责传输保护,关闭时调用 broker.close() 和 server.close()。
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
async function bindManual(broker: ReturnType<typeof mountTools>['broker'], principal: MCPServiceAuthorization['principal'], sessionId: string, signal: AbortSignal) {
|
|
583
|
+
const result = await broker.bind({
|
|
584
|
+
principal,
|
|
585
|
+
taskId: sessionId,
|
|
586
|
+
signal,
|
|
587
|
+
tools: [
|
|
588
|
+
{
|
|
589
|
+
id: 'manual_search',
|
|
590
|
+
serviceId: 'manual',
|
|
591
|
+
tool: 'search_manual', // 模型可见名称与清单名称分开配置。
|
|
592
|
+
description: 'Search authorized manuals', // 提供给模型的说明。
|
|
593
|
+
inputSchema: {
|
|
594
|
+
type: 'object',
|
|
595
|
+
properties: {
|
|
596
|
+
query: { type: 'string' }
|
|
597
|
+
},
|
|
598
|
+
required: ['query'],
|
|
599
|
+
additionalProperties: false
|
|
600
|
+
}, // 调用时校验工具参数。
|
|
601
|
+
}
|
|
602
|
+
]
|
|
603
|
+
}) // 成功为 { servers, revoke },servers 含当前会话的短期 Bearer。
|
|
604
|
+
if (!result.success)
|
|
605
|
+
throw new Error(result.error.message)
|
|
606
|
+
return result.data // 可从 ACPPlatformPolicy.bindTools 返回;会话结束时撤销凭据。
|
|
607
|
+
}
|
|
608
|
+
```
|
|
609
|
+
|
|
447
610
|
#### Memory / RAG / Knowledge
|
|
448
611
|
|
|
449
612
|
原生记忆删除(包括管理员全清)先清向量,再删除权威记录;向量清理失败时记录保留以便重试。SQL 与向量后端不共享事务,后一步失败仍需核对当前状态。
|
|
@@ -955,6 +1118,8 @@ const memories = await ai.memory.recall('经济发展', {
|
|
|
955
1118
|
|
|
956
1119
|
`ai.config` 返回脱敏后的配置快照;`apiKey`、`privateKey`、URL 内嵌凭证等敏感字段不会原样暴露。
|
|
957
1120
|
|
|
1121
|
+
原生记忆新增使用共享关系库事务串行检查主体与全局配额。淘汰每次最多读取最旧 64 条候选并按重要性和时效评分。旧库超过配额时,新写入会先回收一批,直到有余量。自定义共享 Store 可实现 `AIRelStore.withWriteLock` 提供同样的跨节点保证。
|
|
1122
|
+
|
|
958
1123
|
## 错误处理
|
|
959
1124
|
|
|
960
1125
|
```ts
|