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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -4,11 +4,191 @@
4
4
 
5
5
  [Framework home](../../README.en.md) · Related modules: [@h-ai/api-contract](../api-contract/README.en.md) · [@h-ai/core](../core/README.en.md) · [@h-ai/datapipe](../datapipe/README.en.md) · [@h-ai/reldb](../reldb/README.en.md) · [@h-ai/vecdb](../vecdb/README.en.md)
6
6
 
7
- ## Introduction
8
-
9
7
  AI capabilities through a unified `ai` service: LLM chat, image generation, tools, MCP, embeddings, memory, retrieval/RAG, knowledge bases, context management, file parsing, reranking, audio (ASR/TTS), and A2A. Initialize with `ai.init()` on Node.js; browsers access it through APIs/clients.
10
8
 
11
- ## Core features
9
+ ## Quick Start
10
+
11
+ `ai.close()` waits for an initialization already in progress and then cleans up; concurrent closes share one operation. Reinitialization first cleans up the previous instance, and new initialization is rejected while closing.
12
+
13
+ ### Development LLM-only (no database dependencies)
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
+ Development/explicit tests without initialized reldb/vecdb use a temporary process store, lost on close, exit, or instance switching. When either `NODE_ENV` or `HAI_CORE_ENV` is production, temporary stores, SQLite and local vector backends fail initialization. Initialize shared RelDB and network vecdb first, or supply a shared provider with equivalent atomic guarantees.
43
+
44
+ ## Features
45
+
46
+ ### Purpose, inputs and outputs
47
+
48
+ Unless marked direct, AsyncIterable or a direct Promise value, the output column describes HaiResult.data after success has been checked. Provide named request/definition/options variables using the stated real input type. Streams and explicitly throwing helpers need error handling at the consumer boundary.
49
+
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
+
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?, 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.retrieval.addSource` | Register source | `RetrievalSource: id, collection, optional metadata` | `void` | `ai.retrieval.addSource({ id: "docs", collection: "manual" })` |
78
+ | `ai.retrieval.removeSource` | Remove source | `sourceId: string` | `void` | `ai.retrieval.removeSource("docs")` |
79
+ | `ai.retrieval.listSources` | List sources | `none` | `direct Promise<RetrievalSource[]>` | `ai.retrieval.listSources()` |
80
+ | `ai.retrieval.retrieve` | Retrieve candidates | `RetrievalRequest: query, sources?, topK?, minScore?, enableRerank?` | `RetrievalResult` | `ai.retrieval.retrieve({ query: "部署" })` |
81
+ | `ai.rag.query` | Grounded answer | `query: string, RagOptions?` | `RagResult: answer, context, citations, query, model` | `ai.rag.query("如何部署?", { sources: ["docs"] })` |
82
+ | `ai.rag.queryStream` | Grounded stream | `query: string, RagOptions?` | `AsyncIterable<RagStreamEvent>` | `ai.rag.queryStream("如何部署?", { sources: ["docs"] })` |
83
+ | `ai.knowledge.setup` | Prepare collection | `KnowledgeSetupOptions?` | `void; collection ready for ingest` | `ai.knowledge.setup()` |
84
+ | `ai.knowledge.ingest` | Publish document | `{ documentId, content, title?, collection?, ...metadata }` | `KnowledgeIngestResult with revision/cleanupPending` | `ai.knowledge.ingest({ documentId: "intro", content: "入门正文" })` |
85
+ | `ai.knowledge.ingestFile` | Ingest a file | `KnowledgeIngestFileInput including file bytes and document identity` | `KnowledgeIngestResult` | `ai.knowledge.ingestFile(fileInput)` |
86
+ | `ai.knowledge.ingestBatch` | Ingest batch | `KnowledgeIngestInput[], onProgress?` | `KnowledgeIngestBatchResult with per-document outcomes` | `ai.knowledge.ingestBatch(documentInputs, onProgress)` |
87
+ | `ai.knowledge.retrieve` | Retrieve published revision | `query: string, KnowledgeRetrieveOptions?` | `KnowledgeRetrieveResult` | `ai.knowledge.retrieve("部署说明")` |
88
+ | `ai.knowledge.ask` | Answer from knowledge | `query: string, KnowledgeAskOptions?` | `KnowledgeAskResult` | `ai.knowledge.ask("如何恢复备份?")` |
89
+ | `ai.knowledge.findByEntity` | Find by entity | `entityName: string, EntityQueryOptions?` | `EntityDocumentResult[]` | `ai.knowledge.findByEntity("订单")` |
90
+ | `ai.knowledge.listEntities` | List entities | `EntityListOptions?` | `KnowledgeEntity[]` | `ai.knowledge.listEntities()` |
91
+ | `ai.knowledge.listDocuments` | List documents | `KnowledgeDocumentListOptions?` | `KnowledgeDocumentInfo[]` | `ai.knowledge.listDocuments()` |
92
+ | `ai.knowledge.removeDocument` | Remove document | `documentId, KnowledgeDocumentRemoveOptions?` | `void; may fail after visibility revocation if cleanup fails` | `ai.knowledge.removeDocument("intro")` |
93
+ | `ai.knowledge.repair` | Repair cleanup | `{ collection?, offset?, limit? }` | `KnowledgeRepairResult with progress` | `ai.knowledge.repair({ offset: 0, limit: 100 })` |
94
+ | `ai.knowledge.deleteCollection` | Remove collection | `collection name?` | `void; cleanup tombstone remains` | `ai.knowledge.deleteCollection("retired-manual")` |
95
+ | `ai.memory.scoped` | Bind trusted subject | `{ objectId: nonempty string, scope? }` | `direct ScopedMemoryOperations; invalid binding throws TypeError` | `ai.memory.scoped({ objectId: "u1", scope: { topicId: "orders" } })` |
96
+ | `ai.memory.extract` | Extract memories | `ChatMessage[], { objectId, scope?, model?, signal?, ...options }` | `MemoryEntry[]` | `ai.memory.extract(messages, { objectId: "u1" })` |
97
+ | `ai.memory.add` | Store explicit memory | `MemoryEntryInput: objectId, content, type, scope?` | `MemoryEntry` | `ai.memory.add({ objectId: "u1", content: "偏好中文", type: "preference" })` |
98
+ | `ai.memory.get` | Read owned memory | `memoryId, { objectId, scope? } for untrusted IDs` | `MemoryEntry` | `ai.memory.get(memoryId, { objectId: "u1" })` |
99
+ | `ai.memory.update` | Update memory | `memoryId, MemoryUpdateInput, trusted access scope` | `MemoryEntry` | `ai.memory.update(memoryId, { content: "偏好日文" }, { objectId: "u1" })` |
100
+ | `ai.memory.remove` | Remove owned memory | `memoryId, trusted access scope` | `void` | `ai.memory.remove(memoryId, { objectId: "u1" })` |
101
+ | `ai.memory.recall` | Recall memories | `query, { objectId, scope?, topK?, types?, ...options }` | `MemoryEntry[]` | `ai.memory.recall("语言偏好", { objectId: "u1" })` |
102
+ | `ai.memory.injectMemories` | Enrich messages | `ChatMessage[], { objectId, scope?, topK?, ...options }` | `ChatMessage[]` | `ai.memory.injectMemories(messages, { objectId: "u1" })` |
103
+ | `ai.memory.list` | List memories | `MemoryListOptions with objectId/scope filters` | `MemoryEntry[]; incomplete scan fails` | `ai.memory.list({ objectId: "u1" })` |
104
+ | `ai.memory.listPage` | Page memories | `MemoryListPageOptions with objectId/pagination` | `StorePage<MemoryEntry>` | `ai.memory.listPage({ objectId: "u1", offset: 0, limit: 20 })` |
105
+ | `ai.memory.clear` | Clear selected scope | `nonempty MemoryClearOptions` | `void; empty filters are rejected` | `ai.memory.clear({ objectId: "u1" })` |
106
+ | `ai.memory.admin.clearAll` | Trusted administrator clear | `{ confirm: true }; require host administrator authorization` | `void; destructive across subjects` | `ai.memory.admin.clearAll({ confirm: true })` |
107
+ | `ai.persona.save` | Save persona | `PersonaProfileInput: id, name, systemPrompt, objectId?, traits?` | `PersonaProfile` | `ai.persona.save(personaProfile)` |
108
+ | `ai.persona.get` | Get persona | `id, { objectId }?; omitted subject selects system profile` | `PersonaProfile` | `ai.persona.get("tutor", { objectId: "u1" })` |
109
+ | `ai.persona.update` | Update persona | `id, PersonaProfileUpdate, { objectId }?` | `PersonaProfile` | `ai.persona.update("tutor", updates, { objectId: "u1" })` |
110
+ | `ai.persona.remove` | Remove persona | `id, { objectId }?` | `void` | `ai.persona.remove("tutor", { objectId: "u1" })` |
111
+ | `ai.persona.list` | List personas | `{ objectId }?` | `PersonaProfile[]` | `ai.persona.list({ objectId: "u1" })` |
112
+ | `ai.persona.compose` | Compose system prompt | `id, { objectId }?` | `string prompt` | `ai.persona.compose("tutor", { objectId: "u1" })` |
113
+ | `ai.token.estimateText` | Estimate text tokens | `text: string` | `direct number; estimate, not billing usage` | `ai.token.estimateText("Hello 世界")` |
114
+ | `ai.token.estimateMessages` | Estimate message tokens | `ChatMessage[]` | `direct number including protocol overhead` | `ai.token.estimateMessages(messages)` |
115
+ | `ai.summary.generate` | Generate summary text | `ChatMessage[], SummaryOptions?` | `string` | `ai.summary.generate(messages)` |
116
+ | `ai.summary.summarize` | Summary metadata | `ChatMessage[], SummaryOptions?` | `{ summary, tokenCount, coveredMessages }` | `ai.summary.summarize(messages)` |
117
+ | `ai.compress.tryCompress` | Compress to budget | `ChatMessage[], { strategy?, maxTokens?, preserveLastN?, ...options }` | `CompressResult: messages and original/compressed token counts` | `ai.compress.tryCompress(messages, { maxTokens: 4000 })` |
118
+ | `ai.context.createManager` | Create context | `ContextManagerOptions with scope { objectId, sessionId }` | `ContextManager` | `ai.context.createManager({ scope: { objectId: "u1", sessionId: "s1" } })` |
119
+ | `ai.context.restoreManager` | Restore context | `{ objectId, sessionId }, options?` | `ContextManager` | `ai.context.restoreManager({ objectId: "u1", sessionId: "s1" })` |
120
+ | `ai.context.listSessions` | List stored sessions | `objectId` | `SessionInfo[]` | `ai.context.listSessions("u1")` |
121
+ | `ai.context.renameSession` | Rename session | `scope, title` | `void` | `ai.context.renameSession({ objectId: "u1", sessionId: "s1" }, "订单讨论")` |
122
+ | `ai.context.removeSession` | Remove session | `scope` | `void; tombstone prevents scope reuse` | `ai.context.removeSession({ objectId: "u1", sessionId: "s1" })` |
123
+ | `ai.rerank.rerank` | Rerank documents | `RerankRequest: query, documents, model?, topN?` | `RerankResponse with model/results` | `ai.rerank.rerank({ query: "部署", documents: ["配置说明"] })` |
124
+ | `ai.rerank.rerankTexts` | Rerank texts | `query, string[] texts, topN?` | `RerankItem[] with index/relevanceScore` | `ai.rerank.rerankTexts("部署", ["配置说明"], 1)` |
125
+ | `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" })` |
126
+ | `ai.file.parseText` | Extract plain text | `Buffer\|string content, filename?` | `string` | `ai.file.parseText("Hello", "intro.txt")` |
127
+ | `ai.reasoning.run` | Multistep reasoning | `query, ReasoningOptions including strategy/tools?` | `ReasoningResult` | `ai.reasoning.run("审查方案", { strategy: "cot" })` |
128
+ | `ai.reasoning.runStream` | Observe reasoning stream | `query, ReasoningOptions?` | `AsyncIterable<ReasoningStreamEvent>` | `ai.reasoning.runStream("审查方案", { strategy: "react" })` |
129
+ | `ai.audio.transcribe` | Transcribe audio | `TranscriptionRequest: audio, language?, model?, signal?` | `TranscriptionResult: text, language?, segments?` | `ai.audio.transcribe({ audio: { data: wavBytes, format: "wav" } })` |
130
+ | `ai.audio.transcribeStream` | Stream transcription | `TranscriptionStreamRequest: chunks or complete audio` | `AsyncIterable<TranscriptionEvent>` | `ai.audio.transcribeStream(transcriptionInput)` |
131
+ | `ai.audio.synthesize` | Synthesize audio | `SynthesisRequest: text, language?, model?, signal?` | `SynthesisResult: audio and duration metadata` | `ai.audio.synthesize({ text: "你好" })` |
132
+ | `ai.audio.synthesizeStream` | Synthesize segments | `SynthesisStreamRequest: text segment or async segments` | `AsyncIterable<SynthesisEvent>` | `ai.audio.synthesizeStream(synthesisInput)` |
133
+ | `ai.audio.getCapabilities` | Inspect capabilities | `{ operation: transcribe\|synthesize, model? }` | `AudioModelCapabilities` | `ai.audio.getCapabilities({ operation: "synthesize" })` |
134
+ | `ai.image.generate` | Generate images | `{ prompt, referenceImages?, model?, size?, signal? }` | `{ images: GeneratedImage[] } with bytes/MIME` | `ai.image.generate({ prompt: "一座灯塔" })` |
135
+ | `ai.a2a.registerExecutor` | Register executor | `SDK AgentExecutor` | `void` | `ai.a2a.registerExecutor(executor)` |
136
+ | `ai.a2a.getAgentCard` | Agent discovery | `none; configured a2a card` | `A2AAgentCardDocument (A2A 1.0 ProtoJSON)` | `ai.a2a.getAgentCard()` |
137
+ | `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 })` |
138
+ | `ai.a2a.listMessages` | Administrative message query | `A2ATaskFilter: callerId?, contextId?, since?, pagination?` | `StorePage<A2AMessageRecord>` | `ai.a2a.listMessages(messageFilter)` |
139
+ | `ai.a2a.callRemoteAgent` | Call approved remote agent | `allowlisted HTTPS URL, message, A2ACallOptions?` | `A2ACallResult` | `ai.a2a.callRemoteAgent("https://agent.example.com/a2a", "请分析订单")` |
140
+ | `ai.init` | Initialize service | `AIConfigInput?, AIInitOptions?` | `HaiResult<void>; validate dependencies before use` | `ai.init({ llm: { apiKey: process.env.HAI_AI_LLM_APIKEY } })` |
141
+ | `ai.close` | Release service | `none` | `Promise<void>; wait for cleanup` | `ai.close()` |
142
+ | `ai.config` | Read safe config | `none` | `redacted AIConfig or null` | `ai.config` |
143
+ | `ai.isInitialized` | Check lifecycle | `none` | `boolean` | `ai.isInitialized` |
144
+ | `ai.llm.models.list` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.llm.models.list()` |
145
+ | `ai.llm.models.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.llm.models.get("coding")` |
146
+ | `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)` |
147
+ | `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)` |
148
+ | `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)` |
149
+ | `ai.audio.models.list` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.audio.models.list()` |
150
+ | `ai.audio.models.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.audio.models.get("speech")` |
151
+ | `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)` |
152
+ | `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)` |
153
+ | `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)` |
154
+ | `ai.image.models.list` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.image.models.list()` |
155
+ | `ai.image.models.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.image.models.get("poster")` |
156
+ | `ai.image.models.register` | Register database definition | `ImageModelEntry input (id/provider/model)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.image.models.register(imageModelDefinition)` |
157
+ | `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)` |
158
+ | `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)` |
159
+ | `ai.mcp.servers.list` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.mcp.servers.list()` |
160
+ | `ai.mcp.servers.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.mcp.servers.get("tools")` |
161
+ | `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)` |
162
+ | `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)` |
163
+ | `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)` |
164
+ | `ai.retrieval.sources.list` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.retrieval.sources.list()` |
165
+ | `ai.retrieval.sources.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.retrieval.sources.get("docs")` |
166
+ | `ai.retrieval.sources.register` | Register database definition | `RetrievalSource input (id/collection)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.retrieval.sources.register(sourceDefinition)` |
167
+ | `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)` |
168
+ | `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)` |
169
+ | `ai.acp.agents.list` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.acp.agents.list()` |
170
+ | `ai.acp.agents.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.acp.agents.get("coder")` |
171
+ | `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)` |
172
+ | `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)` |
173
+ | `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)` |
174
+ | `ai.acp.workspaces.list` | List merged definitions | `none` | `HaiResult<AIResourceEntry[]>; config wins, list has no database version` | `ai.acp.workspaces.list()` |
175
+ | `ai.acp.workspaces.get` | Read source and version | `id: string` | `HaiResult<AIResourceEntry> with value/source/version?` | `ai.acp.workspaces.get("project")` |
176
+ | `ai.acp.workspaces.register` | Register database definition | `ACPWorkspace input (id/storage/repositories)` | `HaiResult<AIResourceEntry>; config entries are read-only` | `ai.acp.workspaces.register(workspaceDefinition)` |
177
+ | `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)` |
178
+ | `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)` |
179
+ | `ai.acp.agents.initialize` | Preflight agent | `agentId, modelId?` | `HaiResult<{ agentId, mode, modelIds }>; no credentials` | `ai.acp.agents.initialize("coder")` |
180
+ | `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" })` |
181
+ | `ai.acp.workspaces.prepare` | Prepare workspace | `workspaceId` | `HaiResult<main absolute path>; dirty content is retained` | `ai.acp.workspaces.prepare("project")` |
182
+ | `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: "需求" }])` |
183
+ | `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 })` |
184
+ | `ai.acp.sessions.get` | Get session handle | `framework session id` | `HaiResult<managed session handle>; does not resume` | `ai.acp.sessions.get("task-1")` |
185
+ | `ai.acp.sessions.list` | List managed sessions | `workspaceId?` | `HaiResult<ACPSessionInfo[]>` | `ai.acp.sessions.list("project")` |
186
+ | `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")` |
187
+ | `ai.acp.sessions.close` | Stop owned execution | `framework session id` | `HaiResult<void>; source and native history retained` | `ai.acp.sessions.close("task-1")` |
188
+ | `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")` |
189
+ | `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")` |
190
+ | `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" })` |
191
+ | `ai.acp.close` | Close subsystem | `none; normally call ai.close()` | `Promise<void>; cleanup may throw` | `ai.acp.close()` |
12
192
 
