@h-ai/ai 1.0.0-beta.24 → 1.0.0-beta.26
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 +168 -3
- package/README.ja.md +168 -3
- package/README.md +168 -3
- package/dist/{ai-acp-types-B99Oa7WD.d.ts → ai-acp-types-BYUy6Tyx.d.ts} +33 -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 +1008 -437
- 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
|
|
@@ -377,12 +400,77 @@ The Goose 1.57.0 image exposes its native `goose serve` HTTP/WS `/acp` service t
|
|
|
377
400
|
|
|
378
401
|
Declare verified capacity, modalities and reasoning in `llm.models[].capabilities`. Codex needs native Responses; the existing Hai adapter is not a reverse gateway. Code and state persist after close. CAS ownership is released only after owned processes stop; worktrees are not security sandboxes.
|
|
379
402
|
|
|
403
|
+
For DeepSeek Harness, set `protocol: 'chat'` and `baseUrl: 'https://api.deepseek.com'` to reach the official DeepSeek Chat endpoint. An internal relay can retain the official model ID `deepseek-flash` or `deepseek-v4-pro` to apply the same settings. Harness sends instructions as `system`, uses the DeepSeek output budget field, and preserves `reasoning_content` when sending tool results. [DeepSeek Chat API](https://api-docs.deepseek.com/api/create-chat-completion/)
|
|
404
|
+
|
|
380
405
|
Build an Agent image with `minimal`, `documents`, `office`, `browser`, or `developer`. The default includes Git, Node, and the native Agent. Codex also includes bubblewrap. Register a local image ID or remote manifest digest for the execution environment. [Agent images](models/agents/README.md)
|
|
381
406
|
|
|
382
407
|
ACP runs in the Node service. Ordinary methods return HaiResult and stream failures throw. [ACP guide](../cli/templates/skills/hai-ai/acp.md)
|
|
383
408
|
|
|
384
409
|
Managed Git rejects submodules and Git LFS attributes with ACP_UNSUPPORTED instead of reporting incomplete checkouts as ready.
|
|
385
410
|
|
|
411
|
+
##### Run managed ACP for an authenticated user
|
|
412
|
+
|
|
413
|
+
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.
|
|
414
|
+
|
|
415
|
+
`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-接入与模型能力).
|
|
416
|
+
|
|
417
|
+
```ts
|
|
418
|
+
import type { RunnerScope } from '@h-ai/runner' // tenantId and userId come from an authenticated application session.
|
|
419
|
+
import { ai } from '@h-ai/ai' // Use the server instance initialized with Runner.
|
|
420
|
+
|
|
421
|
+
async function summarize(identity: RunnerScope, requestId: string) {
|
|
422
|
+
const agent = ai.acp.scoped(identity) // Bind task, session, and approval access to this principal.
|
|
423
|
+
const options = {
|
|
424
|
+
agentId: 'assistant',
|
|
425
|
+
execution: { mode: 'auto' as const }
|
|
426
|
+
} // assistant is a registered agent.
|
|
427
|
+
const plan = await agent.plan(options) // Returns the effective mode, environment, model, and resources without claiming a container.
|
|
428
|
+
if (!plan.success)
|
|
429
|
+
return plan // Stop before submission when the environment or permissions do not match.
|
|
430
|
+
const result = await agent.run({ ...options, prompt: 'List three release checks', idempotencyKey: requestId }) // Returns taskId, output, and effective options.
|
|
431
|
+
if (!result.success)
|
|
432
|
+
return result // Preserve the HaiResult error on submission, execution, or cleanup failure.
|
|
433
|
+
const events = await agent.tasks.events(result.data.taskId, 0, 20) // Read the first 20 durable events, or [] when empty.
|
|
434
|
+
if (!events.success)
|
|
435
|
+
return events
|
|
436
|
+
return { result: result.data, events: events.data } // For example, output.text contains the answer and events are ordered by sequence.
|
|
437
|
+
}
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
```ts
|
|
441
|
+
import type { RunnerScope } from '@h-ai/runner' // The server-authenticated principal.
|
|
442
|
+
import { ai } from '@h-ai/ai' // assistant is registered and supports worker reuse within a user.
|
|
443
|
+
|
|
444
|
+
async function continueWork(identity: RunnerScope) {
|
|
445
|
+
const agent = ai.acp.scoped(identity) // Access is bound to this principal.
|
|
446
|
+
const created = await agent.sessions.create({
|
|
447
|
+
agentId: 'assistant',
|
|
448
|
+
execution: { mode: 'user' }
|
|
449
|
+
}) // Success yields a session handle with an id.
|
|
450
|
+
if (!created.success)
|
|
451
|
+
return created
|
|
452
|
+
const session = created.data // The handle exposes prompt, stream, changeExecution, and close.
|
|
453
|
+
const run = async () => {
|
|
454
|
+
const first = await session.prompt('Record the acceptance criteria') // Returns this turn's taskId, output, and effective options.
|
|
455
|
+
if (!first.success)
|
|
456
|
+
return first
|
|
457
|
+
const switched = await session.changeExecution({ mode: 'task', acceptNewSession: true }) // Keeps the business id and opens a fresh native session.
|
|
458
|
+
if (!switched.success)
|
|
459
|
+
return switched
|
|
460
|
+
return await session.prompt('Give me an independent acceptance checklist') // The answer is in data.output on success.
|
|
461
|
+
}
|
|
462
|
+
return run().finally(async () => {
|
|
463
|
+
const closed = await session.close() // Success returns data: undefined and releases the session or dedicated environment.
|
|
464
|
+
if (!closed.success)
|
|
465
|
+
throw new Error(closed.error.message)
|
|
466
|
+
})
|
|
467
|
+
}
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
`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.
|
|
471
|
+
|
|
472
|
+
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.
|
|
473
|
+
|
|
386
474
|
#### Configuration and database resource catalogs
|
|
387
475
|
|
|
388
476
|
`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,11 +515,86 @@ await server.connect(new StreamableHTTPServerTransport({
|
|
|
427
515
|
}))
|
|
428
516
|
```
|
|
429
517
|
|
|
518
|
+
##### Call remote MCP services and isolated tool jobs
|
|
519
|
+
|
|
520
|
+
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).
|
|
521
|
+
|
|
522
|
+
```ts
|
|
523
|
+
import type { MCPServiceAuthorization } from '@h-ai/ai' // Build the principal and the parameter-aware authorization callback from IAM.
|
|
524
|
+
import { ai } from '@h-ai/ai' // The initialized server has registered manual and office services.
|
|
525
|
+
|
|
526
|
+
async function searchManual(access: MCPServiceAuthorization, query: string) {
|
|
527
|
+
const result = await ai.mcp.services.invoke({
|
|
528
|
+
serviceId: 'manual',
|
|
529
|
+
tool: 'search_manual',
|
|
530
|
+
arguments: { query }
|
|
531
|
+
}, access) // Returns a standard MCP tool result after catalog and authorization checks.
|
|
532
|
+
if (!result.success)
|
|
533
|
+
return result // Preserve the denial or upstream error.
|
|
534
|
+
return result.data.content // For example, [{ type: 'text', text: '...' }].
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
async function convertDocument(access: MCPServiceAuthorization, fileId: string) {
|
|
538
|
+
const result = await ai.mcp.services.invoke({
|
|
539
|
+
serviceId: 'office',
|
|
540
|
+
tool: 'office.convert',
|
|
541
|
+
arguments: { fileId }
|
|
542
|
+
}, access) // Submit an offline conversion with the authorized object id.
|
|
543
|
+
if (!result.success)
|
|
544
|
+
return result
|
|
545
|
+
return result.data.structuredContent // Example: { fileId: 'pdf-123', name: 'result.pdf' }. Check authorization again on download.
|
|
546
|
+
}
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
```ts
|
|
550
|
+
import type { MCPServiceAuthorization, MCPServiceBrokerOptions } from '@h-ai/ai' // Supply a deployment URL and an authorize callback that rechecks the principal, task, and arguments.
|
|
551
|
+
import { createServer } from 'node:http' // Hosts the example endpoint.
|
|
552
|
+
import { ai } from '@h-ai/ai' // The initialized server has registered the manual service.
|
|
553
|
+
|
|
554
|
+
function mountTools(options: MCPServiceBrokerOptions) {
|
|
555
|
+
const result = ai.mcp.services.createBroker(options) // On success the broker provides bind, handleRequest, and close.
|
|
556
|
+
if (!result.success)
|
|
557
|
+
throw new Error(result.error.message)
|
|
558
|
+
const broker = result.data // Create a broker on each executor.
|
|
559
|
+
const server = createServer((req, res) => {
|
|
560
|
+
void broker.handleRequest(req, res)
|
|
561
|
+
}) // Handle MCP requests on the bound endpoint.
|
|
562
|
+
return { broker, server } // The host listens on its fixed address, protects the transport, and calls broker.close() and server.close() at shutdown.
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
async function bindManual(broker: ReturnType<typeof mountTools>['broker'], principal: MCPServiceAuthorization['principal'], sessionId: string, signal: AbortSignal) {
|
|
566
|
+
const result = await broker.bind({
|
|
567
|
+
principal,
|
|
568
|
+
taskId: sessionId,
|
|
569
|
+
signal,
|
|
570
|
+
tools: [
|
|
571
|
+
{
|
|
572
|
+
id: 'manual_search',
|
|
573
|
+
serviceId: 'manual',
|
|
574
|
+
tool: 'search_manual', // Expose a model-facing name for the catalogued operation.
|
|
575
|
+
description: 'Search authorized manuals', // Description presented to the model.
|
|
576
|
+
inputSchema: {
|
|
577
|
+
type: 'object',
|
|
578
|
+
properties: {
|
|
579
|
+
query: { type: 'string' }
|
|
580
|
+
},
|
|
581
|
+
required: ['query'],
|
|
582
|
+
additionalProperties: false
|
|
583
|
+
}, // Validate call arguments.
|
|
584
|
+
}
|
|
585
|
+
]
|
|
586
|
+
}) // Success returns { servers, revoke }. servers contains this session's short-lived Bearer credential.
|
|
587
|
+
if (!result.success)
|
|
588
|
+
throw new Error(result.error.message)
|
|
589
|
+
return result.data // Return from ACPPlatformPolicy.bindTools. The credential is revoked when the session ends.
|
|
590
|
+
}
|
|
591
|
+
```
|
|
592
|
+
|
|
430
593
|
#### Memory / RAG / Knowledge
|
|
431
594
|
|
|
432
|
-
|
|
595
|
+
The default database Store commits native memory and its pending vector operation in the same transaction. Successful adds, updates, removals, and clears confirm the relational change. The vector index can catch up later. Reads use committed relational records during vector outages. Any node sharing both stores can retry pending operations in batches, including after a restart.
|
|
433
596
|
|
|
434
|
-
`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.
|
|
597
|
+
`ai.memory.scoped({ objectId })` requires a nonempty, non-whitespace subject ID; invalid input immediately throws `TypeError` from the factory instead of creating an unbound instance. Empty public clearing ranges such as `clear({ scope: {} })` fail; cross-subject clearing requires the explicit administrator API. Native memory access statistics and updates use version CAS, so delayed reads cannot resurrect deleted entries. Relational transaction failures return a failed HaiResult. Automatic vector retries require no resubmission from callers.
|
|
435
598
|
|
|
436
599
|
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.
|
|
437
600
|
|
|
@@ -932,6 +1095,8 @@ const memories = await ai.memory.recall('经济发展', {
|
|
|
932
1095
|
|
|
933
1096
|
`ai.config` returns a redacted snapshot without exposing original `apiKey`, `privateKey`, embedded URL credentials, or other secrets.
|
|
934
1097
|
|
|
1098
|
+
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.
|
|
1099
|
+
|
|
935
1100
|
## Error Handling
|
|
936
1101
|
|
|
937
1102
|
```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
|
|
@@ -377,12 +400,77 @@ Goose 1.57.0 イメージは `goose serve` のネイティブ HTTP/WS `/acp` を
|
|
|
377
400
|
|
|
378
401
|
確認済み容量、モダリティ、推論能力は `llm.models[].capabilities` に設定します。Codex は Responses を必要とし、既存 Hai 変換は逆方向ゲートウェイではありません。close 後もコード/状態を保持し、所有プロセス停止を確認後 CAS 占有を解放します。worktree はセキュリティサンドボックスではありません。
|
|
379
402
|
|
|
403
|
+
DeepSeek Harness から公式の DeepSeek Chat に接続する場合、モデルに `protocol: 'chat'` と `baseUrl: 'https://api.deepseek.com'` を指定します。内部リレーでも公式モデル ID `deepseek-flash` または `deepseek-v4-pro` を維持すると、同じ設定が適用されます。Harness は指示を `system` ロールで送信し、DeepSeek の出力上限フィールドを使用します。ツール結果を送信する際は `reasoning_content` を保持します。 [DeepSeek Chat API](https://api-docs.deepseek.com/api/create-chat-completion/)
|
|
404
|
+
|
|
380
405
|
Agent イメージのビルドでは `minimal`、`documents`、`office`、`browser`、`developer` を選択できます。既定のイメージには Git、Node、ネイティブ Agent が含まれ、Codex には bubblewrap も含まれます。実行環境にはローカルのイメージ ID またはリモートのマニフェスト digest を登録します。[Agent イメージ](models/agents/README.md)
|
|
381
406
|
|
|
382
407
|
ACP は Node サービスで実行します。通常の API は HaiResult を返し、ストリームの失敗は例外になります。[ACP ガイド](../cli/templates/skills/hai-ai/acp.md)
|
|
383
408
|
|
|
384
409
|
管理対象 Git でサブモジュールや Git LFS 属性を検出すると ACP_UNSUPPORTED を返し、不完全な内容を準備完了として扱いません。
|
|
385
410
|
|
|
411
|
+
##### 認証済みユーザーの管理対象 ACP を実行する
|
|
412
|
+
|
|
413
|
+
RelDB と [Runner](../runner/README.ja.md) を起動し、起動済みのインスタンスを `ai.init(config, { runner, acpPolicy })` に渡します。`acp.agents` に Agent を登録し、`environmentIds` で固定イメージの Runner 環境を、`modelIds` で `llm.models` のモデルを指定します。Codex には Responses ゲートウェイが必要です。API ノードと実行ノードではデータベースと環境定義を揃えます。終了時は AI、Runner、データベースの順に閉じます。
|
|
414
|
+
|
|
415
|
+
`task` はそのセッション用の専用 Worker を起動します。`user` は主体と起動設定が一致する場合に Worker を再利用できます。`auto` はアプリのポリシーに基づいて選択します。`shared` を利用できるのは、共有を明示的に承認した読み取り専用アダプターで、非公開コンテキスト、ワークスペース、ツールを要求しない場合です。組み込みの Codex、DeepSeek Harness、Goose は専用モードを使用します。[ACP 設定例](../../docs/usage/configuration/ai.md#acp-接入与模型能力)
|
|
416
|
+
|
|
417
|
+
```ts
|
|
418
|
+
import type { RunnerScope } from '@h-ai/runner' // 認証済みアプリセッションから tenantId と userId を取得する。
|
|
419
|
+
import { ai } from '@h-ai/ai' // Runner を渡して初期化済みのサーバーインスタンス。
|
|
420
|
+
|
|
421
|
+
async function summarize(identity: RunnerScope, requestId: string) {
|
|
422
|
+
const agent = ai.acp.scoped(identity) // 以降のジョブ、セッション、承認をこの主体に紐づける。
|
|
423
|
+
const options = {
|
|
424
|
+
agentId: 'assistant',
|
|
425
|
+
execution: { mode: 'auto' as const }
|
|
426
|
+
} // assistant は登録済み Agent。
|
|
427
|
+
const plan = await agent.plan(options) // コンテナを取得せず、有効なモード、環境、モデル、リソースを返す。
|
|
428
|
+
if (!plan.success)
|
|
429
|
+
return plan // 環境や権限が合わない場合は投入しない。
|
|
430
|
+
const result = await agent.run({ ...options, prompt: 'リリースの確認項目を三つ挙げて', idempotencyKey: requestId }) // taskId、output、有効なオプションを返す。
|
|
431
|
+
if (!result.success)
|
|
432
|
+
return result // 投入、実行、後片付けの失敗を HaiResult として返す。
|
|
433
|
+
const events = await agent.tasks.events(result.data.taskId, 0, 20) // 最初の 20 イベントを読み、空なら []。
|
|
434
|
+
if (!events.success)
|
|
435
|
+
return events
|
|
436
|
+
return { result: result.data, events: events.data } // 例として output.text に回答、events に順序付きのイベントが入る。
|
|
437
|
+
}
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
```ts
|
|
441
|
+
import type { RunnerScope } from '@h-ai/runner' // サーバーで認証した主体。
|
|
442
|
+
import { ai } from '@h-ai/ai' // assistant を登録し、同じユーザー内の Worker 再利用が可能とする。
|
|
443
|
+
|
|
444
|
+
async function continueWork(identity: RunnerScope) {
|
|
445
|
+
const agent = ai.acp.scoped(identity) // アクセスをこの主体に紐づける。
|
|
446
|
+
const created = await agent.sessions.create({
|
|
447
|
+
agentId: 'assistant',
|
|
448
|
+
execution: { mode: 'user' }
|
|
449
|
+
}) // 成功時は id 付きのセッションハンドル。
|
|
450
|
+
if (!created.success)
|
|
451
|
+
return created
|
|
452
|
+
const session = created.data // prompt、stream、changeExecution、close が使える。
|
|
453
|
+
const run = async () => {
|
|
454
|
+
const first = await session.prompt('受け入れ条件を記録して') // このターンの taskId、output、有効なオプションを返す。
|
|
455
|
+
if (!first.success)
|
|
456
|
+
return first
|
|
457
|
+
const switched = await session.changeExecution({ mode: 'task', acceptNewSession: true }) // 業務上の id を維持し、新しいネイティブセッションを開始する。
|
|
458
|
+
if (!switched.success)
|
|
459
|
+
return switched
|
|
460
|
+
return await session.prompt('独立した受け入れチェックリストを出して') // 成功時の回答は data.output。
|
|
461
|
+
}
|
|
462
|
+
return run().finally(async () => {
|
|
463
|
+
const closed = await session.close() // 成功時の data は undefined。セッションまたは専用環境を解放する。
|
|
464
|
+
if (!closed.success)
|
|
465
|
+
throw new Error(closed.error.message)
|
|
466
|
+
})
|
|
467
|
+
}
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
`agents.describe(agentId)` で組み込みアダプターの機能を確認できます。`sessions.get(id)` は同じ主体が別の API ノードからハンドルを取得するために使います。`session.stream(prompt, options)` は保存済みイベントを順に返し、失敗時は例外を送出します。`tasks.get(taskId)` は実行受付票、`tasks.cancel(taskId)` はキャンセル受理後の状態を返します。`run` や `prompt` の `onEvent` に届く `accepted` イベントから `taskId` を取得し、別のリクエストで照会やキャンセルを行えます。
|
|
471
|
+
|
|
472
|
+
`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#多用户应用的受管调用)
|
|
473
|
+
|
|
386
474
|
#### 設定とデータベースのリソース一覧
|
|
387
475
|
|
|
388
476
|
`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,11 +515,86 @@ await server.connect(new StreamableHTTPServerTransport({
|
|
|
427
515
|
}))
|
|
428
516
|
```
|
|
429
517
|
|
|
518
|
+
##### リモート MCP と独立ツールジョブを呼び出す
|
|
519
|
+
|
|
520
|
+
`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)
|
|
521
|
+
|
|
522
|
+
```ts
|
|
523
|
+
import type { MCPServiceAuthorization } from '@h-ai/ai' // IAM に基づく主体と、実際の引数を検証する認可コールバックを渡す。
|
|
524
|
+
import { ai } from '@h-ai/ai' // manual と office を登録済みのサーバーインスタンス。
|
|
525
|
+
|
|
526
|
+
async function searchManual(access: MCPServiceAuthorization, query: string) {
|
|
527
|
+
const result = await ai.mcp.services.invoke({
|
|
528
|
+
serviceId: 'manual',
|
|
529
|
+
tool: 'search_manual',
|
|
530
|
+
arguments: { query }
|
|
531
|
+
}, access) // 登録と認可を確認し、標準の MCP ツール結果を返す。
|
|
532
|
+
if (!result.success)
|
|
533
|
+
return result // 拒否または上流サービスの失敗を返す。
|
|
534
|
+
return result.data.content // 例: [{ type: 'text', text: '...' }]。
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
async function convertDocument(access: MCPServiceAuthorization, fileId: string) {
|
|
538
|
+
const result = await ai.mcp.services.invoke({
|
|
539
|
+
serviceId: 'office',
|
|
540
|
+
tool: 'office.convert',
|
|
541
|
+
arguments: { fileId }
|
|
542
|
+
}, access) // 認可済みオブジェクト ID でオフライン変換を投入する。
|
|
543
|
+
if (!result.success)
|
|
544
|
+
return result
|
|
545
|
+
return result.data.structuredContent // 例: { fileId: 'pdf-123', name: 'result.pdf' }。ダウンロード時に再認可する。
|
|
546
|
+
}
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
```ts
|
|
550
|
+
import type { MCPServiceAuthorization, MCPServiceBrokerOptions } from '@h-ai/ai' // デプロイ時の URL と、主体・ジョブ・引数を再確認する authorize を渡す。
|
|
551
|
+
import { createServer } from 'node:http' // 例の HTTP 入口を作成する。
|
|
552
|
+
import { ai } from '@h-ai/ai' // manual を登録済みのサーバーインスタンス。
|
|
553
|
+
|
|
554
|
+
function mountTools(options: MCPServiceBrokerOptions) {
|
|
555
|
+
const result = ai.mcp.services.createBroker(options) // 成功時は bind、handleRequest、close を提供する。
|
|
556
|
+
if (!result.success)
|
|
557
|
+
throw new Error(result.error.message)
|
|
558
|
+
const broker = result.data // 各実行ノードで Broker を作る。
|
|
559
|
+
const server = createServer((req, res) => {
|
|
560
|
+
void broker.handleRequest(req, res)
|
|
561
|
+
}) // 入口の MCP リクエストを処理する。
|
|
562
|
+
return { broker, server } // ホストが固定アドレスを待ち受け、通信を保護し、終了時に broker.close() と server.close() を呼ぶ。
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
async function bindManual(broker: ReturnType<typeof mountTools>['broker'], principal: MCPServiceAuthorization['principal'], sessionId: string, signal: AbortSignal) {
|
|
566
|
+
const result = await broker.bind({
|
|
567
|
+
principal,
|
|
568
|
+
taskId: sessionId,
|
|
569
|
+
signal,
|
|
570
|
+
tools: [
|
|
571
|
+
{
|
|
572
|
+
id: 'manual_search',
|
|
573
|
+
serviceId: 'manual',
|
|
574
|
+
tool: 'search_manual', // モデルに表示する名前と登録済みの操作名を設定する。
|
|
575
|
+
description: 'Search authorized manuals', // モデルに渡す説明。
|
|
576
|
+
inputSchema: {
|
|
577
|
+
type: 'object',
|
|
578
|
+
properties: {
|
|
579
|
+
query: { type: 'string' }
|
|
580
|
+
},
|
|
581
|
+
required: ['query'],
|
|
582
|
+
additionalProperties: false
|
|
583
|
+
}, // 呼び出し時に引数を検証する。
|
|
584
|
+
}
|
|
585
|
+
]
|
|
586
|
+
}) // 成功時は { servers, revoke }。servers に現在のセッション用の短期 Bearer が入る。
|
|
587
|
+
if (!result.success)
|
|
588
|
+
throw new Error(result.error.message)
|
|
589
|
+
return result.data // ACPPlatformPolicy.bindTools から返す。セッション終了時に資格情報が無効になる。
|
|
590
|
+
}
|
|
591
|
+
```
|
|
592
|
+
|
|
430
593
|
#### Memory / RAG / Knowledge
|
|
431
594
|
|
|
432
|
-
|
|
595
|
+
標準のデータベース Store は、ネイティブメモリとベクトル同期の保留操作を同じトランザクションで確定します。追加、更新、削除、一括削除の成功はリレーショナル側の確定を表します。ベクトル索引は後から同期されます。ベクトルストア障害時も確定済みのリレーショナルレコードを参照します。両方のストアを共有する各ノードが、再起動後も保留操作を分割して再試行できます。
|
|
433
596
|
|
|
434
|
-
`ai.memory.scoped({ objectId })` は空でなく空白のみでもない主体 ID を要求し、不正な入力ではファクトリーが直ちに `TypeError` を送出します。未束縛のインスタンスは作成しません。`clear({ scope: {} })` など空範囲の公開削除は失敗し、主体横断の全削除には明示的な管理 API が必要です。ネイティブ記憶のアクセス統計と更新はバージョン CAS
|
|
597
|
+
`ai.memory.scoped({ objectId })` は空でなく空白のみでもない主体 ID を要求し、不正な入力ではファクトリーが直ちに `TypeError` を送出します。未束縛のインスタンスは作成しません。`clear({ scope: {} })` など空範囲の公開削除は失敗し、主体横断の全削除には明示的な管理 API が必要です。ネイティブ記憶のアクセス統計と更新はバージョン CAS を使い、遅れた読み取りで削除済みデータを復活させません。リレーショナル側のトランザクションに失敗した場合は HaiResult で返します。ベクトル同期は自動的に再試行されます。
|
|
435
598
|
|
|
436
599
|
Knowledge は取り込みごとに一意の `revision` と chunk ID を生成します。全文・ベクトル・エンティティを準備し、永続ステージングマニフェストとベクトルを書いた後、共有 Store CAS で完全なスナップショットを一度に公開します。同じ文書の再構築は一つの writer に制限され、失敗時は完全な旧版を保持します。短い新版に旧末尾 chunk が混在しません。検索は未公開版を除外し、公開と競合すれば再試行します。競合が続く場合はエラーを返します。候補拡張や清掃待ちは検索負荷を増やすことがあります。
|
|
437
600
|
|
|
@@ -932,6 +1095,8 @@ const memories = await ai.memory.recall('经济发展', {
|
|
|
932
1095
|
|
|
933
1096
|
`ai.config` はマスク済み設定を返し、`apiKey`、`privateKey`、URL 内認証情報などをそのまま公開しません。
|
|
934
1097
|
|
|
1098
|
+
ネイティブメモリの追加は、共有データベースのトランザクション内で主体別と全体の上限を確認します。古い候補を一度に最大 64 件読み出し、重要度と経過時間から削除対象を選びます。既存データが上限を超えている間は、追加前に分割して整理します。カスタム共有 Store では `AIRelStore.withWriteLock` によって同じノード間の保証を提供できます。
|
|
1099
|
+
|
|
935
1100
|
## エラー処理
|
|
936
1101
|
|
|
937
1102
|
```ts
|