@h-ai/ai 1.0.0-beta.24 → 1.0.0-beta.25
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 +164 -1
- package/README.ja.md +164 -1
- package/README.md +164 -1
- package/dist/{ai-acp-types-B99Oa7WD.d.ts → ai-acp-types-Bwp6PcL8.d.ts} +29 -3
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +1 -1
- package/dist/{chunk-3G4ZLXH4.js → chunk-VEWBD2J4.js} +5 -2
- package/dist/chunk-VEWBD2J4.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +663 -353
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
- package/tools/README.md +43 -6
- package/dist/chunk-3G4ZLXH4.js.map +0 -1
package/README.en.md
CHANGED
|
@@ -55,7 +55,7 @@ Call fragments reuse the initialized service from this page. Named variables sta
|
|
|
55
55
|
| `ai.llm.chatStream` | Stream completion | `same ChatCompletionRequest` | `AsyncIterable<ChatCompletionChunk>; iteration may throw` | `ai.llm.chatStream({ messages })` |
|
|
56
56
|
| `ai.llm.ask` | Text answer | `question: string, AskOptions?` | `string answer` | `ai.llm.ask("解释共享状态")` |
|
|
57
57
|
| `ai.llm.askStream` | Text stream | `question: string, AskOptions?` | `AsyncIterable<string>` | `ai.llm.askStream("解释共享状态")` |
|
|
58
|
-
| `ai.llm.generateObject` | Schema-constrained answer | `Zod schema, messages, model?, maxRepairs?, signal?`
|
|
58
|
+
| `ai.llm.generateObject` | Schema-constrained answer | `Zod schema, messages, model?, responseFormat?, maxRepairs?, signal?` | `schema-inferred T` | `ai.llm.generateObject({ schema: AnswerSchema, messages })` |
|
|
59
59
|
| `ai.llm.listModels` | List models | `none` | `string[] model IDs` | `ai.llm.listModels()` |
|
|
60
60
|
| `ai.llm.getHistory` | Read history | `{ objectId, sessionId }, { limit?, order? }?` | `ChatRecord[]` | `ai.llm.getHistory({ objectId: "u1", sessionId: "s1" })` |
|
|
61
61
|
| `ai.llm.listSessions` | Subject sessions | `objectId: string` | `SessionInfo[]` | `ai.llm.listSessions("u1")` |
|
|
@@ -323,6 +323,29 @@ const temp = await ai.llm.chat({
|
|
|
323
323
|
|
|
324
324
|
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.
|
|
325
325
|
|
|
326
|
+
##### Structured output with `ai.llm.generateObject`
|
|
327
|
+
|
|
328
|
+
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.
|
|
329
|
+
|
|
330
|
+
```ts
|
|
331
|
+
import { ai } from '@h-ai/ai'
|
|
332
|
+
import { z } from 'zod'
|
|
333
|
+
|
|
334
|
+
// AI is initialized with a text model that supports generic JSON mode.
|
|
335
|
+
const result = await ai.llm.generateObject({
|
|
336
|
+
schema: z.object({
|
|
337
|
+
title: z.string()
|
|
338
|
+
}), // Require an object with a string title.
|
|
339
|
+
messages: [
|
|
340
|
+
{ role: 'user', content: 'Suggest a title for a release checklist.' }
|
|
341
|
+
], // Input for this request.
|
|
342
|
+
responseFormat: 'json_object', // Request generic JSON while keeping local Zod validation.
|
|
343
|
+
maxRepairs: 1, // Allow one repair after a parse or validation failure.
|
|
344
|
+
})
|
|
345
|
+
if (result.success)
|
|
346
|
+
process.stdout.write(result.data.title) // For example, Release checklist.
|
|
347
|
+
```
|
|
348
|
+
|
|
326
349
|
#### Tool calls
|
|
327
350
|
|
|
328
351
|
```ts
|
|
@@ -383,6 +406,69 @@ ACP runs in the Node service. Ordinary methods return HaiResult and stream failu
|
|
|
383
406
|
|
|
384
407
|
Managed Git rejects submodules and Git LFS attributes with ACP_UNSUPPORTED instead of reporting incomplete checkouts as ready.
|
|
385
408
|
|
|
409
|
+
##### Run managed ACP for an authenticated user
|
|
410
|
+
|
|
411
|
+
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.
|
|
412
|
+
|
|
413
|
+
`task` starts a dedicated worker for the session. `user` may reuse a worker when the principal and startup settings match. `auto` selects a mode using application policy. `shared` is available to adapters explicitly approved for sharing with a read-only profile and without private context, workspaces, or tools. The built-in Codex, DeepSeek Harness, and Goose adapters use dedicated modes. See the [ACP configuration example](../../docs/usage/configuration/ai.md#acp-接入与模型能力).
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
import type { RunnerScope } from '@h-ai/runner' // tenantId and userId come from an authenticated application session.
|
|
417
|
+
import { ai } from '@h-ai/ai' // Use the server instance initialized with Runner.
|
|
418
|
+
|
|
419
|
+
async function summarize(identity: RunnerScope, requestId: string) {
|
|
420
|
+
const agent = ai.acp.scoped(identity) // Bind task, session, and approval access to this principal.
|
|
421
|
+
const options = {
|
|
422
|
+
agentId: 'assistant',
|
|
423
|
+
execution: { mode: 'auto' as const }
|
|
424
|
+
} // assistant is a registered agent.
|
|
425
|
+
const plan = await agent.plan(options) // Returns the effective mode, environment, model, and resources without claiming a container.
|
|
426
|
+
if (!plan.success)
|
|
427
|
+
return plan // Stop before submission when the environment or permissions do not match.
|
|
428
|
+
const result = await agent.run({ ...options, prompt: 'List three release checks', idempotencyKey: requestId }) // Returns taskId, output, and effective options.
|
|
429
|
+
if (!result.success)
|
|
430
|
+
return result // Preserve the HaiResult error on submission, execution, or cleanup failure.
|
|
431
|
+
const events = await agent.tasks.events(result.data.taskId, 0, 20) // Read the first 20 durable events, or [] when empty.
|
|
432
|
+
if (!events.success)
|
|
433
|
+
return events
|
|
434
|
+
return { result: result.data, events: events.data } // For example, output.text contains the answer and events are ordered by sequence.
|
|
435
|
+
}
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
import type { RunnerScope } from '@h-ai/runner' // The server-authenticated principal.
|
|
440
|
+
import { ai } from '@h-ai/ai' // assistant is registered and supports worker reuse within a user.
|
|
441
|
+
|
|
442
|
+
async function continueWork(identity: RunnerScope) {
|
|
443
|
+
const agent = ai.acp.scoped(identity) // Access is bound to this principal.
|
|
444
|
+
const created = await agent.sessions.create({
|
|
445
|
+
agentId: 'assistant',
|
|
446
|
+
execution: { mode: 'user' }
|
|
447
|
+
}) // Success yields a session handle with an id.
|
|
448
|
+
if (!created.success)
|
|
449
|
+
return created
|
|
450
|
+
const session = created.data // The handle exposes prompt, stream, changeExecution, and close.
|
|
451
|
+
const run = async () => {
|
|
452
|
+
const first = await session.prompt('Record the acceptance criteria') // Returns this turn's taskId, output, and effective options.
|
|
453
|
+
if (!first.success)
|
|
454
|
+
return first
|
|
455
|
+
const switched = await session.changeExecution({ mode: 'task', acceptNewSession: true }) // Keeps the business id and opens a fresh native session.
|
|
456
|
+
if (!switched.success)
|
|
457
|
+
return switched
|
|
458
|
+
return await session.prompt('Give me an independent acceptance checklist') // The answer is in data.output on success.
|
|
459
|
+
}
|
|
460
|
+
return run().finally(async () => {
|
|
461
|
+
const closed = await session.close() // Success returns data: undefined and releases the session or dedicated environment.
|
|
462
|
+
if (!closed.success)
|
|
463
|
+
throw new Error(closed.error.message)
|
|
464
|
+
})
|
|
465
|
+
}
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
`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.
|
|
469
|
+
|
|
470
|
+
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.
|
|
471
|
+
|
|
386
472
|
#### Configuration and database resource catalogs
|
|
387
473
|
|
|
388
474
|
`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.
|
|
@@ -427,6 +513,81 @@ await server.connect(new StreamableHTTPServerTransport({
|
|
|
427
513
|
}))
|
|
428
514
|
```
|
|
429
515
|
|
|
516
|
+
##### Call remote MCP services and isolated tool jobs
|
|
517
|
+
|
|
518
|
+
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).
|
|
519
|
+
|
|
520
|
+
```ts
|
|
521
|
+
import type { MCPServiceAuthorization } from '@h-ai/ai' // Build the principal and the parameter-aware authorization callback from IAM.
|
|
522
|
+
import { ai } from '@h-ai/ai' // The initialized server has registered manual and office services.
|
|
523
|
+
|
|
524
|
+
async function searchManual(access: MCPServiceAuthorization, query: string) {
|
|
525
|
+
const result = await ai.mcp.services.invoke({
|
|
526
|
+
serviceId: 'manual',
|
|
527
|
+
tool: 'search_manual',
|
|
528
|
+
arguments: { query }
|
|
529
|
+
}, access) // Returns a standard MCP tool result after catalog and authorization checks.
|
|
530
|
+
if (!result.success)
|
|
531
|
+
return result // Preserve the denial or upstream error.
|
|
532
|
+
return result.data.content // For example, [{ type: 'text', text: '...' }].
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
async function convertDocument(access: MCPServiceAuthorization, fileId: string) {
|
|
536
|
+
const result = await ai.mcp.services.invoke({
|
|
537
|
+
serviceId: 'office',
|
|
538
|
+
tool: 'office.convert',
|
|
539
|
+
arguments: { fileId }
|
|
540
|
+
}, access) // Submit an offline conversion with the authorized object id.
|
|
541
|
+
if (!result.success)
|
|
542
|
+
return result
|
|
543
|
+
return result.data.structuredContent // Example: { fileId: 'pdf-123', name: 'result.pdf' }. Check authorization again on download.
|
|
544
|
+
}
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
```ts
|
|
548
|
+
import type { MCPServiceAuthorization, MCPServiceBrokerOptions } from '@h-ai/ai' // Supply a deployment URL and an authorize callback that rechecks the principal, task, and arguments.
|
|
549
|
+
import { createServer } from 'node:http' // Hosts the example endpoint.
|
|
550
|
+
import { ai } from '@h-ai/ai' // The initialized server has registered the manual service.
|
|
551
|
+
|
|
552
|
+
function mountTools(options: MCPServiceBrokerOptions) {
|
|
553
|
+
const result = ai.mcp.services.createBroker(options) // On success the broker provides bind, handleRequest, and close.
|
|
554
|
+
if (!result.success)
|
|
555
|
+
throw new Error(result.error.message)
|
|
556
|
+
const broker = result.data // Create a broker on each executor.
|
|
557
|
+
const server = createServer((req, res) => {
|
|
558
|
+
void broker.handleRequest(req, res)
|
|
559
|
+
}) // Handle MCP requests on the bound endpoint.
|
|
560
|
+
return { broker, server } // The host listens on its fixed address, protects the transport, and calls broker.close() and server.close() at shutdown.
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
async function bindManual(broker: ReturnType<typeof mountTools>['broker'], principal: MCPServiceAuthorization['principal'], sessionId: string, signal: AbortSignal) {
|
|
564
|
+
const result = await broker.bind({
|
|
565
|
+
principal,
|
|
566
|
+
taskId: sessionId,
|
|
567
|
+
signal,
|
|
568
|
+
tools: [
|
|
569
|
+
{
|
|
570
|
+
id: 'manual_search',
|
|
571
|
+
serviceId: 'manual',
|
|
572
|
+
tool: 'search_manual', // Expose a model-facing name for the catalogued operation.
|
|
573
|
+
description: 'Search authorized manuals', // Description presented to the model.
|
|
574
|
+
inputSchema: {
|
|
575
|
+
type: 'object',
|
|
576
|
+
properties: {
|
|
577
|
+
query: { type: 'string' }
|
|
578
|
+
},
|
|
579
|
+
required: ['query'],
|
|
580
|
+
additionalProperties: false
|
|
581
|
+
}, // Validate call arguments.
|
|
582
|
+
}
|
|
583
|
+
]
|
|
584
|
+
}) // Success returns { servers, revoke }. servers contains this session's short-lived Bearer credential.
|
|
585
|
+
if (!result.success)
|
|
586
|
+
throw new Error(result.error.message)
|
|
587
|
+
return result.data // Return from ACPPlatformPolicy.bindTools. The credential is revoked when the session ends.
|
|
588
|
+
}
|
|
589
|
+
```
|
|
590
|
+
|
|
430
591
|
#### Memory / RAG / Knowledge
|
|
431
592
|
|
|
432
593
|
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.
|
|
@@ -932,6 +1093,8 @@ const memories = await ai.memory.recall('经济发展', {
|
|
|
932
1093
|
|
|
933
1094
|
`ai.config` returns a redacted snapshot without exposing original `apiKey`, `privateKey`, embedded URL credentials, or other secrets.
|
|
934
1095
|
|
|
1096
|
+
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.
|
|
1097
|
+
|
|
935
1098
|
## Error Handling
|
|
936
1099
|
|
|
937
1100
|
```ts
|
package/README.ja.md
CHANGED
|
@@ -55,7 +55,7 @@ direct・AsyncIterable・直接の Promise 値と記載したもの以外、出
|
|
|
55
55
|
| `ai.llm.chatStream` | 増分応答 | `same ChatCompletionRequest` | `AsyncIterable<ChatCompletionChunk>; iteration may throw` | `ai.llm.chatStream({ messages })` |
|
|
56
56
|
| `ai.llm.ask` | テキスト応答 | `question: string, AskOptions?` | `string answer` | `ai.llm.ask("解释共享状态")` |
|
|
57
57
|
| `ai.llm.askStream` | テキストストリーム | `question: string, AskOptions?` | `AsyncIterable<string>` | `ai.llm.askStream("解释共享状态")` |
|
|
58
|
-
| `ai.llm.generateObject` | Schema 制約付き応答 | `Zod schema, messages, model?, maxRepairs?, signal?`
|
|
58
|
+
| `ai.llm.generateObject` | Schema 制約付き応答 | `Zod schema, messages, model?, responseFormat?, maxRepairs?, signal?` | `schema-inferred T` | `ai.llm.generateObject({ schema: AnswerSchema, messages })` |
|
|
59
59
|
| `ai.llm.listModels` | モデル一覧 | `none` | `string[] model IDs` | `ai.llm.listModels()` |
|
|
60
60
|
| `ai.llm.getHistory` | 会話履歴 | `{ objectId, sessionId }, { limit?, order? }?` | `ChatRecord[]` | `ai.llm.getHistory({ objectId: "u1", sessionId: "s1" })` |
|
|
61
61
|
| `ai.llm.listSessions` | 主体の会話一覧 | `objectId: string` | `SessionInfo[]` | `ai.llm.listSessions("u1")` |
|
|
@@ -323,6 +323,29 @@ const temp = await ai.llm.chat({
|
|
|
323
323
|
|
|
324
324
|
SSE は [WHATWG のイベントストリーム規則](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation)に従い、分割された LF/CRLF/CR、複数 data 行、コロン直後の空白一つ、id/retry の継承、既定の message を扱います。EOF の未完了イベントは配信しません。encodeSSE は data の改行を正規化し、不正なメタデータは明示的に例外を返します。Anthropic/MiMo は UTF-8 reader を共有し、終了・取消・失敗時に本文を取消して解放します。自動再接続や業務再実行は行わず、Anthropic の timeout は本文まで、MiMo は各 HTTP リクエスト単位で適用します。
|
|
325
325
|
|
|
326
|
+
##### `ai.llm.generateObject` で構造化出力を得る
|
|
327
|
+
|
|
328
|
+
モデルまたはゲートウェイの対応機能に合わせて `responseFormat` を選びます。既定の `json_schema` は厳密な JSON Schema を上流へ送ります。`schemaName` はこの方式だけで使い、既定値は `result` です。汎用 JSON モードの Chat ゲートウェイには `json_object` を指定し、フレームワークが Schema をプロンプトに含めます。両方式とも同じ Zod Schema でローカル検証を行います。解析・検証に失敗したときの修復回数は `maxRepairs` で制御し、既定は 1 回です。
|
|
329
|
+
|
|
330
|
+
```ts
|
|
331
|
+
import { ai } from '@h-ai/ai'
|
|
332
|
+
import { z } from 'zod'
|
|
333
|
+
|
|
334
|
+
// 汎用 JSON モードに対応するテキストモデルで AI を初期化済み。
|
|
335
|
+
const result = await ai.llm.generateObject({
|
|
336
|
+
schema: z.object({
|
|
337
|
+
title: z.string()
|
|
338
|
+
}), // title 文字列を持つオブジェクトを要求する。
|
|
339
|
+
messages: [
|
|
340
|
+
{ role: 'user', content: 'リリース確認表のタイトルを考えてください。' }
|
|
341
|
+
], // 今回の入力。
|
|
342
|
+
responseFormat: 'json_object', // 汎用 JSON を要求し、Zod でローカル検証する。
|
|
343
|
+
maxRepairs: 1, // 解析または検証の失敗後に 1 回だけ修復を試す。
|
|
344
|
+
})
|
|
345
|
+
if (result.success)
|
|
346
|
+
process.stdout.write(result.data.title) // 例: リリース確認表。
|
|
347
|
+
```
|
|
348
|
+
|
|
326
349
|
#### ツール呼び出し
|
|
327
350
|
|
|
328
351
|
```ts
|
|
@@ -383,6 +406,69 @@ ACP は Node サービスで実行します。通常の API は HaiResult を返
|
|
|
383
406
|
|
|
384
407
|
管理対象 Git でサブモジュールや Git LFS 属性を検出すると ACP_UNSUPPORTED を返し、不完全な内容を準備完了として扱いません。
|
|
385
408
|
|
|
409
|
+
##### 認証済みユーザーの管理対象 ACP を実行する
|
|
410
|
+
|
|
411
|
+
RelDB と [Runner](../runner/README.ja.md) を起動し、起動済みのインスタンスを `ai.init(config, { runner, acpPolicy })` に渡します。`acp.agents` に Agent を登録し、`environmentIds` で固定イメージの Runner 環境を、`modelIds` で `llm.models` のモデルを指定します。Codex には Responses ゲートウェイが必要です。API ノードと実行ノードではデータベースと環境定義を揃えます。終了時は AI、Runner、データベースの順に閉じます。
|
|
412
|
+
|
|
413
|
+
`task` はそのセッション用の専用 Worker を起動します。`user` は主体と起動設定が一致する場合に Worker を再利用できます。`auto` はアプリのポリシーに基づいて選択します。`shared` を利用できるのは、共有を明示的に承認した読み取り専用アダプターで、非公開コンテキスト、ワークスペース、ツールを要求しない場合です。組み込みの Codex、DeepSeek Harness、Goose は専用モードを使用します。[ACP 設定例](../../docs/usage/configuration/ai.md#acp-接入与模型能力)
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
import type { RunnerScope } from '@h-ai/runner' // 認証済みアプリセッションから tenantId と userId を取得する。
|
|
417
|
+
import { ai } from '@h-ai/ai' // Runner を渡して初期化済みのサーバーインスタンス。
|
|
418
|
+
|
|
419
|
+
async function summarize(identity: RunnerScope, requestId: string) {
|
|
420
|
+
const agent = ai.acp.scoped(identity) // 以降のジョブ、セッション、承認をこの主体に紐づける。
|
|
421
|
+
const options = {
|
|
422
|
+
agentId: 'assistant',
|
|
423
|
+
execution: { mode: 'auto' as const }
|
|
424
|
+
} // assistant は登録済み Agent。
|
|
425
|
+
const plan = await agent.plan(options) // コンテナを取得せず、有効なモード、環境、モデル、リソースを返す。
|
|
426
|
+
if (!plan.success)
|
|
427
|
+
return plan // 環境や権限が合わない場合は投入しない。
|
|
428
|
+
const result = await agent.run({ ...options, prompt: 'リリースの確認項目を三つ挙げて', idempotencyKey: requestId }) // taskId、output、有効なオプションを返す。
|
|
429
|
+
if (!result.success)
|
|
430
|
+
return result // 投入、実行、後片付けの失敗を HaiResult として返す。
|
|
431
|
+
const events = await agent.tasks.events(result.data.taskId, 0, 20) // 最初の 20 イベントを読み、空なら []。
|
|
432
|
+
if (!events.success)
|
|
433
|
+
return events
|
|
434
|
+
return { result: result.data, events: events.data } // 例として output.text に回答、events に順序付きのイベントが入る。
|
|
435
|
+
}
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
import type { RunnerScope } from '@h-ai/runner' // サーバーで認証した主体。
|
|
440
|
+
import { ai } from '@h-ai/ai' // assistant を登録し、同じユーザー内の Worker 再利用が可能とする。
|
|
441
|
+
|
|
442
|
+
async function continueWork(identity: RunnerScope) {
|
|
443
|
+
const agent = ai.acp.scoped(identity) // アクセスをこの主体に紐づける。
|
|
444
|
+
const created = await agent.sessions.create({
|
|
445
|
+
agentId: 'assistant',
|
|
446
|
+
execution: { mode: 'user' }
|
|
447
|
+
}) // 成功時は id 付きのセッションハンドル。
|
|
448
|
+
if (!created.success)
|
|
449
|
+
return created
|
|
450
|
+
const session = created.data // prompt、stream、changeExecution、close が使える。
|
|
451
|
+
const run = async () => {
|
|
452
|
+
const first = await session.prompt('受け入れ条件を記録して') // このターンの taskId、output、有効なオプションを返す。
|
|
453
|
+
if (!first.success)
|
|
454
|
+
return first
|
|
455
|
+
const switched = await session.changeExecution({ mode: 'task', acceptNewSession: true }) // 業務上の id を維持し、新しいネイティブセッションを開始する。
|
|
456
|
+
if (!switched.success)
|
|
457
|
+
return switched
|
|
458
|
+
return await session.prompt('独立した受け入れチェックリストを出して') // 成功時の回答は data.output。
|
|
459
|
+
}
|
|
460
|
+
return run().finally(async () => {
|
|
461
|
+
const closed = await session.close() // 成功時の data は undefined。セッションまたは専用環境を解放する。
|
|
462
|
+
if (!closed.success)
|
|
463
|
+
throw new Error(closed.error.message)
|
|
464
|
+
})
|
|
465
|
+
}
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
`agents.describe(agentId)` で組み込みアダプターの機能を確認できます。`sessions.get(id)` は同じ主体が別の API ノードからハンドルを取得するために使います。`session.stream(prompt, options)` は保存済みイベントを順に返し、失敗時は例外を送出します。`tasks.get(taskId)` は実行受付票、`tasks.cancel(taskId)` はキャンセル受理後の状態を返します。`run` や `prompt` の `onEvent` に届く `accepted` イベントから `taskId` を取得し、別のリクエストで照会やキャンセルを行えます。
|
|
469
|
+
|
|
470
|
+
`acpPolicy` で `workspaceId` のスナップショット、ナレッジ、メモリ、ファイル、スキル、ツールを認可します。下記の MCP 入口には `allowTools` と `bindTools` を使います。`approval` イベントの `approvalId` に対して、同じ主体で `approvals.respond(id, 'allow-once' | 'allow-session' | 'always-allow' | 'deny')` を呼びます。成功時は `undefined` です。`approvals.rules(offset, limit)` は `expiresAt` を持つ有効なルールをページ取得し、`approvals.revoke(ruleId)` は主体自身のルールを取り消します。`full-access` にはアプリの明示的な承認と `task` モードが必要です。ワークスペースは読み取り専用スナップショットです。モード切り替え時にユーザーが確認した `historySummary` を渡せます。[管理対象 ACP の利用例](../../docs/usage/development/ai-acp.md#多用户应用的受管调用)
|
|
471
|
+
|
|
386
472
|
#### 設定とデータベースのリソース一覧
|
|
387
473
|
|
|
388
474
|
`llm.models`、`audio.models`、`image.models`、`mcp.servers`、`retrieval.sources`、`acp.agents/workspaces` は設定と DB を統合します。同じ ID は設定を優先し、設定は読み取り専用です。DB は list/get/register/update/remove に対応し、value/source/version と任意のバージョン照合を使用します。非同期呼び出しは最新の定義を読み、同期音声機能照会は直近のローカル情報を使います。エラーは 090–094。定義には認証情報が含まれるため、信頼できるサーバー管理 API として使用します。
|
|
@@ -427,6 +513,81 @@ await server.connect(new StreamableHTTPServerTransport({
|
|
|
427
513
|
}))
|
|
428
514
|
```
|
|
429
515
|
|
|
516
|
+
##### リモート MCP と独立ツールジョブを呼び出す
|
|
517
|
+
|
|
518
|
+
`mcp.servers` の `transport: http` に外部 Streamable HTTP の URL と `allowedTools` を登録します。認証には `headerEnv` からサーバーの環境変数を参照します。`transport: job` では同じ API からオフラインの文書、Office、OCR を実行できます。`environmentId`、許可する操作、任意の `pool` を設定し、Runner と `mcpJobFiles` を `ai.init` に渡します。ジョブには認可済みの `fileId` を渡します。実行ノードがアクセス権を再確認し、成果物をオブジェクト ID で返します。ブラウザーイメージは独立して運用します。[MCP の設定](../../docs/usage/configuration/ai.md#mcp和a2a) · [ツールイメージ](tools/README.md)
|
|
519
|
+
|
|
520
|
+
```ts
|
|
521
|
+
import type { MCPServiceAuthorization } from '@h-ai/ai' // IAM に基づく主体と、実際の引数を検証する認可コールバックを渡す。
|
|
522
|
+
import { ai } from '@h-ai/ai' // manual と office を登録済みのサーバーインスタンス。
|
|
523
|
+
|
|
524
|
+
async function searchManual(access: MCPServiceAuthorization, query: string) {
|
|
525
|
+
const result = await ai.mcp.services.invoke({
|
|
526
|
+
serviceId: 'manual',
|
|
527
|
+
tool: 'search_manual',
|
|
528
|
+
arguments: { query }
|
|
529
|
+
}, access) // 登録と認可を確認し、標準の MCP ツール結果を返す。
|
|
530
|
+
if (!result.success)
|
|
531
|
+
return result // 拒否または上流サービスの失敗を返す。
|
|
532
|
+
return result.data.content // 例: [{ type: 'text', text: '...' }]。
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
async function convertDocument(access: MCPServiceAuthorization, fileId: string) {
|
|
536
|
+
const result = await ai.mcp.services.invoke({
|
|
537
|
+
serviceId: 'office',
|
|
538
|
+
tool: 'office.convert',
|
|
539
|
+
arguments: { fileId }
|
|
540
|
+
}, access) // 認可済みオブジェクト ID でオフライン変換を投入する。
|
|
541
|
+
if (!result.success)
|
|
542
|
+
return result
|
|
543
|
+
return result.data.structuredContent // 例: { fileId: 'pdf-123', name: 'result.pdf' }。ダウンロード時に再認可する。
|
|
544
|
+
}
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
```ts
|
|
548
|
+
import type { MCPServiceAuthorization, MCPServiceBrokerOptions } from '@h-ai/ai' // デプロイ時の URL と、主体・ジョブ・引数を再確認する authorize を渡す。
|
|
549
|
+
import { createServer } from 'node:http' // 例の HTTP 入口を作成する。
|
|
550
|
+
import { ai } from '@h-ai/ai' // manual を登録済みのサーバーインスタンス。
|
|
551
|
+
|
|
552
|
+
function mountTools(options: MCPServiceBrokerOptions) {
|
|
553
|
+
const result = ai.mcp.services.createBroker(options) // 成功時は bind、handleRequest、close を提供する。
|
|
554
|
+
if (!result.success)
|
|
555
|
+
throw new Error(result.error.message)
|
|
556
|
+
const broker = result.data // 各実行ノードで Broker を作る。
|
|
557
|
+
const server = createServer((req, res) => {
|
|
558
|
+
void broker.handleRequest(req, res)
|
|
559
|
+
}) // 入口の MCP リクエストを処理する。
|
|
560
|
+
return { broker, server } // ホストが固定アドレスを待ち受け、通信を保護し、終了時に broker.close() と server.close() を呼ぶ。
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
async function bindManual(broker: ReturnType<typeof mountTools>['broker'], principal: MCPServiceAuthorization['principal'], sessionId: string, signal: AbortSignal) {
|
|
564
|
+
const result = await broker.bind({
|
|
565
|
+
principal,
|
|
566
|
+
taskId: sessionId,
|
|
567
|
+
signal,
|
|
568
|
+
tools: [
|
|
569
|
+
{
|
|
570
|
+
id: 'manual_search',
|
|
571
|
+
serviceId: 'manual',
|
|
572
|
+
tool: 'search_manual', // モデルに表示する名前と登録済みの操作名を設定する。
|
|
573
|
+
description: 'Search authorized manuals', // モデルに渡す説明。
|
|
574
|
+
inputSchema: {
|
|
575
|
+
type: 'object',
|
|
576
|
+
properties: {
|
|
577
|
+
query: { type: 'string' }
|
|
578
|
+
},
|
|
579
|
+
required: ['query'],
|
|
580
|
+
additionalProperties: false
|
|
581
|
+
}, // 呼び出し時に引数を検証する。
|
|
582
|
+
}
|
|
583
|
+
]
|
|
584
|
+
}) // 成功時は { servers, revoke }。servers に現在のセッション用の短期 Bearer が入る。
|
|
585
|
+
if (!result.success)
|
|
586
|
+
throw new Error(result.error.message)
|
|
587
|
+
return result.data // ACPPlatformPolicy.bindTools から返す。セッション終了時に資格情報が無効になる。
|
|
588
|
+
}
|
|
589
|
+
```
|
|
590
|
+
|
|
430
591
|
#### Memory / RAG / Knowledge
|
|
431
592
|
|
|
432
593
|
native 記憶の削除は管理者の全削除を含め、先にベクトルを削除してから権威レコードを削除します。ベクトル削除失敗時は再試行用にレコードを保持します。SQL とベクトルは同じトランザクションではないため、後段の失敗時も状態確認が必要です。
|
|
@@ -932,6 +1093,8 @@ const memories = await ai.memory.recall('经济发展', {
|
|
|
932
1093
|
|
|
933
1094
|
`ai.config` はマスク済み設定を返し、`apiKey`、`privateKey`、URL 内認証情報などをそのまま公開しません。
|
|
934
1095
|
|
|
1096
|
+
ネイティブメモリの追加は、共有データベースのトランザクション内で主体別と全体の上限を確認します。古い候補を一度に最大 64 件読み出し、重要度と経過時間から削除対象を選びます。既存データが上限を超えている間は、追加前に分割して整理します。カスタム共有 Store では `AIRelStore.withWriteLock` によって同じノード間の保証を提供できます。
|
|
1097
|
+
|
|
935
1098
|
## エラー処理
|
|
936
1099
|
|
|
937
1100
|
```ts
|
package/README.md
CHANGED
|
@@ -55,7 +55,7 @@ finally {
|
|
|
55
55
|
| `ai.llm.chatStream` | 逐块回答 | `same ChatCompletionRequest` | `AsyncIterable<ChatCompletionChunk>; iteration may throw` | `ai.llm.chatStream({ messages })` |
|
|
56
56
|
| `ai.llm.ask` | 纯文本问答 | `question: string, AskOptions?` | `string answer` | `ai.llm.ask("解释共享状态")` |
|
|
57
57
|
| `ai.llm.askStream` | 纯文本流 | `question: string, AskOptions?` | `AsyncIterable<string>` | `ai.llm.askStream("解释共享状态")` |
|
|
58
|
-
| `ai.llm.generateObject` | 受 Schema 约束的答案 | `Zod schema, messages, model?, maxRepairs?, signal?`
|
|
58
|
+
| `ai.llm.generateObject` | 受 Schema 约束的答案 | `Zod schema, messages, model?, responseFormat?, maxRepairs?, signal?` | `schema-inferred T` | `ai.llm.generateObject({ schema: AnswerSchema, messages })` |
|
|
59
59
|
| `ai.llm.listModels` | 查询模型 | `none` | `string[] model IDs` | `ai.llm.listModels()` |
|
|
60
60
|
| `ai.llm.getHistory` | 读取对话历史 | `{ objectId, sessionId }, { limit?, order? }?` | `ChatRecord[]` | `ai.llm.getHistory({ objectId: "u1", sessionId: "s1" })` |
|
|
61
61
|
| `ai.llm.listSessions` | 列出主体会话 | `objectId: string` | `SessionInfo[]` | `ai.llm.listSessions("u1")` |
|
|
@@ -344,6 +344,29 @@ const temp = await ai.llm.chat({
|
|
|
344
344
|
|
|
345
345
|
SSE 文本解码遵循 [WHATWG 事件流规则](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation):LF/CRLF/CR 跨片、多行 data、仅去冒号后一个空格、继承有效 id/retry;空或缺省 event 按 message,EOF 不补空行派发残余事件。encodeSSE 规范化 data 换行,并对 id/event 换行、id 的 NUL 或无效 retry 显式抛错。Anthropic/MiMo 共用内部 UTF-8 流读取;消费方退出、取消、协议结束和失败均取消正文并释放 reader,不自动重连或重放业务。Anthropic timeout 覆盖正文,MiMo 保留每个 HTTP 请求的独立 timeout。
|
|
346
346
|
|
|
347
|
+
##### 结构化输出:`ai.llm.generateObject`
|
|
348
|
+
|
|
349
|
+
按模型或网关的响应能力选择 `responseFormat`。默认 `json_schema` 向上游发送严格 JSON Schema,`schemaName` 只用于此模式,默认 `result`。仅支持通用 JSON 的 Chat 网关使用 `json_object`,框架将 Schema 放入提示词。两种模式都在本地用同一个 Zod Schema 校验,解析或校验失败时可按 `maxRepairs` 修复,默认一次。
|
|
350
|
+
|
|
351
|
+
```ts
|
|
352
|
+
import { ai } from '@h-ai/ai'
|
|
353
|
+
import { z } from 'zod'
|
|
354
|
+
|
|
355
|
+
// 已初始化 AI,llm 使用支持通用 JSON 模式的文本模型。
|
|
356
|
+
const result = await ai.llm.generateObject({
|
|
357
|
+
schema: z.object({
|
|
358
|
+
title: z.string()
|
|
359
|
+
}), // 要求返回含 title 字符串的对象。
|
|
360
|
+
messages: [
|
|
361
|
+
{ role: 'user', content: '为发布检查表生成标题。' }
|
|
362
|
+
], // 本次输入。
|
|
363
|
+
responseFormat: 'json_object', // 请求通用 JSON,仍会执行本地 Zod 校验。
|
|
364
|
+
maxRepairs: 1, // 解析或校验失败时允许再请求一次。
|
|
365
|
+
})
|
|
366
|
+
if (result.success)
|
|
367
|
+
process.stdout.write(result.data.title) // 例如:发布检查表。
|
|
368
|
+
```
|
|
369
|
+
|
|
347
370
|
#### 工具调用
|
|
348
371
|
|
|
349
372
|
```ts
|
|
@@ -402,6 +425,69 @@ Goose 1.57.0 镜像提供原生 `goose serve` HTTP/WS `/acp` 服务,通过 cus
|
|
|
402
425
|
|
|
403
426
|
托管 Git 遇到子模块或 Git LFS 属性时明确返回 ACP_UNSUPPORTED,避免将不完整工程报告为就绪。
|
|
404
427
|
|
|
428
|
+
##### 按用户运行受管 ACP
|
|
429
|
+
|
|
430
|
+
服务启动时先初始化 RelDB 和 [Runner](../runner/README.md),再将已启动的实例传给 `ai.init(config, { runner, acpPolicy })`。在 `acp.agents` 注册 Agent,并用 `environmentIds` 绑定 Runner 的固定镜像环境,用 `modelIds` 绑定 `llm.models` 的模型。Codex 需要 Responses 网关。API 和执行节点使用共享数据库与相同环境定义。关闭服务时先关闭 AI,再关闭 Runner 和数据库。
|
|
431
|
+
|
|
432
|
+
`task` 为本次会话启动独占 Worker,`user` 可在同一主体与启动配置下复用。`auto` 按策略选择。`shared` 只适用于明确支持共享的只读适配器,且会话不能申请私有上下文、工作区或工具,内置 Codex、DeepSeek Harness 和 Goose 仍使用独立模式。配置示例见 [ACP 配置](../../docs/usage/configuration/ai.md#acp-接入与模型能力)。
|
|
433
|
+
|
|
434
|
+
```ts
|
|
435
|
+
import type { RunnerScope } from '@h-ai/runner' // tenantId 和 userId 来自已认证的应用会话。
|
|
436
|
+
import { ai } from '@h-ai/ai' // 使用已注入 Runner 的服务端实例。
|
|
437
|
+
|
|
438
|
+
async function summarize(identity: RunnerScope, requestId: string) {
|
|
439
|
+
const agent = ai.acp.scoped(identity) // 将后续任务、会话和权限访问绑定到此主体。
|
|
440
|
+
const options = {
|
|
441
|
+
agentId: 'assistant',
|
|
442
|
+
execution: { mode: 'auto' as const }
|
|
443
|
+
} // assistant 是已登记的 Agent。
|
|
444
|
+
const plan = await agent.plan(options) // 返回实际模式、环境、模型和资源设置,不领取容器。
|
|
445
|
+
if (!plan.success)
|
|
446
|
+
return plan // 环境或权限不满足时不提交。
|
|
447
|
+
const result = await agent.run({ ...options, prompt: '列出三条发布检查项', idempotencyKey: requestId }) // 返回 taskId、output 和生效选项。
|
|
448
|
+
if (!result.success)
|
|
449
|
+
return result // 提交、执行或清理失败时返回 HaiResult 错误。
|
|
450
|
+
const events = await agent.tasks.events(result.data.taskId, 0, 20) // 读取前 20 个持久事件,空页为 []。
|
|
451
|
+
if (!events.success)
|
|
452
|
+
return events
|
|
453
|
+
return { result: result.data, events: events.data } // 例如 output.text 是模型回答,events 含按序号排列的事件。
|
|
454
|
+
}
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
```ts
|
|
458
|
+
import type { RunnerScope } from '@h-ai/runner' // 服务端认证主体。
|
|
459
|
+
import { ai } from '@h-ai/ai' // assistant 已登记,并允许在同一用户内复用 Worker。
|
|
460
|
+
|
|
461
|
+
async function continueWork(identity: RunnerScope) {
|
|
462
|
+
const agent = ai.acp.scoped(identity) // 成功访问只限当前主体的资源。
|
|
463
|
+
const created = await agent.sessions.create({
|
|
464
|
+
agentId: 'assistant',
|
|
465
|
+
execution: { mode: 'user' }
|
|
466
|
+
}) // 成功得到含 id 的会话句柄。
|
|
467
|
+
if (!created.success)
|
|
468
|
+
return created
|
|
469
|
+
const session = created.data // 句柄提供 prompt、stream、changeExecution 和 close。
|
|
470
|
+
const run = async () => {
|
|
471
|
+
const first = await session.prompt('记下验收目标') // 返回这一轮的 taskId、output 与生效选项。
|
|
472
|
+
if (!first.success)
|
|
473
|
+
return first
|
|
474
|
+
const switched = await session.changeExecution({ mode: 'task', acceptNewSession: true }) // 保留业务 id,建立新的原生会话。
|
|
475
|
+
if (!switched.success)
|
|
476
|
+
return switched
|
|
477
|
+
return await session.prompt('给出独立验收清单') // 模型回答位于成功结果的 data.output。
|
|
478
|
+
}
|
|
479
|
+
return run().finally(async () => {
|
|
480
|
+
const closed = await session.close() // 成功的 data 为 undefined,释放会话或独占任务环境。
|
|
481
|
+
if (!closed.success)
|
|
482
|
+
throw new Error(closed.error.message)
|
|
483
|
+
})
|
|
484
|
+
}
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
使用 `agents.describe(agentId)` 查询内置适配器的能力,`sessions.get(id)` 由同一主体在其他 API 节点取得句柄,`session.stream(prompt, options)` 迭代持久事件并在失败时抛错。`tasks.get(taskId)` 返回执行回执,`tasks.cancel(taskId)` 接受取消并返回当前状态。可在 `run` 或 `prompt` 的 `onEvent` 中取得 `accepted` 事件的 `taskId`,然后用另一请求查看或取消。
|
|
488
|
+
|
|
489
|
+
`acpPolicy` 负责 `workspaceId` 快照、知识库、记忆、文件、Skills 和工具的业务授权。`allowTools` 与 `bindTools` 可接入下文的 MCP 入口。应用取得 `approval` 事件中的 `approvalId` 后,从同一主体调用 `approvals.respond(id, 'allow-once' | 'allow-session' | 'always-allow' | 'deny')`,成功返回 `undefined`。`approvals.rules(offset, limit)` 分页返回仍可用的规则和 `expiresAt`,`approvals.revoke(ruleId)` 撤销当前主体的规则。`full-access` 需要应用明确允许且使用 `task`。工作区提供只读快照,切换后可按需带入用户确认的 `historySummary`。更多示例见 [受管调用](../../docs/usage/development/ai-acp.md#多用户应用的受管调用)。
|
|
490
|
+
|
|
405
491
|
#### 配置与数据库资源清单
|
|
406
492
|
|
|
407
493
|
`llm.models`、`audio.models`、`image.models`、`mcp.servers`、`retrieval.sources`、`acp.agents/workspaces` 合并配置和数据库。配置同 ID 优先且只读,数据库支持 list/get/register/update/remove;条目返回 value/source/version,更新可检查版本。异步调用读取最新定义,音频同步能力查询使用最近刷新快照。资源错误为 090–094。管理定义可能含模型密钥,仅在可信服务端使用。
|
|
@@ -446,6 +532,81 @@ await server.connect(new StreamableHTTPServerTransport({
|
|
|
446
532
|
}))
|
|
447
533
|
```
|
|
448
534
|
|
|
535
|
+
##### 调用远程 MCP 和独立工具作业
|
|
536
|
+
|
|
537
|
+
在 `mcp.servers` 的 `transport: http` 条目中登记第三方 Streamable HTTP 地址和 `allowedTools`。需要认证时用 `headerEnv` 引用服务器环境变量。`transport: job` 可用同一套调用接口运行离线文档、Office 和 OCR 工具。为作业配置 `environmentId`、允许操作和可选 `pool`,将 Runner 与 `mcpJobFiles` 传给 `ai.init`。作业请求只传已授权的 `fileId`,执行节点再次检查文件权限,产物以对象 ID 返回。浏览器镜像由部署方单独运行。详见 [MCP 配置](../../docs/usage/configuration/ai.md#mcp和a2a) 与 [工具镜像](tools/README.md)。
|
|
538
|
+
|
|
539
|
+
```ts
|
|
540
|
+
import type { MCPServiceAuthorization } from '@h-ai/ai' // 应用从 IAM 构造主体和按实际参数复核权限的回调。
|
|
541
|
+
import { ai } from '@h-ai/ai' // 服务端已初始化,并登记了 manual 与 office 服务。
|
|
542
|
+
|
|
543
|
+
async function searchManual(access: MCPServiceAuthorization, query: string) {
|
|
544
|
+
const result = await ai.mcp.services.invoke({
|
|
545
|
+
serviceId: 'manual',
|
|
546
|
+
tool: 'search_manual',
|
|
547
|
+
arguments: { query }
|
|
548
|
+
}, access) // 目录和授权通过后得到标准 MCP 工具结果。
|
|
549
|
+
if (!result.success)
|
|
550
|
+
return result // 权限拒绝或上游失败时保留错误。
|
|
551
|
+
return result.data.content // 例如 [{ type: 'text', text: '...' }]。
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
async function convertDocument(access: MCPServiceAuthorization, fileId: string) {
|
|
555
|
+
const result = await ai.mcp.services.invoke({
|
|
556
|
+
serviceId: 'office',
|
|
557
|
+
tool: 'office.convert',
|
|
558
|
+
arguments: { fileId }
|
|
559
|
+
}, access) // 用授权对象 ID 提交离线转换。
|
|
560
|
+
if (!result.success)
|
|
561
|
+
return result
|
|
562
|
+
return result.data.structuredContent // 成功示例 { fileId: 'pdf-123', name: 'result.pdf' },下载需再次验权。
|
|
563
|
+
}
|
|
564
|
+
```
|
|
565
|
+
|
|
566
|
+
```ts
|
|
567
|
+
import type { MCPServiceAuthorization, MCPServiceBrokerOptions } from '@h-ai/ai' // url 由部署方指定,authorize 每次检查当前主体、任务和参数。
|
|
568
|
+
import { createServer } from 'node:http' // 提供示例 HTTP 请求入口。
|
|
569
|
+
import { ai } from '@h-ai/ai' // 服务端已初始化,并登记了 manual 服务。
|
|
570
|
+
|
|
571
|
+
function mountTools(options: MCPServiceBrokerOptions) {
|
|
572
|
+
const result = ai.mcp.services.createBroker(options) // 成功返回 bind、handleRequest 和 close。
|
|
573
|
+
if (!result.success)
|
|
574
|
+
throw new Error(result.error.message)
|
|
575
|
+
const broker = result.data // 每个执行节点创建自己的入口。
|
|
576
|
+
const server = createServer((req, res) => {
|
|
577
|
+
void broker.handleRequest(req, res)
|
|
578
|
+
}) // 处理绑定地址上的 MCP 请求。
|
|
579
|
+
return { broker, server } // 宿主监听固定地址并负责传输保护,关闭时调用 broker.close() 和 server.close()。
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
async function bindManual(broker: ReturnType<typeof mountTools>['broker'], principal: MCPServiceAuthorization['principal'], sessionId: string, signal: AbortSignal) {
|
|
583
|
+
const result = await broker.bind({
|
|
584
|
+
principal,
|
|
585
|
+
taskId: sessionId,
|
|
586
|
+
signal,
|
|
587
|
+
tools: [
|
|
588
|
+
{
|
|
589
|
+
id: 'manual_search',
|
|
590
|
+
serviceId: 'manual',
|
|
591
|
+
tool: 'search_manual', // 模型可见名称与清单名称分开配置。
|
|
592
|
+
description: 'Search authorized manuals', // 提供给模型的说明。
|
|
593
|
+
inputSchema: {
|
|
594
|
+
type: 'object',
|
|
595
|
+
properties: {
|
|
596
|
+
query: { type: 'string' }
|
|
597
|
+
},
|
|
598
|
+
required: ['query'],
|
|
599
|
+
additionalProperties: false
|
|
600
|
+
}, // 调用时校验工具参数。
|
|
601
|
+
}
|
|
602
|
+
]
|
|
603
|
+
}) // 成功为 { servers, revoke },servers 含当前会话的短期 Bearer。
|
|
604
|
+
if (!result.success)
|
|
605
|
+
throw new Error(result.error.message)
|
|
606
|
+
return result.data // 可从 ACPPlatformPolicy.bindTools 返回;会话结束时撤销凭据。
|
|
607
|
+
}
|
|
608
|
+
```
|
|
609
|
+
|
|
449
610
|
#### Memory / RAG / Knowledge
|
|
450
611
|
|
|
451
612
|
原生记忆删除(包括管理员全清)先清向量,再删除权威记录;向量清理失败时记录保留以便重试。SQL 与向量后端不共享事务,后一步失败仍需核对当前状态。
|
|
@@ -957,6 +1118,8 @@ const memories = await ai.memory.recall('经济发展', {
|
|
|
957
1118
|
|
|
958
1119
|
`ai.config` 返回脱敏后的配置快照;`apiKey`、`privateKey`、URL 内嵌凭证等敏感字段不会原样暴露。
|
|
959
1120
|
|
|
1121
|
+
原生记忆新增使用共享关系库事务串行检查主体与全局配额。淘汰每次最多读取最旧 64 条候选并按重要性和时效评分。旧库超过配额时,新写入会先回收一批,直到有余量。自定义共享 Store 可实现 `AIRelStore.withWriteLock` 提供同样的跨节点保证。
|
|
1122
|
+
|
|
960
1123
|
## 错误处理
|
|
961
1124
|
|
|
962
1125
|
```ts
|