13
193
  - `ai.tools`: tool definitions, registries, and batch execution; no initialization required.
14
194
  - `ai.stream`: ChatCompletion stream chunk processing; no initialization required.
@@ -32,34 +212,7 @@ AI capabilities through a unified `ai` service: LLM chat, image generation, tool
32
212
 
33
213
  For the full method list, error codes, and longer examples, see [REFERENCE.md (Chinese)](./REFERENCE.md).
34
214
 
35
- ## Getting started
36
-
37
- ### Quick start
38
-
39
- #### Development LLM-only (no database dependencies)
40
-
41
- ```ts
42
- import { ai } from '@h-ai/ai'
43
-
44
- const init = await ai.init({
45
- llm: {
46
- model: 'gpt-4o-mini',
47
- apiKey: process.env.HAI_AI_LLM_APIKEY,
48
- },
49
- })
50
- if (!init.success)
51
- return init
52
-
53
- const result = await ai.llm.chat({
54
- messages: [{ role: 'user', content: '你好!' }],
55
- })
56
-
57
- await ai.close()
58
- ```
59
-
60
- Development/explicit tests without initialized reldb/vecdb use a temporary process store, lost on close, exit, or instance switching. When either `NODE_ENV` or `HAI_CORE_ENV` is production, temporary stores, SQLite and local vector backends fail initialization. Initialize shared RelDB and network vecdb first, or supply a shared provider with equivalent atomic guarantees.
61
-
62
- #### Persistent DB provider (reldb + vecdb)
215
+ ### Persistent DB provider (reldb + vecdb)
63
216
 
