@h-ai/ai 0.1.0-alpha.66 → 0.1.0-alpha.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -4,9 +4,11 @@
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
+
7
9
  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
10
 
9
- ## Capabilities
11
+ ## Core features
10
12
 
11
13
  - `ai.tools`: tool definitions, registries, and batch execution; no initialization required.
12
14
  - `ai.stream`: ChatCompletion stream chunk processing; no initialization required.
@@ -27,9 +29,11 @@ AI capabilities through a unified `ai` service: LLM chat, image generation, tool
27
29
 
28
30
  For the full method list, error codes, and longer examples, see [REFERENCE.md (Chinese)](./REFERENCE.md).
29
31
 
30
- ## Quick start
32
+ ## Getting started
33
+
34
+ ### Quick start
31
35
 
32
- ### LLM-only (no database dependencies)
36
+ #### LLM-only (no database dependencies)
33
37
 
34
38
  ```ts
35
39
  import { ai } from '@h-ai/ai'
@@ -52,7 +56,7 @@ await ai.close()
52
56
 
53
57
  Without initialized reldb/vecdb, AI stores session/runtime state in a temporary in-process store. Data does not survive `ai.close()`, process exit, or instance switching. Use the DB provider below for persistent Memory, Context, Persona, or sessions across restarts.
54
58
 
55
- ### Persistent DB provider (reldb + vecdb)
59
+ #### Persistent DB provider (reldb + vecdb)
56
60
 
57
61
  ```ts
58
62
  import { ai } from '@h-ai/ai'
@@ -84,7 +88,7 @@ await vecdb.close()
84
88
  await reldb.close()
85
89
  ```
86
90
 
87
- ### Custom StoreProvider
91
+ #### Custom StoreProvider
88
92
 
89
93
  ```ts
90
94
  import type { AIStoreProvider } from '@h-ai/ai'
