@h-ai/ai 1.0.0-beta.18 → 1.0.0-beta.19

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
@@ -34,6 +34,8 @@ For the full method list, error codes, and longer examples, see [REFERENCE.md (C
34
34
 
35
35
  ## Getting started
36
36
 
37
+ `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.
38
+
37
39
  ### Quick start
38
40
 
39
41
  #### Development LLM-only (no database dependencies)
@@ -51,7 +53,9 @@ if (!init.success)
51
53
  return init
52
54
 
53
55
  const result = await ai.llm.chat({
54
- messages: [{ role: 'user', content: '你好!' }],
56
+ messages: [
57
+ { role: 'user', content: '你好!' }
58
+ ],
55
59
  })
56
60
 
57
61
  await ai.close()
@@ -80,7 +84,11 @@ try {
80
84
  })
81
85
  if (!initialized.success)
82
86
  throw new Error(initialized.error.message)
83
- const result = await ai.llm.chat({ messages: [{ role: 'user', content: 'Hello!' }] })
87
+ const result = await ai.llm.chat({
88
+ messages: [
89
+ { role: 'user', content: 'Hello!' }
90
+ ]
91
+ })
84
92
  if (!result.success)
85
93
  throw new Error(result.error.message)
86
94
  const reply = result.data.choices[0]?.message.content ?? ''
@@ -111,7 +119,9 @@ import { ai } from '@h-ai/ai'
111
119
  const storeProvider: AIStoreProvider = createMyStoreProvider()
112
120
 
113
121
  await ai.init(
114
- { llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY } },
122
+ {
123
+ llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY }
124
+ },
115
125
  { storeProvider },
116
126
  )
117
127
 
@@ -174,7 +184,9 @@ const registry = ai.tools.createRegistry({
174
184
  const registered = registry.register(ai.tools.define({
175
185
  name: 'get_weather',
176
186
  description: '获取天气',
177
- parameters: z.object({ city: z.string() }),
187
+ parameters: z.object({
188
+ city: z.string()
189
+ }),
178
190
  // handler 第二参为执行上下文:可响应取消(打断/超时)、感知截止时间与交互主体
179
191
  handler: async ({ city }, { signal }) => {
180
192
  const res = await fetch(`https://api.example.com/weather?city=${city}`, { signal })
@@ -191,7 +203,10 @@ const result = await registry.execute(toolCall, { signal: controller.signal, obj
191
203
  // 批量调用默认串行,避免副作用工具并发启动;纯读取且确认安全时才显式并行
192
204
  const batch = await registry.executeAll(toolCalls)
193
205
 
194
- const chat = await ai.llm.chat({ messages, tools: registry.getDefinitions() })
206
+ const chat = await ai.llm.chat({
207
+ messages,
208
+ tools: registry.getDefinitions()
209
+ })
195
210
  ```
196
211
 
197
212
  #### ACP agents, workspaces and sessions
@@ -223,7 +238,9 @@ Managed Git rejects submodules and Git LFS attributes with ACP_UNSUPPORTED inste
223
238
 
224
239
  #### A2A protocol boundaries
225
240
 
226
- `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.
241
+ Remote-call headers override existing fields case-insensitively. Fixed JSON-RPC endpoints reject HTTP redirects, preventing authentication headers from reaching redirect targets.
242
+
243
+ `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.
227
244
 
228
245
  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.
229
246
 
@@ -244,15 +261,25 @@ import { z } from 'zod'
244
261
  const server = createMcpServer({ name: 'my-server', version: '1.0.0' })
245
262
  server.registerTool('search', {
246
263
  description: '搜索',
247
- inputSchema: { query: z.string() },
264
+ inputSchema: {
265
+ query: z.string()
266
+ },
248
267
  }, async ({ query }) => ({
249
- content: [{ type: 'text', text: `Results for ${query}` }],
268
+ content: [
269
+ { type: 'text', text: `Results for ${query}` }
270
+ ],
271
+ }))
272
+ await server.connect(new StreamableHTTPServerTransport({
273
+ sessionIdGenerator: () => globalThis.crypto.randomUUID()
250
274
  }))
251
- await server.connect(new StreamableHTTPServerTransport({ sessionIdGenerator: () => globalThis.crypto.randomUUID() }))
252
275
  ```
253
276
 
254
277
  #### Memory / RAG / Knowledge
255
278
 
279
+ Native memory deletion, including administrator clear-all, cleans vectors before removing authoritative records. Failed vector cleanup retains records for retry. SQL and vector storage do not share a transaction; a later failure still requires checking current state.
280
+
281
+ `ai.memory.scoped({ objectId })` requires a nonempty, non-whitespace subject ID; invalid input immediately throws `TypeError` from the factory instead of creating an unbound instance. Empty public clearing ranges such as `clear({ scope: {} })` fail; cross-subject clearing requires the explicit administrator API. Native memory access statistics and updates use version CAS, so delayed reads cannot resurrect deleted entries. Database and vector cleanup failures return failed HaiResult values.
282
+
256
283
  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.
257
284
 
258
285
  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.
@@ -270,15 +297,23 @@ if (!enriched.success) {
270
297
  }
271
298
 
272
299
  // 多租户推荐入口:scoped() 绑定主体与作用域,所有操作自动携带 objectId / scope(含归属校验),杜绝「忘记传 objectId」越权
273
- const memory = ai.memory.scoped({ objectId: 'user-001', scope: { topicId: 't-1', personaId: 'p-1' } })
300
+ const memory = ai.memory.scoped({
301
+ objectId: 'user-001',
302
+ scope: { topicId: 't-1', personaId: 'p-1' }
303
+ })
274
304
  await memory.add({ content: '用户偏好中文', type: 'preference' })
275
305
  const recalled = await memory.recall('语言偏好')
276
306
 
277
307
  // clear 拒绝空过滤(防误清全局);全局清空只能显式走管理接口
278
- await memory.clear({ types: ['event'] }) // 仅清该作用域内的 event
308
+ await memory.clear({
309
+ types: ['event']
310
+ }) // 仅清该作用域内的 event
279
311
  await ai.memory.admin.clearAll({ confirm: true }) // 危险:清空整个记忆后端,需显式确认
280
312
 
281
- const rag = await ai.rag.query('核心架构是什么?', { sources: ['docs'], topK: 5 })
313
+ const rag = await ai.rag.query('核心架构是什么?', {
314
+ sources: ['docs'],
315
+ topK: 5
316
+ })
282
317
 
283
318
  const setup = await ai.knowledge.setup()
284
319
  if (setup.success) {
@@ -309,11 +344,33 @@ await ai.init({
309
344
  audio: {
310
345
  inheritLlmApiKey: true,
311
346
  models: [
312
- { id: 'asr', provider: 'qwen', model: 'qwen3-asr-flash-realtime', operations: ['transcribe'] },
313
- { id: 'tts', provider: 'qwen', model: 'qwen3-tts-flash-realtime', operations: ['synthesize'] },
347
+ {
348
+ id: 'asr',
349
+ provider: 'qwen',
350
+ model: 'qwen3-asr-flash-realtime',
351
+ operations: ['transcribe']
352
+ },
353
+ {
354
+ id: 'tts',
355
+ provider: 'qwen',
356
+ model: 'qwen3-tts-flash-realtime',
357
+ operations: ['synthesize']
358
+ },
314
359
  // 自托管:whisper / indextts 必须显式配置 baseUrl
315
- { id: 'whisper', provider: 'whisper', model: 'faster-whisper-large-v3', operations: ['transcribe'], baseUrl: 'http://127.0.0.1:8101/v1' },
316
- { id: 'indextts', provider: 'indextts', model: 'indextts-2.5', operations: ['synthesize'], baseUrl: 'http://127.0.0.1:8102/v1' },
360
+ {
361
+ id: 'whisper',
362
+ provider: 'whisper',
363
+ model: 'faster-whisper-large-v3',
364
+ operations: ['transcribe'],
365
+ baseUrl: 'http://127.0.0.1:8101/v1'
366
+ },
367
+ {
368
+ id: 'indextts',
369
+ provider: 'indextts',
370
+ model: 'indextts-2.5',
371
+ operations: ['synthesize'],
372
+ baseUrl: 'http://127.0.0.1:8102/v1'
373
+ },
317
374
  ],
318
375
  transcribeModel: 'asr',
319
376
  synthesizeModel: 'tts',
@@ -440,6 +497,12 @@ Downloads require public HTTPS on default port 443 without URL credentials. Sock
440
497
 
441
498
  `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.
442
499
 
500
+ #### File parsing
501
+
502
+ 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.
503
+
504
+ 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.
505
+
443
506
  #### Context manager
444
507
 
445
508
  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.
@@ -472,7 +535,10 @@ With `turnCommit: 'manual'`, results are not stored automatically. A `turnId` is
472
535
  `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:
473
536
 
474
537
  ```ts
475
- const created = ai.context.createManager({ scope: { objectId: 'user-001', sessionId: 'sess-001' }, turnCommit: 'manual' })
538
+ const created = ai.context.createManager({
539
+ scope: { objectId: 'user-001', sessionId: 'sess-001' },
540
+ turnCommit: 'manual'
541
+ })
476
542
  if (!created.success)
477
543
  return created
478
544
  const m = created.data
@@ -510,7 +576,9 @@ turns short-term memory + summaries into **cross-session long-term memory**, com
510
576
 
511
577
  ```ts
512
578
  // 会话结束时固化:整合摘要 → 提取长期记忆(写入不含 sessionId 的持久作用域)
513
- const result = await manager.consolidate({ scope: { userId: 'user-001', personaId: 'xiaoq' } })
579
+ const result = await manager.consolidate({
580
+ scope: { userId: 'user-001', personaId: 'xiaoq' }
581
+ })
514
582
  if (result.success) {
515
583
  // result.data.summary —— 本次会话整合摘要
516
584
  // result.data.memories —— 固化到长期记忆的条目
@@ -535,11 +603,15 @@ const composed = await ai.persona.compose('xiaoq')
535
603
  const manager = ai.context.createManager({
536
604
  scope: { objectId: 'user-001', sessionId: 'persona-session' },
537
605
  systemPrompt: composed.data,
538
- memory: { enable: true, enableExtract: true, scope: { personaId: 'xiaoq' } },
606
+ memory: {
607
+ enable: true,
608
+ enableExtract: true,
609
+ scope: { personaId: 'xiaoq' }
610
+ },
539
611
  })
540
612
  ```
541
613
 
542
- `ai.persona` exposes `save` / `get` / `update` / `remove` / `list` / `compose`. Profiles are shared globally, not isolated by `objectId`.
614
+ `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.
543
615
 
544
616
  ### Configuration
545
617
 
@@ -593,7 +665,7 @@ memory:
593
665
  When loading through `core.config.load('ai', ...)`, convention-based environment variables override YAML:
594
666
  for example `HAI_AI_LLM_APIKEY`, `HAI_AI_LLM_BASEURL`, and `HAI_AI_LLM_MODEL`.
595
667
 
596
- Enable mem0 (the embedded mem0ai/oss engine):
668
+ Enable the Mem0 data-format adapter:
597
669
 
598
670
  ```yaml
599
671
  memory:
@@ -602,15 +674,13 @@ memory:
602
674
  ```
603
675
 
604
676
  - **`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.
605
- - **`mem0` (mem0ai/oss)**: directly embeds the `mem0ai/oss` `Memory` engine without cloud services. LLM/Embedder come from `llm` configuration; `qdrant` can reuse vecdb. The adapter maps only Qdrant with complete connection settings. Production (`NODE_ENV` or `HAI_CORE_ENV=production`) rejects actual ephemeral fallback even when `memory.allowEphemeralFallback: true`; missing backends also fail. Explicit fallback is limited to development or `HAI_E2E=1` / `HAI_E2E_MOCK=1`. History is disabled by default.
606
-
607
- 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 })`.
677
+ - **`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.
608
678
 
609
- Mem0 3.3.1 still calls `QdrantClient.search`. The catalog and AI optional peer pin the tested `@qdrant/js-client-rest` version `1.18.0`; startup checks this public method and rejects incompatible installations. Do not override it with 1.19, which removed that method.
679
+ 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 })`.
610
680
 
611
- The adapter injects a dedicated client through the SDK's public `client` configuration. Mem0 Qdrant upserts and deletes use `wait: true`, awaiting server application before readback or the next deletion batch.
681
+ 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.
612
682
 
613
- Mem0 with pgvector is rejected in every environment: the SDK privately owns a PostgreSQL connection without a public close API, so the framework cannot manage its lifecycle. Use `memory.provider: native` for pgvector; native support is retained. `disableHistory: true` selects a resource-free history implementation and creates no history SQLite file. The factory awaits backend readiness through one bounded public read before reporting success.
683
+ 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.
614
684
 
615
685
  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.
616
686
 
package/README.ja.md CHANGED
@@ -34,6 +34,8 @@
34
34
 
35
35
  ## 使い始める
36
36
 
37
+ `ai.close()` は進行中の初期化を待ってから解放し、並行する close は一つにまとめます。再初期化は旧インスタンスを先に解放し、終了処理中の新規初期化は拒否します。
38
+
37
39
  ### クイックスタート
38
40
 
39
41
  #### 開発用 LLM のみ(DB 依存なし)
@@ -51,7 +53,9 @@ if (!init.success)
51
53
  return init
52
54
 
53
55
  const result = await ai.llm.chat({
54
- messages: [{ role: 'user', content: '你好!' }],
56
+ messages: [
57
+ { role: 'user', content: '你好!' }
58
+ ],
55
59
  })
56
60
 
57
61
  await ai.close()
@@ -80,7 +84,11 @@ try {
80
84
  })
81
85
  if (!initialized.success)
82
86
  throw new Error(initialized.error.message)
83
- const result = await ai.llm.chat({ messages: [{ role: 'user', content: 'Hello!' }] })
87
+ const result = await ai.llm.chat({
88
+ messages: [
89
+ { role: 'user', content: 'Hello!' }
90
+ ]
91
+ })
84
92
  if (!result.success)
85
93
  throw new Error(result.error.message)
86
94
  const reply = result.data.choices[0]?.message.content ?? ''
@@ -111,7 +119,9 @@ import { ai } from '@h-ai/ai'
111
119
  const storeProvider: AIStoreProvider = createMyStoreProvider()
112
120
 
113
121
  await ai.init(
114
- { llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY } },
122
+ {
123
+ llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY }
124
+ },
115
125
  { storeProvider },
116
126
  )
117
127
 
@@ -174,7 +184,9 @@ const registry = ai.tools.createRegistry({
174
184
  const registered = registry.register(ai.tools.define({
175
185
  name: 'get_weather',
176
186
  description: '获取天气',
177
- parameters: z.object({ city: z.string() }),
187
+ parameters: z.object({
188
+ city: z.string()
189
+ }),
178
190
  // handler 第二参为执行上下文:可响应取消(打断/超时)、感知截止时间与交互主体
179
191
  handler: async ({ city }, { signal }) => {
180
192
  const res = await fetch(`https://api.example.com/weather?city=${city}`, { signal })
@@ -191,7 +203,10 @@ const result = await registry.execute(toolCall, { signal: controller.signal, obj
191
203
  // 批量调用默认串行,避免副作用工具并发启动;纯读取且确认安全时才显式并行
192
204
  const batch = await registry.executeAll(toolCalls)
193
205
 
194
- const chat = await ai.llm.chat({ messages, tools: registry.getDefinitions() })
206
+ const chat = await ai.llm.chat({
207
+ messages,
208
+ tools: registry.getDefinitions()
209
+ })
195
210
  ```
196
211
 
197
212
  #### ACP エージェント、ワークスペースとセッション
@@ -223,7 +238,9 @@ Goose 1.57.0 イメージは `goose serve` のネイティブ HTTP/WS `/acp` を
223
238
 
224
239
  #### A2A プロトコルの境界
225
240
 
226
- `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 対応は宣言しません。業務リソースの認可はアプリの責任です。
241
+ リモート呼び出しのヘッダーは大文字小文字を区別せず上書きします。固定 JSON-RPC URL は HTTP リダイレクトを拒否し、認証ヘッダーを転送先へ渡しません。
242
+
243
+ `ai.a2a.getAgentCard()` は `supportedInterfaces`、MIME、streaming 機能を含むHTTP 検出応答に直接使える標準 A2A 1.0 ProtoJSON を返します。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 対応は宣言しません。業務リソースの認可はアプリの責任です。
227
244
 
228
245
  A2A の journal・context 所有者・メッセージテーブルは `ai.init()` で初期化します。取得・キャンセル・継続は信頼された `agentId` で分離します。匿名は共通主体のため、本番は信頼された伝送層で認証してください。`listMessages` は `callerId`・`contextId`・`since` を持つ管理 API であり、未認可クライアントへ公開しません。
229
246
 
@@ -244,15 +261,25 @@ import { z } from 'zod'
244
261
  const server = createMcpServer({ name: 'my-server', version: '1.0.0' })
245
262
  server.registerTool('search', {
246
263
  description: '搜索',
247
- inputSchema: { query: z.string() },
264
+ inputSchema: {
265
+ query: z.string()
266
+ },
248
267
  }, async ({ query }) => ({
249
- content: [{ type: 'text', text: `Results for ${query}` }],
268
+ content: [
269
+ { type: 'text', text: `Results for ${query}` }
270
+ ],
271
+ }))
272
+ await server.connect(new StreamableHTTPServerTransport({
273
+ sessionIdGenerator: () => globalThis.crypto.randomUUID()
250
274
  }))
251
- await server.connect(new StreamableHTTPServerTransport({ sessionIdGenerator: () => globalThis.crypto.randomUUID() }))
252
275
  ```
253
276
 
254
277
  #### Memory / RAG / Knowledge
255
278
 
279
+ native 記憶の削除は管理者の全削除を含め、先にベクトルを削除してから権威レコードを削除します。ベクトル削除失敗時は再試行用にレコードを保持します。SQL とベクトルは同じトランザクションではないため、後段の失敗時も状態確認が必要です。
280
+
281
+ `ai.memory.scoped({ objectId })` は空でなく空白のみでもない主体 ID を要求し、不正な入力ではファクトリーが直ちに `TypeError` を送出します。未束縛のインスタンスは作成しません。`clear({ scope: {} })` など空範囲の公開削除は失敗し、主体横断の全削除には明示的な管理 API が必要です。ネイティブ記憶のアクセス統計と更新はバージョン CAS を使い、遅れた読み取りで削除済みデータを復活させません。DB・ベクトル削除の失敗は失敗の HaiResult で返します。
282
+
256
283
  Knowledge は取り込みごとに一意の `revision` と chunk ID を生成します。全文・ベクトル・エンティティを準備し、永続ステージングマニフェストとベクトルを書いた後、共有 Store CAS で完全なスナップショットを一度に公開します。同じ文書の再構築は一つの writer に制限され、失敗時は完全な旧版を保持します。短い新版に旧末尾 chunk が混在しません。検索は未公開版を除外し、公開と競合すれば再試行します。競合が続く場合はエラーを返します。候補拡張や清掃待ちは検索負荷を増やすことがあります。
257
284
 
258
285
  成功結果の `revision` と `cleanupPending` を確認してください。後者が true の場合、新版は公開済みですが旧ベクトルの清掃が残っています。`repair({ collection, offset, limit })` で全ページを定期処理してください。setup は最初の 100 マニフェストを確認します。ステージングは保存先時計で 5 分後に失効し、旧 writer は公開できません。遅延した外部書き込みを繰り返し清掃するため、放棄版の墓碑は永久保持し、ログと共に削除しません。SQL とベクトルは共通トランザクションではありません。文書・集合の削除は先に可視性を取り消し、清掃失敗を返します。集合削除は空ベクトル集合と世代墓碑を補償用に残し、再 setup で旧世代を復元しません。
@@ -270,15 +297,23 @@ if (!enriched.success) {
270
297
  }
271
298
 
272
299
  // 多租户推荐入口:scoped() 绑定主体与作用域,所有操作自动携带 objectId / scope(含归属校验),杜绝「忘记传 objectId」越权
273
- const memory = ai.memory.scoped({ objectId: 'user-001', scope: { topicId: 't-1', personaId: 'p-1' } })
300
+ const memory = ai.memory.scoped({
301
+ objectId: 'user-001',
302
+ scope: { topicId: 't-1', personaId: 'p-1' }
303
+ })
274
304
  await memory.add({ content: '用户偏好中文', type: 'preference' })
275
305
  const recalled = await memory.recall('语言偏好')
276
306
 
277
307
  // clear 拒绝空过滤(防误清全局);全局清空只能显式走管理接口
278
- await memory.clear({ types: ['event'] }) // 仅清该作用域内的 event
308
+ await memory.clear({
309
+ types: ['event']
310
+ }) // 仅清该作用域内的 event
279
311
  await ai.memory.admin.clearAll({ confirm: true }) // 危险:清空整个记忆后端,需显式确认
280
312
 
281
- const rag = await ai.rag.query('核心架构是什么?', { sources: ['docs'], topK: 5 })
313
+ const rag = await ai.rag.query('核心架构是什么?', {
314
+ sources: ['docs'],
315
+ topK: 5
316
+ })
282
317
 
283
318
  const setup = await ai.knowledge.setup()
284
319
  if (setup.success) {
@@ -309,11 +344,33 @@ await ai.init({
309
344
  audio: {
310
345
  inheritLlmApiKey: true,
311
346
  models: [
312
- { id: 'asr', provider: 'qwen', model: 'qwen3-asr-flash-realtime', operations: ['transcribe'] },
313
- { id: 'tts', provider: 'qwen', model: 'qwen3-tts-flash-realtime', operations: ['synthesize'] },
347
+ {
348
+ id: 'asr',
349
+ provider: 'qwen',
350
+ model: 'qwen3-asr-flash-realtime',
351
+ operations: ['transcribe']
352
+ },
353
+ {
354
+ id: 'tts',
355
+ provider: 'qwen',
356
+ model: 'qwen3-tts-flash-realtime',
357
+ operations: ['synthesize']
358
+ },
314
359
  // 自托管:whisper / indextts 必须显式配置 baseUrl
315
- { id: 'whisper', provider: 'whisper', model: 'faster-whisper-large-v3', operations: ['transcribe'], baseUrl: 'http://127.0.0.1:8101/v1' },
316
- { id: 'indextts', provider: 'indextts', model: 'indextts-2.5', operations: ['synthesize'], baseUrl: 'http://127.0.0.1:8102/v1' },
360
+ {
361
+ id: 'whisper',
362
+ provider: 'whisper',
363
+ model: 'faster-whisper-large-v3',
364
+ operations: ['transcribe'],
365
+ baseUrl: 'http://127.0.0.1:8101/v1'
366
+ },
367
+ {
368
+ id: 'indextts',
369
+ provider: 'indextts',
370
+ model: 'indextts-2.5',
371
+ operations: ['synthesize'],
372
+ baseUrl: 'http://127.0.0.1:8102/v1'
373
+ },
317
374
  ],
318
375
  transcribeModel: 'asr',
319
376
  synthesizeModel: 'tts',
@@ -440,6 +497,12 @@ if (result.success) {
440
497
 
441
498
  `image.maxImageBytes` は出力/参照画像ごとに既定 20971520(20 MiB、最大 100 MiB)、`image.maxImages` は出力/参照画像数ごとに既定 4(最大 16)です。URL は順次取得し、解凍後を含む実測バイト数が上限を超えると応答をキャンセルします。JSON は `max(64 KiB, 2 × maxImageBytes)`、エラー本文は 64 KiB までです。モデル `timeout` は既定 120000ms で API・リダイレクト・全ダウンロードを含み、`signal` で全体をキャンセルできます。出力は PNG/JPEG/GIF/WebP の MIME とマジック値の一致を要求し、SVG は拒否します。完全な画像デコード・寸法検証は行いません。アドレス拒否・上限超過・タイムアウトはそれぞれ `IMAGE_DOWNLOAD_BLOCKED`・`IMAGE_TOO_LARGE`・`IMAGE_TIMEOUT` を返すため、success を確認してください。
442
499
 
500
+ #### ファイル解析(File)
501
+
502
+ 業務のファイル内容と名前を `ai.file.parse({ content, filename, options: { outputFormat: 'markdown' } })` に渡します。`success` を確認してから `data.text` を読み、通常のテキストには `outputFormat: 'text'` を使います。HTML は parse5 と反復走査で処理し、script/style を除外して、見出し・リスト・リンク・画像・引用・コード・表などの一般的な Markdown 構造を保持します。不正なタグの正規表現バックトラック対策として正常な文書を切り詰めません。
503
+
504
+ 結果はテキストまたは Markdown であり、信頼済み HTML ではありません。テキストバインディングまたはフレームワークの `MarkdownRenderer` で表示し、直接 `{@html}` に渡さないでください。設定、引数、エラーコードは従来の契約を維持します。
505
+
443
506
  #### Context 管理
444
507
 
445
508
  自動記憶抽出は現在のノードのバックグラウンドで動作し、`pendingMemoryTasks=0` だけでは成功を示しません。`flush()` は当該バッチを待ち、例外と失敗 HaiResult を件数付き `MEMORY_EXTRACT_FAILED` として返します。同時の観測者は同じ結果を受け取り、戻り時点で報告を確認済みとし、次回は新規タスクだけを観測します。部分実行の可能性がある処理を自動再実行しません。`save()`・`reset({ waitForMemoryTasks: true })`・`consolidate()` は失敗時に後続の書き込みへ進まず、プロセス停止後の外部効果は別途確認します。
@@ -472,7 +535,10 @@ if (manager.success) {
472
535
  `chatStream` は**モデル呼び出し前**にターン登録と `turn_started` を行います(`turn_started → delta* → done`、キャンセル時は `turn_started → delta* → cancelled`)。途中で `AbortSignal` により中止しても `turnId` と生成済みテキストを取得し、実際の内容を保存できます:
473
536
 
474
537
  ```ts
475
- const created = ai.context.createManager({ scope: { objectId: 'user-001', sessionId: 'sess-001' }, turnCommit: 'manual' })
538
+ const created = ai.context.createManager({
539
+ scope: { objectId: 'user-001', sessionId: 'sess-001' },
540
+ turnCommit: 'manual'
541
+ })
476
542
  if (!created.success)
477
543
  return created
478
544
  const m = created.data
@@ -510,7 +576,9 @@ const turns = m.getTurns()
510
576
 
511
577
  ```ts
512
578
  // 会话结束时固化:整合摘要 → 提取长期记忆(写入不含 sessionId 的持久作用域)
513
- const result = await manager.consolidate({ scope: { userId: 'user-001', personaId: 'xiaoq' } })
579
+ const result = await manager.consolidate({
580
+ scope: { userId: 'user-001', personaId: 'xiaoq' }
581
+ })
514
582
  if (result.success) {
515
583
  // result.data.summary —— 本次会话整合摘要
516
584
  // result.data.memories —— 固化到长期记忆的条目
@@ -535,11 +603,15 @@ const composed = await ai.persona.compose('xiaoq')
535
603
  const manager = ai.context.createManager({
536
604
  scope: { objectId: 'user-001', sessionId: 'persona-session' },
537
605
  systemPrompt: composed.data,
538
- memory: { enable: true, enableExtract: true, scope: { personaId: 'xiaoq' } },
606
+ memory: {
607
+ enable: true,
608
+ enableExtract: true,
609
+ scope: { personaId: 'xiaoq' }
610
+ },
539
611
  })
540
612
  ```
541
613
 
542
- `ai.persona` は `save` / `get` / `update` / `remove` / `list` / `compose` を提供します。プロフィールは全体で共有し、`objectId` では分離しません。
614
+ `ai.persona` は `save` / `get` / `update` / `remove` / `list` / `compose` を提供し、`[objectId, id]` ごとにプロフィールを分離します。保存時は `objectId`、その他は `{ objectId }` を渡し、省略すると `system` のプラットフォーム用プロフィールを参照します。テナント操作には信頼された認証主体を結び付けてください。クライアントが送るプロフィール ID 自体はアクセス権を与えません。
543
615
 
544
616
  ### 設定
545
617
 
@@ -593,7 +665,7 @@ memory:
593
665
  `core.config.load('ai', ...)` では規約に沿う環境変数が YAML より優先されます:
594
666
  例:`HAI_AI_LLM_APIKEY`、`HAI_AI_LLM_BASEURL`、`HAI_AI_LLM_MODEL`。
595
667
 
596
- mem0(組み込み mem0ai/oss エンジン)の有効化:
668
+ Mem0 データ形式アダプターの有効化:
597
669
 
598
670
  ```yaml
599
671
  memory:
@@ -602,17 +674,15 @@ memory:
602
674
  ```
603
675
 
604
676
  - **`native`(既定・推奨)**:HAI のネイティブエンジンは vecdb、reldb、LLM、Embedding を再利用します。`extract` は **Mem0 型の一括マージ**で、抽出した事実と既存記憶に 1 回の LLM 呼び出しで ADD / UPDATE / DELETE / NONE を決定し、増分更新・重複除去・矛盾削除・`category` 分類を実現します。`maxEntriesPerObject`、`maxEntriesGlobal`、`recencyDecay`、`embeddingEnabled`、`writebackRelatedTopK` が適用されます。削除は `objectId` ごとなので、ある主体の大量書き込みでほかの主体の記憶は失いません。scope の候補は `objectId` で絞り(≤ `maxEntriesPerObject`)、PostgreSQL はさらに JSONB 包含検索へ scope を渡して **GIN インデックス**を使います。SQLite/MySQL はメモリー照合で同じ結果を返します。
605
- - **`mem0`(mem0ai/oss)**:`mem0ai/oss` の `Memory` エンジンを直接組み込み、クラウドを使いません。LLM/Embedder は `llm` 設定から取得し、`qdrant` は vecdb を再利用できます。現在のアダプターは完全な接続設定を持つ Qdrant のみをマッピングします。本番(`NODE_ENV` または `HAI_CORE_ENV=production`)では `memory.allowEphemeralFallback: true` でも実際のメモリーへの移行を拒否し、バックエンド未指定も失敗します。一時利用は開発または明示的な `HAI_E2E=1` / `HAI_E2E_MOCK=1` に限ります。履歴は既定で無効です。
606
-
607
- 両 Provider は同じ `ai.memory.*`(`extract` / `recall` / `injectMemories` / `add` / `update` / `get` / `remove` / `list` / `listPage` / `clear`)を提供し、`objectId` の主体分離と `{ topicId, personaId }` などの `scope` をサポートします。`recall` / `list` / `listPage` / `clear` は scope を厳密に絞り、`clear` に `types` / `scope` を渡すと同時一致のみを削除します。mem0 の `extract` は共通抽出器で分類・採点(`types` / `model` / `minImportance` / `systemPrompt`)後、`infer:false` で `hai_type` / `hai_importance` を保存します。`recall` も `types` と `recencyWeight` 減衰に対応し、native と同じ動作です。Mem0 はテキストとメタデータをその場で更新し、`id` と作成時刻を保持します。SDK の検索は `filters.user_id`、書き込みと主体全体の削除は `userId` を使います。SDK に一覧カーソルがないため、`list` / `listPage` / 条件付き `clear` は期限切れを含む主体候補 1000 件まで対応します。1 件余分に読み、超過は `MEMORY_LIST_INCOMPLETE`(906)で失敗します。不正確な total や一部のみの条件付き削除は行いません。候補が完全な場合、UTC の有効期限、型、scope で絞ってからページ分割します。主体全体の `deleteAll` は一覧上限の対象外です。公開 API の空条件 clear は拒否し、全主体の削除は信頼された管理者による明示的な `admin.clearAll({ confirm: true })` に限定します。
677
+ - **`mem0`(データ形式アダプター)**:抽出と Embedding は Hai が行い、ネイティブ HTTP で Qdrant の Mem0 UUID/payload 形式を読み書きします。既存データも読み取れます。上流の完全なエンジン、テレメトリー、履歴 DB は実行しません。完全な接続設定を持つ Qdrant のみ対応します。本番(`NODE_ENV` または `HAI_CORE_ENV=production`)は一時ストレージへの移行を拒否します。開発・明示的 E2E のみ `memory.allowEphemeralFallback: true` を指定できます。他の永続バックエンドは `native` を選択します。
608
678
 
609
- Mem0 3.3.1 は `QdrantClient.search` を呼び出すため、カタログと AI の optional peer は検証済みの `@qdrant/js-client-rest` `1.18.0` に固定します。起動時に公開メソッドを確認し、不整合は設定エラーにします。このメソッドを削除した 1.19 への上書きはできません。
679
+ 両 Provider は同じ `ai.memory.*`(`extract` / `recall` / `injectMemories` / `add` / `update` / `get` / `remove` / `list` / `listPage` / `clear`)を提供し、`objectId` の主体分離と `{ topicId, personaId }` などの `scope` をサポートします。`recall` / `list` / `listPage` / `clear` は scope を厳密に絞り、`clear` に `types` / `scope` を渡すと同時一致のみを削除します。mem0 の `extract` は共通抽出器で分類・採点(`types` / `model` / `minImportance` / `systemPrompt`)後、直接 `hai_type` / `hai_importance` を保存します。`recall` も `types` と `recencyWeight` 減衰に対応し、native と同じ動作です。Mem0 はテキストとメタデータをその場で更新し、`id` と作成時刻を保持します。候補走査は有界のため、`list` / `listPage` / 条件付き `clear` は期限切れを含む主体候補 1000 件まで対応します。1 件余分に読み、超過は `MEMORY_LIST_INCOMPLETE`(906)で失敗します。不正確な total や一部のみの条件付き削除は行いません。候補が完全な場合、UTC の有効期限、型、scope で絞ってからページ分割します。主体全体の削除 は一覧上限の対象外です。公開 API の空条件 clear は拒否し、全主体の削除は信頼された管理者による明示的な `admin.clearAll({ confirm: true })` に限定します。
610
680
 
611
- アダプターは SDK の公開 `client` 設定から専用クライアントを渡します。Mem0 の Qdrant 書き込みと削除は `wait: true` を指定し、サーバーでの適用完了後に書き込み後の読み取りや次の削除バッチへ進みます。
681
+ Mem0 形式ストレージと VecDB の Qdrant Provider は追加 SDK なしでネイティブ HTTP を使います。固定 REST 要求は `query` とエンコードしたパスを使用し、30 秒のタイムアウトは応答本文全体を含みます。16 MiB を超える応答は明示的に失敗します。書き込みと削除は `wait=true` の適用完了を待ちます。一覧と条件付き削除は期限切れを含む主体候補 1000 件まで完全性を確認し、超過時は `MEMORY_LIST_INCOMPLETE` を返して部分削除しません。主体全体の削除はこの一覧上限の対象外です。
612
682
 
613
- Mem0 + pgvector は全環境で起動を拒否します。SDK が PostgreSQL 接続を私有オブジェクトに保持し、公開された close API がないためです。pgvector は `memory.provider: native` で利用でき、ネイティブの対応は維持します。`disableHistory: true` はリソースを持たない履歴実装を選び、履歴 SQLite ファイルを作成しません。ファクトリーは上限付きの公開読み取りでバックエンドの準備完了を待ってから成功を公開します。
683
+ Qdrant 形式バックエンドは 1.19 以降が必要で、HTTP リダイレクトを拒否します。更新はサーバーの `update_only` と主体・版条件を同じ原子書き込みに適用し、削除済み・同時変更済みの行を拒否します。遅延更新で削除行は復活しません。書き込み後の版確認に失敗した場合は実際の効果を照合してください。
614
684
 
615
- SDK の追加応答には完全な業務フィールドがないため、`add` / `extract` は書き込み後に保存済みレコードを読み取ります。extract は全ての進行中の書き込み完了を待ちます。書き込みまたは再読み取り失敗時、`error.ext.requiresEffectReconciliation=true` と既知の ID の `memoryIds` を返します(応答消失時は空の場合もあります)。主体の実データを照合してから復旧し、add/extract を無条件に繰り返さないでください。自動再実行は行いません。
685
+ 追加書き込みの応答には完全な業務フィールドがないため、`add` / `extract` は書き込み後に保存済みレコードを読み取ります。extract は全ての進行中の書き込み完了を待ちます。書き込みまたは再読み取り失敗時、`error.ext.requiresEffectReconciliation=true` と既知の ID の `memoryIds` を返します(応答消失時は空の場合もあります)。主体の実データを照合してから復旧し、add/extract を無条件に繰り返さないでください。自動再実行は行いません。
616
686
 
617
687
  **候補集合と scope の検索漏れ**:`topK` で先に切り捨てると、別の話題・人格の関連性が高い記憶が対象 scope を押し出します。そのため `recall` / `injectMemories` は `topK × candidateMultiplier`(既定 5)件を取得してから絞り、`topK` 件にします。`topicId` + `personaId` など細かく分離する場合は `candidateMultiplier` を増やせます:
618
688