64
217
  ```ts
65
218
  import { ai } from '@h-ai/ai'
@@ -80,7 +233,11 @@ try {
80
233
  })
81
234
  if (!initialized.success)
82
235
  throw new Error(initialized.error.message)
83
- const result = await ai.llm.chat({ messages: [{ role: 'user', content: 'Hello!' }] })
236
+ const result = await ai.llm.chat({
237
+ messages: [
238
+ { role: 'user', content: 'Hello!' }
239
+ ]
240
+ })
84
241
  if (!result.success)
85
242
  throw new Error(result.error.message)
86
243
  const reply = result.data.choices[0]?.message.content ?? ''
@@ -102,7 +259,7 @@ if (failures.length)
102
259
 
103
260
  Concurrent MySQL first startup accepts only the explicit mysql2 ER_DUP_KEYNAME/1061 error, then verifies the actual columns and order, non-unique full columns, ascending visible BTREE, and no expressions. An existing index with the wrong definition fails. The account needs table creation and INDEX privileges; metadata, permission, or other DDL failures return CONFIGURATION_ERROR from ai.init. All started DDL settles before return. MySQL DDL is not rolled back: repair privileges/schema before retrying partial initialization. Check each initialization result, reject business traffic on failure, and close AI, vecdb, and reldb in reverse order.
104
261
 
105
- #### Custom StoreProvider
262
+ ### Custom StoreProvider
106
263
 
107
264
  ```ts
108
265
  import type { AIStoreProvider } from '@h-ai/ai'
@@ -111,7 +268,9 @@ import { ai } from '@h-ai/ai'
111
268
  const storeProvider: AIStoreProvider = createMyStoreProvider()
112
269
 
113
270
  await ai.init(
114
- { llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY } },
271
+ {
272
+ llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY }
273
+ },
115
274
  { storeProvider },
116
275
  )
117
276
 
@@ -146,17 +305,17 @@ const controller = new AbortController()
146
305
  const cancellable = ai.llm.chat({ messages, signal: controller.signal })
147
306
  // controller.abort()
148
307
 
149
- // 多协议:模型的 api 决定底层走 Chat Completions / Responses / Anthropic,公共请求响应形状不变
308
+ // 多协议:模型的 protocol 决定底层走 Chat Completions / Responses / Anthropic,公共请求响应形状不变
150
309
  // - chat(默认):OpenAI Chat Completions(兼容绝大多数厂商)
151
310
  // - responses:OpenAI Responses API(/v1/responses)
152
311
  // - anthropic:Anthropic Messages API(Claude 原生协议,环境变量 ANTHROPIC_API_KEY / ANTHROPIC_BASE_URL)
153
- const claude = await ai.llm.chat({ messages, model: 'claude' }) // 该模型配置 api: anthropic
312
+ const claude = await ai.llm.chat({ messages, model: 'claude' }) // 该模型配置 protocol: anthropic
154
313
 
