@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.en.md
CHANGED
|
@@ -49,146 +49,148 @@ Unless marked direct, AsyncIterable or a direct Promise value, the output column
|
|
|
49
49
|
|
|
50
50
|
Call fragments reuse the initialized service from this page. Named variables stand for application-provided requests, schemas, resource definitions or options. Follow the corresponding examples for setup and failure handling. Check HaiResult.success and await asynchronous calls.
|
|
51
51
|
|
|
52
|
-
| Entry | Use case
|
|
53
|
-
| --------------------------------- |
|
|
54
|
-
| `ai.llm.chat` | Single answer
|
|
55
|
-
| `ai.llm.chatStream` | Stream completion
|
|
56
|
-
| `ai.llm.ask` | Text answer
|
|
57
|
-
| `ai.llm.askStream` | Text stream
|
|
58
|
-
| `ai.llm.generateObject` | Schema-constrained answer
|
|
59
|
-
| `ai.llm.listModels` | List models
|
|
60
|
-
| `ai.llm.getHistory` | Read history
|
|
61
|
-
| `ai.llm.listSessions` | Subject sessions
|
|
62
|
-
| `ai.tools.define` | Define a tool
|
|
63
|
-
| `ai.tools.createRegistry` | Create tool registry
|
|
64
|
-
| `ai.stream.createProcessor` | Accumulate chunks
|
|
65
|
-
| `ai.stream.collect` | Consume a chat stream
|
|
66
|
-
| `ai.stream.createSSEDecoder` | Decode split SSE
|
|
67
|
-
| `ai.stream.encodeSSE` | Encode SSE
|
|
68
|
-
| `ai.embedding.embed` | Embedding request
|
|
69
|
-
| `ai.embedding.embedText` | Embed one text
|
|
70
|
-
| `ai.embedding.embedBatch` | Embed many texts
|
|
71
|
-
| `ai.mcp.registerTool` | Register local tool
|
|
72
|
-
| `ai.mcp.registerResource` | Register resource
|
|
73
|
-
| `ai.mcp.registerPrompt` | Register prompt
|
|
74
|
-
| `ai.mcp.callTool` | Call local tool
|
|
75
|
-
| `ai.mcp.readResource` | Read resource
|
|
76
|
-
| `ai.mcp.getPrompt` | Build prompt
|
|
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
|
+
| Entry | Use case | Input | Output | Call fragment |
|
|
53
|
+
| --------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
|
|
54
|
+
| `ai.llm.chat` | Single answer | `ChatCompletionRequest: messages, model?, signal?, tools?` | `ChatCompletionResponse: choices, model, usage?` | `ai.llm.chat({ messages: [{ role: "user", content: "你好" }] })` |
|
|
55
|
+
| `ai.llm.chatStream` | Stream completion | `same ChatCompletionRequest` | `AsyncIterable<ChatCompletionChunk>; iteration may throw` | `ai.llm.chatStream({ messages })` |
|
|
56
|
+
| `ai.llm.ask` | Text answer | `question: string, AskOptions?` | `string answer` | `ai.llm.ask("解释共享状态")` |
|
|
57
|
+
| `ai.llm.askStream` | Text stream | `question: string, AskOptions?` | `AsyncIterable<string>` | `ai.llm.askStream("解释共享状态")` |
|
|
58
|
+
| `ai.llm.generateObject` | Schema-constrained answer | `Zod schema, messages, model?, responseFormat?, maxRepairs?, signal?` | `schema-inferred T` | `ai.llm.generateObject({ schema: AnswerSchema, messages })` |
|
|
59
|
+
| `ai.llm.listModels` | List models | `none` | `string[] model IDs` | `ai.llm.listModels()` |
|
|
60
|
+
| `ai.llm.getHistory` | Read history | `{ objectId, sessionId }, { limit?, order? }?` | `ChatRecord[]` | `ai.llm.getHistory({ objectId: "u1", sessionId: "s1" })` |
|
|
61
|
+
| `ai.llm.listSessions` | Subject sessions | `objectId: string` | `SessionInfo[]` | `ai.llm.listSessions("u1")` |
|
|
62
|
+
| `ai.tools.define` | Define a tool | `{ name, description, parameters: Zod schema, handler, timeoutMs? }` | `direct Tool<TInput,TOutput>; no init required` | `ai.tools.define(toolDefinition)` |
|
|
63
|
+
| `ai.tools.createRegistry` | Create tool registry | `{ authorize? }?` | `direct ToolRegistryOperations; no init required` | `ai.tools.createRegistry({ authorize })` |
|
|
64
|
+
| `ai.stream.createProcessor` | Accumulate chunks | `none` | `direct StreamProcessor` | `ai.stream.createProcessor()` |
|
|
65
|
+
| `ai.stream.collect` | Consume a chat stream | `AsyncIterable<ChatCompletionChunk>` | `Promise<StreamResult>; stream failure rejects` | `ai.stream.collect(ai.llm.chatStream({ messages }))` |
|
|
66
|
+
| `ai.stream.createSSEDecoder` | Decode split SSE | `none` | `direct SSEDecoder with decode/reset` | `ai.stream.createSSEDecoder()` |
|
|
67
|
+
| `ai.stream.encodeSSE` | Encode SSE | `SSEEvent: data, event?, id?, retry?` | `direct string; invalid metadata throws` | `ai.stream.encodeSSE({ data: "Hello" })` |
|
|
68
|
+
| `ai.embedding.embed` | Embedding request | `EmbeddingRequest with input/model?` | `EmbeddingResponse` | `ai.embedding.embed({ input: "产品说明" })` |
|
|
69
|
+
| `ai.embedding.embedText` | Embed one text | `text: string` | `number[]` | `ai.embedding.embedText("产品说明")` |
|
|
70
|
+
| `ai.embedding.embedBatch` | Embed many texts | `texts: string[]` | `number[][] in input order` | `ai.embedding.embedBatch(["简介", "部署"])` |
|
|
71
|
+
| `ai.mcp.registerTool` | Register local tool | `MCPToolDefinition, typed handler` | `void` | `ai.mcp.registerTool(mcpToolDefinition, toolHandler)` |
|
|
72
|
+
| `ai.mcp.registerResource` | Register resource | `MCPResource, async content handler` | `void` | `ai.mcp.registerResource(resourceDefinition, readContent)` |
|
|
73
|
+
| `ai.mcp.registerPrompt` | Register prompt | `MCPPrompt, args => Promise<MCPPromptMessage[]>` | `void` | `ai.mcp.registerPrompt(promptDefinition, buildMessages)` |
|
|
74
|
+
| `ai.mcp.callTool` | Call local tool | `name, arguments, MCPContext?` | `unknown tool result` | `ai.mcp.callTool("search", { query: "配置" })` |
|
|
75
|
+
| `ai.mcp.readResource` | Read resource | `resource URI` | `MCPResourceContent with exactly text or blob` | `ai.mcp.readResource("docs://intro")` |
|
|
76
|
+
| `ai.mcp.getPrompt` | Build prompt | `name, Record<string,string> arguments` | `MCPPromptMessage[]` | `ai.mcp.getPrompt("review", { topic: "API" })` |
|
|
77
|
+
| `ai.mcp.services.invoke` | Call an authorized remote tool | Request, authenticated principal, and authorization function | `HaiResult<CallToolResult>` | `ai.mcp.services.invoke(request, authorization)` |
|
|
78
|
+
| `ai.mcp.services.createBroker` | Mount a tool endpoint for ACP sessions | Fixed URL and live authorization function | `HaiResult<MCPServiceBroker>` | `ai.mcp.services.createBroker(brokerOptions)` |
|
|
79
|
+
| `ai.retrieval.addSource` | Register source | `RetrievalSource: id, collection, optional metadata` | `void` | `ai.retrieval.addSource({ id: "docs", collection: "manual" })` |
|
|
80
|
+
| `ai.retrieval.removeSource` | Remove source | `sourceId: string` | `void` | `ai.retrieval.removeSource("docs")` |
|
|
81
|
+
| `ai.retrieval.listSources` | List sources | `none` | `direct Promise<RetrievalSource[]>` | `ai.retrieval.listSources()` |
|
|
82
|
+
| `ai.retrieval.retrieve` | Retrieve candidates | `RetrievalRequest: query, sources?, topK?, minScore?, enableRerank?` | `RetrievalResult` | `ai.retrieval.retrieve({ query: "部署" })` |
|
|
83
|
+
| `ai.rag.query` | Grounded answer | `query: string, RagOptions?` | `RagResult: answer, context, citations, query, model` | `ai.rag.query("如何部署?", { sources: ["docs"] })` |
|
|
84
|
+
| `ai.rag.queryStream` | Grounded stream | `query: string, RagOptions?` | `AsyncIterable<RagStreamEvent>` | `ai.rag.queryStream("如何部署?", { sources: ["docs"] })` |
|
|
85
|
+
| `ai.knowledge.setup` | Prepare collection | `KnowledgeSetupOptions?` | `void; collection ready for ingest` | `ai.knowledge.setup()` |
|
|
86
|
+
| `ai.knowledge.ingest` | Publish document | `{ documentId, content, title?, collection?, ...metadata }` | `KnowledgeIngestResult with revision/cleanupPending` | `ai.knowledge.ingest({ documentId: "intro", content: "入门正文" })` |
|
|
87
|
+
| `ai.knowledge.ingestFile` | Ingest a file | `KnowledgeIngestFileInput including file bytes and document identity` | `KnowledgeIngestResult` | `ai.knowledge.ingestFile(fileInput)` |
|
|
88
|
+
| `ai.knowledge.ingestBatch` | Ingest batch | `KnowledgeIngestInput[], onProgress?` | `KnowledgeIngestBatchResult with per-document outcomes` | `ai.knowledge.ingestBatch(documentInputs, onProgress)` |
|
|
89
|
+
| `ai.knowledge.retrieve` | Retrieve published revision | `query: string, KnowledgeRetrieveOptions?` | `KnowledgeRetrieveResult` | `ai.knowledge.retrieve("部署说明")` |
|
|
90
|
+
| `ai.knowledge.ask` | Answer from knowledge | `query: string, KnowledgeAskOptions?` | `KnowledgeAskResult` | `ai.knowledge.ask("如何恢复备份?")` |
|
|
91
|
+
| `ai.knowledge.findByEntity` | Find by entity | `entityName: string, EntityQueryOptions?` | `EntityDocumentResult[]` | `ai.knowledge.findByEntity("订单")` |
|
|
92
|
+
| `ai.knowledge.listEntities` | List entities | `EntityListOptions?` | `KnowledgeEntity[]` | `ai.knowledge.listEntities()` |
|
|
93
|
+
| `ai.knowledge.listDocuments` | List documents | `KnowledgeDocumentListOptions?` | `KnowledgeDocumentInfo[]` | `ai.knowledge.listDocuments()` |
|
|
94
|
+
| `ai.knowledge.removeDocument` | Remove document | `documentId, KnowledgeDocumentRemoveOptions?` | `void; may fail after visibility revocation if cleanup fails` | `ai.knowledge.removeDocument("intro")` |
|
|
95
|
+
| `ai.knowledge.repair` | Repair cleanup | `{ collection?, offset?, limit? }` | `KnowledgeRepairResult with progress` | `ai.knowledge.repair({ offset: 0, limit: 100 })` |
|
|
96
|
+
| `ai.knowledge.deleteCollection` | Remove collection | `collection name?` | `void; cleanup tombstone remains` | `ai.knowledge.deleteCollection("retired-manual")` |
|
|
97
|
+
| `ai.memory.scoped` | Bind trusted subject | `{ objectId: nonempty string, scope? }` | `direct ScopedMemoryOperations; invalid binding throws TypeError` | `ai.memory.scoped({ objectId: "u1", scope: { topicId: "orders" } })` |
|
|
98
|
+
| `ai.memory.extract` | Extract memories | `ChatMessage[], { objectId, scope?, model?, signal?, ...options }` | `MemoryEntry[]` | `ai.memory.extract(messages, { objectId: "u1" })` |
|
|
99
|
+
| `ai.memory.add` | Store explicit memory | `MemoryEntryInput: objectId, content, type, scope?` | `MemoryEntry` | `ai.memory.add({ objectId: "u1", content: "偏好中文", type: "preference" })` |
|
|
100
|
+
| `ai.memory.get` | Read owned memory | `memoryId, { objectId, scope? } for untrusted IDs` | `MemoryEntry` | `ai.memory.get(memoryId, { objectId: "u1" })` |
|
|
101
|
+
| `ai.memory.update` | Update memory | `memoryId, MemoryUpdateInput, trusted access scope` | `MemoryEntry` | `ai.memory.update(memoryId, { content: "偏好日文" }, { objectId: "u1" })` |
|
|
102
|
+
| `ai.memory.remove` | Remove owned memory | `memoryId, trusted access scope` | `void` | `ai.memory.remove(memoryId, { objectId: "u1" })` |
|
|
103
|
+
| `ai.memory.recall` | Recall memories | `query, { objectId, scope?, topK?, types?, ...options }` | `MemoryEntry[]` | `ai.memory.recall("语言偏好", { objectId: "u1" })` |
|
|
104
|
+
| `ai.memory.injectMemories` | Enrich messages | `ChatMessage[], { objectId, scope?, topK?, ...options }` | `ChatMessage[]` | `ai.memory.injectMemories(messages, { objectId: "u1" })` |
|
|
105
|
+
| `ai.memory.list` | List memories | `MemoryListOptions with objectId/scope filters` | `MemoryEntry[]; incomplete scan fails` | `ai.memory.list({ objectId: "u1" })` |
|
|
106
|
+
| `ai.memory.listPage` | Page memories | `MemoryListPageOptions with objectId/pagination` | `StorePage<MemoryEntry>` | `ai.memory.listPage({ objectId: "u1", offset: 0, limit: 20 })` |
|
|
107
|
+
| `ai.memory.clear` | Clear selected scope | `nonempty MemoryClearOptions` | `void; empty filters are rejected` | `ai.memory.clear({ objectId: "u1" })` |
|
|
108
|
+
| `ai.memory.admin.clearAll` | Trusted administrator clear | `{ confirm: true }; require host administrator authorization` | `void; destructive across subjects` | `ai.memory.admin.clearAll({ confirm: true })` |
|
|
109
|
+
| `ai.persona.save` | Save persona | `PersonaProfileInput: id, name, systemPrompt, objectId?, traits?` | `PersonaProfile` | `ai.persona.save(personaProfile)` |
|
|
110
|
+
| `ai.persona.get` | Get persona | `id, { objectId }?; omitted subject selects system profile` | `PersonaProfile` | `ai.persona.get("tutor", { objectId: "u1" })` |
|
|
111
|
+
| `ai.persona.update` | Update persona | `id, PersonaProfileUpdate, { objectId }?` | `PersonaProfile` | `ai.persona.update("tutor", updates, { objectId: "u1" })` |
|
|
112
|
+
| `ai.persona.remove` | Remove persona | `id, { objectId }?` | `void` | `ai.persona.remove("tutor", { objectId: "u1" })` |
|
|
113
|
+
| `ai.persona.list` | List personas | `{ objectId }?` | `PersonaProfile[]` | `ai.persona.list({ objectId: "u1" })` |
|
|
114
|
+
| `ai.persona.compose` | Compose system prompt | `id, { objectId }?` | `string prompt` | `ai.persona.compose("tutor", { objectId: "u1" })` |
|
|
115
|
+
| `ai.token.estimateText` | Estimate text tokens | `text: string` | `direct number; estimate, not billing usage` | `ai.token.estimateText("Hello 世界")` |
|
|
116
|
+
| `ai.token.estimateMessages` | Estimate message tokens | `ChatMessage[]` | `direct number including protocol overhead` | `ai.token.estimateMessages(messages)` |
|
|
117
|
+
| `ai.summary.generate` | Generate summary text | `ChatMessage[], SummaryOptions?` | `string` | `ai.summary.generate(messages)` |
|
|
118
|
+
| `ai.summary.summarize` | Summary metadata | `ChatMessage[], SummaryOptions?` | `{ summary, tokenCount, coveredMessages }` | `ai.summary.summarize(messages)` |
|
|
119
|
+
| `ai.compress.tryCompress` | Compress to budget | `ChatMessage[], { strategy?, maxTokens?, preserveLastN?, ...options }` | `CompressResult: messages and original/compressed token counts` | `ai.compress.tryCompress(messages, { maxTokens: 4000 })` |
|
|
120
|
+
| `ai.context.createManager` | Create context | `ContextManagerOptions with scope { objectId, sessionId }` | `ContextManager` | `ai.context.createManager({ scope: { objectId: "u1", sessionId: "s1" } })` |
|
|
121
|
+
| `ai.context.restoreManager` | Restore context | `{ objectId, sessionId }, options?` | `ContextManager` | `ai.context.restoreManager({ objectId: "u1", sessionId: "s1" })` |
|
|
122
|
+
| `ai.context.listSessions` | List stored sessions | `objectId` | `SessionInfo[]` | `ai.context.listSessions("u1")` |
|
|
123
|
+
| `ai.context.renameSession` | Rename session | `scope, title` | `void` | `ai.context.renameSession({ objectId: "u1", sessionId: "s1" }, "订单讨论")` |
|
|
124
|
+
| `ai.context.removeSession` | Remove session | `scope` | `void; tombstone prevents scope reuse` | `ai.context.removeSession({ objectId: "u1", sessionId: "s1" })` |
|
|
125
|
+
| `ai.rerank.rerank` | Rerank documents | `RerankRequest: query, documents, model?, topN?` | `RerankResponse with model/results` | `ai.rerank.rerank({ query: "部署", documents: ["配置说明"] })` |
|
|
126
|
+
| `ai.rerank.rerankTexts` | Rerank texts | `query, string[] texts, topN?` | `RerankItem[] with index/relevanceScore` | `ai.rerank.rerankTexts("部署", ["配置说明"], 1)` |
|
|
127
|
+
| `ai.file.parse` | Parse a file | `FileParseRequest with content, filename, options?` | `FileParseResult; extraction is not HTML sanitization` | `ai.file.parse({ content: "<p>正文</p>", filename: "intro.html" })` |
|
|
128
|
+
| `ai.file.parseText` | Extract plain text | `Buffer\|string content, filename?` | `string` | `ai.file.parseText("Hello", "intro.txt")` |
|
|
129
|
+
| `ai.reasoning.run` | Multistep reasoning | `query, ReasoningOptions including strategy/tools?` | `ReasoningResult` | `ai.reasoning.run("审查方案", { strategy: "cot" })` |
|
|
130
|
+
| `ai.reasoning.runStream` | Observe reasoning stream | `query, ReasoningOptions?` | `AsyncIterable<ReasoningStreamEvent>` | `ai.reasoning.runStream("审查方案", { strategy: "react" })` |
|
|
131
|
+
| `ai.audio.transcribe` | Transcribe audio | `TranscriptionRequest: audio, language?, model?, signal?` | `TranscriptionResult: text, language?, segments?` | `ai.audio.transcribe({ audio: { data: wavBytes, format: "wav" } })` |
|
|
132
|
+
| `ai.audio.transcribeStream` | Stream transcription | `TranscriptionStreamRequest: chunks or complete audio` | `AsyncIterable<TranscriptionEvent>` | `ai.audio.transcribeStream(transcriptionInput)` |
|
|
133
|
+
| `ai.audio.synthesize` | Synthesize audio | `SynthesisRequest: text, language?, model?, signal?` | `SynthesisResult: audio and duration metadata` | `ai.audio.synthesize({ text: "你好" })` |
|
|
134
|
+
| `ai.audio.synthesizeStream` | Synthesize segments | `SynthesisStreamRequest: text segment or async segments` | `AsyncIterable<SynthesisEvent>` | `ai.audio.synthesizeStream(synthesisInput)` |
|
|
135
|
+
| `ai.audio.getCapabilities` | Inspect capabilities | `{ operation: transcribe\|synthesize, model? }` | `AudioModelCapabilities` | `ai.audio.getCapabilities({ operation: "synthesize" })` |
|
|
136
|
+
| `ai.image.generate` | Generate images | `{ prompt, referenceImages?, model?, size?, signal? }` | `{ images: GeneratedImage[] } with bytes/MIME` | `ai.image.generate({ prompt: "一座灯塔" })` |
|
|
137
|
+
| `ai.a2a.registerExecutor` | Register executor | `SDK AgentExecutor` | `void` | `ai.a2a.registerExecutor(executor)` |
|
|
138
|
+
| `ai.a2a.getAgentCard` | Agent discovery | `none; configured a2a card` | `A2AAgentCardDocument (A2A 1.0 ProtoJSON)` | `ai.a2a.getAgentCard()` |
|
|
139
|
+
| `ai.a2a.handleRequest` | Handle protocol request | `unknown JSON-RPC body, trusted context.agentId?` | `direct Promise<A2AHandleResult>; JSON-RPC/SSE outcome` | `ai.a2a.handleRequest(body, { agentId: trustedAgentId })` |
|
|
140
|
+
| `ai.a2a.listMessages` | Administrative message query | `A2ATaskFilter: callerId?, contextId?, since?, pagination?` | `StorePage<A2AMessageRecord>` | `ai.a2a.listMessages(messageFilter)` |
|
|
141
|
+
| `ai.a2a.callRemoteAgent` | Call approved remote agent | `allowlisted HTTPS URL, message, A2ACallOptions?` | `A2ACallResult` | `ai.a2a.callRemoteAgent("https://agent.example.com/a2a", "请分析订单")` |
|
|
142
|
+
| `ai.init` | Initialize service | `AIConfigInput?, AIInitOptions?` | `HaiResult<void>; validate dependencies before use` | `ai.init({ llm: { apiKey: process.env.HAI_AI_LLM_APIKEY } })` |
|
|
143
|
+
| `ai.close` | Release service | `none` | `Promise<void>; wait for cleanup` | `ai.close()` |
|
|
144
|
+
| `ai.config` | Read safe config | `none` | `redacted AIConfig or null` | `ai.config` |
|
|
145
|
+
| `ai.isInitialized` | Check lifecycle | `none` | `boolean` | `ai.isInitialized` |
|
|
146
|
+
| `ai.llm.models.list` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.llm.models.list()` |
|
|
147
|
+
| `ai.llm.models.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.llm.models.get("coding")` |
|
|
148
|
+
| `ai.llm.models.register` | Register database definition | `ModelEntry input (id/model/protocol/credentials/capabilities)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.llm.models.register(modelDefinition)` |
|
|
149
|
+
| `ai.llm.models.update` | Replace using a version | `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` | Remove database definition | `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` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.audio.models.list()` |
|
|
152
|
+
| `ai.audio.models.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.audio.models.get("speech")` |
|
|
153
|
+
| `ai.audio.models.register` | Register database definition | `AudioModelEntry input (id/provider/model/operations)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.audio.models.register(audioModelDefinition)` |
|
|
154
|
+
| `ai.audio.models.update` | Replace using a version | `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` | Remove database definition | `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` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.image.models.list()` |
|
|
157
|
+
| `ai.image.models.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.image.models.get("poster")` |
|
|
158
|
+
| `ai.image.models.register` | Register database definition | `ImageModelEntry input (id/provider/model)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.image.models.register(imageModelDefinition)` |
|
|
159
|
+
| `ai.image.models.update` | Replace using a version | `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` | Remove database definition | `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` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.mcp.servers.list()` |
|
|
162
|
+
| `ai.mcp.servers.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.mcp.servers.get("tools")` |
|
|
163
|
+
| `ai.mcp.servers.register` | Register database definition | `MCPExternalServer input (id/transport/url or command)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.mcp.servers.register(mcpServerDefinition)` |
|
|
164
|
+
| `ai.mcp.servers.update` | Replace using a version | `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` | Remove database definition | `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` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.retrieval.sources.list()` |
|
|
167
|
+
| `ai.retrieval.sources.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.retrieval.sources.get("docs")` |
|
|
168
|
+
| `ai.retrieval.sources.register` | Register database definition | `RetrievalSource input (id/collection)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.retrieval.sources.register(sourceDefinition)` |
|
|
169
|
+
| `ai.retrieval.sources.update` | Replace using a version | `RetrievalSource input (id/collection), expectedVersion?` | `HaiResult<AIResourceEntry>; full replacement, conflict fails` | `ai.retrieval.sources.update(sourceDefinition, current.data.version)` |
|
|
170
|
+
| `ai.retrieval.sources.remove` | Remove database definition | `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` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.acp.agents.list()` |
|
|
172
|
+
| `ai.acp.agents.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.acp.agents.get("coder")` |
|
|
173
|
+
| `ai.acp.agents.register` | Register database definition | `ACPAgent input (id/mode/adapter/modelIds)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.acp.agents.register(agentDefinition)` |
|
|
174
|
+
| `ai.acp.agents.update` | Replace using a version | `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` | Remove database definition | `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` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.acp.workspaces.list()` |
|
|
177
|
+
| `ai.acp.workspaces.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.acp.workspaces.get("project")` |
|
|
178
|
+
| `ai.acp.workspaces.register` | Register database definition | `ACPWorkspace input (id/storage/repositories)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.acp.workspaces.register(workspaceDefinition)` |
|
|
179
|
+
| `ai.acp.workspaces.update` | Replace using a version | `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` | Remove database definition | `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` | Preflight agent | `agentId, modelId?` | `HaiResult<{ agentId, mode, modelIds }>; no credentials` | `ai.acp.agents.initialize("coder")` |
|
|
182
|
+
| `ai.acp.agents.check` | Connect and handshake | `agentId, { workspaceId?, ...ACPClientOptions }` | `HaiResult<native initialize response>; owned connection is closed` | `ai.acp.agents.check("coder", { workspaceId: "project" })` |
|
|
183
|
+
| `ai.acp.workspaces.prepare` | Prepare workspace | `workspaceId` | `HaiResult<main absolute path>; dirty content is retained` | `ai.acp.workspaces.prepare("project")` |
|
|
184
|
+
| `ai.acp.workspaces.importFiles` | Import controlled files | `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` | Start managed session | `ACPCreateSessionOptions: agentId/workspaceId/newWorktree?` | `HaiResult<managed session handle>` | `ai.acp.sessions.create({ agentId: "coder", workspaceId: "project", newWorktree: true })` |
|
|
186
|
+
| `ai.acp.sessions.get` | Get session handle | `framework session id` | `HaiResult<managed session handle>; does not resume` | `ai.acp.sessions.get("task-1")` |
|
|
187
|
+
| `ai.acp.sessions.list` | List managed sessions | `workspaceId?` | `HaiResult<ACPSessionInfo[]>` | `ai.acp.sessions.list("project")` |
|
|
188
|
+
| `ai.acp.sessions.resume` | Resume native session | `framework session id, ACPClientOptions?` | `HaiResult<managed session handle>; definition changes may reject` | `ai.acp.sessions.resume("task-1")` |
|
|
189
|
+
| `ai.acp.sessions.close` | Stop owned execution | `framework session id` | `HaiResult<void>; source and native history retained` | `ai.acp.sessions.close("task-1")` |
|
|
190
|
+
| `ai.acp.sessions.reclaimWorktree` | Reclaim clean worktree | `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` | Remove session record | `closed or failed framework session id` | `HaiResult<void>; worktree and native history retained` | `ai.acp.sessions.remove("task-1")` |
|
|
192
|
+
| `ai.acp.connect` | Connect native transport | `ACPTransport: stdio/http/ws, ACPClientOptions?` | `HaiResult<connection handle>` | `ai.acp.connect({ type: "http", url: "https://agent.example.com/acp" })` |
|
|
193
|
+
| `ai.acp.close` | Close subsystem | `none; normally call ai.close()` | `Promise<void>; cleanup may throw` | `ai.acp.close()` |
|
|
192
194
|
|
|
193
195
|
- `ai.tools`: tool definitions, registries, and batch execution; no initialization required.
|
|
194
196
|
- `ai.stream`: ChatCompletion stream chunk processing; no initialization required.
|
|
@@ -321,6 +323,29 @@ const temp = await ai.llm.chat({
|
|
|
321
323
|
|
|
322
324
|
SSE text decoding follows [WHATWG event-stream rules](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation): split LF/CRLF/CR, multiline data, one optional space, inherited valid id/retry, default message events, and no dispatch of unfinished EOF data. encodeSSE normalizes data line endings and explicitly throws for invalid metadata. Anthropic/MiMo share an internal UTF-8 reader that cancels/releases the body on exit, cancellation, termination or failure, without reconnecting or replaying business operations. Anthropic deadlines cover the body; MiMo retains separate deadlines per HTTP request.
|
|
323
325
|
|
|
326
|
+
##### Structured output with `ai.llm.generateObject`
|
|
327
|
+
|
|
328
|
+
Choose `responseFormat` according to the model or gateway. The default, `json_schema`, sends a strict JSON Schema upstream. `schemaName` applies to that mode and defaults to `result`. Use `json_object` for Chat gateways that support generic JSON mode. The framework adds the schema to the prompt. Both modes validate locally with the same Zod schema and use `maxRepairs` for parse or validation failures, defaulting to one repair.
|
|
329
|
+
|
|
330
|
+
```ts
|
|
331
|
+
import { ai } from '@h-ai/ai'
|
|
332
|
+
import { z } from 'zod'
|
|
333
|
+
|
|
334
|
+
// AI is initialized with a text model that supports generic JSON mode.
|
|
335
|
+
const result = await ai.llm.generateObject({
|
|
336
|
+
schema: z.object({
|
|
337
|
+
title: z.string()
|
|
338
|
+
}), // Require an object with a string title.
|
|
339
|
+
messages: [
|
|
340
|
+
{ role: 'user', content: 'Suggest a title for a release checklist.' }
|
|
341
|
+
], // Input for this request.
|
|
342
|
+
responseFormat: 'json_object', // Request generic JSON while keeping local Zod validation.
|
|
343
|
+
maxRepairs: 1, // Allow one repair after a parse or validation failure.
|
|
344
|
+
})
|
|
345
|
+
if (result.success)
|
|
346
|
+
process.stdout.write(result.data.title) // For example, Release checklist.
|
|
347
|
+
```
|
|
348
|
+
|
|
324
349
|
#### Tool calls
|
|
325
350
|
|
|
326
351
|
```ts
|
|
@@ -375,10 +400,75 @@ The Goose 1.57.0 image exposes its native `goose serve` HTTP/WS `/acp` service t
|
|
|
375
400
|
|
|
376
401
|
Declare verified capacity, modalities and reasoning in `llm.models[].capabilities`. Codex needs native Responses; the existing Hai adapter is not a reverse gateway. Code and state persist after close. CAS ownership is released only after owned processes stop; worktrees are not security sandboxes.
|
|
377
402
|
|
|
378
|
-
|
|
403
|
+
Build an Agent image with `minimal`, `documents`, `office`, `browser`, or `developer`. The default includes Git, Node, and the native Agent. Codex also includes bubblewrap. Register a local image ID or remote manifest digest for the execution environment. [Agent images](models/agents/README.md)
|
|
404
|
+
|
|
405
|
+
ACP runs in the Node service. Ordinary methods return HaiResult and stream failures throw. [ACP guide](../cli/templates/skills/hai-ai/acp.md)
|
|
379
406
|
|
|
380
407
|
Managed Git rejects submodules and Git LFS attributes with ACP_UNSUPPORTED instead of reporting incomplete checkouts as ready.
|
|
381
408
|
|
|
409
|
+
##### Run managed ACP for an authenticated user
|
|
410
|
+
|
|
411
|
+
Start RelDB and [Runner](../runner/README.en.md), then pass the initialized instance to `ai.init(config, { runner, acpPolicy })`. Register agents in `acp.agents`. Set `environmentIds` to pinned Runner environments and `modelIds` to entries in `llm.models`. Codex needs a Responses gateway. API and executor nodes share the database and use the same environment definitions. On shutdown, close AI, Runner, and the database in that order.
|
|
412
|
+
|
|
413
|
+
`task` starts a dedicated worker for the session. `user` may reuse a worker when the principal and startup settings match. `auto` selects a mode using application policy. `shared` is available to adapters explicitly approved for sharing with a read-only profile and without private context, workspaces, or tools. The built-in Codex, DeepSeek Harness, and Goose adapters use dedicated modes. See the [ACP configuration example](../../docs/usage/configuration/ai.md#acp-接入与模型能力).
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
import type { RunnerScope } from '@h-ai/runner' // tenantId and userId come from an authenticated application session.
|
|
417
|
+
import { ai } from '@h-ai/ai' // Use the server instance initialized with Runner.
|
|
418
|
+
|
|
419
|
+
async function summarize(identity: RunnerScope, requestId: string) {
|
|
420
|
+
const agent = ai.acp.scoped(identity) // Bind task, session, and approval access to this principal.
|
|
421
|
+
const options = {
|
|
422
|
+
agentId: 'assistant',
|
|
423
|
+
execution: { mode: 'auto' as const }
|
|
424
|
+
} // assistant is a registered agent.
|
|
425
|
+
const plan = await agent.plan(options) // Returns the effective mode, environment, model, and resources without claiming a container.
|
|
426
|
+
if (!plan.success)
|
|
427
|
+
return plan // Stop before submission when the environment or permissions do not match.
|
|
428
|
+
const result = await agent.run({ ...options, prompt: 'List three release checks', idempotencyKey: requestId }) // Returns taskId, output, and effective options.
|
|
429
|
+
if (!result.success)
|
|
430
|
+
return result // Preserve the HaiResult error on submission, execution, or cleanup failure.
|
|
431
|
+
const events = await agent.tasks.events(result.data.taskId, 0, 20) // Read the first 20 durable events, or [] when empty.
|
|
432
|
+
if (!events.success)
|
|
433
|
+
return events
|
|
434
|
+
return { result: result.data, events: events.data } // For example, output.text contains the answer and events are ordered by sequence.
|
|
435
|
+
}
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
import type { RunnerScope } from '@h-ai/runner' // The server-authenticated principal.
|
|
440
|
+
import { ai } from '@h-ai/ai' // assistant is registered and supports worker reuse within a user.
|
|
441
|
+
|
|
442
|
+
async function continueWork(identity: RunnerScope) {
|
|
443
|
+
const agent = ai.acp.scoped(identity) // Access is bound to this principal.
|
|
444
|
+
const created = await agent.sessions.create({
|
|
445
|
+
agentId: 'assistant',
|
|
446
|
+
execution: { mode: 'user' }
|
|
447
|
+
}) // Success yields a session handle with an id.
|
|
448
|
+
if (!created.success)
|
|
449
|
+
return created
|
|
450
|
+
const session = created.data // The handle exposes prompt, stream, changeExecution, and close.
|
|
451
|
+
const run = async () => {
|
|
452
|
+
const first = await session.prompt('Record the acceptance criteria') // Returns this turn's taskId, output, and effective options.
|
|
453
|
+
if (!first.success)
|
|
454
|
+
return first
|
|
455
|
+
const switched = await session.changeExecution({ mode: 'task', acceptNewSession: true }) // Keeps the business id and opens a fresh native session.
|
|
456
|
+
if (!switched.success)
|
|
457
|
+
return switched
|
|
458
|
+
return await session.prompt('Give me an independent acceptance checklist') // The answer is in data.output on success.
|
|
459
|
+
}
|
|
460
|
+
return run().finally(async () => {
|
|
461
|
+
const closed = await session.close() // Success returns data: undefined and releases the session or dedicated environment.
|
|
462
|
+
if (!closed.success)
|
|
463
|
+
throw new Error(closed.error.message)
|
|
464
|
+
})
|
|
465
|
+
}
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
`agents.describe(agentId)` reports built-in adapter capabilities. `sessions.get(id)` obtains a handle from another API node for the same principal. `session.stream(prompt, options)` yields durable events and throws on failure. `tasks.get(taskId)` returns the execution receipt. `tasks.cancel(taskId)` acknowledges cancellation and returns current status. Read the `taskId` from the `accepted` event in a `run` or `prompt` observer to query or cancel from another request.
|
|
469
|
+
|
|
470
|
+
The application supplies `acpPolicy` to authorize `workspaceId` snapshots, knowledge, memory, files, skills, and tools. Use `allowTools` and `bindTools` for the MCP broker below. After receiving an `approval` event, the same principal calls `approvals.respond(id, 'allow-once' | 'allow-session' | 'always-allow' | 'deny')` with its `approvalId`. Success returns `undefined`. `approvals.rules(offset, limit)` pages through valid rules with `expiresAt`, and `approvals.revoke(ruleId)` revokes a rule owned by the principal. `full-access` requires explicit application approval and `task` mode. A workspace provides a read-only snapshot. Mode changes can carry a user-approved `historySummary`. See [managed ACP usage](../../docs/usage/development/ai-acp.md#多用户应用的受管调用) for additional examples.
|
|
471
|
+
|
|
382
472
|
#### Configuration and database resource catalogs
|
|
383
473
|
|
|
384
474
|
`llm.models`, `audio.models`, `image.models`, `mcp.servers`, `retrieval.sources`, and `acp.agents/workspaces` merge configuration and database entries. Configuration wins duplicate IDs and is read-only. Database entries support list/get/register/update/remove with value/source/version metadata and optional version checks. Async calls read current definitions; synchronous audio capability checks use the latest local snapshot. Catalog errors use 090–094. Definitions may contain model credentials; expose only authorized, selected fields.
|
|
@@ -423,6 +513,81 @@ await server.connect(new StreamableHTTPServerTransport({
|
|
|
423
513
|
}))
|
|
424
514
|
```
|
|
425
515
|
|
|
516
|
+
##### Call remote MCP services and isolated tool jobs
|
|
517
|
+
|
|
518
|
+
Register a third-party Streamable HTTP URL and `allowedTools` under `mcp.servers` with `transport: http`. Use `headerEnv` to reference server-side credentials. With `transport: job`, the same API can run offline document, Office, and OCR tools. Set `environmentId`, allowed operations, and an optional `pool`, and pass Runner and `mcpJobFiles` to `ai.init`. Jobs take an authorized `fileId`. Executors recheck file access and return an object ID for any artifact. Deploy the browser image independently. See [MCP configuration](../../docs/usage/configuration/ai.md#mcp和a2a) and [tool images](tools/README.md).
|
|
519
|
+
|
|
520
|
+
```ts
|
|
521
|
+
import type { MCPServiceAuthorization } from '@h-ai/ai' // Build the principal and the parameter-aware authorization callback from IAM.
|
|
522
|
+
import { ai } from '@h-ai/ai' // The initialized server has registered manual and office services.
|
|
523
|
+
|
|
524
|
+
async function searchManual(access: MCPServiceAuthorization, query: string) {
|
|
525
|
+
const result = await ai.mcp.services.invoke({
|
|
526
|
+
serviceId: 'manual',
|
|
527
|
+
tool: 'search_manual',
|
|
528
|
+
arguments: { query }
|
|
529
|
+
}, access) // Returns a standard MCP tool result after catalog and authorization checks.
|
|
530
|
+
if (!result.success)
|
|
531
|
+
return result // Preserve the denial or upstream error.
|
|
532
|
+
return result.data.content // For example, [{ type: 'text', text: '...' }].
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
async function convertDocument(access: MCPServiceAuthorization, fileId: string) {
|
|
536
|
+
const result = await ai.mcp.services.invoke({
|
|
537
|
+
serviceId: 'office',
|
|
538
|
+
tool: 'office.convert',
|
|
539
|
+
arguments: { fileId }
|
|
540
|
+
}, access) // Submit an offline conversion with the authorized object id.
|
|
541
|
+
if (!result.success)
|
|
542
|
+
return result
|
|
543
|
+
return result.data.structuredContent // Example: { fileId: 'pdf-123', name: 'result.pdf' }. Check authorization again on download.
|
|
544
|
+
}
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
```ts
|
|
548
|
+
import type { MCPServiceAuthorization, MCPServiceBrokerOptions } from '@h-ai/ai' // Supply a deployment URL and an authorize callback that rechecks the principal, task, and arguments.
|
|
549
|
+
import { createServer } from 'node:http' // Hosts the example endpoint.
|
|
550
|
+
import { ai } from '@h-ai/ai' // The initialized server has registered the manual service.
|
|
551
|
+
|
|
552
|
+
function mountTools(options: MCPServiceBrokerOptions) {
|
|
553
|
+
const result = ai.mcp.services.createBroker(options) // On success the broker provides bind, handleRequest, and close.
|
|
554
|
+
if (!result.success)
|
|
555
|
+
throw new Error(result.error.message)
|
|
556
|
+
const broker = result.data // Create a broker on each executor.
|
|
557
|
+
const server = createServer((req, res) => {
|
|
558
|
+
void broker.handleRequest(req, res)
|
|
559
|
+
}) // Handle MCP requests on the bound endpoint.
|
|
560
|
+
return { broker, server } // The host listens on its fixed address, protects the transport, and calls broker.close() and server.close() at shutdown.
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
async function bindManual(broker: ReturnType<typeof mountTools>['broker'], principal: MCPServiceAuthorization['principal'], sessionId: string, signal: AbortSignal) {
|
|
564
|
+
const result = await broker.bind({
|
|
565
|
+
principal,
|
|
566
|
+
taskId: sessionId,
|
|
567
|
+
signal,
|
|
568
|
+
tools: [
|
|
569
|
+
{
|
|
570
|
+
id: 'manual_search',
|
|
571
|
+
serviceId: 'manual',
|
|
572
|
+
tool: 'search_manual', // Expose a model-facing name for the catalogued operation.
|
|
573
|
+
description: 'Search authorized manuals', // Description presented to the model.
|
|
574
|
+
inputSchema: {
|
|
575
|
+
type: 'object',
|
|
576
|
+
properties: {
|
|
577
|
+
query: { type: 'string' }
|
|
578
|
+
},
|
|
579
|
+
required: ['query'],
|
|
580
|
+
additionalProperties: false
|
|
581
|
+
}, // Validate call arguments.
|
|
582
|
+
}
|
|
583
|
+
]
|
|
584
|
+
}) // Success returns { servers, revoke }. servers contains this session's short-lived Bearer credential.
|
|
585
|
+
if (!result.success)
|
|
586
|
+
throw new Error(result.error.message)
|
|
587
|
+
return result.data // Return from ACPPlatformPolicy.bindTools. The credential is revoked when the session ends.
|
|
588
|
+
}
|
|
589
|
+
```
|
|
590
|
+
|
|
426
591
|
#### Memory / RAG / Knowledge
|
|
427
592
|
|
|
428
593
|
Native memory deletion, including administrator clear-all, cleans vectors before removing authoritative records. Failed vector cleanup retains records for retry. SQL and vector storage do not share a transaction; a later failure still requires checking current state.
|
|
@@ -928,6 +1093,8 @@ const memories = await ai.memory.recall('经济发展', {
|
|
|
928
1093
|
|
|
929
1094
|
`ai.config` returns a redacted snapshot without exposing original `apiKey`, `privateKey`, embedded URL credentials, or other secrets.
|
|
930
1095
|
|
|
1096
|
+
Native memory inserts check subject and global quotas inside a shared database transaction. Eviction scores up to 64 of the oldest candidates per batch by importance and recency. Existing data above quota is reduced in batches before new entries can be stored. Custom shared stores can implement `AIRelStore.withWriteLock` to provide the same cross-node guarantee.
|
|
1097
|
+
|
|
931
1098
|
## Error Handling
|
|
932
1099
|
|
|
933
1100
|
```ts
|