@h-ai/ai 1.0.0-beta.30 → 1.0.0-beta.31
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 +11 -1114
- package/README.ja.md +10 -1113
- package/README.md +11 -1137
- package/dist/{ai-acp-types-DuPV5UGi.d.ts → ai-acp-types-C0ab9EBY.d.ts} +4960 -5220
- package/dist/ai-file-types-BN7l67hR.d.ts +167 -0
- package/dist/ai-file-worker.d.ts +38 -0
- package/dist/ai-file-worker.js +85 -0
- package/dist/ai-file-worker.js.map +1 -0
- package/dist/ai-video-archive-worker.d.ts +32 -0
- package/dist/ai-video-archive-worker.js +102 -0
- package/dist/ai-video-archive-worker.js.map +1 -0
- package/dist/browser.d.ts +5 -2
- package/dist/browser.js +4 -3
- package/dist/chunk-A357G2JF.js +971 -0
- package/dist/chunk-A357G2JF.js.map +1 -0
- package/dist/{chunk-NRDLMUSY.js → chunk-C6T3ONVG.js} +4 -8
- package/dist/chunk-C6T3ONVG.js.map +1 -0
- package/dist/{chunk-LENTVEBE.js → chunk-CYWCDBIC.js} +251 -973
- package/dist/chunk-CYWCDBIC.js.map +1 -0
- package/dist/chunk-OWR55FRO.js +140 -0
- package/dist/chunk-OWR55FRO.js.map +1 -0
- package/dist/{chunk-ILUCWONQ.js → chunk-UVBQCI7A.js} +3 -3
- package/dist/{chunk-ILUCWONQ.js.map → chunk-UVBQCI7A.js.map} +1 -1
- package/dist/client/index.js +2 -2
- package/dist/index.d.ts +6 -3
- package/dist/index.js +1357 -700
- package/dist/index.js.map +1 -1
- package/models/agents/README.md +3 -1
- package/models/agents/deepseek-harness/Dockerfile +2 -0
- package/package.json +10 -10
- package/dist/chunk-LENTVEBE.js.map +0 -1
- package/dist/chunk-NRDLMUSY.js.map +0 -1
- package/tools/.dockerignore +0 -4
- package/tools/README.md +0 -111
- package/tools/archives.py +0 -56
- package/tools/browser/Dockerfile +0 -19
- package/tools/browser/operation.py +0 -50
- package/tools/browser/render.mjs +0 -40
- package/tools/documents/Dockerfile +0 -20
- package/tools/documents/operation.py +0 -80
- package/tools/ocr/Dockerfile +0 -19
- package/tools/ocr/operation.py +0 -18
- package/tools/office/Dockerfile +0 -21
- package/tools/office/office_job.py +0 -65
- package/tools/office/operation.py +0 -43
- package/tools/tests/image-smoke.mjs +0 -83
- package/tools/tests/test_hai_tool.py +0 -82
- package/tools/tool.py +0 -145
package/README.en.md
CHANGED
|
@@ -6,1132 +6,29 @@
|
|
|
6
6
|
|
|
7
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.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
[Tools](../tools/README.en.md) owns shared definitions and execution. `ai.tools.adapt` handles model protocols; `createBuiltinTools` wraps images, audio, document rewriting and an optional full website-video workflow. `createMcpTools/createBroker` reuse MCP. Factories do not call models immediately; the host configures enabled tools, resource permissions and Runner. See the [AI tools guide](../cli/templates/skills/hai-ai/tools.md) (Chinese).
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
## Quick Start
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
Install with pnpm: `pnpm add @h-ai/ai`.
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
import { ai } from '@h-ai/ai'
|
|
15
|
+
[Open the quick-start guide](../../docs/usage/function/ai.en.md#quick-start).
|
|
17
16
|
|
|
18
|
-
|
|
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)
|
|
17
|
+
## Configuration Reference
|
|
26
18
|
|
|
27
|
-
|
|
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
|
-
```
|
|
19
|
+
Generated projects define model names, endpoints, and other model settings in `config/_ai.yml`. At startup, the application reads the file and passes the settings object to `ai.init(config, options)`.
|
|
41
20
|
|
|
42
|
-
|
|
21
|
+
See the [configuration reference](../../docs/usage/configuration/ai.en.md) for configuration entry points, defaults, accepted values and when changes take effect.
|
|
43
22
|
|
|
44
23
|
## Features
|
|
45
24
|
|
|
46
|
-
|
|
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?, 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()` |
|
|
194
|
-
|
|
195
|
-
- `ai.tools`: tool definitions, registries, and batch execution; no initialization required.
|
|
196
|
-
- `ai.stream`: ChatCompletion stream chunk processing; no initialization required.
|
|
197
|
-
- `ai.llm`: non-streaming/streaming chat, model lists, and history.
|
|
198
|
-
- `ai.mcp` / `createMcpServer`: an in-process MCP registry and a standalone MCP server.
|
|
199
|
-
- `ai.embedding`: individual/batch text embeddings.
|
|
200
|
-
- `ai.memory`: memory extraction, storage, recall, and injection.
|
|
201
|
-
- `ai.persona`: AI persona profiles (system prompts + traits) and prompt composition.
|
|
202
|
-
- `ai.retrieval` / `ai.rag`: multi-source vector retrieval and retrieval-augmented answers.
|
|
203
|
-
- `ai.knowledge`: document ingestion, entity-enhanced retrieval, and knowledge answers.
|
|
204
|
-
- `ai.context`: integrated sessions combining LLM + Memory + RAG + compression.
|
|
205
|
-
- `ai.file` / `ai.rerank`: file parsing/OCR and text reranking.
|
|
206
|
-
- `ai.audio`: ASR and TTS with full and streaming calls for OpenAI / MiMo / Qwen / Doubao.
|
|
207
|
-
- `ai.image`: OpenAI GPT Image, Google Gemini Image / Nano Banana, Qwen-Image 2.0/3.0, Seedream 4.x/5.x, and Pollinations free-quota models.
|
|
208
|
-
- `ai.a2a`: Agent-to-Agent request handling and remote calls.
|
|
209
|
-
- `@h-ai/ai/client`: standalone browser Audio WebSocket client.
|
|
210
|
-
|
|
211
|
-
`@h-ai/ai/client` exports only `createAudioClient({ url, getTicket })` and Audio client types. Use typed domain methods from `@h-ai/api-client` for HTTP. Default chat completions are non-streaming; bind application contracts for streaming and A2A. Redundant string-path clients and SSE helpers have been removed. The browser does not export the Node `ai` singleton.
|
|
212
|
-
|
|
213
|
-
- `AIStoreProvider`: storage abstraction. Production requires `stateScope: 'shared'`; the built-in provider needs initialized PostgreSQL/MySQL and a network vecdb. Development/explicit tests may use a temporary store.
|
|
214
|
-
|
|
215
|
-
For the full method list, error codes, and longer examples, see [REFERENCE.md (Chinese)](./REFERENCE.md).
|
|
216
|
-
|
|
217
|
-
### Persistent DB provider (reldb + vecdb)
|
|
218
|
-
|
|
219
|
-
```ts
|
|
220
|
-
import { ai } from '@h-ai/ai'
|
|
221
|
-
import { reldb } from '@h-ai/reldb'
|
|
222
|
-
import { vecdb } from '@h-ai/vecdb'
|
|
223
|
-
|
|
224
|
-
// 开发/测试使用本地后端;生产改为共享 PostgreSQL/MySQL 与网络 vecdb。
|
|
225
|
-
const failures: unknown[] = []
|
|
226
|
-
try {
|
|
227
|
-
const database = await reldb.init({ type: 'sqlite', database: './ai.db' })
|
|
228
|
-
if (!database.success)
|
|
229
|
-
throw new Error(database.error.message)
|
|
230
|
-
const vectors = await vecdb.init({ type: 'lancedb', path: './ai-vec.db' })
|
|
231
|
-
if (!vectors.success)
|
|
232
|
-
throw new Error(vectors.error.message)
|
|
233
|
-
const initialized = await ai.init({
|
|
234
|
-
llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY },
|
|
235
|
-
})
|
|
236
|
-
if (!initialized.success)
|
|
237
|
-
throw new Error(initialized.error.message)
|
|
238
|
-
const result = await ai.llm.chat({
|
|
239
|
-
messages: [
|
|
240
|
-
{ role: 'user', content: 'Hello!' }
|
|
241
|
-
]
|
|
242
|
-
})
|
|
243
|
-
if (!result.success)
|
|
244
|
-
throw new Error(result.error.message)
|
|
245
|
-
const reply = result.data.choices[0]?.message.content ?? ''
|
|
246
|
-
}
|
|
247
|
-
catch (error) {
|
|
248
|
-
failures.push(error)
|
|
249
|
-
}
|
|
250
|
-
finally {
|
|
251
|
-
await ai.close()
|
|
252
|
-
for (const service of [vecdb, reldb]) {
|
|
253
|
-
const closed = await service.close()
|
|
254
|
-
if (!closed.success)
|
|
255
|
-
failures.push(new Error(closed.error.message))
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
if (failures.length)
|
|
259
|
-
throw new AggregateError(failures, 'AI operation or cleanup failed')
|
|
260
|
-
```
|
|
261
|
-
|
|
262
|
-
With the default PostgreSQL Store, nodes can call `ai.init` concurrently on a fresh database or during an upgrade. A transaction-level advisory lock serializes creation of tables, indexes, and write-gate rows. On failure, the transaction rolls back. Retry after correcting the permissions or schema. Startup reuses existing indexes. The vector rebuild runs after commit and can resume on a surviving node.
|
|
263
|
-
|
|
264
|
-
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.
|
|
265
|
-
|
|
266
|
-
### Custom StoreProvider
|
|
267
|
-
|
|
268
|
-
```ts
|
|
269
|
-
import type { AIStoreProvider } from '@h-ai/ai'
|
|
270
|
-
import { ai } from '@h-ai/ai'
|
|
271
|
-
|
|
272
|
-
const storeProvider: AIStoreProvider = createMyStoreProvider()
|
|
273
|
-
|
|
274
|
-
await ai.init(
|
|
275
|
-
{
|
|
276
|
-
llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY }
|
|
277
|
-
},
|
|
278
|
-
{ storeProvider },
|
|
279
|
-
)
|
|
280
|
-
|
|
281
|
-
await ai.close()
|
|
282
|
-
```
|
|
283
|
-
|
|
284
|
-
### API contracts
|
|
285
|
-
|
|
286
|
-
- Public access uses the `ai` service and a few standalone factories such as `createMcpServer`.
|
|
287
|
-
- Lifecycle: `await ai.init(config, options?)` / `await ai.close()`; closure waits for custom `AIStoreProvider.close()`.
|
|
288
|
-
- Domain methods return `HaiResult<T>` or `Promise<HaiResult<T>>`, with failures expressed by `result.success === false` and `result.error.code`. Streaming `AsyncIterable`, client transports, and third-party callbacks can throw during establishment or iteration.
|
|
289
|
-
- `ai.tools` and `ai.stream` are pure-function subsystems usable without initialization.
|
|
290
|
-
- Development/tests without reldb/vecdb use temporary storage; both initialized selects DB storage. Production validates the real database/vector backend capability. Custom providers must accurately declare `stateScope`.
|
|
291
|
-
|
|
292
|
-
Inject stores through the public AIStoreProvider extension. Built-in LLM providers, factory dependencies and Context dependencies are internal. Configure model endpoints through configuration; history queries, AskOptions and ChatRecord remain public.
|
|
293
|
-
|
|
294
|
-
### API overview
|
|
295
|
-
|
|
296
|
-
#### LLM
|
|
297
|
-
|
|
298
|
-
```ts
|
|
299
|
-
const result = await ai.llm.chat({ messages })
|
|
300
|
-
for await (const chunk of ai.llm.chatStream({ messages })) {
|
|
301
|
-
const delta = chunk.choices[0]?.delta?.content
|
|
302
|
-
if (delta) {
|
|
303
|
-
process.stdout.write(delta)
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
// 请求取消:传入 AbortSignal,主持人打断/用户切换时 abort() 立即停止上游生成与计费
|
|
308
|
-
const controller = new AbortController()
|
|
309
|
-
const cancellable = ai.llm.chat({ messages, signal: controller.signal })
|
|
310
|
-
// controller.abort()
|
|
311
|
-
|
|
312
|
-
// 多协议:模型的 protocol 决定底层走 Chat Completions / Responses / Anthropic,公共请求响应形状不变
|
|
313
|
-
// - chat(默认):OpenAI Chat Completions(兼容绝大多数厂商)
|
|
314
|
-
// - responses:OpenAI Responses API(/v1/responses)
|
|
315
|
-
// - anthropic:Anthropic Messages API(Claude 原生协议,环境变量 ANTHROPIC_API_KEY / ANTHROPIC_BASE_URL)
|
|
316
|
-
const claude = await ai.llm.chat({ messages, model: 'claude' }) // 该模型配置 protocol: anthropic
|
|
317
|
-
|
|
318
|
-
// 临时模型:单次请求绕过配置注册模型,直接指定端点与凭据(chat/chatStream/ask/askStream 均支持)
|
|
319
|
-
// 临时客户端按 TTL 缓存(llm.tempModelCacheTtl,默认 10 分钟),与常驻模型客户端隔离
|
|
320
|
-
const temp = await ai.llm.chat({
|
|
321
|
-
messages,
|
|
322
|
-
tempModel: { model: 'claude-3-5-sonnet', protocol: 'anthropic', apiKey: process.env.TEMP_LLM_API_KEY },
|
|
323
|
-
})
|
|
324
|
-
```
|
|
325
|
-
|
|
326
|
-
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.
|
|
327
|
-
|
|
328
|
-
##### Structured output with `ai.llm.generateObject`
|
|
329
|
-
|
|
330
|
-
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.
|
|
331
|
-
|
|
332
|
-
```ts
|
|
333
|
-
import { ai } from '@h-ai/ai'
|
|
334
|
-
import { z } from 'zod'
|
|
335
|
-
|
|
336
|
-
// AI is initialized with a text model that supports generic JSON mode.
|
|
337
|
-
const result = await ai.llm.generateObject({
|
|
338
|
-
schema: z.object({
|
|
339
|
-
title: z.string()
|
|
340
|
-
}), // Require an object with a string title.
|
|
341
|
-
messages: [
|
|
342
|
-
{ role: 'user', content: 'Suggest a title for a release checklist.' }
|
|
343
|
-
], // Input for this request.
|
|
344
|
-
responseFormat: 'json_object', // Request generic JSON while keeping local Zod validation.
|
|
345
|
-
maxRepairs: 1, // Allow one repair after a parse or validation failure.
|
|
346
|
-
})
|
|
347
|
-
if (result.success)
|
|
348
|
-
process.stdout.write(result.data.title) // For example, Release checklist.
|
|
349
|
-
```
|
|
350
|
-
|
|
351
|
-
#### Tool calls
|
|
352
|
-
|
|
353
|
-
```ts
|
|
354
|
-
import { z } from 'zod'
|
|
355
|
-
|
|
356
|
-
const registry = ai.tools.createRegistry({
|
|
357
|
-
// 统一授权在 Zod 校验后、handler 前执行;false/异常均 fail-closed
|
|
358
|
-
authorize: ({ toolName, context }) => canExecuteTool(context.objectId, toolName),
|
|
359
|
-
})
|
|
360
|
-
const registered = registry.register(ai.tools.define({
|
|
361
|
-
name: 'get_weather',
|
|
362
|
-
description: '获取天气',
|
|
363
|
-
parameters: z.object({
|
|
364
|
-
city: z.string()
|
|
365
|
-
}),
|
|
366
|
-
// handler 第二参为执行上下文:可响应取消(打断/超时)、感知截止时间与交互主体
|
|
367
|
-
handler: async ({ city }, { signal }) => {
|
|
368
|
-
const res = await fetch(`https://api.example.com/weather?city=${city}`, { signal })
|
|
369
|
-
return res.json()
|
|
370
|
-
},
|
|
371
|
-
timeoutMs: 10_000, // 本工具默认超时(可被 execute 的 deadline / timeoutMs 覆盖)
|
|
372
|
-
}))
|
|
373
|
-
if (!registered.success)
|
|
374
|
-
return registered
|
|
375
|
-
|
|
376
|
-
// 执行时可传入取消信号 / 超时 / 作用域;取消或超时返回 TOOL_TIMEOUT,且不再等待未响应的 handler
|
|
377
|
-
const result = await registry.execute(toolCall, { signal: controller.signal, objectId: 'user-001', timeoutMs: 30_000 })
|
|
378
|
-
|
|
379
|
-
// 批量调用默认串行,避免副作用工具并发启动;纯读取且确认安全时才显式并行
|
|
380
|
-
const batch = await registry.executeAll(toolCalls)
|
|
381
|
-
|
|
382
|
-
const chat = await ai.llm.chat({
|
|
383
|
-
messages,
|
|
384
|
-
tools: registry.getDefinitions()
|
|
385
|
-
})
|
|
386
|
-
```
|
|
387
|
-
|
|
388
|
-
#### ACP agents, workspaces and sessions
|
|
389
|
-
|
|
390
|
-
`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.
|
|
391
|
-
|
|
392
|
-
Podman does not inherit proxy variables from its remote service. Configure proxies explicitly through agent/workspace `environmentRefs`, using addresses reachable from the container.
|
|
393
|
-
|
|
394
|
-
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.
|
|
395
|
-
|
|
396
|
-
- `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.
|
|
397
|
-
- `workspaces.register/prepare/importFiles` manage directories or persistent volumes, multiple Git repositories and plain files. Every repository requires `mainBranch`; prepare preserves dirty directories.
|
|
398
|
-
- Use workspace `gitEnvironmentRefs` for credentials scoped to remote Git operations and agent `environmentRefs` for agent-only values. The existing workspace `environmentRefs` remains shared.
|
|
399
|
-
- `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.
|
|
400
|
-
- 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.
|
|
401
|
-
- `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.
|
|
402
|
-
|
|
403
|
-
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.
|
|
404
|
-
|
|
405
|
-
For DeepSeek Harness, set `protocol: 'chat'` and `baseUrl: 'https://api.deepseek.com'` to reach the official DeepSeek Chat endpoint. An internal relay can retain the official model ID `deepseek-flash` or `deepseek-v4-pro` to apply the same settings. Harness sends instructions as `system`, uses the DeepSeek output budget field, and preserves `reasoning_content` when sending tool results. [DeepSeek Chat API](https://api-docs.deepseek.com/api/create-chat-completion/)
|
|
406
|
-
|
|
407
|
-
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)
|
|
408
|
-
|
|
409
|
-
ACP runs in the Node service. Ordinary methods return HaiResult and stream failures throw. [ACP guide](../cli/templates/skills/hai-ai/acp.md)
|
|
410
|
-
|
|
411
|
-
Managed Git rejects submodules and Git LFS attributes with ACP_UNSUPPORTED instead of reporting incomplete checkouts as ready.
|
|
412
|
-
|
|
413
|
-
##### Run managed ACP for an authenticated user
|
|
414
|
-
|
|
415
|
-
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.
|
|
416
|
-
|
|
417
|
-
`task` starts a dedicated worker for the session. `user` may reuse a worker when the principal and startup settings match. `auto` checks shared eligibility before asking the application whether to reuse a personal worker, then falls back to a dedicated worker. `shared` is read-only and excludes private context, workspaces, and tools. Set `sharedMode` with the pinned DeepSeek Harness 0.2.1-rc.5 image to opt in. Codex and Goose use personal or dedicated workers. See the [ACP configuration example](../../docs/usage/configuration/ai.md#acp-接入与模型能力).
|
|
418
|
-
|
|
419
|
-
```ts
|
|
420
|
-
import type { RunnerScope } from '@h-ai/runner' // tenantId and userId come from an authenticated application session.
|
|
421
|
-
import { ai } from '@h-ai/ai' // Use the server instance initialized with Runner.
|
|
422
|
-
|
|
423
|
-
async function summarize(identity: RunnerScope, requestId: string) {
|
|
424
|
-
const agent = ai.acp.scoped(identity) // Bind task, session, and approval access to this principal.
|
|
425
|
-
const options = {
|
|
426
|
-
agentId: 'assistant',
|
|
427
|
-
execution: { mode: 'auto' as const }
|
|
428
|
-
} // assistant is a registered agent.
|
|
429
|
-
const plan = await agent.plan(options) // Returns the effective mode, environment, model, and resources without claiming a container.
|
|
430
|
-
if (!plan.success)
|
|
431
|
-
return plan // Stop before submission when the environment or permissions do not match.
|
|
432
|
-
const result = await agent.run({ ...options, prompt: 'List three release checks', idempotencyKey: requestId }) // Returns taskId, output, and effective options.
|
|
433
|
-
if (!result.success)
|
|
434
|
-
return result // Preserve the HaiResult error on submission, execution, or cleanup failure.
|
|
435
|
-
const events = await agent.tasks.events(result.data.taskId, 0, 20) // Read the first 20 durable events, or [] when empty.
|
|
436
|
-
if (!events.success)
|
|
437
|
-
return events
|
|
438
|
-
return { result: result.data, events: events.data } // For example, output.text contains the answer and events are ordered by sequence.
|
|
439
|
-
}
|
|
440
|
-
```
|
|
441
|
-
|
|
442
|
-
```ts
|
|
443
|
-
import type { RunnerScope } from '@h-ai/runner' // The server-authenticated principal.
|
|
444
|
-
import { ai } from '@h-ai/ai' // assistant is registered and supports worker reuse within a user.
|
|
445
|
-
|
|
446
|
-
async function continueWork(identity: RunnerScope) {
|
|
447
|
-
const agent = ai.acp.scoped(identity) // Access is bound to this principal.
|
|
448
|
-
const created = await agent.sessions.create({
|
|
449
|
-
agentId: 'assistant',
|
|
450
|
-
execution: { mode: 'user' }
|
|
451
|
-
}) // Success yields a session handle with an id.
|
|
452
|
-
if (!created.success)
|
|
453
|
-
return created
|
|
454
|
-
const session = created.data // The handle exposes prompt, stream, changeExecution, and close.
|
|
455
|
-
const run = async () => {
|
|
456
|
-
const first = await session.prompt('Record the acceptance criteria') // Returns this turn's taskId, output, and effective options.
|
|
457
|
-
if (!first.success)
|
|
458
|
-
return first
|
|
459
|
-
const switched = await session.changeExecution({ mode: 'task', acceptNewSession: true }) // Keeps the business id and opens a fresh native session.
|
|
460
|
-
if (!switched.success)
|
|
461
|
-
return switched
|
|
462
|
-
return await session.prompt('Give me an independent acceptance checklist') // The answer is in data.output on success.
|
|
463
|
-
}
|
|
464
|
-
return run().finally(async () => {
|
|
465
|
-
const closed = await session.close() // Success returns data: undefined and releases the session or dedicated environment.
|
|
466
|
-
if (!closed.success)
|
|
467
|
-
throw new Error(closed.error.message)
|
|
468
|
-
})
|
|
469
|
-
}
|
|
470
|
-
```
|
|
471
|
-
|
|
472
|
-
`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.
|
|
473
|
-
|
|
474
|
-
`session.submit({ prompt, idempotencyKey, context })` returns a receipt independent of the browser connection. Read `tasks.events(taskId, after, limit)` from the last received sequence after reconnecting. Check `session.status()` before submitting to an idle session. `workspaces.readGitSnapshot` loads authorized source files for dedicated workers. Completed turns can publish a patch. After explicit confirmation, `workspaces.publishSnapshot` pushes a separate `agent/` branch. See the [Agent workspace example](../../apps/agent/README.md).
|
|
475
|
-
|
|
476
|
-
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.
|
|
477
|
-
|
|
478
|
-
#### Configuration and database resource catalogs
|
|
479
|
-
|
|
480
|
-
`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.
|
|
481
|
-
|
|
482
|
-
[Resource catalogs](../cli/templates/skills/hai-ai/resources.md) · [ACP](../cli/templates/skills/hai-ai/acp.md)
|
|
483
|
-
|
|
484
|
-
#### A2A protocol boundaries
|
|
485
|
-
|
|
486
|
-
Remote-call headers override existing fields case-insensitively. Fixed JSON-RPC endpoints reject HTTP redirects, preventing authentication headers from reaching redirect targets.
|
|
487
|
-
|
|
488
|
-
`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.
|
|
489
|
-
|
|
490
|
-
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.
|
|
491
|
-
|
|
492
|
-
Tasks and events use one shared journal, without a separate legacy TaskStore. Push notification configuration and authenticated extended card RPCs return standard SDK unsupported/unconfigured errors without executing tasks. Executor types remain public; internal handler/Store assembly types are outside the public contract.
|
|
493
|
-
|
|
494
|
-
Inbound messages must persist before the executor starts, with shared generation/deadline checks repeated after that wait. Agent messages await logging inside the existing bounded event queue before journal publication. Logging failure produces a failed/interrupted Task rather than a false success; retrying the same message does not rerun business effects. Logs and the journal are separate records: a log is not proof of delivery. Reconcile possible effects using the Task's `requiresEffectReconciliation` marker. Query failures return `A2A_LIST_MESSAGES_FAILED` (984) without raw SQL or connection details.
|
|
495
|
-
|
|
496
|
-
Task and events publish in one CAS, so any node can subscribe. A retry with identical message ID/content reuses the current result; changed content or an older round fails. Cross-node cancellation invokes the real execution owner's executor.cancelTask. Pending cancellation blocks new messages on the same Task so a late callback cannot affect a later execution. Input-required tasks can continue after node restart. Expired leases, absolute deadlines, or an executor returning only working become failed/interrupted with `metadata.haiExecution.requiresEffectReconciliation=true`; late owners cannot write and unknown external effects are never replayed automatically. `a2a.execution` defaults to `leaseMs: 30000`, `pollIntervalMs: 250`, `maxExecutionMs: 300000`. Limits are 1 MiB/message, 8 MiB/journal, 2048 events/round, 256 receipts/Task and 32 reference tasks. Use stable business idempotency keys and reconcile unknown effects. See the [state/deployment matrix (Chinese)](../../.agents/instructions/distributed-state.md) for guarantees and validation boundaries.
|
|
497
|
-
|
|
498
|
-
#### MCP Server
|
|
499
|
-
|
|
500
|
-
`ai.mcp` is an in-process registry; standalone `createMcpServer` uses SDK transports, with no automatic registration between them. `ai.mcp` compiles tool JSON schemas at registration and validates call inputs. Resources must contain exactly one of `text` / `blob`. Prompt arguments and SDK message outputs are validated, with image/audio support. HTTP examples show transport connection only; applications must mount request handling/authentication and close the server on exit.
|
|
501
|
-
|
|
502
|
-
```ts
|
|
503
|
-
import { createMcpServer, StreamableHTTPServerTransport } from '@h-ai/ai'
|
|
504
|
-
import { z } from 'zod'
|
|
505
|
-
|
|
506
|
-
const server = createMcpServer({ name: 'my-server', version: '1.0.0' })
|
|
507
|
-
server.registerTool('search', {
|
|
508
|
-
description: '搜索',
|
|
509
|
-
inputSchema: {
|
|
510
|
-
query: z.string()
|
|
511
|
-
},
|
|
512
|
-
}, async ({ query }) => ({
|
|
513
|
-
content: [
|
|
514
|
-
{ type: 'text', text: `Results for ${query}` }
|
|
515
|
-
],
|
|
516
|
-
}))
|
|
517
|
-
await server.connect(new StreamableHTTPServerTransport({
|
|
518
|
-
sessionIdGenerator: () => globalThis.crypto.randomUUID()
|
|
519
|
-
}))
|
|
520
|
-
```
|
|
521
|
-
|
|
522
|
-
##### Call remote MCP services and isolated tool jobs
|
|
523
|
-
|
|
524
|
-
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).
|
|
525
|
-
|
|
526
|
-
```ts
|
|
527
|
-
import type { MCPServiceAuthorization } from '@h-ai/ai' // Build the principal and the parameter-aware authorization callback from IAM.
|
|
528
|
-
import { ai } from '@h-ai/ai' // The initialized server has registered manual and office services.
|
|
529
|
-
|
|
530
|
-
async function searchManual(access: MCPServiceAuthorization, query: string) {
|
|
531
|
-
const result = await ai.mcp.services.invoke({
|
|
532
|
-
serviceId: 'manual',
|
|
533
|
-
tool: 'search_manual',
|
|
534
|
-
arguments: { query }
|
|
535
|
-
}, access) // Returns a standard MCP tool result after catalog and authorization checks.
|
|
536
|
-
if (!result.success)
|
|
537
|
-
return result // Preserve the denial or upstream error.
|
|
538
|
-
return result.data.content // For example, [{ type: 'text', text: '...' }].
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
async function convertDocument(access: MCPServiceAuthorization, fileId: string) {
|
|
542
|
-
const result = await ai.mcp.services.invoke({
|
|
543
|
-
serviceId: 'office',
|
|
544
|
-
tool: 'office.convert',
|
|
545
|
-
arguments: { fileId }
|
|
546
|
-
}, access) // Submit an offline conversion with the authorized object id.
|
|
547
|
-
if (!result.success)
|
|
548
|
-
return result
|
|
549
|
-
return result.data.structuredContent // Example: { fileId: 'pdf-123', name: 'result.pdf' }. Check authorization again on download.
|
|
550
|
-
}
|
|
551
|
-
```
|
|
552
|
-
|
|
553
|
-
```ts
|
|
554
|
-
import type { MCPServiceAuthorization, MCPServiceBrokerOptions } from '@h-ai/ai' // Supply a deployment URL and an authorize callback that rechecks the principal, task, and arguments.
|
|
555
|
-
import { createServer } from 'node:http' // Hosts the example endpoint.
|
|
556
|
-
import { ai } from '@h-ai/ai' // The initialized server has registered the manual service.
|
|
557
|
-
|
|
558
|
-
function mountTools(options: MCPServiceBrokerOptions) {
|
|
559
|
-
const result = ai.mcp.services.createBroker(options) // On success the broker provides bind, handleRequest, and close.
|
|
560
|
-
if (!result.success)
|
|
561
|
-
throw new Error(result.error.message)
|
|
562
|
-
const broker = result.data // Create a broker on each executor.
|
|
563
|
-
const server = createServer((req, res) => {
|
|
564
|
-
void broker.handleRequest(req, res)
|
|
565
|
-
}) // Handle MCP requests on the bound endpoint.
|
|
566
|
-
return { broker, server } // The host listens on its fixed address, protects the transport, and calls broker.close() and server.close() at shutdown.
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
async function bindManual(broker: ReturnType<typeof mountTools>['broker'], principal: MCPServiceAuthorization['principal'], sessionId: string, signal: AbortSignal) {
|
|
570
|
-
const result = await broker.bind({
|
|
571
|
-
principal,
|
|
572
|
-
taskId: sessionId,
|
|
573
|
-
signal,
|
|
574
|
-
tools: [
|
|
575
|
-
{
|
|
576
|
-
id: 'manual_search',
|
|
577
|
-
serviceId: 'manual',
|
|
578
|
-
tool: 'search_manual', // Expose a model-facing name for the catalogued operation.
|
|
579
|
-
description: 'Search authorized manuals', // Description presented to the model.
|
|
580
|
-
inputSchema: {
|
|
581
|
-
type: 'object',
|
|
582
|
-
properties: {
|
|
583
|
-
query: { type: 'string' }
|
|
584
|
-
},
|
|
585
|
-
required: ['query'],
|
|
586
|
-
additionalProperties: false
|
|
587
|
-
}, // Validate call arguments.
|
|
588
|
-
}
|
|
589
|
-
]
|
|
590
|
-
}) // Success returns { servers, revoke }. servers contains this session's short-lived Bearer credential.
|
|
591
|
-
if (!result.success)
|
|
592
|
-
throw new Error(result.error.message)
|
|
593
|
-
return result.data // Return from ACPPlatformPolicy.bindTools. The credential is revoked when the session ends.
|
|
594
|
-
}
|
|
595
|
-
```
|
|
596
|
-
|
|
597
|
-
#### Memory / RAG / Knowledge
|
|
598
|
-
|
|
599
|
-
The default database Store commits native memory and its pending vector operation in the same transaction. Successful adds, updates, removals, and clears confirm the relational change. The vector index can catch up later. Reads use committed relational records during vector outages. Any node sharing both stores can retry pending operations in batches, including after a restart.
|
|
600
|
-
|
|
601
|
-
Set the native memory vector namespace in `ai.init({ memory: { vectorNamespace: 'orders-prod' } })`. The default is `default`. Independent relational databases get separate collections even on a shared Qdrant server. Nodes for one application use the same database, namespace, and vector backend. On upgrade, the background worker rebuilds the index from stored relational embeddings. Existing memories remain searchable and the legacy shared collection stays intact. Cleanup checks only the dedicated collection and saves its cursor after each page, so it catches late writes and resumes after a restart. [Upgrade procedure](../../docs/usage/configuration/ai.md#从旧共享集合升级)
|
|
602
|
-
|
|
603
|
-
`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. Relational transaction failures return a failed HaiResult. Automatic vector retries require no resubmission from callers.
|
|
604
|
-
|
|
605
|
-
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.
|
|
606
|
-
|
|
607
|
-
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.
|
|
608
|
-
|
|
609
|
-
The DB Store propagates collection and vector failures. LanceDB uses persistent primary-key atomic merge. Qdrant writes/deletes wait until applied and counts are exact. Multiple nodes must share relational storage and a server vector backend. Custom KnowledgeStore implementations must provide the same publication and compensation contract.
|
|
610
|
-
|
|
611
|
-
With LanceDB, collection dimensions and metrics persist in the Arrow schema; connection metrics only affect new collections. Reuse the same persistent directory after restart and rebuild collections when embedding dimensions change. Local paths on separate nodes do not share data; distributed Knowledge should use a server vector backend.
|
|
612
|
-
|
|
613
|
-
Knowledge `retrieve/ask` and the default DB Store forward `filter` to the vector provider and propagate validation/query failures. Knowledge returns `KNOWLEDGE_RETRIEVE_FAILED` (`RAG_FAILED` from ask), without disguising failure as empty results. LanceDB supports AND equality on literal top-level keys with string, finite number, boolean, or null values, such as `{ tenant: 'acme', active: true }`. Null never matches missing keys; objects, arrays, and undefined are unsupported. Filtering precedes vector topK. Check null/complex-value semantics separately for other backends. LanceDB metadata now uses native JSON fields and retains nested JSON; rebuild legacy string-metadata collections before writing or filtering.
|
|
614
|
-
|
|
615
|
-
```ts
|
|
616
|
-
const enriched = await ai.memory.injectMemories(messages, { objectId: 'user-001', topK: 5 })
|
|
617
|
-
if (!enriched.success) {
|
|
618
|
-
return enriched
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
// 多租户推荐入口:scoped() 绑定主体与作用域,所有操作自动携带 objectId / scope(含归属校验),杜绝「忘记传 objectId」越权
|
|
622
|
-
const memory = ai.memory.scoped({
|
|
623
|
-
objectId: 'user-001',
|
|
624
|
-
scope: { topicId: 't-1', personaId: 'p-1' }
|
|
625
|
-
})
|
|
626
|
-
await memory.add({ content: '用户偏好中文', type: 'preference' })
|
|
627
|
-
const recalled = await memory.recall('语言偏好')
|
|
628
|
-
|
|
629
|
-
// clear 拒绝空过滤(防误清全局);全局清空只能显式走管理接口
|
|
630
|
-
await memory.clear({
|
|
631
|
-
types: ['event']
|
|
632
|
-
}) // 仅清该作用域内的 event
|
|
633
|
-
await ai.memory.admin.clearAll({ confirm: true }) // 危险:清空整个记忆后端,需显式确认
|
|
634
|
-
|
|
635
|
-
const rag = await ai.rag.query('核心架构是什么?', {
|
|
636
|
-
sources: ['docs'],
|
|
637
|
-
topK: 5
|
|
638
|
-
})
|
|
639
|
-
|
|
640
|
-
const setup = await ai.knowledge.setup()
|
|
641
|
-
if (setup.success) {
|
|
642
|
-
const ingested = await ai.knowledge.ingest({ documentId: 'doc-001', content: markdownText, title: '产品手册' })
|
|
643
|
-
if (!ingested.success)
|
|
644
|
-
return ingested
|
|
645
|
-
if (ingested.data.cleanupPending) {
|
|
646
|
-
const repaired = await ai.knowledge.repair({ offset: 0, limit: 100 })
|
|
647
|
-
if (!repaired.success)
|
|
648
|
-
return repaired
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
```
|
|
652
|
-
|
|
653
|
-
Knowledge chunks use datapipe units and hard bounds: words for word mode, Unicode code points otherwise, retaining separators from cleaned text. AI defaults remain markdown/maxSize=1500/overlap=200; a smaller maxSize override must also keep inherited overlap below it. Invalid chunk configuration or expressions return KNOWLEDGE_INGEST_FAILED before embedding and revision publication, without an unbounded whole-document fallback.
|
|
654
|
-
|
|
655
|
-
#### Audio
|
|
656
|
-
|
|
657
|
-
Register audio models in `ai.init()` and map the default transcription/synthesis models first. Credentials fall back to platform environment variables. Enable `inheritLlmApiKey` explicitly only when LLM and audio models are confirmed to share credentials:
|
|
658
|
-
|
|
659
|
-
`provider` identifies the protocol, not deployment location. `openai` / `mimo` / `qwen` / `doubao` are cloud platforms; `whisper` (ASR) / `indextts` (TTS) are self-hostable protocols with no canonical endpoint and require explicit `baseUrl`. One protocol can switch among cloud, intranet, and local endpoints without changing business code. Missing cloud credentials return `CONFIGURATION_ERROR`. Self-hosted services may omit credentials; configured `apiKey` is sent as `Authorization: Bearer`.
|
|
660
|
-
|
|
661
|
-
```ts
|
|
662
|
-
await ai.init({
|
|
663
|
-
llm: {
|
|
664
|
-
apiKey: process.env.HAI_AI_LLM_APIKEY,
|
|
665
|
-
},
|
|
666
|
-
audio: {
|
|
667
|
-
inheritLlmApiKey: true,
|
|
668
|
-
models: [
|
|
669
|
-
{
|
|
670
|
-
id: 'asr',
|
|
671
|
-
provider: 'qwen',
|
|
672
|
-
model: 'qwen3-asr-flash-realtime',
|
|
673
|
-
operations: ['transcribe']
|
|
674
|
-
},
|
|
675
|
-
{
|
|
676
|
-
id: 'tts',
|
|
677
|
-
provider: 'qwen',
|
|
678
|
-
model: 'qwen3-tts-flash-realtime',
|
|
679
|
-
operations: ['synthesize']
|
|
680
|
-
},
|
|
681
|
-
// 自托管:whisper / indextts 必须显式配置 baseUrl
|
|
682
|
-
{
|
|
683
|
-
id: 'whisper',
|
|
684
|
-
provider: 'whisper',
|
|
685
|
-
model: 'faster-whisper-large-v3',
|
|
686
|
-
operations: ['transcribe'],
|
|
687
|
-
baseUrl: 'http://127.0.0.1:8101/v1'
|
|
688
|
-
},
|
|
689
|
-
{
|
|
690
|
-
id: 'indextts',
|
|
691
|
-
provider: 'indextts',
|
|
692
|
-
model: 'indextts-2.5',
|
|
693
|
-
operations: ['synthesize'],
|
|
694
|
-
baseUrl: 'http://127.0.0.1:8102/v1'
|
|
695
|
-
},
|
|
696
|
-
],
|
|
697
|
-
transcribeModel: 'asr',
|
|
698
|
-
synthesizeModel: 'tts',
|
|
699
|
-
},
|
|
700
|
-
})
|
|
701
|
-
|
|
702
|
-
// 完整识别(可选热词、时间戳粒度与 VAD;strictCapabilities 要求模型真实支持所请求能力)
|
|
703
|
-
const result = await ai.audio.transcribe({
|
|
704
|
-
audio: { data: wavBytes, format: 'wav' },
|
|
705
|
-
language: 'zh',
|
|
706
|
-
contextHints: ['专有名词'],
|
|
707
|
-
timestampGranularities: ['segment', 'word'],
|
|
708
|
-
vad: true,
|
|
709
|
-
model: 'whisper',
|
|
710
|
-
})
|
|
711
|
-
if (result.success) {
|
|
712
|
-
const text = result.data.text
|
|
713
|
-
const language = result.data.language // 实际检测语言
|
|
714
|
-
const words = result.data.segments?.[0]?.words // 词级时间轴(毫秒整数)
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
// 说话人 / 风格参考合成(IndexTTS):speakerReference 表达“谁在说”,styleReference 表达“怎么说”
|
|
718
|
-
const cloned = await ai.audio.synthesize({
|
|
719
|
-
text: '我们下午三点出发。',
|
|
720
|
-
language: 'zh',
|
|
721
|
-
model: 'indextts',
|
|
722
|
-
speakerReference: { audio: speakerWav, language: 'ja' },
|
|
723
|
-
styleReference: { audio: styleWav },
|
|
724
|
-
styleStrength: 0.8,
|
|
725
|
-
targetDurationMs: 3280, // 目标时长(与 speed 互斥),metadata.durationMatched 反馈是否达标
|
|
726
|
-
durationToleranceMs: 120,
|
|
727
|
-
})
|
|
728
|
-
|
|
729
|
-
// 实时识别(持续音频输入 → 领域事件流:speech_started / transcript / speech_stopped)
|
|
730
|
-
for await (const event of ai.audio.transcribeStream({
|
|
731
|
-
audio: { chunks: microphoneChunks, format: 'pcm16', sampleRate: 16000 },
|
|
732
|
-
})) {
|
|
733
|
-
if (event.type === 'speech_started')
|
|
734
|
-
onSpeechStart() // 支持服务端 VAD 的平台会在检测到说话时立即产出,可据此取消上游生成
|
|
735
|
-
else if (event.type === 'transcript')
|
|
736
|
-
updateTranscript(event.text, event.final)
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
// 流式合成:调用方为文本段分配稳定 ID,事件可精确关联文本与音频;signal 可随时打断
|
|
740
|
-
const controller = new AbortController()
|
|
741
|
-
for await (const event of ai.audio.synthesizeStream({
|
|
742
|
-
text: { id: 'answer-1', text: '欢迎参加访谈。' },
|
|
743
|
-
voice: 'Cherry',
|
|
744
|
-
instruction: '用轻快的语气',
|
|
745
|
-
signal: controller.signal,
|
|
746
|
-
})) {
|
|
747
|
-
if (event.type === 'segment_started')
|
|
748
|
-
prepareDecoder(event.format, event.sampleRate, event.channels) // 真实输出格式来自服务端解析后的 Provider 输出
|
|
749
|
-
else if (event.type === 'audio')
|
|
750
|
-
await player.write(event.data)
|
|
751
|
-
else if (event.type === 'segment_done')
|
|
752
|
-
markSegmentReadyToCommit(event.segmentId)
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
// 实时会话启动前按操作校验模型能力
|
|
756
|
-
const caps = ai.audio.getCapabilities({ operation: 'synthesize', model: 'tts' })
|
|
757
|
-
if (caps.success && caps.data.synthesize?.streamingAudioOutput) { /* 可实时 TTS */ }
|
|
758
|
-
```
|
|
759
|
-
|
|
760
|
-
`ai.audio.synthesize` returns normalized `AudioContent` bytes. To return browser-playable Base64 over an API, use `serializePlayableAudio(result.data)`, which wraps `pcm16` in a WAV container and passes WAV/MP3 through:
|
|
761
|
-
|
|
762
|
-
```ts
|
|
763
|
-
import { serializePlayableAudio } from '@h-ai/ai'
|
|
764
|
-
|
|
765
|
-
const synthesized = await ai.audio.synthesize({ text: '欢迎参加访谈。', voice: 'Cherry' })
|
|
766
|
-
if (!synthesized.success)
|
|
767
|
-
return synthesized
|
|
768
|
-
|
|
769
|
-
const playable = serializePlayableAudio(synthesized.data)
|
|
770
|
-
if (!playable.success)
|
|
771
|
-
return playable
|
|
772
|
-
|
|
773
|
-
return playable.data
|
|
774
|
-
```
|
|
775
|
-
|
|
776
|
-
`OptionalSecretSchema` covers optional LLM, Audio, and Image secrets: YAML `null`, empty strings, and whitespace-only strings normalize to `undefined`. Audio key precedence is model `apiKey` → inherited LLM `apiKey` when enabled → platform environment variables. `inheritLlmApiKey` is off by default to avoid using keys across vendors.
|
|
777
|
-
|
|
778
|
-
> `synthesizeStream` emits `segment_started → audio* → segment_done` strictly. `segment_started` carries **actual output audio parameters** (`format` / `sampleRate` / `channels`) resolved by the server/provider. Players must decode from these rather than guess from requested parameters, and add segment text to `spokenText` only after its audio has actually finished playing. Applications manage playback state.
|
|
779
|
-
|
|
780
|
-
Cancellation, timeout, and connection problems become domain errors: `AbortSignal` → `AUDIO_CANCELLED`, timeout → `AUDIO_TIMEOUT`, connection failure or abnormal disconnect before `end` → `AUDIO_CONNECTION_FAILED`. `audio.maxStreamDurationMs` limits real-time connections (default five minutes).
|
|
781
|
-
|
|
782
|
-
Browsers/mobile clients use the unified audio WebSocket exposed by `@h-ai/serv`. `@h-ai/ai/client` offers the same `audio.*` API as Node, hiding transport details. Browser clients distinguish completion, cancellation (`AUDIO_CANCELLED`), and abnormal disconnect (`AUDIO_CONNECTION_FAILED`); cancellation or disconnect before `end` throws the domain code. `synthesize` never treats incomplete audio as success.
|
|
783
|
-
|
|
784
|
-
IndexTTS pairs the same Undici version's fetch, Agent, and multipart types on Node. Model `timeout` covers response-header and body waits; user cancellation returns `AUDIO_CANCELLED`, and deadlines return `AUDIO_TIMEOUT`. Dedicated connections close after success, failure, or cancellation. Segmented streaming fallback retains errors during iteration.
|
|
785
|
-
|
|
786
|
-
> For self-hosted CPU/GPU model services (faster-whisper / IndexTTS / Qwen3-4B), weight downloads, and offline bundles, see [models/ (Chinese)](./models/README.md). Images and weights prefer ModelScope, with automatic HuggingFace mirror fallback.
|
|
787
|
-
|
|
788
|
-
#### Image generation
|
|
789
|
-
|
|
790
|
-
After model registration in `ai.init()`, callers receive normalized image bytes without vendor-specific Base64, inline data, or temporary URLs:
|
|
791
|
-
|
|
792
|
-
```ts
|
|
793
|
-
await ai.init({
|
|
794
|
-
image: {
|
|
795
|
-
models: [
|
|
796
|
-
{ id: 'image', provider: 'openai', model: 'gpt-image-2' },
|
|
797
|
-
{ id: 'free', provider: 'pollinations', model: 'zimage' },
|
|
798
|
-
],
|
|
799
|
-
generateModel: 'image',
|
|
800
|
-
},
|
|
801
|
-
})
|
|
802
|
-
|
|
803
|
-
const result = await ai.image.generate({
|
|
804
|
-
prompt: '一个正在构建开源框架的友好机器人',
|
|
805
|
-
size: { width: 1024, height: 1024 },
|
|
806
|
-
referenceImages: [
|
|
807
|
-
{ data: await readImage('character.png'), mimeType: 'image/png' },
|
|
808
|
-
],
|
|
809
|
-
})
|
|
810
|
-
if (result.success) {
|
|
811
|
-
const { data, mimeType } = result.data.images[0]!
|
|
812
|
-
await saveImage(data, mimeType)
|
|
813
|
-
}
|
|
814
|
-
```
|
|
815
|
-
|
|
816
|
-
`referenceImages` is optional. Public APIs accept only image bytes and MIME; providers convert multipart, `inlineData`, and Data URLs. Set credentials on model entries or with `HAI_AI_IMAGE_<PROVIDER>_APIKEY` / vendor environment variables. Qwen and Seedream temporary URLs are downloaded immediately inside providers and never exposed publicly. See [REFERENCE.md (Chinese)](./REFERENCE.md#image) for model details and API differences.
|
|
817
|
-
|
|
818
|
-
Downloads require public HTTPS on default port 443 without URL credentials. Socket DNS lookup validates every returned address and connects using those same results. Private, loopback, link-local, mapped/translated, and reserved IPv4/IPv6 addresses are blocked. Each of at most three redirects is checked again. Downloads use isolated connections without vendor authentication or application cookies. `baseUrl` is trusted operator configuration; vendor API calls reject redirects.
|
|
819
|
-
|
|
820
|
-
`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.
|
|
821
|
-
|
|
822
|
-
#### File parsing
|
|
823
|
-
|
|
824
|
-
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.
|
|
825
|
-
|
|
826
|
-
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.
|
|
827
|
-
|
|
828
|
-
#### Context manager
|
|
829
|
-
|
|
830
|
-
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.
|
|
831
|
-
|
|
832
|
-
```ts
|
|
833
|
-
const manager = ai.context.createManager({
|
|
834
|
-
scope: { objectId: 'user-001', sessionId: 'sess-001' },
|
|
835
|
-
compress: { auto: true, strategy: 'hybrid', maxTokens: 8000 },
|
|
836
|
-
memory: { enable: true, enableExtract: true },
|
|
837
|
-
concurrency: 'reject', // 单活动生成(默认):活动生成期间的新 chat 返回 CONTEXT_BUSY;'queue' 则排队
|
|
838
|
-
})
|
|
839
|
-
if (manager.success) {
|
|
840
|
-
const reply = await manager.data.chat('你好')
|
|
841
|
-
const saved = await manager.data.save()
|
|
842
|
-
if (!saved.success)
|
|
843
|
-
return saved
|
|
844
|
-
// reset 生命周期完整:终止活动生成、清空消息/摘要/轮次,默认保留系统提示词
|
|
845
|
-
await manager.data.reset() // 可传 { preserveSystemPrompt, cancelActiveTurn, waitForMemoryTasks }
|
|
846
|
-
}
|
|
847
|
-
```
|
|
848
|
-
|
|
849
|
-
A manager permits **one active generation** by default, preventing out-of-order messages when the next user message is written before the previous AI run exits. `reset()` is asynchronous: it stops active generation, releases concurrency barriers, clears turns, and rewrites Persona/System Prompt by default.
|
|
850
|
-
|
|
851
|
-
##### Actual conversation state (Conversation Commit Layer)
|
|
852
|
-
|
|
853
|
-
By default (`turnCommit: 'auto'`), `chat` / `chatStream` store the **full generated text** in context. In a generation → TTS → playback flow, however, speech can be interrupted halfway. The next turn's shared conversation state should contain **what was actually played**, rather than everything the model intended to say.
|
|
854
|
-
|
|
855
|
-
With `turnCommit: 'manual'`, results are not stored automatically. A `turnId` is returned so the caller can explicitly commit the text reflecting what actually happened.
|
|
856
|
-
|
|
857
|
-
`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:
|
|
858
|
-
|
|
859
|
-
```ts
|
|
860
|
-
const created = ai.context.createManager({
|
|
861
|
-
scope: { objectId: 'user-001', sessionId: 'sess-001' },
|
|
862
|
-
turnCommit: 'manual'
|
|
863
|
-
})
|
|
864
|
-
if (!created.success)
|
|
865
|
-
return created
|
|
866
|
-
const m = created.data
|
|
867
|
-
const controller = new AbortController()
|
|
868
|
-
|
|
869
|
-
for await (const ev of m.chatStream('请展开讲讲', { signal: controller.signal })) {
|
|
870
|
-
if (ev.type === 'turn_started') {
|
|
871
|
-
await m.markTurnSpeaking(ev.turnId) // 可选:标记进入播放
|
|
872
|
-
}
|
|
873
|
-
else if (ev.type === 'delta') {
|
|
874
|
-
feedTts(ev.text) // 边生成边合成播放
|
|
875
|
-
}
|
|
876
|
-
else if (ev.type === 'done') {
|
|
877
|
-
await m.commitTurn(ev.turnId) // 完整提交
|
|
878
|
-
}
|
|
879
|
-
else if (ev.type === 'cancelled') {
|
|
880
|
-
// 生成被 controller.abort() 取消:轮次保留,只提交实际播放出去的部分
|
|
881
|
-
await m.interruptTurn(ev.turnId, { text: actuallySpokenText })
|
|
882
|
-
}
|
|
883
|
-
}
|
|
884
|
-
|
|
885
|
-
// 观测每一轮的 generated / committed / status
|
|
886
|
-
const turns = m.getTurns()
|
|
887
|
-
```
|
|
888
|
-
|
|
889
|
-
- `commitTurn(turnId, { text? })`: commit actual text (defaults to full generated text), setting state to `completed`.
|
|
890
|
-
- `interruptTurn(turnId, { text? })`: store only what was actually expressed (omission means nothing was expressed, so nothing is stored), setting state to `interrupted`.
|
|
891
|
-
- Only `committed` content enters context and memory extraction. Uncommitted/discarded text does not affect future turns.
|
|
892
|
-
- If `interruptTurn` interrupts before stream completion (for example a host interrupts just as the model finishes), `chatStream` **does not emit `done`**, preventing accidental post-completion commits.
|
|
893
|
-
|
|
894
|
-
##### Session consolidation (Memory lifecycle)
|
|
895
|
-
|
|
896
|
-
During a session, each turn extracts **short-term session memory** with `scope: { sessionId }`. At session end, `consolidate()`
|
|
897
|
-
turns short-term memory + summaries into **cross-session long-term memory**, completing `Session Memory → Summary → Long-term Memory`:
|
|
898
|
-
|
|
899
|
-
```ts
|
|
900
|
-
// 会话结束时固化:整合摘要 → 提取长期记忆(写入不含 sessionId 的持久作用域)
|
|
901
|
-
const created = ai.context.createManager({
|
|
902
|
-
scope: { objectId: 'user-001', sessionId: 'sess-001' }
|
|
903
|
-
})
|
|
904
|
-
if (!created.success)
|
|
905
|
-
return created
|
|
906
|
-
const result = await created.data.consolidate({
|
|
907
|
-
scope: { userId: 'user-001', personaId: 'xiaoq' }
|
|
908
|
-
})
|
|
909
|
-
if (result.success) {
|
|
910
|
-
// result.data.summary —— 本次会话整合摘要
|
|
911
|
-
// result.data.memories —— 固化到长期记忆的条目
|
|
912
|
-
}
|
|
913
|
-
```
|
|
914
|
-
|
|
915
|
-
#### Persona (AI character profiles)
|
|
916
|
-
|
|
917
|
-
Memory uses `objectId` / `scope` to identify whose memories they are; Persona defines who the AI is through
|
|
918
|
-
stable system prompts and character traits, linked to long-term memory through `scope: { personaId }`:
|
|
919
|
-
|
|
920
|
-
```ts
|
|
921
|
-
await ai.persona.save({
|
|
922
|
-
id: 'xiaoq',
|
|
923
|
-
name: '小Q',
|
|
924
|
-
systemPrompt: '你是一位经济学家,善于从长期视角分析问题。',
|
|
925
|
-
traits: ['数据驱动', '偏好引用真实案例'],
|
|
926
|
-
})
|
|
927
|
-
|
|
928
|
-
// 组合出可直接喂给 ContextManager 的系统提示词(systemPrompt + traits)
|
|
929
|
-
const composed = await ai.persona.compose('xiaoq')
|
|
930
|
-
if (!composed.success)
|
|
931
|
-
return composed
|
|
932
|
-
const manager = ai.context.createManager({
|
|
933
|
-
scope: { objectId: 'user-001', sessionId: 'persona-session' },
|
|
934
|
-
systemPrompt: composed.data,
|
|
935
|
-
memory: {
|
|
936
|
-
enable: true,
|
|
937
|
-
enableExtract: true,
|
|
938
|
-
scope: { personaId: 'xiaoq' }
|
|
939
|
-
},
|
|
940
|
-
})
|
|
941
|
-
```
|
|
942
|
-
|
|
943
|
-
`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.
|
|
944
|
-
|
|
945
|
-
### Security boundaries
|
|
946
|
-
|
|
947
|
-
- Treat prompts, retrieved documents, and model outputs as untrusted. Do not insert user content into non-overridable system rules.
|
|
948
|
-
- 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.
|
|
949
|
-
- `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.
|
|
950
|
-
- Do not log full prompts, tool arguments, A2A headers, temporary model credentials, or remote URLs with queries. Audits should retain redacted summaries only.
|
|
951
|
-
|
|
952
|
-
### Using returned handles
|
|
953
|
-
|
|
954
|
-
`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.
|
|
955
|
-
|
|
956
|
-
| Entry | Use case | Input | Output | Call fragment |
|
|
957
|
-
| -------------------------- | ------------------------ | ---------------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------- |
|
|
958
|
-
| `registry.register` | Register one tool | `Tool` | `HaiResult<void>; duplicate rejected` | `registry.register(tool)` |
|
|
959
|
-
| `registry.registerMany` | Register tools | `Tool[]` | `HaiResult<void>` | `registry.registerMany(tools)` |
|
|
960
|
-
| `registry.replace` | Explicitly replace tool | `Tool with existing name` | `HaiResult<void>` | `registry.replace(tool)` |
|
|
961
|
-
| `registry.unregister` | Unregister tool | `tool name` | `boolean` | `registry.unregister("search")` |
|
|
962
|
-
| `registry.get` | Get tool | `tool name` | `Tool or undefined` | `registry.get("search")` |
|
|
963
|
-
| `registry.has` | Check tool | `tool name` | `boolean` | `registry.has("search")` |
|
|
964
|
-
| `registry.getNames` | Tool names | `none` | `string[]` | `registry.getNames()` |
|
|
965
|
-
| `registry.getDefinitions` | Model-facing definitions | `none` | `ToolDefinition[]` | `registry.getDefinitions()` |
|
|
966
|
-
| `registry.execute` | Execute authorized tool | `ToolCall, ToolExecutionOptions?` | `Promise<HaiResult<ToolMessage>>` | `registry.execute(toolCall, { objectId: "u1" })` |
|
|
967
|
-
| `registry.executeAll` | Execute calls | `ToolCall[], { parallel?, ...executionOptions }` | `Promise<HaiResult<ToolMessage[]>>` | `registry.executeAll(toolCalls)` |
|
|
968
|
-
| `registry.clear` | Clear local tools | `none` | `void` | `registry.clear()` |
|
|
969
|
-
| `registry.size` | Tool count | `none` | `number` | `registry.size` |
|
|
970
|
-
| `manager.addMessage` | Add message | `ChatMessage` | `Promise<HaiResult<void>>` | `manager.addMessage({ role: "user", content: "你好" })` |
|
|
971
|
-
| `manager.getMessages` | Read message snapshot | `none` | `HaiResult<ChatMessage[]>` | `manager.getMessages()` |
|
|
972
|
-
| `manager.reload` | Reload shared state | `none` | `Promise<HaiResult<void>>` | `manager.reload()` |
|
|
973
|
-
| `manager.getTokenUsage` | Observe budget | `none` | `HaiResult<{ current, budget }>` | `manager.getTokenUsage()` |
|
|
974
|
-
| `manager.getSummaries` | Read summaries | `none` | `HaiResult<SummaryResult[]>` | `manager.getSummaries()` |
|
|
975
|
-
| `manager.save` | Save context | `none` | `Promise<HaiResult<void>>` | `manager.save()` |
|
|
976
|
-
| `manager.flush` | Flush background memory | `none` | `Promise<HaiResult<void>>` | `manager.flush()` |
|
|
977
|
-
| `manager.reset` | Reset conversation | `ContextResetOptions?` | `Promise<HaiResult<void>>` | `manager.reset({ preserveSystemPrompt: true })` |
|
|
978
|
-
| `manager.getTurns` | Read actual turns | `none` | `HaiResult<ConversationTurn[]>` | `manager.getTurns()` |
|
|
979
|
-
| `manager.markTurnSpeaking` | Mark speaking | `turnId` | `Promise<HaiResult<void>>` | `manager.markTurnSpeaking(turnId)` |
|
|
980
|
-
| `manager.commitTurn` | Commit actual content | `turnId, { text? }` | `Promise<HaiResult<void>>` | `manager.commitTurn(turnId, { text: spokenText })` |
|
|
981
|
-
| `manager.interruptTurn` | Commit interruption | `turnId, { text? }` | `Promise<HaiResult<void>>` | `manager.interruptTurn(turnId, { text: spokenText })` |
|
|
982
|
-
| `manager.consolidate` | Consolidate memory | `ConsolidateOptions?` | `Promise<HaiResult<{ summary, memories }>>` | `manager.consolidate({ scope: { personaId: "tutor" } })` |
|
|
983
|
-
| `manager.chat` | Stateful answer | `message: string, ContextChatOptions?` | `Promise<HaiResult<ContextChatResult>>` | `manager.chat("请继续")` |
|
|
984
|
-
| `manager.chatStream` | Stateful stream | `message: string, ContextChatOptions?` | `AsyncIterable<ContextStreamEvent>` | `manager.chatStream("请继续")` |
|
|
985
|
-
| `session.info` | Read managed session | `none` | `Promise<HaiResult<ACPSessionInfo>>` | `session.info()` |
|
|
986
|
-
| `session.prompt` | Execute one turn | `ContentBlock[], AbortSignal?` | `Promise<HaiResult<{ text, stopReason, events }>>` | `session.prompt([{ type: "text", text: "检查工程" }])` |
|
|
987
|
-
| `session.promptStructured` | Validate JSON output | `ContentBlock[], Zod schema, AbortSignal?` | `Promise<HaiResult<schema-inferred T>>` | `session.promptStructured(content, OutputSchema)` |
|
|
988
|
-
| `session.stream` | Observe native events | `ContentBlock[], AbortSignal?` | `AsyncIterable<SessionNotification>; failure throws` | `session.stream([{ type: "text", text: "检查工程" }])` |
|
|
989
|
-
| `session.cancel` | Cancel turn | `none` | `Promise<HaiResult<void>>` | `session.cancel()` |
|
|
990
|
-
| `session.setMode` | Select advertised mode | `native mode ID` | `Promise<HaiResult<native mode response>>` | `session.setMode("code")` |
|
|
991
|
-
| `session.setConfigOption` | Set native option | `native option key and allowed value` | `Promise<HaiResult<native config response>>` | `session.setConfigOption("model", "coding")` |
|
|
992
|
-
| `session.updateMain` | Fast-forward main | `none; execution and preview must be stopped` | `Promise<HaiResult<ACPGitReport[]>>; partial failure reports in cause` | `session.updateMain()` |
|
|
993
|
-
| `session.publish` | Commit and push | `{ mode, message, author }; managed isolated session only` | `Promise<HaiResult<ACPGitReport[]>>` | `session.publish(publishOptions)` |
|
|
994
|
-
| `session.close` | Stop and retain state | `none` | `Promise<HaiResult<void>>` | `session.close()` |
|
|
995
|
-
| `connection.authenticate` | Native authentication | `advertised authentication method ID` | `Promise<HaiResult<native auth response>>` | `connection.authenticate("api-key")` |
|
|
996
|
-
| `connection.createSession` | Create native session | `absolute remote cwd, McpServer[]?` | `Promise<HaiResult<{ id, prompt, cancel }>>` | `connection.createSession("/workspace/project", [])` |
|
|
997
|
-
| `connection.listSessions` | Native sessions | `cursor?` | `Promise<HaiResult<native paginated response>>` | `connection.listSessions()` |
|
|
998
|
-
| `connection.deleteSession` | Delete native session | `native session ID` | `Promise<HaiResult<native delete response>>` | `connection.deleteSession(nativeId)` |
|
|
999
|
-
| `connection.close` | Close native connection | `none` | `Promise<HaiResult<void>>` | `connection.close()` |
|
|
1000
|
-
|
|
1001
|
-
## Configuration
|
|
1002
|
-
|
|
1003
|
-
### Choose configuration by task
|
|
1004
|
-
|
|
1005
|
-
| Configuration entry | Scenario | Input | Effect | Example |
|
|
1006
|
-
| ------------------- | -------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
1007
|
-
| `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 } }` |
|
|
1008
|
-
| `embedding` | Embedding vectors | model?, dimensions?, batchSize? | consistent vector dimensions for the target collection | `{ embedding: { dimensions: 1536, batchSize: 100 } }` |
|
|
1009
|
-
| `mcp` | External tool servers | servers with transport/endpoints or commands | registered server definitions; application authorizes tool execution | `{ mcp: { servers: [] } }` |
|
|
1010
|
-
| `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 }] } }` |
|
|
1011
|
-
| `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 } } }` |
|
|
1012
|
-
| `memory` | Subject memory backend | provider, quotas, recencyDecay, defaultTopK, candidateMultiplier | native or Mem0-format behavior with explicit persistence limits | `{ memory: { provider: "native", defaultTopK: 10 } }` |
|
|
1013
|
-
| `token` | Token estimate | tokenRatio > 0; default 0.25 | local token budget estimates; not provider billing usage | `{ token: { tokenRatio: 0.25 } }` |
|
|
1014
|
-
| `summary` | Summary policy | systemPrompt? | prompt used by summary generation; model from llm.scenarios | `{ summary: { systemPrompt: "保留已确认决策和待办" } }` |
|
|
1015
|
-
| `compress` | Context compression | defaultStrategy, defaultMaxTokens, preserveLastN | compression defaults; 0 budget derives from model limit | `{ compress: { defaultStrategy: "hybrid", defaultMaxTokens: 4000, preserveLastN: 4 } }` |
|
|
1016
|
-
| `file` | OCR instructions | systemPrompt?; model via llm.scenarios.ocr | text extraction instructions; not HTML sanitization | `{ file: { systemPrompt: "只提取可见文字" } }` |
|
|
1017
|
-
| `audio` | Audio models and limits | models, transcribeModel/synthesizeModel, maxAudioBytes/maxStreamDurationMs | provider capability/operation selection and bounded input/stream | `see Audio examples` |
|
|
1018
|
-
| `image` | Image models and download limits | models, generateModel, maxImageBytes, maxImages; timeout per model | generated bytes with MIME; unsafe downloads rejected | `see Image examples` |
|
|
1019
|
-
| `a2a` | Agent discovery and leases | agentCard and execution lease/poll/deadline options | ProtoJSON discovery and shared task journal | `see A2A protocol section` |
|
|
1020
|
-
| `acp` | Agent execution limits | agents/workspaces and execution content/event limits | validated definitions and managed native sessions | `see ACP guide` |
|
|
1021
|
-
|
|
1022
|
-
Rerank inherits the global LLM timeout with per-model overrides; the deadline covers the request and response body, returning RERANK_API_ERROR on timeout.
|
|
1023
|
-
|
|
1024
|
-
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.
|
|
1025
|
-
|
|
1026
|
-
```yaml
|
|
1027
|
-
llm:
|
|
1028
|
-
apiKey: ''
|
|
1029
|
-
baseUrl: https://api.openai.com/v1
|
|
1030
|
-
model: gpt-4o-mini
|
|
1031
|
-
protocol: chat # chat(默认)| responses | anthropic —— 底层 API 协议,对使用方透明
|
|
1032
|
-
timeout: 60000
|
|
1033
|
-
tempModelCacheTtl: 600000 # 临时模型客户端缓存 TTL(毫秒,默认 10 分钟)
|
|
1034
|
-
models: # 可为每个模型单独指定协议
|
|
1035
|
-
- {id: fast, model: gpt-4o-mini}
|
|
1036
|
-
- {id: strong, model: gpt-4.1, protocol: responses}
|
|
1037
|
-
- {id: claude, model: claude-3-5-sonnet-latest, protocol: anthropic}
|
|
1038
|
-
scenarios:
|
|
1039
|
-
chat: fast
|
|
1040
|
-
reasoning: strong
|
|
1041
|
-
embedding: embed
|
|
1042
|
-
|
|
1043
|
-
embedding:
|
|
1044
|
-
dimensions: 1536
|
|
1045
|
-
batchSize: 100
|
|
1046
|
-
|
|
1047
|
-
knowledge:
|
|
1048
|
-
collection: hai_ai_knowledge
|
|
1049
|
-
dimension: 1536
|
|
1050
|
-
cleanOptions:
|
|
1051
|
-
removeHtml: true
|
|
1052
|
-
normalizeWhitespace: true
|
|
1053
|
-
chunkOptions:
|
|
1054
|
-
mode: markdown
|
|
1055
|
-
maxSize: 1500
|
|
1056
|
-
overlap: 200
|
|
1057
|
-
|
|
1058
|
-
memory:
|
|
1059
|
-
provider: native # native | mem0
|
|
1060
|
-
maxEntriesPerObject: 1000 # 单主体(objectId)最大记忆条数
|
|
1061
|
-
maxEntriesGlobal: 100000 # 跨所有主体的全局上限
|
|
1062
|
-
recencyDecay: 0.95
|
|
1063
|
-
embeddingEnabled: true
|
|
1064
|
-
defaultTopK: 10
|
|
1065
|
-
candidateMultiplier: 5 # 候选池倍数:先取回 topK×倍数 条候选,再按 scope/重要性过滤,最后截取 topK
|
|
1066
|
-
writebackRelatedTopK: 20
|
|
1067
|
-
```
|
|
1068
|
-
|
|
1069
|
-
When loading through `core.config.load('ai', ...)`, convention-based environment variables override YAML:
|
|
1070
|
-
for example `HAI_AI_LLM_APIKEY`, `HAI_AI_LLM_BASEURL`, and `HAI_AI_LLM_MODEL`.
|
|
1071
|
-
|
|
1072
|
-
Enable the Mem0 data-format adapter:
|
|
1073
|
-
|
|
1074
|
-
```yaml
|
|
1075
|
-
memory:
|
|
1076
|
-
provider: mem0
|
|
1077
|
-
defaultTopK: 10
|
|
1078
|
-
```
|
|
1079
|
-
|
|
1080
|
-
- **`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.
|
|
1081
|
-
- **`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.
|
|
1082
|
-
|
|
1083
|
-
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 })`.
|
|
1084
|
-
|
|
1085
|
-
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.
|
|
1086
|
-
|
|
1087
|
-
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.
|
|
1088
|
-
|
|
1089
|
-
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.
|
|
1090
|
-
|
|
1091
|
-
**Candidate pools and scope recall misses**: filtering scope after truncating to `topK` can let higher-ranked memories from other topics/personas displace the target scope. `recall` / `injectMemories` therefore fetch `topK × candidateMultiplier` candidates (default multiplier 5), filter, then take `topK`. Increase `candidateMultiplier` for finer isolation such as `topicId` + `personaId`:
|
|
1092
|
-
|
|
1093
|
-
```ts
|
|
1094
|
-
const memories = await ai.memory.recall('经济发展', {
|
|
1095
|
-
objectId: 'user-001',
|
|
1096
|
-
scope: { topicId: 'C' },
|
|
1097
|
-
topK: 10,
|
|
1098
|
-
candidateMultiplier: 8, // 覆盖配置默认值,扩大候选池
|
|
1099
|
-
})
|
|
1100
|
-
```
|
|
1101
|
-
|
|
1102
|
-
`ai.config` returns a redacted snapshot without exposing original `apiKey`, `privateKey`, embedded URL credentials, or other secrets.
|
|
1103
|
-
|
|
1104
|
-
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.
|
|
1105
|
-
|
|
1106
|
-
## Error Handling
|
|
1107
|
-
|
|
1108
|
-
```ts
|
|
1109
|
-
const result = await ai.llm.chat({ messages })
|
|
1110
|
-
if (!result.success) {
|
|
1111
|
-
switch (result.error.code) {
|
|
1112
|
-
case HaiAIError.NOT_INITIALIZED.code:
|
|
1113
|
-
// 先调用 ai.init()
|
|
1114
|
-
break
|
|
1115
|
-
case HaiAIError.API_ERROR.code:
|
|
1116
|
-
// 上游模型服务失败,可重试或降级
|
|
1117
|
-
break
|
|
1118
|
-
}
|
|
1119
|
-
}
|
|
1120
|
-
```
|
|
25
|
+
[Browse the API list](../../docs/usage/function/ai.en.md#api-reference) for entry points, inputs, results and examples.
|
|
1121
26
|
|
|
1122
|
-
|
|
27
|
+
## Data Structures
|
|
1123
28
|
|
|
1124
|
-
|
|
1125
|
-
- `hai:ai:100-107`: LLM and history.
|
|
1126
|
-
- `hai:ai:300-302`:Embedding。
|
|
1127
|
-
- `hai:ai:600-701`:Retrieval/RAG。
|
|
1128
|
-
- `hai:ai:800-805`:Knowledge。
|
|
1129
|
-
- `hai:ai:050-059`:Audio。
|
|
1130
|
-
- `hai:ai:060-068`: Image, including blocked downloads, resource limits, and total deadlines.
|
|
1131
|
-
- `hai:ai:900-906`:Memory。
|
|
1132
|
-
- `hai:ai:980-984`:A2A。
|
|
29
|
+
See the [data reference](../../docs/usage/data/ai.en.md) for the built-in DB Store, vector collections and native memory namespaces.
|
|
1133
30
|
|
|
1134
|
-
## Development
|
|
31
|
+
## Development and Testing
|
|
1135
32
|
|
|
1136
33
|
```bash
|
|
1137
34
|
pnpm --filter @h-ai/ai typecheck
|