155
314
  // 临时模型:单次请求绕过配置注册模型,直接指定端点与凭据(chat/chatStream/ask/askStream 均支持)
156
315
  // 临时客户端按 TTL 缓存(llm.tempModelCacheTtl,默认 10 分钟),与常驻模型客户端隔离
157
316
  const temp = await ai.llm.chat({
158
317
  messages,
159
- tempModel: { model: 'claude-3-5-sonnet', api: 'anthropic', apiKey: 'sk-temp' },
318
+ tempModel: { model: 'claude-3-5-sonnet', protocol: 'anthropic', apiKey: process.env.TEMP_LLM_API_KEY },
160
319
  })
161
320
  ```
162
321
 
@@ -174,7 +333,9 @@ const registry = ai.tools.createRegistry({
174
333
  const registered = registry.register(ai.tools.define({
175
334
  name: 'get_weather',
176
335
  description: '获取天气',
177
- parameters: z.object({ city: z.string() }),
336
+ parameters: z.object({
337
+ city: z.string()
338
+ }),
178
339
  // handler 第二参为执行上下文:可响应取消(打断/超时)、感知截止时间与交互主体
179
340
  handler: async ({ city }, { signal }) => {
180
341
  const res = await fetch(`https://api.example.com/weather?city=${city}`, { signal })