@@ -100,7 +104,7 @@ await ai.init(
100
104
  await ai.close()
101
105
  ```
102
106
 
103
- ## API contracts
107
+ ### API contracts
104
108
 
105
109
  - Public access uses the `ai` service and a few standalone factories such as `createMcpServer`.
106
110
  - Lifecycle: `await ai.init(config, options?)` / `await ai.close()`; closure waits for custom `AIStoreProvider.close()`.
@@ -108,9 +112,9 @@ await ai.close()
108
112
  - `ai.tools` and `ai.stream` are pure-function subsystems usable without initialization.
109
113
  - Without reldb/vecdb, storage is temporary and in-process; with both initialized, DB storage is automatic. Custom providers can encapsulate other backends.
110
114
 
111
- ## API overview
115
+ ### API overview
112
116
 
113
- ### LLM
117
+ #### LLM
114
118
 
115
119
  ```ts
116
120
  const result = await ai.llm.chat({ messages })
@@ -140,7 +144,7 @@ const temp = await ai.llm.chat({
140
144
  })
141
145
  ```
142
146
 
143
- ### Tool calls
147
+ #### Tool calls
144
148
 
145
149
  ```ts
146
150
  import { z } from 'zod'
@@ -172,13 +176,13 @@ const batch = await registry.executeAll(toolCalls)
172
176
  const chat = await ai.llm.chat({ messages, tools: registry.getDefinitions() })
173
177
  ```
174
178
 
175
- ### A2A protocol boundaries
179
+ #### A2A protocol boundaries
176
180
 
177
181
  `ai.a2a.getAgentCard()` returns a complete A2A 0.3 Agent Card with `protocolVersion`, MIME, and streaming capabilities. Kit discovery defaults to `/.well-known/agent-card.json`. `handleRequest()` always returns JSON-RPC/SSE results; uninitialized calls return JSON-RPC errors. Trusted HTTP `agentId` maps to executor `context.user.userName`. JSON-RPC/SSE are supported; push notifications, gRPC, and REST are not claimed. Applications remain responsible for business resource authorization.
178
182
 
179
183
  A2A task/message tables initialize during `ai.init()`. Tasks are read in trusted `agentId` scopes, including get/cancel/continuation. Anonymous requests share one scope, so deployments requiring isolation must enable authentication. `listMessages` is a server administration API with `callerId`, `contextId`, and `since` filters; never expose it to unauthorized clients. Legacy tasks lack reliable subjects; upgrades neither infer ownership nor delete data. After review, applications must migrate `object_id` to `user:<agentId>` (`anonymous` for anonymous records). Legacy messages lacking subject/context fields do not match corresponding filters.
180
184
 
181
- ### MCP Server
185
+ #### MCP Server
182
186
 
183
187
  `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.
184
188
 
@@ -193,10 +197,10 @@ server.registerTool('search', {
193
197
  }, async ({ query }) => ({
194
198
  content: [{ type: 'text', text: `Results for ${query}` }],
195
199
  }))
196
- await server.connect(new StreamableHTTPServerTransport({ sessionIdGenerator: crypto.randomUUID }))
200
+ await server.connect(new StreamableHTTPServerTransport({ sessionIdGenerator: () => globalThis.crypto.randomUUID() }))
197
201
  ```
198
202
 
199
- ### Memory / RAG / Knowledge
203
+ #### Memory / RAG / Knowledge
200
204
 
201
205
  ```ts
202
206
  const enriched = await ai.memory.injectMemories(messages, { objectId: 'user-001', topK: 5 })
@@ -221,7 +225,7 @@ if (setup.success) {
221
225
  }
222
226
  ```
223
227
 
224
- ### Audio
228
+ #### Audio
225
229
 
226
230
  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:
227
231
 
@@ -330,7 +334,7 @@ Browsers/mobile clients use the unified audio WebSocket exposed by `@h-ai/serv`.
330
334
 
331
335
  > 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.
332
336
 
333
- ### Image generation
337
+ #### Image generation
334
338
 
335
339
  After model registration in `ai.init()`, callers receive normalized image bytes without vendor-specific Base64, inline data, or temporary URLs:
336
340
 
@@ -360,7 +364,7 @@ if (result.success) {
360
364
 
361
365
  `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.
362
366
 
363
- ### Context manager
367
+ #### Context manager
364
368
 
365
369
  ```ts
366
370
  const manager = ai.context.createManager({
@@ -379,7 +383,7 @@ if (manager.success) {
379
383
 
380
384
  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.
381
385
 
382
- #### Actual conversation state (Conversation Commit Layer)
386
+ ##### Actual conversation state (Conversation Commit Layer)
383
387
 
384
388
  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.
385
389
 
@@ -416,7 +420,7 @@ const turns = m.getTurns()
416
420
  - Only `committed` content enters context and memory extraction. Uncommitted/discarded text does not affect future turns.
417
421
  - 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.
418
422
 
419
- #### Session consolidation (Memory lifecycle)
423
+ ##### Session consolidation (Memory lifecycle)
420
424
 
421
425
  During a session, each turn extracts **short-term session memory** with `scope: { sessionId }`. At session end, `consolidate()`
422
426
  turns short-term memory + summaries into **cross-session long-term memory**, completing `Session Memory → Summary → Long-term Memory`:
@@ -430,7 +434,7 @@ if (result.success) {
430
434
  }
431
435
  ```
432
436
 
433
- ### Persona (AI character profiles)
437
+ #### Persona (AI character profiles)
434
438
 
435
439
  Memory uses `objectId` / `scope` to identify whose memories they are; Persona defines who the AI is through
436
440
  stable system prompts and character traits, linked to long-term memory through `scope: { personaId }`:
@@ -525,14 +529,14 @@ const memories = await ai.memory.recall('经济发展', {
525
529
 
526
530
  `ai.config` returns a redacted snapshot without exposing original `apiKey`, `privateKey`, embedded URL credentials, or other secrets.
527
531
 
528
- ## Security boundaries
532
+ ### Security boundaries
529
533
 
530
534
  - Treat prompts, retrieved documents, and model outputs as untrusted. Do not insert user content into non-overridable system rules.
531
535
  - 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.
532
536
  - `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.
533
537
  - Do not log full prompts, tool arguments, A2A headers, temporary model credentials, or remote URLs with queries. Audits should retain redacted summaries only.
534
538
 
535
- ## Error handling
539
+ ### Error handling
536
540
 
537
541
  ```ts
538
542
  const result = await ai.llm.chat({ messages })
@@ -560,7 +564,7 @@ Common error ranges:
560
564
  - `hai:ai:900-905`:Memory。
561
565
  - `hai:ai:980-984`:A2A。
562
566
 
563
- ## Tests
567
+ ## Development and testing
564
568
 
565
569
  ```bash
566
570
  pnpm --filter @h-ai/ai typecheck
package/README.ja.md CHANGED
@@ -4,9 +4,11 @@
4
4
 
5
5
  [フレームワークのホーム](../../README.ja.md) · 関連モジュール:[@h-ai/api-contract](../api-contract/README.ja.md) · [@h-ai/core](../core/README.ja.md) · [@h-ai/datapipe](../datapipe/README.ja.md) · [@h-ai/reldb](../reldb/README.ja.md) · [@h-ai/vecdb](../vecdb/README.ja.md)
6
6
 
7
+ ## 概要
8
+
7
9
  共通の `ai` サービスで LLM 対話、画像生成、ツール、MCP、Embedding、記憶、検索/RAG、知識ベース、コンテキスト管理、ファイル解析、Rerank、音声(ASR/TTS)、A2A を提供します。Node.js では `ai.init()` で初期化し、ブラウザーからは API/client を経由します。
8
10
 
9
- ## 機能概要
11
+ ## 主な機能
10
12
 
11
13
  - `ai.tools`:ツール定義・登録・一括実行。初期化不要。
12
14
  - `ai.stream`:ChatCompletion のストリーミング chunk 処理。初期化不要。
@@ -27,9 +29,11 @@
27
29
 
28
30
  詳しいメソッド一覧・エラーコード・長い例は [REFERENCE.md(中国語)](./REFERENCE.md) を参照してください。
29
31
 
30
- ## クイックスタート
32
+ ## 使い始める
33
+
34
+ ### クイックスタート
31
35
 
32
- ### LLM のみ(DB 依存なし)
36
+ #### LLM のみ(DB 依存なし)
33
37
 
34
38
  ```ts
35
39
  import { ai } from '@h-ai/ai'
@@ -52,7 +56,7 @@ await ai.close()
52
56
 
53
57
  reldb/vecdb が未初期化の場合、AI はセッションなどの状態をプロセス内の一時 Store に保存します。`ai.close()`、プロセス終了、インスタンス切り替え後は保持されません。Memory、Context、Persona、セッションを再起動後も保持する場合は以下の DB Provider を使います。
54
58
 
55
- ### 永続 DB Provider(reldb + vecdb)
59
+ #### 永続 DB Provider(reldb + vecdb)
56
60
 
57
61
  ```ts
58
62
  import { ai } from '@h-ai/ai'
@@ -84,7 +88,7 @@ await vecdb.close()
84
88
  await reldb.close()
85
89
  ```
86
90
 
87
- ### 独自 StoreProvider
91
+ #### 独自 StoreProvider
88
92
 
89
93
  ```ts
90
94
  import type { AIStoreProvider } from '@h-ai/ai'
@@ -100,7 +104,7 @@ await ai.init(
100
104
  await ai.close()
101
105
  ```
102
106
 
103
- ## API 契約
107
+ ### API 契約
104
108
 
105
109
  - 公開入口は `ai` サービスと `createMcpServer` など少数の独立ファクトリー。
106
110
  - ライフサイクルは `await ai.init(config, options?)` / `await ai.close()`。終了時は独自 `AIStoreProvider.close()` を待ちます。
@@ -108,9 +112,9 @@ await ai.close()
108
112
  - `ai.tools` と `ai.stream` は純粋関数で、初期化せず使用できます。
109
113
  - reldb/vecdb がなければプロセス内の一時 Store、両方が初期化済みなら DB Provider を自動使用します。独自 Provider はほかの保存先を隠蔽できます。
110
114
 
111
- ## API 一覧
115
+ ### API 一覧
112
116
 
113
- ### LLM
117
+ #### LLM
114
118
 
115
119
  ```ts
116
120
  const result = await ai.llm.chat({ messages })
@@ -140,7 +144,7 @@ const temp = await ai.llm.chat({
140
144
  })
141
145
  ```
142
146
 
143
- ### ツール呼び出し
147
+ #### ツール呼び出し
144
148
 
145
149
  ```ts
146
150
  import { z } from 'zod'
@@ -172,13 +176,13 @@ const batch = await registry.executeAll(toolCalls)
172
176
  const chat = await ai.llm.chat({ messages, tools: registry.getDefinitions() })
173
177
  ```
174
178
 
175
- ### A2A プロトコルの境界
179
+ #### A2A プロトコルの境界
176
180
 
177
181
  `ai.a2a.getAgentCard()` は `protocolVersion`、MIME、streaming 機能を含む完全な A2A 0.3 Agent Card を返します。Kit の既定検出パスは `/.well-known/agent-card.json`。`handleRequest()` は常に JSON-RPC/SSE の結果を返し、未初期化時は JSON-RPC エラーです。信頼された HTTP の `agentId` を executor の `context.user.userName` に対応付けます。JSON-RPC/SSE に対応し、push notifications・gRPC・REST 対応は宣言しません。業務リソースの認可はアプリの責任です。
178
182
 
179
183
  A2A のタスク・メッセージテーブルは `ai.init()` で初期化します。取得・キャンセル・継続を含め、タスクは信頼された `agentId` で分離します。匿名は共通 scope なので、分離が必要な環境は認証を有効にしてください。`listMessages` はサーバー管理 API で `callerId`・`contextId`・`since` を使えますが、未認可クライアントへ公開しません。旧タスクの主体は信頼できず、更新時に所有者の推定や自動削除はしません。アプリ側の審査後に `object_id` を `user:<agentId>`(匿名は `anonymous`)へ移行します。主体・context を持たない旧メッセージは対応フィルターに一致しません。
180
184
 
181
- ### MCP Server
185
+ #### MCP Server
182
186
 
183
187
  `ai.mcp` はプロセス内の登録機能、独立 `createMcpServer` は SDK transport を使い、互いの自動登録はしません。`ai.mcp` は登録時にツールの JSON Schema をコンパイルし、呼び出し時に入力を検証します。リソースは `text` / `blob` のいずれか一方だけを持ちます。プロンプト引数・SDK メッセージ出力も検証し、画像・音声に対応します。HTTP 例は transport 接続のみで、アプリがリクエスト処理・認証を接続し、終了時に server を閉じる必要があります。
184
188
 
@@ -193,10 +197,10 @@ server.registerTool('search', {
193
197
  }, async ({ query }) => ({
194
198
  content: [{ type: 'text', text: `Results for ${query}` }],
195
199
  }))
196
- await server.connect(new StreamableHTTPServerTransport({ sessionIdGenerator: crypto.randomUUID }))
200
+ await server.connect(new StreamableHTTPServerTransport({ sessionIdGenerator: () => globalThis.crypto.randomUUID() }))
197
201
  ```
198
202
 
199
- ### Memory / RAG / Knowledge
203
+ #### Memory / RAG / Knowledge
200
204
 
201
205
  ```ts
202
206
  const enriched = await ai.memory.injectMemories(messages, { objectId: 'user-001', topK: 5 })
@@ -221,7 +225,7 @@ if (setup.success) {
221
225
  }
222
226
  ```
223
227
 
224
- ### 音声(Audio)
228
+ #### 音声(Audio)
225
229
 
226
230
  先に `ai.init()` で音声モデルを登録し、既定の認識・合成モデルを対応付けます。認証情報はプラットフォームの環境変数へフォールバックします。LLM と音声が同じ認証情報を使うと確認できた場合にのみ、`inheritLlmApiKey` を明示的に有効化してください:
227
231
 
@@ -330,7 +334,7 @@ return playable.data
330
334
 
331
335
  > 自前の CPU/GPU モデルサービス(faster-whisper / IndexTTS / Qwen3-4B)、重み取得、オフライン化は [models/(中国語)](./models/README.md) を参照してください。イメージ・重みは ModelScope を優先し、HuggingFace ミラーへ自動フォールバックします。
332
336
 
333
- ### 画像生成(Image)
337
+ #### 画像生成(Image)
334
338
 
335
339
  `ai.init()` で登録後、呼び出し元は標準化された画像バイト列のみを受け取り、サービス固有の Base64・インラインデータ・一時 URL を意識しません:
336
340
 
@@ -360,7 +364,7 @@ if (result.success) {
360
364
 
361
365
  `referenceImages` は省略可能です。公開層は画像バイト列と MIME のみを受け付け、multipart・`inlineData`・Data URL は Provider が変換します。認証情報はモデル項目、`HAI_AI_IMAGE_<PROVIDER>_APIKEY`、サービス環境変数で指定できます。Qwen・Seedream の一時 URL は Provider 内ですぐダウンロードし、公開戻り値に出しません。詳細は [REFERENCE.md(中国語)](./REFERENCE.md#image) を参照してください。
362
366
 
363
- ### Context 管理
367
+ #### Context 管理
364
368
 
365
369
  ```ts
366
370
  const manager = ai.context.createManager({
@@ -379,7 +383,7 @@ if (manager.success) {
379
383
 
380
384
  同じ管理器では既定で**同時に 1 つの生成のみ**を許可し、前の AI が終了する前に次の user が書き込まれる順序乱れを防ぎます。`reset()` は非同期で、活動中の生成を停止し、並行処理の障壁を解放、ターンを消去し、既定で Persona/System Prompt を再登録します。
381
385
 
382
- #### 実際の対話状態(Conversation Commit Layer)
386
+ ##### 実際の対話状態(Conversation Commit Layer)
383
387
 
384
388
  既定(`turnCommit: 'auto'`)では `chat` / `chatStream` が**生成した全文**を context に保存します。しかし生成 → TTS → 再生の途中で発話が遮られた場合、次のターンで共有すべき状態は全文ではなく**実際に再生された部分**です。
385
389
 
@@ -416,7 +420,7 @@ const turns = m.getTurns()
416
420
  - `committed` の内容のみが context・記憶抽出に入り、未保存・破棄された部分は後続ターンへ影響しません。
417
421
  - 流れの完了前に `interruptTurn` で遮った場合(司会が割り込む瞬間にモデルが終了する場合など)、`chatStream` は **`done` を返しません**。正常終了と誤認した追加保存を防ぎます。
418
422
 
419
- #### セッションの定着(Memory ライフサイクル)
423
+ ##### セッションの定着(Memory ライフサイクル)
420
424
 
421
425
  セッション中は各ターンで `scope: { sessionId }` の**短期セッション記憶**を抽出し、終了時に `consolidate()` で
422
426
  短期記憶 + 要約を**セッションをまたぐ長期記憶**にします。`Session Memory → Summary → Long-term Memory` の流れです:
@@ -430,7 +434,7 @@ if (result.success) {
430
434
  }
431
435
  ```
432
436
 
433
- ### Persona(AI の人格)
437
+ #### Persona(AI の人格)
434
438
 
435
439
  Memory は `objectId` / `scope` で誰の記憶かを表し、Persona は AI が誰かを定義します。各 AI に
436
440
  安定したシステムプロンプト・性格を定義し、`scope: { personaId }` で長期記憶と関連付けます:
@@ -525,14 +529,14 @@ const memories = await ai.memory.recall('经济发展', {
525
529
 
526
530
  `ai.config` はマスク済み設定を返し、`apiKey`、`privateKey`、URL 内認証情報などをそのまま公開しません。
527
531
 
528
- ## セキュリティ上の境界
532
+ ### セキュリティ上の境界
529
533
 
530
534
  - Prompt・検索文書・モデル出力は信頼できない入力として扱い、変更不可のシステム規則へユーザー内容を組み込まないでください。
531
535
  - Zod はツール引数の形を検証するだけで権限を保証しません。高権限 handler は主体・テナント・所有者・割当量を確認し、自動実行を許可したツールのみをモデルへ登録してください。
532
536
  - `callRemoteAgent()` は `ai.init()` のみで使える独立クライアントで、Agent Card・ローカル executor は不要です。非 HTTP(S)・URL 内認証情報を拒否しますが、アプリは origin 許可リストと出口側での DNS リバインディング・内部網へのリダイレクト・クラウドメタデータ対策を行う必要があります。
533
537
  - 完全な Prompt・ツール引数・A2A headers・一時認証情報・query 付き遠隔 URL を記録せず、監査が必要な場合もマスク済みの概要のみ保存してください。
534
538
 
535
- ## エラー処理
539
+ ### エラー処理
536
540
 
537
541
  ```ts
538
542
  const result = await ai.llm.chat({ messages })
@@ -560,7 +564,7 @@ if (!result.success) {
560
564
  - `hai:ai:900-905`:Memory。
561
565
  - `hai:ai:980-984`:A2A。
562
566
 
563
- ## テスト
567
+ ## 開発とテスト
564
568
 
565
569
  ```bash
566
570
  pnpm --filter @h-ai/ai typecheck
@@ -569,6 +573,6 @@ pnpm --filter @h-ai/ai test
569
573
  pnpm --filter @h-ai/ai build
570
574
  ```
571
575
 
572
- ## License
576
+ ## ライセンス
573
577
 
574
578
  Apache-2.0
package/README.md CHANGED
@@ -4,9 +4,11 @@
4
4
 
5
5
  [框架首页](../../README.md) · 相关模块:[@h-ai/api-contract](../api-contract/README.md) · [@h-ai/core](../core/README.md) · [@h-ai/datapipe](../datapipe/README.md) · [@h-ai/reldb](../reldb/README.md) · [@h-ai/vecdb](../vecdb/README.md)
6
6
 
7
+ ## 简介
8
+
7
9
  AI 能力模块,提供统一的 `ai` 服务对象,覆盖 LLM 对话、文生图、工具调用、MCP、Embedding、记忆、检索/RAG、知识库、上下文管理、文件解析、Rerank、语音(ASR/TTS)与 A2A。Node.js 侧通过 `ai.init()` 初始化,浏览器侧通过 API/client 代理访问。
8
10
 
9
- ## 能力概览
11
+ ## 核心功能清单
10
12
 
11
13
  - `ai.tools`:工具定义、注册表、批量执行;无需初始化。
12
14
  - `ai.stream`:ChatCompletion 流式 chunk 处理;无需初始化。
@@ -27,9 +29,11 @@ AI 能力模块,提供统一的 `ai` 服务对象,覆盖 LLM 对话、文生
27
29
 
28
30
  更完整的方法清单、错误码与长示例见 [REFERENCE.md](./REFERENCE.md)。
29
31
 
30
- ## 快速开始
32
+ ## 使用入门
33
+
34
+ ### 快速开始
31
35
 
32
- ### LLM-only(零数据库依赖)
36
+ #### LLM-only(零数据库依赖)
33
37
 
34
38
  ```ts
35
39
  import { ai } from '@h-ai/ai'
@@ -52,7 +56,7 @@ await ai.close()
52
56
 
53
57
  未初始化 reldb/vecdb 时,AI 使用进程内临时 Store 保存会话等运行时状态;`ai.close()`、进程退出或多实例切换后数据不会保留。需要 Memory、Context、Persona 或会话跨重启持久化时,使用下面的 DB Provider。
54
58
 
55
- ### 持久化 DB Provider(reldb + vecdb)
59
+ #### 持久化 DB Provider(reldb + vecdb)
56
60
 
57
61
  ```ts
58
62
  import { ai } from '@h-ai/ai'
@@ -84,7 +88,7 @@ await vecdb.close()
84
88
  await reldb.close()
85
89
  ```
86
90
 
87
- ### 自定义 StoreProvider
91
+ #### 自定义 StoreProvider
88
92
 
89
93
  ```ts
90
94
  import type { AIStoreProvider } from '@h-ai/ai'
@@ -100,7 +104,7 @@ await ai.init(
100
104
  await ai.close()
101
105
  ```
102
106
 
103
- ## API 契约
107
+ ### API 契约
104
108
 
105
109
  - 对外只通过 `ai` 服务对象和少量独立工厂(如 `createMcpServer`)访问。
106
110
  - 生命周期为 `await ai.init(config, options?)` / `await ai.close()`;关闭会等待自定义 `AIStoreProvider.close()`。
@@ -108,9 +112,9 @@ await ai.close()
108
112
  - `ai.tools` 与 `ai.stream` 是纯函数子系统,无需初始化即可使用。
109
113
  - 未初始化 reldb/vecdb 时默认使用进程内临时 Store;两者均已初始化时自动使用 DB Provider。自定义 Provider 可隐藏其他存储后端。
110
114
 
111
- ## API 概览
115
+ ### API 概览
112
116
 
113
- ### LLM
117
+ #### LLM
114
118
 
115
119
  ```ts
116
120
  const result = await ai.llm.chat({ messages })
@@ -140,7 +144,7 @@ const temp = await ai.llm.chat({
140
144
  })
141
145
  ```
142
146
 
143
- ### 工具调用
147
+ #### 工具调用
144
148
 
145
149
  ```ts
146
150
  import { z } from 'zod'
@@ -172,13 +176,13 @@ const batch = await registry.executeAll(toolCalls)
172
176
  const chat = await ai.llm.chat({ messages, tools: registry.getDefinitions() })
173
177
  ```
174
178
 
175
- ### A2A 协议边界
179
+ #### A2A 协议边界
176
180
 
177
181
  `ai.a2a.getAgentCard()` 返回完整 A2A 0.3 Agent Card,含 `protocolVersion`、MIME 和 streaming 能力;Kit 默认发现路径为 `/.well-known/agent-card.json`。`handleRequest()` 始终返回 JSON-RPC/SSE 处理结果,未初始化返回 JSON-RPC 错误。可信 HTTP 认证上下文的 `agentId` 映射为 executor 的 `context.user.userName`。当前支持 JSON-RPC/SSE,不声明 push notifications、gRPC 或 REST 支持;业务资源授权仍由应用负责。
178
182
 
179
183
  A2A 的任务表和消息表在 `ai.init()` 阶段初始化。任务按可信 `agentId` 隔离读取(含获取、取消和继续消息);匿名请求共享匿名作用域,需隔离的部署必须开启认证。`listMessages` 是服务端管理接口,支持 `callerId`、`contextId`、`since` 过滤,不能直接向未授权客户端暴露。旧版任务记录没有可靠主体信息,升级后不会自动推断归属或删除数据,需由应用审核后迁移 `object_id` 为 `user:<agentId>`(匿名为 `anonymous`)。旧消息缺少主体/上下文字段时不会匹配相应过滤条件。
180
184
 
181
- ### MCP Server
185
+ #### MCP Server
182
186
 
183
187
  `ai.mcp` 是进程内注册表,独立 `createMcpServer` 使用 SDK transport,两者不会自动互相注册。`ai.mcp` 在注册时编译工具 JSON Schema,调用时校验输入;资源输出必须恰好含 `text` / `blob` 之一;提示词参数与 SDK 消息输出均校验,支持图片和音频内容。HTTP 示例只展示 transport 连接,应用仍须挂载请求处理与认证,并在退出时关闭 server。
184
188
 
@@ -193,10 +197,10 @@ server.registerTool('search', {
193
197
  }, async ({ query }) => ({
194
198
  content: [{ type: 'text', text: `Results for ${query}` }],
195
199
  }))
196
- await server.connect(new StreamableHTTPServerTransport({ sessionIdGenerator: crypto.randomUUID }))
200
+ await server.connect(new StreamableHTTPServerTransport({ sessionIdGenerator: () => globalThis.crypto.randomUUID() }))
197
201
  ```
198
202
 
199
- ### Memory / RAG / Knowledge
203
+ #### Memory / RAG / Knowledge
200
204
 
201
205
  ```ts
202
206
  const enriched = await ai.memory.injectMemories(messages, { objectId: 'user-001', topK: 5 })
@@ -221,7 +225,7 @@ if (setup.success) {
221
225
  }
222
226
  ```
223
227
 
224
- ### 语音(Audio)
228
+ #### 语音(Audio)
225
229
 
226
230
  先在 `ai.init()` 中注册语音模型并映射默认识别/合成模型。凭据默认回退到平台环境变量;只有 LLM 与语音模型确认使用同一凭据时,才显式启用 `inheritLlmApiKey`:
227
231
 
@@ -330,7 +334,7 @@ return playable.data
330
334
 
331
335
  > 自托管模型服务(faster-whisper / IndexTTS / Qwen3-4B 的 CPU/GPU Docker 镜像、权重下载与离线打包)见 [`models/`](./models/README.md)。镜像与权重下载优先使用 ModelScope,自动回退 HuggingFace 镜像。
332
336
 
333
- ### 文生图(Image)
337
+ #### 文生图(Image)
334
338
 
335
339
  在 `ai.init()` 注册模型后,调用方只接收标准化图片字节,不感知厂商 Base64、内联数据或临时 URL:
336
340
 
@@ -360,7 +364,7 @@ if (result.success) {
360
364
 
361
365
  `referenceImages` 可省略;公共层只接受图片字节与 MIME,multipart、`inlineData`、Data URL 等差异由 Provider 转换。凭据可在模型条目传入,或使用 `HAI_AI_IMAGE_<PROVIDER>_APIKEY` / 厂商环境变量。Qwen 与 Seedream 返回的临时 URL 会在 Provider 内立即下载,不会泄漏到公共返回值。完整接口差异与模型说明见 [REFERENCE.md](./REFERENCE.md#image)。
362
366
 
363
- ### Context 管理器
367
+ #### Context 管理器
364
368
 
365
369
  ```ts
366
370
  const manager = ai.context.createManager({
@@ -379,7 +383,7 @@ if (manager.success) {
379
383
 
380
384
  同一管理器默认实行**单活动生成**,避免「上一轮 AI 尚未退出,下一轮 user 消息先写入」导致的消息乱序;`reset()` 现为异步并会终止活动生成、释放并发屏障、清空轮次并默认重新写入 Persona/System Prompt。
381
385
 
382
- #### 真实对话状态(Conversation Commit Layer)
386
+ ##### 真实对话状态(Conversation Commit Layer)
383
387
 
384
388
  默认(`turnCommit: 'auto'`)下,`chat` / `chatStream` 会把**模型生成的完整文本**写入上下文。但在「模型生成 → TTS 合成 → 实际播放」链路中,AI 可能说到一半就被打断——此时进入下一轮所有参与者可见的对话状态,应当是**实际播放出去的部分**,而非模型本想说完的全文。
385
389
 
@@ -416,7 +420,7 @@ const turns = m.getTurns()
416
420
  - 只有 `committed` 的内容进入上下文与记忆提取;未提交/被打断丢弃的部分不会污染后续轮次。
417
421
  - 若轮次在流完成前已被 `interruptTurn` 打断(如主持人抢话,同时上游模型恰好正常结束),`chatStream` **不会再产出 `done`**,避免业务层误判为正常完成后继续提交文本。
418
422
 
419
- #### 会话固化(Memory 生命周期)
423
+ ##### 会话固化(Memory 生命周期)
420
424
 
421
425
  会话进行中,每轮对话按 `scope: { sessionId }` 提取**短期会话记忆**;会话结束时用 `consolidate()`
422
426
  把「短期记忆 + 摘要」沉淀为**跨会话长期记忆**,形成 `Session Memory → Summary → Long-term Memory` 闭环:
@@ -430,7 +434,7 @@ if (result.success) {
430
434
  }
431
435
  ```
432
436
 
433
- ### Persona(AI 角色人格)
437
+ #### Persona(AI 角色人格)
434
438
 
435
439
  Memory 用 `objectId` / `scope` 回答「谁的记忆」;Persona 回答「AI 是谁」——为每个 AI 角色定义
436
440
  稳定的系统提示词与性格特征,并通过 `scope: { personaId }` 关联其长期记忆:
@@ -525,14 +529,14 @@ const memories = await ai.memory.recall('经济发展', {
525
529
 
526
530
  `ai.config` 返回脱敏后的配置快照;`apiKey`、`privateKey`、URL 内嵌凭证等敏感字段不会原样暴露。
527
531
 
528
- ## 安全边界
532
+ ### 安全边界
529
533
 
530
534
  - Prompt、检索文档和模型输出都按不可信输入处理;不要把用户内容拼进不可覆盖的系统规则。
531
535
  - Zod 只校验工具参数形状,不代表调用者有权限。高权限工具必须在 handler 内再次校验身份、租户、资源归属与配额,并只把允许自动执行的工具注册给模型。
532
536
  - `callRemoteAgent()` 是独立客户端能力,只依赖 `ai.init()`,不要求配置 Agent Card 或注册本地 executor。它拒绝非 HTTP(S) 和 URL 内嵌凭据,但应用仍必须对远端 origin 配置白名单,并在出口代理处限制 DNS 重绑定、重定向到私网和云元数据地址。
533
537
  - 不记录完整 Prompt、工具参数、A2A headers、临时模型凭据或带 query 的远端 URL;确需审计时仅保存脱敏摘要。
534
538
 
535
- ## 错误处理
539
+ ### 错误处理
536
540
 
537
541
  ```ts
538
542
  const result = await ai.llm.chat({ messages })
@@ -560,7 +564,7 @@ if (!result.success) {
560
564
  - `hai:ai:900-905`:Memory。
561
565
  - `hai:ai:980-984`:A2A。
562
566
 
563
- ## 测试
567
+ ## 开发测试
564
568
 
565
569
  ```bash
566
570
  pnpm --filter @h-ai/ai typecheck
@@ -569,6 +573,6 @@ pnpm --filter @h-ai/ai test
569
573
  pnpm --filter @h-ai/ai build
570
574
  ```
571
575
 
572
- ## License
576
+ ## 许可证
573
577
 
574
578
  Apache-2.0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@h-ai/ai",
3
3
  "type": "module",
4
- "version": "0.1.0-alpha.66",
4
+ "version": "0.1.0-alpha.67",
5
5
  "description": "Hai Framework AI module (LLM, MCP, tools, and clients).",
6
6
  "license": "Apache-2.0",
7
7
  "exports": {
@@ -30,11 +30,11 @@
30
30
  },
31
31
  "dependencies": {
32
32
  "@a2a-js/sdk": "^0.3.12",
33
- "@h-ai/api-contract": "0.1.0-alpha.66",
34
- "@h-ai/core": "0.1.0-alpha.66",
35
- "@h-ai/datapipe": "0.1.0-alpha.66",
36
- "@h-ai/reldb": "0.1.0-alpha.66",
37
- "@h-ai/vecdb": "0.1.0-alpha.66",
33
+ "@h-ai/api-contract": "0.1.0-alpha.67",
34
+ "@h-ai/core": "0.1.0-alpha.67",
35
+ "@h-ai/datapipe": "0.1.0-alpha.67",
36
+ "@h-ai/reldb": "0.1.0-alpha.67",
37
+ "@h-ai/vecdb": "0.1.0-alpha.67",
38
38
  "@modelcontextprotocol/sdk": "^1.32.1",
39
39
  "mem0ai": "^3.3.1",
40
40
  "nanoid": "^6.0.2",