@h-ai/ai 1.0.0-beta.3 → 1.0.0-beta.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +567 -69
- package/README.ja.md +568 -70
- package/README.md +569 -71
- package/dist/{ai-audio-ws-protocol-1VhScfis.d.ts → ai-acp-types-DuPV5UGi.d.ts} +4922 -333
- package/dist/browser.d.ts +8 -5
- package/dist/browser.js +3 -3
- package/dist/{chunk-GMQFIWND.js → chunk-ILUCWONQ.js} +101 -13
- package/dist/chunk-ILUCWONQ.js.map +1 -0
- package/dist/{chunk-GAC5RLAG.js → chunk-LENTVEBE.js} +566 -45
- package/dist/chunk-LENTVEBE.js.map +1 -0
- package/dist/{chunk-HYMP57AC.js → chunk-NRDLMUSY.js} +25 -2
- package/dist/chunk-NRDLMUSY.js.map +1 -0
- package/dist/client/index.d.ts +28 -2
- package/dist/client/index.js +2 -2
- package/dist/index.d.ts +9 -13
- package/dist/index.js +10537 -1966
- package/dist/index.js.map +1 -1
- package/models/agents/README.md +119 -0
- package/models/agents/build.mjs +177 -0
- package/models/agents/codex-acp/Dockerfile +21 -0
- package/models/agents/codex-acp/agent.json +16 -0
- package/models/agents/deepseek-harness/Dockerfile +18 -0
- package/models/agents/deepseek-harness/agent.json +14 -0
- package/models/agents/goose/Dockerfile +29 -0
- package/models/agents/goose/agent.json +14 -0
- package/package.json +27 -31
- package/tools/.dockerignore +4 -0
- package/tools/README.md +111 -0
- package/tools/archives.py +56 -0
- package/tools/browser/Dockerfile +19 -0
- package/tools/browser/operation.py +50 -0
- package/tools/browser/render.mjs +40 -0
- package/tools/documents/Dockerfile +20 -0
- package/tools/documents/operation.py +80 -0
- package/tools/ocr/Dockerfile +19 -0
- package/tools/ocr/operation.py +18 -0
- package/tools/office/Dockerfile +21 -0
- package/tools/office/office_job.py +65 -0
- package/tools/office/operation.py +43 -0
- package/tools/tests/image-smoke.mjs +83 -0
- package/tools/tests/test_hai_tool.py +82 -0
- package/tools/tool.py +145 -0
- package/dist/chunk-GAC5RLAG.js.map +0 -1
- package/dist/chunk-GMQFIWND.js.map +0 -1
- package/dist/chunk-HYMP57AC.js.map +0 -1
package/README.en.md
CHANGED
|
@@ -4,11 +4,193 @@
|
|
|
4
4
|
|
|
5
5
|
[Framework home](../../README.en.md) · Related modules: [@h-ai/api-contract](../api-contract/README.en.md) · [@h-ai/core](../core/README.en.md) · [@h-ai/datapipe](../datapipe/README.en.md) · [@h-ai/reldb](../reldb/README.en.md) · [@h-ai/vecdb](../vecdb/README.en.md)
|
|
6
6
|
|
|
7
|
-
## Introduction
|
|
8
|
-
|
|
9
7
|
AI capabilities through a unified `ai` service: LLM chat, image generation, tools, MCP, embeddings, memory, retrieval/RAG, knowledge bases, context management, file parsing, reranking, audio (ASR/TTS), and A2A. Initialize with `ai.init()` on Node.js; browsers access it through APIs/clients.
|
|
10
8
|
|
|
11
|
-
##
|
|
9
|
+
## Quick Start
|
|
10
|
+
|
|
11
|
+
`ai.close()` waits for an initialization already in progress and then cleans up; concurrent closes share one operation. Reinitialization first cleans up the previous instance, and new initialization is rejected while closing.
|
|
12
|
+
|
|
13
|
+
### Development LLM-only (no database dependencies)
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { ai } from '@h-ai/ai'
|
|
17
|
+
|
|
18
|
+
const init = await ai.init({
|
|
19
|
+
llm: {
|
|
20
|
+
model: 'gpt-4o-mini',
|
|
21
|
+
apiKey: process.env.HAI_AI_LLM_APIKEY,
|
|
22
|
+
},
|
|
23
|
+
})
|
|
24
|
+
if (!init.success)
|
|
25
|
+
throw new Error(init.error.message)
|
|
26
|
+
|
|
27
|
+
try {
|
|
28
|
+
const result = await ai.llm.chat({
|
|
29
|
+
messages: [
|
|
30
|
+
{ role: 'user', content: '你好!' }
|
|
31
|
+
],
|
|
32
|
+
})
|
|
33
|
+
if (!result.success)
|
|
34
|
+
throw new Error(result.error.message)
|
|
35
|
+
const reply = result.data.choices[0]?.message.content ?? ''
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
await ai.close()
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Development/explicit tests without initialized reldb/vecdb use a temporary process store, lost on close, exit, or instance switching. When either `NODE_ENV` or `HAI_CORE_ENV` is production, temporary stores, SQLite and local vector backends fail initialization. Initialize shared RelDB and network vecdb first, or supply a shared provider with equivalent atomic guarantees.
|
|
43
|
+
|
|
44
|
+
## Features
|
|
45
|
+
|
|
46
|
+
### Purpose, inputs and outputs
|
|
47
|
+
|
|
48
|
+
Unless marked direct, AsyncIterable or a direct Promise value, the output column describes HaiResult.data after success has been checked. Provide named request/definition/options variables using the stated real input type. Streams and explicitly throwing helpers need error handling at the consumer boundary.
|
|
49
|
+
|
|
50
|
+
Call fragments reuse the initialized service from this page. Named variables stand for application-provided requests, schemas, resource definitions or options. Follow the corresponding examples for setup and failure handling. Check HaiResult.success and await asynchronous calls.
|
|
51
|
+
|
|
52
|
+
| Entry | Use case | Input | Output | Call fragment |
|
|
53
|
+
| --------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
|
|
54
|
+
| `ai.llm.chat` | Single answer | `ChatCompletionRequest: messages, model?, signal?, tools?` | `ChatCompletionResponse: choices, model, usage?` | `ai.llm.chat({ messages: [{ role: "user", content: "你好" }] })` |
|
|
55
|
+
| `ai.llm.chatStream` | Stream completion | `same ChatCompletionRequest` | `AsyncIterable<ChatCompletionChunk>; iteration may throw` | `ai.llm.chatStream({ messages })` |
|
|
56
|
+
| `ai.llm.ask` | Text answer | `question: string, AskOptions?` | `string answer` | `ai.llm.ask("解释共享状态")` |
|
|
57
|
+
| `ai.llm.askStream` | Text stream | `question: string, AskOptions?` | `AsyncIterable<string>` | `ai.llm.askStream("解释共享状态")` |
|
|
58
|
+
| `ai.llm.generateObject` | Schema-constrained answer | `Zod schema, messages, model?, 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()` |
|
|
12
194
|
|
|
13
195
|
- `ai.tools`: tool definitions, registries, and batch execution; no initialization required.
|
|
14
196
|
- `ai.stream`: ChatCompletion stream chunk processing; no initialization required.
|
|
@@ -32,34 +214,7 @@ AI capabilities through a unified `ai` service: LLM chat, image generation, tool
|
|
|
32
214
|
|
|
33
215
|
For the full method list, error codes, and longer examples, see [REFERENCE.md (Chinese)](./REFERENCE.md).
|
|
34
216
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
### Quick start
|
|
38
|
-
|
|
39
|
-
#### Development LLM-only (no database dependencies)
|
|
40
|
-
|
|
41
|
-
```ts
|
|
42
|
-
import { ai } from '@h-ai/ai'
|
|
43
|
-
|
|
44
|
-
const init = await ai.init({
|
|
45
|
-
llm: {
|
|
46
|
-
model: 'gpt-4o-mini',
|
|
47
|
-
apiKey: process.env.HAI_AI_LLM_APIKEY,
|
|
48
|
-
},
|
|
49
|
-
})
|
|
50
|
-
if (!init.success)
|
|
51
|
-
return init
|
|
52
|
-
|
|
53
|
-
const result = await ai.llm.chat({
|
|
54
|
-
messages: [{ role: 'user', content: '你好!' }],
|
|
55
|
-
})
|
|
56
|
-
|
|
57
|
-
await ai.close()
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
Development/explicit tests without initialized reldb/vecdb use a temporary process store, lost on close, exit, or instance switching. When either `NODE_ENV` or `HAI_CORE_ENV` is production, temporary stores, SQLite and local vector backends fail initialization. Initialize shared RelDB and network vecdb first, or supply a shared provider with equivalent atomic guarantees.
|
|
61
|
-
|
|
62
|
-
#### Persistent DB provider (reldb + vecdb)
|
|
217
|
+
### Persistent DB provider (reldb + vecdb)
|
|
63
218
|
|
|
64
219
|
```ts
|
|
65
220
|
import { ai } from '@h-ai/ai'
|
|
@@ -80,7 +235,11 @@ try {
|
|
|
80
235
|
})
|
|
81
236
|
if (!initialized.success)
|
|
82
237
|
throw new Error(initialized.error.message)
|
|
83
|
-
const result = await ai.llm.chat({
|
|
238
|
+
const result = await ai.llm.chat({
|
|
239
|
+
messages: [
|
|
240
|
+
{ role: 'user', content: 'Hello!' }
|
|
241
|
+
]
|
|
242
|
+
})
|
|
84
243
|
if (!result.success)
|
|
85
244
|
throw new Error(result.error.message)
|
|
86
245
|
const reply = result.data.choices[0]?.message.content ?? ''
|
|
@@ -100,9 +259,11 @@ if (failures.length)
|
|
|
100
259
|
throw new AggregateError(failures, 'AI operation or cleanup failed')
|
|
101
260
|
```
|
|
102
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
|
+
|
|
103
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.
|
|
104
265
|
|
|
105
|
-
|
|
266
|
+
### Custom StoreProvider
|
|
106
267
|
|
|
107
268
|
```ts
|
|
108
269
|
import type { AIStoreProvider } from '@h-ai/ai'
|
|
@@ -111,7 +272,9 @@ import { ai } from '@h-ai/ai'
|
|
|
111
272
|
const storeProvider: AIStoreProvider = createMyStoreProvider()
|
|
112
273
|
|
|
113
274
|
await ai.init(
|
|
114
|
-
{
|
|
275
|
+
{
|
|
276
|
+
llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY }
|
|
277
|
+
},
|
|
115
278
|
{ storeProvider },
|
|
116
279
|
)
|
|
117
280
|
|
|
@@ -156,12 +319,35 @@ const claude = await ai.llm.chat({ messages, model: 'claude' }) // 该模型配
|
|
|
156
319
|
// 临时客户端按 TTL 缓存(llm.tempModelCacheTtl,默认 10 分钟),与常驻模型客户端隔离
|
|
157
320
|
const temp = await ai.llm.chat({
|
|
158
321
|
messages,
|
|
159
|
-
tempModel: { model: 'claude-3-5-sonnet', protocol: 'anthropic', apiKey:
|
|
322
|
+
tempModel: { model: 'claude-3-5-sonnet', protocol: 'anthropic', apiKey: process.env.TEMP_LLM_API_KEY },
|
|
160
323
|
})
|
|
161
324
|
```
|
|
162
325
|
|
|
163
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.
|
|
164
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
|
+
|
|
165
351
|
#### Tool calls
|
|
166
352
|
|
|
167
353
|
```ts
|
|
@@ -174,7 +360,9 @@ const registry = ai.tools.createRegistry({
|
|
|
174
360
|
const registered = registry.register(ai.tools.define({
|
|
175
361
|
name: 'get_weather',
|
|
176
362
|
description: '获取天气',
|
|
177
|
-
parameters: z.object({
|
|
363
|
+
parameters: z.object({
|
|
364
|
+
city: z.string()
|
|
365
|
+
}),
|
|
178
366
|
// handler 第二参为执行上下文:可响应取消(打断/超时)、感知截止时间与交互主体
|
|
179
367
|
handler: async ({ city }, { signal }) => {
|
|
180
368
|
const res = await fetch(`https://api.example.com/weather?city=${city}`, { signal })
|
|
@@ -191,12 +379,113 @@ const result = await registry.execute(toolCall, { signal: controller.signal, obj
|
|
|
191
379
|
// 批量调用默认串行,避免副作用工具并发启动;纯读取且确认安全时才显式并行
|
|
192
380
|
const batch = await registry.executeAll(toolCalls)
|
|
193
381
|
|
|
194
|
-
const chat = await ai.llm.chat({
|
|
382
|
+
const chat = await ai.llm.chat({
|
|
383
|
+
messages,
|
|
384
|
+
tools: registry.getDefinitions()
|
|
385
|
+
})
|
|
195
386
|
```
|
|
196
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
|
+
|
|
197
484
|
#### A2A protocol boundaries
|
|
198
485
|
|
|
199
|
-
|
|
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.
|
|
200
489
|
|
|
201
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.
|
|
202
491
|
|
|
@@ -217,15 +506,102 @@ import { z } from 'zod'
|
|
|
217
506
|
const server = createMcpServer({ name: 'my-server', version: '1.0.0' })
|
|
218
507
|
server.registerTool('search', {
|
|
219
508
|
description: '搜索',
|
|
220
|
-
inputSchema: {
|
|
509
|
+
inputSchema: {
|
|
510
|
+
query: z.string()
|
|
511
|
+
},
|
|
221
512
|
}, async ({ query }) => ({
|
|
222
|
-
content: [
|
|
513
|
+
content: [
|
|
514
|
+
{ type: 'text', text: `Results for ${query}` }
|
|
515
|
+
],
|
|
516
|
+
}))
|
|
517
|
+
await server.connect(new StreamableHTTPServerTransport({
|
|
518
|
+
sessionIdGenerator: () => globalThis.crypto.randomUUID()
|
|
223
519
|
}))
|
|
224
|
-
|
|
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
|
+
}
|
|
225
595
|
```
|
|
226
596
|
|
|
227
597
|
#### Memory / RAG / Knowledge
|
|
228
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
|
+
|
|
229
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.
|
|
230
606
|
|
|
231
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.
|
|
@@ -243,15 +619,23 @@ if (!enriched.success) {
|
|
|
243
619
|
}
|
|
244
620
|
|
|
245
621
|
// 多租户推荐入口:scoped() 绑定主体与作用域,所有操作自动携带 objectId / scope(含归属校验),杜绝「忘记传 objectId」越权
|
|
246
|
-
const memory = ai.memory.scoped({
|
|
622
|
+
const memory = ai.memory.scoped({
|
|
623
|
+
objectId: 'user-001',
|
|
624
|
+
scope: { topicId: 't-1', personaId: 'p-1' }
|
|
625
|
+
})
|
|
247
626
|
await memory.add({ content: '用户偏好中文', type: 'preference' })
|
|
248
627
|
const recalled = await memory.recall('语言偏好')
|
|
249
628
|
|
|
250
629
|
// clear 拒绝空过滤(防误清全局);全局清空只能显式走管理接口
|
|
251
|
-
await memory.clear({
|
|
630
|
+
await memory.clear({
|
|
631
|
+
types: ['event']
|
|
632
|
+
}) // 仅清该作用域内的 event
|
|
252
633
|
await ai.memory.admin.clearAll({ confirm: true }) // 危险:清空整个记忆后端,需显式确认
|
|
253
634
|
|
|
254
|
-
const rag = await ai.rag.query('核心架构是什么?', {
|
|
635
|
+
const rag = await ai.rag.query('核心架构是什么?', {
|
|
636
|
+
sources: ['docs'],
|
|
637
|
+
topK: 5
|
|
638
|
+
})
|
|
255
639
|
|
|
256
640
|
const setup = await ai.knowledge.setup()
|
|
257
641
|
if (setup.success) {
|
|
@@ -282,11 +666,33 @@ await ai.init({
|
|
|
282
666
|
audio: {
|
|
283
667
|
inheritLlmApiKey: true,
|
|
284
668
|
models: [
|
|
285
|
-
{
|
|
286
|
-
|
|
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
|
+
},
|
|
287
681
|
// 自托管:whisper / indextts 必须显式配置 baseUrl
|
|
288
|
-
{
|
|
289
|
-
|
|
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
|
+
},
|
|
290
696
|
],
|
|
291
697
|
transcribeModel: 'asr',
|
|
292
698
|
synthesizeModel: 'tts',
|
|
@@ -413,6 +819,12 @@ Downloads require public HTTPS on default port 443 without URL credentials. Sock
|
|
|
413
819
|
|
|
414
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.
|
|
415
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
|
+
|
|
416
828
|
#### Context manager
|
|
417
829
|
|
|
418
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.
|
|
@@ -445,7 +857,10 @@ With `turnCommit: 'manual'`, results are not stored automatically. A `turnId` is
|
|
|
445
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:
|
|
446
858
|
|
|
447
859
|
```ts
|
|
448
|
-
const created = ai.context.createManager({
|
|
860
|
+
const created = ai.context.createManager({
|
|
861
|
+
scope: { objectId: 'user-001', sessionId: 'sess-001' },
|
|
862
|
+
turnCommit: 'manual'
|
|
863
|
+
})
|
|
449
864
|
if (!created.success)
|
|
450
865
|
return created
|
|
451
866
|
const m = created.data
|
|
@@ -483,7 +898,14 @@ turns short-term memory + summaries into **cross-session long-term memory**, com
|
|
|
483
898
|
|
|
484
899
|
```ts
|
|
485
900
|
// 会话结束时固化:整合摘要 → 提取长期记忆(写入不含 sessionId 的持久作用域)
|
|
486
|
-
const
|
|
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
|
+
})
|
|
487
909
|
if (result.success) {
|
|
488
910
|
// result.data.summary —— 本次会话整合摘要
|
|
489
911
|
// result.data.memories —— 固化到长期记忆的条目
|
|
@@ -505,18 +927,101 @@ await ai.persona.save({
|
|
|
505
927
|
|
|
506
928
|
// 组合出可直接喂给 ContextManager 的系统提示词(systemPrompt + traits)
|
|
507
929
|
const composed = await ai.persona.compose('xiaoq')
|
|
930
|
+
if (!composed.success)
|
|
931
|
+
return composed
|
|
508
932
|
const manager = ai.context.createManager({
|
|
509
933
|
scope: { objectId: 'user-001', sessionId: 'persona-session' },
|
|
510
934
|
systemPrompt: composed.data,
|
|
511
|
-
memory: {
|
|
935
|
+
memory: {
|
|
936
|
+
enable: true,
|
|
937
|
+
enableExtract: true,
|
|
938
|
+
scope: { personaId: 'xiaoq' }
|
|
939
|
+
},
|
|
512
940
|
})
|
|
513
941
|
```
|
|
514
942
|
|
|
515
|
-
`ai.persona` exposes `save` / `get` / `update` / `remove` / `list` / `compose
|
|
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.
|
|
516
944
|
|
|
517
|
-
###
|
|
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.
|
|
518
951
|
|
|
519
|
-
|
|
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.
|
|
520
1025
|
|
|
521
1026
|
```yaml
|
|
522
1027
|
llm:
|
|
@@ -564,7 +1069,7 @@ memory:
|
|
|
564
1069
|
When loading through `core.config.load('ai', ...)`, convention-based environment variables override YAML:
|
|
565
1070
|
for example `HAI_AI_LLM_APIKEY`, `HAI_AI_LLM_BASEURL`, and `HAI_AI_LLM_MODEL`.
|
|
566
1071
|
|
|
567
|
-
Enable
|
|
1072
|
+
Enable the Mem0 data-format adapter:
|
|
568
1073
|
|
|
569
1074
|
```yaml
|
|
570
1075
|
memory:
|
|
@@ -573,15 +1078,13 @@ memory:
|
|
|
573
1078
|
```
|
|
574
1079
|
|
|
575
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.
|
|
576
|
-
- **`mem0` (
|
|
577
|
-
|
|
578
|
-
Both providers share `ai.memory.*` (`extract` / `recall` / `injectMemories` / `add` / `update` / `get` / `remove` / `list` / `listPage` / `clear`) with `objectId` isolation and key-value `scope` filters such as `{ topicId, personaId }`. `recall` / `list` / `listPage` / `clear` strictly filter scope; `clear` with `types` / `scope` deletes only jointly matching entries. mem0 `extract` uses the shared extractor for classification/scoring (`types` / `model` / `minImportance` / `systemPrompt`), then writes with `infer:false`, preserving `hai_type` / `hai_importance`. Its `recall` supports `types` and `recencyWeight` decay, matching native behavior. Mem0 updates text and metadata in place, preserving `id` and creation time. SDK queries use `filters.user_id`; writes and whole-subject deletion use `userId`. With no SDK list cursor, `list`, `listPage`, and filtered `clear` support at most 1000 raw subject candidates, including expired records. One extra candidate detects truncation; exceeding the bound returns `MEMORY_LIST_INCOMPLETE` (906), without a fabricated total or partial filtered deletion. Complete candidates are filtered by UTC expiration date, type and scope before pagination. Whole-subject `deleteAll` is independent of this listing limit. Public empty-filter clear is rejected; only trusted administration may explicitly call `admin.clearAll({ confirm: true })`.
|
|
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.
|
|
579
1082
|
|
|
580
|
-
|
|
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 })`.
|
|
581
1084
|
|
|
582
|
-
|
|
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.
|
|
583
1086
|
|
|
584
|
-
|
|
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.
|
|
585
1088
|
|
|
586
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.
|
|
587
1090
|
|
|
@@ -598,14 +1101,9 @@ const memories = await ai.memory.recall('经济发展', {
|
|
|
598
1101
|
|
|
599
1102
|
`ai.config` returns a redacted snapshot without exposing original `apiKey`, `privateKey`, embedded URL credentials, or other secrets.
|
|
600
1103
|
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
- Treat prompts, retrieved documents, and model outputs as untrusted. Do not insert user content into non-overridable system rules.
|
|
604
|
-
- 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.
|
|
605
|
-
- `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.
|
|
606
|
-
- Do not log full prompts, tool arguments, A2A headers, temporary model credentials, or remote URLs with queries. Audits should retain redacted summaries only.
|
|
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.
|
|
607
1105
|
|
|
608
|
-
|
|
1106
|
+
## Error Handling
|
|
609
1107
|
|
|
610
1108
|
```ts
|
|
611
1109
|
const result = await ai.llm.chat({ messages })
|
|
@@ -633,7 +1131,7 @@ Common error ranges:
|
|
|
633
1131
|
- `hai:ai:900-906`:Memory。
|
|
634
1132
|
- `hai:ai:980-984`:A2A。
|
|
635
1133
|
|
|
636
|
-
## Development
|
|
1134
|
+
## Development
|
|
637
1135
|
|
|
638
1136
|
```bash
|
|
639
1137
|
pnpm --filter @h-ai/ai typecheck
|