@@ -191,12 +352,44 @@ const result = await registry.execute(toolCall, { signal: controller.signal, obj
191
352
  // 批量调用默认串行,避免副作用工具并发启动;纯读取且确认安全时才显式并行
192
353
  const batch = await registry.executeAll(toolCalls)
193
354
 
194
- const chat = await ai.llm.chat({ messages, tools: registry.getDefinitions() })
355
+ const chat = await ai.llm.chat({
356
+ messages,
357
+ tools: registry.getDefinitions()
358
+ })
195
359
  ```
196
360
 
361
+ #### ACP agents, workspaces and sessions
362
+
363
+ `ai.acp` runs on Node: `embedded` starts a local process, `builtin-service` starts a Podman/Docker container (ready Podman first), and `custom-service` connects to a native HTTP/WS ACP service. Codex/dsh use stdio; unsupported transports are not silently bridged.
364
+
365
+ Podman does not inherit proxy variables from its remote service. Configure proxies explicitly through agent/workspace `environmentRefs`, using addresses reachable from the container.
366
+
367
+ The Goose 1.57.0 image exposes its native `goose serve` HTTP/WS `/acp` service through custom-service with `X-Secret-Key`. Goose manages its models; deployment owns workspace/state volumes. Real remote E2E verifies native resume when advertised.
368
+
369
+ - `agents.register/get/list/update/remove/initialize/check` manage definitions. The `codex` and `deepseek-harness` adapters reference `llm.models`; use `generic` or trusted `AIInitOptions.acpAdapters` for other agents. External services own their models.
370
+ - `workspaces.register/prepare/importFiles` manage directories or persistent volumes, multiple Git repositories and plain files. Every repository requires `mainBranch`; prepare preserves dirty directories.
371
+ - Use workspace `gitEnvironmentRefs` for credentials scoped to remote Git operations and agent `environmentRefs` for agent-only values. The existing workspace `environmentRefs` remains shared.
372
+ - `sessions.create/resume/get/list/close` manage native sessions. `newWorktree: true` creates matching branches from each committed local main branch. Set `repositoryId` to start and resume at a registered repository root so the agent can discover its rules and skills. Prompt, stream, strict structured output, permission callbacks, MCP, configuration and cancellation use native ACP capabilities.
373
+ - A successful `session.info()` exposes `data.workspace` for local or same-node volume previews, including after the agent closes. Stop the preview and save changes before calling `sessions.reclaimWorktree(id)` to remove the session's clean worktrees. Branches, plain files, native history and volumes are retained.
374
+ - `session.updateMain()` fetches and fast-forwards configured main branches. `publish({ mode: 'merge-main' | 'push-branch', message, author })` publishes managed isolated sessions only, with per-repository partial-failure reports and no force push. Both stop execution first; resume explicitly to continue.
375
+
376
+ 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
+
378
+ See the [ACP guide](../cli/templates/skills/hai-ai/acp.md) and [agent images](models/agents/README.md). Images include Git/Node/Python, optional Java/Rust/Go, and both codex-acp and codex in the Codex image. Errors use `hai:ai:070`–`084`; ordinary methods return HaiResult, while stream failures throw.
379
+
380
+ Managed Git rejects submodules and Git LFS attributes with ACP_UNSUPPORTED instead of reporting incomplete checkouts as ready.
381
+
382
+ #### Configuration and database resource catalogs
383
+
384
+ `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.
385
+
386
+ [Resource catalogs](../cli/templates/skills/hai-ai/resources.md) · [ACP](../cli/templates/skills/hai-ai/acp.md)
387
+
197
388
  #### A2A protocol boundaries
198
389
 
199
- `ai.a2a.getAgentCard()` returns a complete A2A 0.3 Agent Card with `protocolVersion`, MIME, and streaming capabilities. Kit discovery defaults to `/.well-known/agent-card.json`. `handleRequest()` always returns JSON-RPC/SSE results; uninitialized calls return JSON-RPC errors. Trusted HTTP `agentId` maps to executor `context.user.userName`. JSON-RPC/SSE are supported; push notifications, gRPC, and REST are not claimed. Applications remain responsible for business resource authorization.
390
+ Remote-call headers override existing fields case-insensitively. Fixed JSON-RPC endpoints reject HTTP redirects, preventing authentication headers from reaching redirect targets.
391
+
392
+ `ai.a2a.getAgentCard()` returns standard A2A 1.0 ProtoJSON ready for an HTTP discovery response, with `supportedInterfaces`, MIME, and streaming capabilities. Kit discovery defaults to `/.well-known/agent-card.json`. `handleRequest()` always returns JSON-RPC/SSE results; uninitialized calls return JSON-RPC errors. Trusted HTTP `agentId` maps to executor `context.user.userName`. JSON-RPC/SSE are supported; push notifications, gRPC, and REST are not claimed. Applications remain responsible for business resource authorization.
200
393
 
201
394
  A2A journal, context ownership and message tables initialize during `ai.init()`. Tasks use trusted `agentId` scopes for get/cancel/continuation. Anonymous requests share one principal; authenticate at the trusted transport boundary in production. `listMessages` is a server administration API with `callerId`, `contextId`, and `since`; never expose it to unauthorized clients.
202
395
 
@@ -217,15 +410,25 @@ import { z } from 'zod'
217
410
  const server = createMcpServer({ name: 'my-server', version: '1.0.0' })
218
411
  server.registerTool('search', {
219
412
  description: '搜索',
220
- inputSchema: { query: z.string() },
413
+ inputSchema: {
414
+ query: z.string()
415
+ },
221
416
  }, async ({ query }) => ({
222
- content: [{ type: 'text', text: `Results for ${query}` }],
417
+ content: [
418
+ { type: 'text', text: `Results for ${query}` }
419
+ ],
420
+ }))
421
+ await server.connect(new StreamableHTTPServerTransport({
422
+ sessionIdGenerator: () => globalThis.crypto.randomUUID()
223
423
  }))
224
- await server.connect(new StreamableHTTPServerTransport({ sessionIdGenerator: () => globalThis.crypto.randomUUID() }))
225
424
  ```
226
425
 
227
426
  #### Memory / RAG / Knowledge
228
427
 
428
+ 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.
429
+
430
+ `ai.memory.scoped({ objectId })` requires a nonempty, non-whitespace subject ID; invalid input immediately throws `TypeError` from the factory instead of creating an unbound instance. Empty public clearing ranges such as `clear({ scope: {} })` fail; cross-subject clearing requires the explicit administrator API. Native memory access statistics and updates use version CAS, so delayed reads cannot resurrect deleted entries. Database and vector cleanup failures return failed HaiResult values.
431
+
229
432
  Each Knowledge ingestion creates a unique `revision` and chunk IDs. It prepares all chunks, embeddings and entities, persists a staging manifest, writes vectors, then publishes the complete document and entity snapshot with shared Store CAS. Only one writer can rebuild a document at a time. Failure preserves the complete old version; shorter replacements cannot expose old trailing chunks. Retrieval filters unpublished revisions and retries around publication; sustained contention returns an error. Candidate expansion and cleanup backlogs can increase query cost.
230
433
 
231
434
  Successful ingestion returns `revision` and `cleanupPending`. A true flag means the new version is published but old vectors still require cleanup. Paginate `repair({ collection, offset, limit })` regularly across every manifest; setup checks the first 100. Staging expires after five minutes according to the storage clock and an expired writer cannot publish. Abandoned writes retain permanent cleanup tombstones so later scans can remove delayed external writes; do not prune these with logs. SQL and vector storage do not share a transaction. Removal hides data first and reports cleanup failures. Collection deletion retains the empty vector collection and generation tombstones for compensation; setup never revives the previous generation.
@@ -243,15 +446,23 @@ if (!enriched.success) {
243
446
  }
244
447
 
245
448
  // 多租户推荐入口:scoped() 绑定主体与作用域,所有操作自动携带 objectId / scope(含归属校验),杜绝「忘记传 objectId」越权
246
- const memory = ai.memory.scoped({ objectId: 'user-001', scope: { topicId: 't-1', personaId: 'p-1' } })
449
+ const memory = ai.memory.scoped({
450
+ objectId: 'user-001',
451
+ scope: { topicId: 't-1', personaId: 'p-1' }
452
+ })
247
453
  await memory.add({ content: '用户偏好中文', type: 'preference' })
248
454
  const recalled = await memory.recall('语言偏好')
249
455
 
250
456
  // clear 拒绝空过滤(防误清全局);全局清空只能显式走管理接口
251
- await memory.clear({ types: ['event'] }) // 仅清该作用域内的 event
457
+ await memory.clear({
458
+ types: ['event']
459
+ }) // 仅清该作用域内的 event
252
460
  await ai.memory.admin.clearAll({ confirm: true }) // 危险:清空整个记忆后端,需显式确认
253
461
 
254
- const rag = await ai.rag.query('核心架构是什么?', { sources: ['docs'], topK: 5 })
462
+ const rag = await ai.rag.query('核心架构是什么?', {
463
+ sources: ['docs'],
464
+ topK: 5
465
+ })
255
466
 
256
467
  const setup = await ai.knowledge.setup()
257
468
  if (setup.success) {
@@ -282,11 +493,33 @@ await ai.init({
282
493
  audio: {
283
494
  inheritLlmApiKey: true,
284
495
  models: [
285
- { id: 'asr', provider: 'qwen', model: 'qwen3-asr-flash-realtime', operations: ['transcribe'] },
286
- { id: 'tts', provider: 'qwen', model: 'qwen3-tts-flash-realtime', operations: ['synthesize'] },
496
+ {
497
+ id: 'asr',
498
+ provider: 'qwen',
499
+ model: 'qwen3-asr-flash-realtime',
500
+ operations: ['transcribe']
501
+ },
502
+ {
503
+ id: 'tts',
504
+ provider: 'qwen',
505
+ model: 'qwen3-tts-flash-realtime',
506
+ operations: ['synthesize']
507
+ },
287
508
  // 自托管:whisper / indextts 必须显式配置 baseUrl
288
- { id: 'whisper', provider: 'whisper', model: 'faster-whisper-large-v3', operations: ['transcribe'], baseUrl: 'http://127.0.0.1:8101/v1' },
289
- { id: 'indextts', provider: 'indextts', model: 'indextts-2.5', operations: ['synthesize'], baseUrl: 'http://127.0.0.1:8102/v1' },
509
+ {
510
+ id: 'whisper',
511
+ provider: 'whisper',
512
+ model: 'faster-whisper-large-v3',
513
+ operations: ['transcribe'],
514
+ baseUrl: 'http://127.0.0.1:8101/v1'
515
+ },
516
+ {
517
+ id: 'indextts',
518
+ provider: 'indextts',
519
+ model: 'indextts-2.5',
520
+ operations: ['synthesize'],
521
+ baseUrl: 'http://127.0.0.1:8102/v1'
522
+ },
290
523
  ],
291
524
  transcribeModel: 'asr',
292
525
  synthesizeModel: 'tts',
@@ -413,6 +646,12 @@ Downloads require public HTTPS on default port 443 without URL credentials. Sock
413
646
 
414
647
  `image.maxImageBytes` defaults to 20971520 (20 MiB; maximum 100 MiB) per output/reference image. `image.maxImages` defaults to 4 (maximum 16) for output/reference counts, with sequential URL downloads. Actual streamed bytes, including decompressed bytes, are bounded and excess responses are cancelled. JSON responses are limited to `max(64 KiB, 2 × maxImageBytes)` and error bodies to 64 KiB. Model `timeout` defaults to 120000ms for the entire vendor request, redirects, and downloads; `signal` cancels the whole process. Outputs require matching PNG/JPEG/GIF/WebP MIME and magic bytes; SVG is rejected. Magic checks do not decode complete images or verify dimensions. Address rejection, limits, and deadlines return `IMAGE_DOWNLOAD_BLOCKED`, `IMAGE_TOO_LARGE`, and `IMAGE_TIMEOUT`; check success before use.
415
648
 
649
+ #### File parsing
650
+
651
+ Pass the business file content and filename to `ai.file.parse({ content, filename, options: { outputFormat: 'markdown' } })`. Check `success` before reading `data.text`; use `outputFormat: 'text'` for plain text. HTML uses parse5 and iterative traversal, omits script/style content, and preserves common Markdown headings, lists, links, images, quotations, code and tables. Normal documents are not truncated to avoid malformed-tag regex backtracking.
652
+
653
+ The result is text or Markdown, not trusted HTML. Render it with text bindings or the framework's `MarkdownRenderer`. Configuration, parameters and error codes retain their existing contract.
654
+
416
655
  #### Context manager
417
656
 
418
657
  Automatic memory extraction runs locally in the background; `pendingMemoryTasks=0` does not imply success. `flush()` waits for the batch and returns `MEMORY_EXTRACT_FAILED` with a count for thrown errors or failed HaiResults. Concurrent observers share that result. Returning acknowledges the report; later flushes observe new tasks without replaying partially completed effects. `save()`, `reset({ waitForMemoryTasks: true })`, and `consolidate()` return that failure before subsequent writes. Reconcile external effects after a process crash.
@@ -445,7 +684,10 @@ With `turnCommit: 'manual'`, results are not stored automatically. A `turnId` is
445
684
  `chatStream` registers a turn and emits `turn_started` **before calling the model** (`turn_started → delta* → done`, or `turn_started → delta* → cancelled` on cancellation). Even if `AbortSignal` cancels generation midway, the caller gets `turnId` and generated text for committing actual content:
446
685
 
447
686
  ```ts
448
- const created = ai.context.createManager({ scope: { objectId: 'user-001', sessionId: 'sess-001' }, turnCommit: 'manual' })
687
+ const created = ai.context.createManager({
688
+ scope: { objectId: 'user-001', sessionId: 'sess-001' },
689
+ turnCommit: 'manual'
690
+ })
449
691
  if (!created.success)
450
692
  return created
451
693
  const m = created.data
@@ -483,7 +725,14 @@ turns short-term memory + summaries into **cross-session long-term memory**, com
483
725
 
484
726
  ```ts
485
727
  // 会话结束时固化:整合摘要 → 提取长期记忆(写入不含 sessionId 的持久作用域)
486
- const result = await manager.consolidate({ scope: { userId: 'user-001', personaId: 'xiaoq' } })
728
+ const created = ai.context.createManager({
729
+ scope: { objectId: 'user-001', sessionId: 'sess-001' }
730
+ })
731
+ if (!created.success)
732
+ return created
733
+ const result = await created.data.consolidate({
734
+ scope: { userId: 'user-001', personaId: 'xiaoq' }
735
+ })
487
736
  if (result.success) {
488
737
  // result.data.summary —— 本次会话整合摘要
489
738
  // result.data.memories —— 固化到长期记忆的条目
@@ -505,29 +754,114 @@ await ai.persona.save({
505
754
 
506
755
  // 组合出可直接喂给 ContextManager 的系统提示词(systemPrompt + traits)
507
756
  const composed = await ai.persona.compose('xiaoq')
757
+ if (!composed.success)
758
+ return composed
508
759
  const manager = ai.context.createManager({
509
760
  scope: { objectId: 'user-001', sessionId: 'persona-session' },
510
761
  systemPrompt: composed.data,
511
- memory: { enable: true, enableExtract: true, scope: { personaId: 'xiaoq' } },
762
+ memory: {
763
+ enable: true,
764
+ enableExtract: true,
765
+ scope: { personaId: 'xiaoq' }
766
+ },
512
767
  })
513
768
  ```
514
769
 
515
- `ai.persona` exposes `save` / `get` / `update` / `remove` / `list` / `compose`. Profiles are shared globally, not isolated by `objectId`.
770
+ `ai.persona` exposes `save` / `get` / `update` / `remove` / `list` / `compose`, with profiles isolated by `[objectId, id]`. Supply `objectId` when saving and `{ objectId }` for other operations; omission selects the `system` platform profile. Bind tenant operations to a trusted authenticated subject; a client-provided profile ID does not authorize access.
771
+
772
+ ### Security boundaries
773
+
774
+ - Treat prompts, retrieved documents, and model outputs as untrusted. Do not insert user content into non-overridable system rules.
775
+ - Zod validates tool argument shapes, not caller permissions. High-privilege handlers must verify identity, tenant, ownership, and quota, and expose only tools allowed to execute automatically.
776
+ - `callRemoteAgent()` is an independent client requiring only `ai.init()`, without Agent Card or local executors. It rejects non-HTTP(S) and embedded URL credentials; applications must still allowlist origins and enforce egress protection against DNS rebinding, private-network redirects, and cloud metadata access.
777
+ - Do not log full prompts, tool arguments, A2A headers, temporary model credentials, or remote URLs with queries. Audits should retain redacted summaries only.
516
778
 
517
- ### Configuration
779
+ ### Using returned handles
780
+
781
+ `registry` comes from ai.tools.createRegistry(); `manager` is successful data from context.createManager/restoreManager; `session` is successful data from managed ACP sessions.create/get/resume; `connection` comes from acp.connect. Respect each handle's lifecycle and authorization. Scoped Memory exposes the same ten operations above with objectId/scope bound by the factory; per-call overrides are omitted.
782
+
783
+ | Entry | Use case | Input | Output | Call fragment |
784
+ | -------------------------- | ------------------------ | ---------------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------- |
785
+ | `registry.register` | Register one tool | `Tool` | `HaiResult<void>; duplicate rejected` | `registry.register(tool)` |
786
+ | `registry.registerMany` | Register tools | `Tool[]` | `HaiResult<void>` | `registry.registerMany(tools)` |
787
+ | `registry.replace` | Explicitly replace tool | `Tool with existing name` | `HaiResult<void>` | `registry.replace(tool)` |
788
+ | `registry.unregister` | Unregister tool | `tool name` | `boolean` | `registry.unregister("search")` |
789
+ | `registry.get` | Get tool | `tool name` | `Tool or undefined` | `registry.get("search")` |
790
+ | `registry.has` | Check tool | `tool name` | `boolean` | `registry.has("search")` |
791
+ | `registry.getNames` | Tool names | `none` | `string[]` | `registry.getNames()` |
792
+ | `registry.getDefinitions` | Model-facing definitions | `none` | `ToolDefinition[]` | `registry.getDefinitions()` |
793
+ | `registry.execute` | Execute authorized tool | `ToolCall, ToolExecutionOptions?` | `Promise<HaiResult<ToolMessage>>` | `registry.execute(toolCall, { objectId: "u1" })` |
794
+ | `registry.executeAll` | Execute calls | `ToolCall[], { parallel?, ...executionOptions }` | `Promise<HaiResult<ToolMessage[]>>` | `registry.executeAll(toolCalls)` |
795
+ | `registry.clear` | Clear local tools | `none` | `void` | `registry.clear()` |
796
+ | `registry.size` | Tool count | `none` | `number` | `registry.size` |
797
+ | `manager.addMessage` | Add message | `ChatMessage` | `Promise<HaiResult<void>>` | `manager.addMessage({ role: "user", content: "你好" })` |
798
+ | `manager.getMessages` | Read message snapshot | `none` | `HaiResult<ChatMessage[]>` | `manager.getMessages()` |
799
+ | `manager.reload` | Reload shared state | `none` | `Promise<HaiResult<void>>` | `manager.reload()` |
800
+ | `manager.getTokenUsage` | Observe budget | `none` | `HaiResult<{ current, budget }>` | `manager.getTokenUsage()` |
801
+ | `manager.getSummaries` | Read summaries | `none` | `HaiResult<SummaryResult[]>` | `manager.getSummaries()` |
802
+ | `manager.save` | Save context | `none` | `Promise<HaiResult<void>>` | `manager.save()` |
803
+ | `manager.flush` | Flush background memory | `none` | `Promise<HaiResult<void>>` | `manager.flush()` |
804
+ | `manager.reset` | Reset conversation | `ContextResetOptions?` | `Promise<HaiResult<void>>` | `manager.reset({ preserveSystemPrompt: true })` |
805
+ | `manager.getTurns` | Read actual turns | `none` | `HaiResult<ConversationTurn[]>` | `manager.getTurns()` |
806
+ | `manager.markTurnSpeaking` | Mark speaking | `turnId` | `Promise<HaiResult<void>>` | `manager.markTurnSpeaking(turnId)` |
807
+ | `manager.commitTurn` | Commit actual content | `turnId, { text? }` | `Promise<HaiResult<void>>` | `manager.commitTurn(turnId, { text: spokenText })` |
808
+ | `manager.interruptTurn` | Commit interruption | `turnId, { text? }` | `Promise<HaiResult<void>>` | `manager.interruptTurn(turnId, { text: spokenText })` |
809
+ | `manager.consolidate` | Consolidate memory | `ConsolidateOptions?` | `Promise<HaiResult<{ summary, memories }>>` | `manager.consolidate({ scope: { personaId: "tutor" } })` |
810
+ | `manager.chat` | Stateful answer | `message: string, ContextChatOptions?` | `Promise<HaiResult<ContextChatResult>>` | `manager.chat("请继续")` |
811
+ | `manager.chatStream` | Stateful stream | `message: string, ContextChatOptions?` | `AsyncIterable<ContextStreamEvent>` | `manager.chatStream("请继续")` |
812
+ | `session.info` | Read managed session | `none` | `Promise<HaiResult<ACPSessionInfo>>` | `session.info()` |
813
+ | `session.prompt` | Execute one turn | `ContentBlock[], AbortSignal?` | `Promise<HaiResult<{ text, stopReason, events }>>` | `session.prompt([{ type: "text", text: "检查工程" }])` |
814
+ | `session.promptStructured` | Validate JSON output | `ContentBlock[], Zod schema, AbortSignal?` | `Promise<HaiResult<schema-inferred T>>` | `session.promptStructured(content, OutputSchema)` |
815
+ | `session.stream` | Observe native events | `ContentBlock[], AbortSignal?` | `AsyncIterable<SessionNotification>; failure throws` | `session.stream([{ type: "text", text: "检查工程" }])` |
816
+ | `session.cancel` | Cancel turn | `none` | `Promise<HaiResult<void>>` | `session.cancel()` |
817
+ | `session.setMode` | Select advertised mode | `native mode ID` | `Promise<HaiResult<native mode response>>` | `session.setMode("code")` |
818
+ | `session.setConfigOption` | Set native option | `native option key and allowed value` | `Promise<HaiResult<native config response>>` | `session.setConfigOption("model", "coding")` |
819
+ | `session.updateMain` | Fast-forward main | `none; execution and preview must be stopped` | `Promise<HaiResult<ACPGitReport[]>>; partial failure reports in cause` | `session.updateMain()` |
820
+ | `session.publish` | Commit and push | `{ mode, message, author }; managed isolated session only` | `Promise<HaiResult<ACPGitReport[]>>` | `session.publish(publishOptions)` |
821
+ | `session.close` | Stop and retain state | `none` | `Promise<HaiResult<void>>` | `session.close()` |
822
+ | `connection.authenticate` | Native authentication | `advertised authentication method ID` | `Promise<HaiResult<native auth response>>` | `connection.authenticate("api-key")` |
823
+ | `connection.createSession` | Create native session | `absolute remote cwd, McpServer[]?` | `Promise<HaiResult<{ id, prompt, cancel }>>` | `connection.createSession("/workspace/project", [])` |
824
+ | `connection.listSessions` | Native sessions | `cursor?` | `Promise<HaiResult<native paginated response>>` | `connection.listSessions()` |
825
+ | `connection.deleteSession` | Delete native session | `native session ID` | `Promise<HaiResult<native delete response>>` | `connection.deleteSession(nativeId)` |
826
+ | `connection.close` | Close native connection | `none` | `Promise<HaiResult<void>>` | `connection.close()` |
827
+
828
+ ## Configuration
829
+
830
+ ### Choose configuration by task
831
+
832
+ | Configuration entry | Scenario | Input | Effect | Example |
833
+ | ------------------- | -------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
834
+ | `llm` | Model connection and protocol | model, protocol, apiKey/baseUrl, timeout, models/scenarios | chat/Responses/Anthropic selection; normalized model requests | `{ llm: { model: "gpt-4o-mini", timeout: 60000 } }` |
835
+ | `embedding` | Embedding vectors | model?, dimensions?, batchSize? | consistent vector dimensions for the target collection | `{ embedding: { dimensions: 1536, batchSize: 100 } }` |
836
+ | `mcp` | External tool servers | servers with transport/endpoints or commands | registered server definitions; application authorizes tool execution | `{ mcp: { servers: [] } }` |
837
+ | `retrieval` | Default retrieval sources | sources: { id, collection, topK?, minScore?, filter? }[] | queryable source definitions; does not import documents | `{ retrieval: { sources: [{ id: "docs", collection: "manual", topK: 5 }] } }` |
838
+ | `knowledge` | Publication and chunking | collection, dimension, cleanOptions, chunkOptions | versioned document/vector publication and bounded chunks | `{ knowledge: { collection: "manual", dimension: 1536, chunkOptions: { maxSize: 1500, overlap: 200 } } }` |
839
+ | `memory` | Subject memory backend | provider, quotas, recencyDecay, defaultTopK, candidateMultiplier | native or Mem0-format behavior with explicit persistence limits | `{ memory: { provider: "native", defaultTopK: 10 } }` |
840
+ | `token` | Token estimate | tokenRatio > 0; default 0.25 | local token budget estimates; not provider billing usage | `{ token: { tokenRatio: 0.25 } }` |
841
+ | `summary` | Summary policy | systemPrompt? | prompt used by summary generation; model from llm.scenarios | `{ summary: { systemPrompt: "保留已确认决策和待办" } }` |
842
+ | `compress` | Context compression | defaultStrategy, defaultMaxTokens, preserveLastN | compression defaults; 0 budget derives from model limit | `{ compress: { defaultStrategy: "hybrid", defaultMaxTokens: 4000, preserveLastN: 4 } }` |
843
+ | `file` | OCR instructions | systemPrompt?; model via llm.scenarios.ocr | text extraction instructions; not HTML sanitization | `{ file: { systemPrompt: "只提取可见文字" } }` |
844
+ | `audio` | Audio models and limits | models, transcribeModel/synthesizeModel, maxAudioBytes/maxStreamDurationMs | provider capability/operation selection and bounded input/stream | `see Audio examples` |
845
+ | `image` | Image models and download limits | models, generateModel, maxImageBytes, maxImages; timeout per model | generated bytes with MIME; unsafe downloads rejected | `see Image examples` |
846
+ | `a2a` | Agent discovery and leases | agentCard and execution lease/poll/deadline options | ProtoJSON discovery and shared task journal | `see A2A protocol section` |
847
+ | `acp` | Agent execution limits | agents/workspaces and execution content/event limits | validated definitions and managed native sessions | `see ACP guide` |
848
+
849
+ Rerank inherits the global LLM timeout with per-model overrides; the deadline covers the request and response body, returning RERANK_API_ERROR on timeout.
850
+
851
+ Set the request protocol with `llm.protocol`, `llm.models[].protocol` or per-call `tempModel.protocol`: `chat | responses | anthropic`. Environment names are `HAI_AI_LLM_PROTOCOL` and `HAI_AI_LLM_MODELS_0_PROTOCOL` (adjust the model index). Supply credentials with `apiKey` or private environment variables.
518
852
 
519
853
  ```yaml
520
854
  llm:
521
855
  apiKey: ''
522
856
  baseUrl: https://api.openai.com/v1
523
857
  model: gpt-4o-mini
524
- api: chat # chat(默认)| responses | anthropic —— 底层 API 协议,对使用方透明
858
+ protocol: chat # chat(默认)| responses | anthropic —— 底层 API 协议,对使用方透明
525
859
  timeout: 60000
526
860
  tempModelCacheTtl: 600000 # 临时模型客户端缓存 TTL(毫秒,默认 10 分钟)
527
861
  models: # 可为每个模型单独指定协议
528
862
  - {id: fast, model: gpt-4o-mini}
529
- - {id: strong, model: gpt-4.1, api: responses}
530
- - {id: claude, model: claude-3-5-sonnet-latest, api: anthropic}
863
+ - {id: strong, model: gpt-4.1, protocol: responses}
864
+ - {id: claude, model: claude-3-5-sonnet-latest, protocol: anthropic}
531
865
  scenarios:
532
866
  chat: fast
533
867
  reasoning: strong
@@ -562,7 +896,7 @@ memory:
562
896
  When loading through `core.config.load('ai', ...)`, convention-based environment variables override YAML:
563
897
  for example `HAI_AI_LLM_APIKEY`, `HAI_AI_LLM_BASEURL`, and `HAI_AI_LLM_MODEL`.
564
898
 
565
- Enable mem0 (the embedded mem0ai/oss engine):
899
+ Enable the Mem0 data-format adapter:
566
900
 
567
901
  ```yaml
568
902
  memory:
@@ -571,15 +905,13 @@ memory:
571
905
  ```
572
906
 
573
907
  - **`native` (default, recommended)**: HAI's native engine reuses vecdb, reldb, LLM, and Embedding. `extract` uses **Mem0-style batch merging**: one LLM call decides ADD / UPDATE / DELETE / NONE for extracted facts and related existing memories, providing incremental updates, deduplication, contradiction removal, and `category` labels. `maxEntriesPerObject`, `maxEntriesGlobal`, `recencyDecay`, `embeddingEnabled`, and `writebackRelatedTopK` apply. Eviction is partitioned by `objectId`, so heavy writes by one subject do not evict others' memories. `scope` candidates are narrowed by `objectId` (≤ `maxEntriesPerObject`); PostgreSQL also pushes scope into a JSONB containment query using a **GIN index**. SQLite/MySQL fall back to equivalent in-memory matching.
574
- - **`mem0` (mem0ai/oss)**: directly embeds the `mem0ai/oss` `Memory` engine without cloud services. LLM/Embedder come from `llm` configuration; `qdrant` can reuse vecdb. The adapter maps only Qdrant with complete connection settings. Production (`NODE_ENV` or `HAI_CORE_ENV=production`) rejects actual ephemeral fallback even when `memory.allowEphemeralFallback: true`; missing backends also fail. Explicit fallback is limited to development or `HAI_E2E=1` / `HAI_E2E_MOCK=1`. History is disabled by default.
575
-
576
- Both providers share `ai.memory.*` (`extract` / `recall` / `injectMemories` / `add` / `update` / `get` / `remove` / `list` / `listPage` / `clear`) with `objectId` isolation and key-value `scope` filters such as `{ topicId, personaId }`. `recall` / `list` / `listPage` / `clear` strictly filter scope; `clear` with `types` / `scope` deletes only jointly matching entries. mem0 `extract` uses the shared extractor for classification/scoring (`types` / `model` / `minImportance` / `systemPrompt`), then writes with `infer:false`, preserving `hai_type` / `hai_importance`. Its `recall` supports `types` and `recencyWeight` decay, matching native behavior. Mem0 updates text and metadata in place, preserving `id` and creation time. SDK queries use `filters.user_id`; writes and whole-subject deletion use `userId`. With no SDK list cursor, `list`, `listPage`, and filtered `clear` support at most 1000 raw subject candidates, including expired records. One extra candidate detects truncation; exceeding the bound returns `MEMORY_LIST_INCOMPLETE` (906), without a fabricated total or partial filtered deletion. Complete candidates are filtered by UTC expiration date, type and scope before pagination. Whole-subject `deleteAll` is independent of this listing limit. Public empty-filter clear is rejected; only trusted administration may explicitly call `admin.clearAll({ confirm: true })`.
908
+ - **`mem0` (data-format adapter)**: Hai performs extraction and Embedding, then uses native HTTP to read and write the Mem0 UUID/payload format in Qdrant, including existing data. It does not run the full upstream engine, telemetry, or a history database. Only Qdrant with complete connection settings is supported. Production (`NODE_ENV` or `HAI_CORE_ENV=production`) rejects ephemeral fallback; development or explicit E2E may set `memory.allowEphemeralFallback: true`. Use `native` for other persistent backends.
577
909
 
578
- Mem0 3.3.1 still calls `QdrantClient.search`. The catalog and AI optional peer pin the tested `@qdrant/js-client-rest` version `1.18.0`; startup checks this public method and rejects incompatible installations. Do not override it with 1.19, which removed that method.
910
+ Both providers share `ai.memory.*` (`extract` / `recall` / `injectMemories` / `add` / `update` / `get` / `remove` / `list` / `listPage` / `clear`) with `objectId` isolation and key-value `scope` filters such as `{ topicId, personaId }`. `recall` / `list` / `listPage` / `clear` strictly filter scope; `clear` with `types` / `scope` deletes only jointly matching entries. mem0 `extract` uses the shared extractor for classification/scoring (`types` / `model` / `minImportance` / `systemPrompt`), then writes directly, preserving `hai_type` / `hai_importance`. Its `recall` supports `types` and `recencyWeight` decay, matching native behavior. Mem0 updates text and metadata in place, preserving `id` and creation time. With bounded candidate scanning, `list`, `listPage`, and filtered `clear` support at most 1000 raw subject candidates, including expired records. One extra candidate detects truncation; exceeding the bound returns `MEMORY_LIST_INCOMPLETE` (906), without a fabricated total or partial filtered deletion. Complete candidates are filtered by UTC expiration date, type and scope before pagination. Whole-subject deletion is independent of this listing limit. Public empty-filter clear is rejected; only trusted administration may explicitly call `admin.clearAll({ confirm: true })`.
579
911
 
580
- The adapter injects a dedicated client through the SDK's public `client` configuration. Mem0 Qdrant upserts and deletes use `wait: true`, awaiting server application before readback or the next deletion batch.
912
+ Mem0 storage and the VecDB Qdrant provider use native HTTP without an extra SDK. Fixed REST requests use `query` and encoded path segments. A 30-second timeout covers the complete response body; responses over 16 MiB fail explicitly. Writes and deletes await the completed `wait=true` receipt. Lists and filtered deletion validate at most 1000 raw candidates per subject, including expired rows; overflow returns `MEMORY_LIST_INCOMPLETE` and performs no partial filtered deletion. Whole-subject deletion is independent of this list limit.
581
913
 
582
- Mem0 with pgvector is rejected in every environment: the SDK privately owns a PostgreSQL connection without a public close API, so the framework cannot manage its lifecycle. Use `memory.provider: native` for pgvector; native support is retained. `disableHistory: true` selects a resource-free history implementation and creates no history SQLite file. The factory awaits backend readiness through one bounded public read before reporting success.
914
+ The Qdrant format backend requires version 1.19 or newer and rejects HTTP redirects. Updates use server-side `update_only` with subject/revision conditions in one atomic write, rejecting deleted or concurrently changed rows. Late updates cannot recreate deleted records. Failed post-write revision verification still requires reconciliation of actual effects.
583
915
 
584
916
  SDK add receipts omit full business fields, so `add` / `extract` read the stored record before returning. Extraction waits for all pending writes. A write or readback failure sets `error.ext.requiresEffectReconciliation=true` and retains known IDs in `memoryIds` (possibly empty if receipts were lost). Reconcile subject records before recovery; blindly repeating add/extract can duplicate committed writes. The framework does not replay automatically.
585
917
 
@@ -596,14 +928,7 @@ const memories = await ai.memory.recall('经济发展', {
596
928
 
597
929
  `ai.config` returns a redacted snapshot without exposing original `apiKey`, `privateKey`, embedded URL credentials, or other secrets.
598
930
 
599
- ### Security boundaries
600
-
601
- - Treat prompts, retrieved documents, and model outputs as untrusted. Do not insert user content into non-overridable system rules.
602
- - Zod validates tool argument shapes, not caller permissions. High-privilege handlers must verify identity, tenant, ownership, and quota, and expose only tools allowed to execute automatically.
603
- - `callRemoteAgent()` is an independent client requiring only `ai.init()`, without Agent Card or local executors. It rejects non-HTTP(S) and embedded URL credentials; applications must still allowlist origins and enforce egress protection against DNS rebinding, private-network redirects, and cloud metadata access.
604
- - Do not log full prompts, tool arguments, A2A headers, temporary model credentials, or remote URLs with queries. Audits should retain redacted summaries only.
605
-
606
- ### Error handling
931
+ ## Error Handling
607
932
 
608
933
  ```ts
609
934
  const result = await ai.llm.chat({ messages })
@@ -631,7 +956,7 @@ Common error ranges:
631
956
  - `hai:ai:900-906`:Memory。
632
957
  - `hai:ai:980-984`:A2A。
633
958
 
634
- ## Development and testing
959
+ ## Development
635
960
 
636
961
  ```bash
637
962
  pnpm --filter @h-ai/ai typecheck