import * as _h_ai_core from '@h-ai/core'; import { HaiResult, HaiError } from '@h-ai/core'; import * as _h_ai_runner from '@h-ai/runner'; import { RunnerJson, RunnerScope, RunnerFunctions } from '@h-ai/runner'; import { TaskState } from '@a2a-js/sdk'; import { AgentExecutor } from '@a2a-js/sdk/server'; import * as zod from 'zod'; import { z, ZodType } from 'zod'; import { F as FileOperations } from './ai-file-types-BMfnQU4W.js'; import { CleanOptionsInput, ChunkOptionsInput } from '@h-ai/datapipe'; import { e as AudioOperations, a as AudioContent, P as PlayableAudio, b as AudioFormat } from './ai-audio-types-4R5yUAVl.js'; import * as zod_v4_core from 'zod/v4/core'; import * as _agentclientprotocol_sdk from '@agentclientprotocol/sdk'; import { McpServer, ContentBlock, RequestPermissionRequest, SessionNotification, ClientRequestHandlersByMethod, ClientCapabilities } from '@agentclientprotocol/sdk'; import { ToolDefinition as ToolDefinition$1, ToolRegistryOperations as ToolRegistryOperations$1, ToolExecutionOptions } from '@h-ai/tools'; import OpenAI from 'openai'; import { ToolServiceContext, ToolSet, ToolArtifactAccess, ToolSubmitRequest, ToolService, ToolArtifact, ToolArtifactReference } from '@h-ai/tools/server'; import { CallToolRequest, PromptMessage, CallToolResult } from '@modelcontextprotocol/sdk/types.js'; import { IncomingMessage, ServerResponse } from 'node:http'; /** * 工程主分支必须显式填写。 * @example * ```ts * import { ACPRepositorySchema } from '@h-ai/ai' * const repository = ACPRepositorySchema.parse({ id: 'api', url: 'https://example.com/api.git', mainBranch: 'trunk' }) * ``` */ declare const ACPRepositorySchema: z.ZodObject<{ id: z.ZodString; url: z.ZodString; mainBranch: z.ZodString; remote: z.ZodDefault; }, z.core.$strict>; /** * 工作区持久目录或容器卷。 * @example * ```ts * import { ACPWorkspaceSchema } from '@h-ai/ai' * const workspace = ACPWorkspaceSchema.parse({ id: 'project', storage: { type: 'directory', path: '/srv/project' }, repositories: [] }) * ``` */ declare const ACPWorkspaceSchema: z.ZodObject<{ id: z.ZodString; storage: z.ZodDiscriminatedUnion<[z.ZodObject<{ type: z.ZodLiteral<"directory">; path: z.ZodString; }, z.core.$strict>, z.ZodObject<{ type: z.ZodLiteral<"volume">; name: z.ZodString; engine: z.ZodDefault>; image: z.ZodString; }, z.core.$strict>], "type">; repositories: z.ZodDefault; }, z.core.$strict>>>; environmentRefs: z.ZodDefault>; gitEnvironmentRefs: z.ZodDefault>; }, z.core.$strict>; /** * Agent 定义,仅保存凭据引用。 * @example * ```ts * import { ACPAgentSchema } from '@h-ai/ai' * const agent = ACPAgentSchema.parse({ id: 'coder', name: 'Coder', mode: 'embedded', adapter: 'codex', modelIds: ['coding'], defaultModelId: 'coding' }) * ``` */ declare const ACPAgentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ mode: z.ZodLiteral<"custom-service">; transport: z.ZodEnum<{ http: "http"; ws: "ws"; }>; url: z.ZodURL; headerEnv: z.ZodDefault>; supportedTransports: z.ZodArray>; id: z.ZodString; name: z.ZodString; enabled: z.ZodDefault; adapter: z.ZodDefault; modelIds: z.ZodDefault>; defaultModelId: z.ZodOptional; environmentRefs: z.ZodDefault>; environmentIds: z.ZodDefault>; sharedMode: z.ZodDefault; allowedCapabilities: z.ZodDefault>>; defaults: z.ZodOptional; reasoningEffort: z.ZodOptional; temperature: z.ZodOptional; maxOutputTokens: z.ZodOptional; }, z.core.$strict>>; execution: z.ZodOptional>; environmentId: z.ZodOptional; resources: z.ZodOptional; memoryMiB: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>; workspaceId: z.ZodOptional; context: z.ZodOptional>; knowledgeBaseIds: z.ZodOptional>; skillIds: z.ZodOptional>; memory: z.ZodOptional; spaceId: z.ZodOptional; write: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; tools: z.ZodOptional>; }, z.core.$strict>>; capabilities: z.ZodOptional>; permissions: z.ZodOptional>; approval: z.ZodOptional>; ruleIds: z.ZodOptional>; }, z.core.$strict>>; limits: z.ZodOptional; runTimeoutMs: z.ZodOptional; approvalTimeoutMs: z.ZodOptional; maxOutputBytes: z.ZodOptional; }, z.core.$strict>>; output: z.ZodOptional; schema: z.ZodOptional>; }, z.core.$strict>>; native: z.ZodOptional; }, z.core.$strict>>; metadata: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>, z.ZodObject<{ mode: z.ZodLiteral<"embedded">; transport: z.ZodDefault>; command: z.ZodOptional; args: z.ZodOptional>; id: z.ZodString; name: z.ZodString; enabled: z.ZodDefault; adapter: z.ZodDefault; modelIds: z.ZodDefault>; defaultModelId: z.ZodOptional; environmentRefs: z.ZodDefault>; environmentIds: z.ZodDefault>; sharedMode: z.ZodDefault; allowedCapabilities: z.ZodDefault>>; defaults: z.ZodOptional; reasoningEffort: z.ZodOptional; temperature: z.ZodOptional; maxOutputTokens: z.ZodOptional; }, z.core.$strict>>; execution: z.ZodOptional>; environmentId: z.ZodOptional; resources: z.ZodOptional; memoryMiB: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>; workspaceId: z.ZodOptional; context: z.ZodOptional>; knowledgeBaseIds: z.ZodOptional>; skillIds: z.ZodOptional>; memory: z.ZodOptional; spaceId: z.ZodOptional; write: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; tools: z.ZodOptional>; }, z.core.$strict>>; capabilities: z.ZodOptional>; permissions: z.ZodOptional>; approval: z.ZodOptional>; ruleIds: z.ZodOptional>; }, z.core.$strict>>; limits: z.ZodOptional; runTimeoutMs: z.ZodOptional; approvalTimeoutMs: z.ZodOptional; maxOutputBytes: z.ZodOptional; }, z.core.$strict>>; output: z.ZodOptional; schema: z.ZodOptional>; }, z.core.$strict>>; native: z.ZodOptional; }, z.core.$strict>>; metadata: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>, z.ZodObject<{ mode: z.ZodLiteral<"builtin-service">; transport: z.ZodDefault>; image: z.ZodString; engine: z.ZodDefault>; command: z.ZodOptional; args: z.ZodOptional>; id: z.ZodString; name: z.ZodString; enabled: z.ZodDefault; adapter: z.ZodDefault; modelIds: z.ZodDefault>; defaultModelId: z.ZodOptional; environmentRefs: z.ZodDefault>; environmentIds: z.ZodDefault>; sharedMode: z.ZodDefault; allowedCapabilities: z.ZodDefault>>; defaults: z.ZodOptional; reasoningEffort: z.ZodOptional; temperature: z.ZodOptional; maxOutputTokens: z.ZodOptional; }, z.core.$strict>>; execution: z.ZodOptional>; environmentId: z.ZodOptional; resources: z.ZodOptional; memoryMiB: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>; workspaceId: z.ZodOptional; context: z.ZodOptional>; knowledgeBaseIds: z.ZodOptional>; skillIds: z.ZodOptional>; memory: z.ZodOptional; spaceId: z.ZodOptional; write: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; tools: z.ZodOptional>; }, z.core.$strict>>; capabilities: z.ZodOptional>; permissions: z.ZodOptional>; approval: z.ZodOptional>; ruleIds: z.ZodOptional>; }, z.core.$strict>>; limits: z.ZodOptional; runTimeoutMs: z.ZodOptional; approvalTimeoutMs: z.ZodOptional; maxOutputBytes: z.ZodOptional; }, z.core.$strict>>; output: z.ZodOptional; schema: z.ZodOptional>; }, z.core.$strict>>; native: z.ZodOptional; }, z.core.$strict>>; metadata: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>], "mode">; /** * 会话 Git 发布请求。 * @example * ```ts * import { ACPPublishSchema } from '@h-ai/ai' * const request = ACPPublishSchema.parse({ mode: 'push-branch', message: 'Implement task', author: { name: 'Developer', email: 'developer@example.com' } }) * ``` */ declare const ACPPublishSchema: z.ZodObject<{ mode: z.ZodEnum<{ "merge-main": "merge-main"; "push-branch": "push-branch"; }>; message: z.ZodString; author: z.ZodObject<{ name: z.ZodString; email: z.ZodEmail; }, z.core.$strict>; }, z.core.$strict>; /** * ACP 执行限制。 * @example * ```ts * import { ACPConfigSchema } from '@h-ai/ai' * const config = ACPConfigSchema.parse({ promptTimeout: 300000 }) * ``` */ declare const ACPConfigSchema: z.ZodObject<{ agents: z.ZodDefault; transport: z.ZodEnum<{ http: "http"; ws: "ws"; }>; url: z.ZodURL; headerEnv: z.ZodDefault>; supportedTransports: z.ZodArray>; id: z.ZodString; name: z.ZodString; enabled: z.ZodDefault; adapter: z.ZodDefault; modelIds: z.ZodDefault>; defaultModelId: z.ZodOptional; environmentRefs: z.ZodDefault>; environmentIds: z.ZodDefault>; sharedMode: z.ZodDefault; allowedCapabilities: z.ZodDefault>>; defaults: z.ZodOptional; reasoningEffort: z.ZodOptional; temperature: z.ZodOptional; maxOutputTokens: z.ZodOptional; }, z.core.$strict>>; execution: z.ZodOptional>; environmentId: z.ZodOptional; resources: z.ZodOptional; memoryMiB: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>; workspaceId: z.ZodOptional; context: z.ZodOptional>; knowledgeBaseIds: z.ZodOptional>; skillIds: z.ZodOptional>; memory: z.ZodOptional; spaceId: z.ZodOptional; write: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; tools: z.ZodOptional>; }, z.core.$strict>>; capabilities: z.ZodOptional>; permissions: z.ZodOptional>; approval: z.ZodOptional>; ruleIds: z.ZodOptional>; }, z.core.$strict>>; limits: z.ZodOptional; runTimeoutMs: z.ZodOptional; approvalTimeoutMs: z.ZodOptional; maxOutputBytes: z.ZodOptional; }, z.core.$strict>>; output: z.ZodOptional; schema: z.ZodOptional>; }, z.core.$strict>>; native: z.ZodOptional; }, z.core.$strict>>; metadata: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>, z.ZodObject<{ mode: z.ZodLiteral<"embedded">; transport: z.ZodDefault>; command: z.ZodOptional; args: z.ZodOptional>; id: z.ZodString; name: z.ZodString; enabled: z.ZodDefault; adapter: z.ZodDefault; modelIds: z.ZodDefault>; defaultModelId: z.ZodOptional; environmentRefs: z.ZodDefault>; environmentIds: z.ZodDefault>; sharedMode: z.ZodDefault; allowedCapabilities: z.ZodDefault>>; defaults: z.ZodOptional; reasoningEffort: z.ZodOptional; temperature: z.ZodOptional; maxOutputTokens: z.ZodOptional; }, z.core.$strict>>; execution: z.ZodOptional>; environmentId: z.ZodOptional; resources: z.ZodOptional; memoryMiB: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>; workspaceId: z.ZodOptional; context: z.ZodOptional>; knowledgeBaseIds: z.ZodOptional>; skillIds: z.ZodOptional>; memory: z.ZodOptional; spaceId: z.ZodOptional; write: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; tools: z.ZodOptional>; }, z.core.$strict>>; capabilities: z.ZodOptional>; permissions: z.ZodOptional>; approval: z.ZodOptional>; ruleIds: z.ZodOptional>; }, z.core.$strict>>; limits: z.ZodOptional; runTimeoutMs: z.ZodOptional; approvalTimeoutMs: z.ZodOptional; maxOutputBytes: z.ZodOptional; }, z.core.$strict>>; output: z.ZodOptional; schema: z.ZodOptional>; }, z.core.$strict>>; native: z.ZodOptional; }, z.core.$strict>>; metadata: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>, z.ZodObject<{ mode: z.ZodLiteral<"builtin-service">; transport: z.ZodDefault>; image: z.ZodString; engine: z.ZodDefault>; command: z.ZodOptional; args: z.ZodOptional>; id: z.ZodString; name: z.ZodString; enabled: z.ZodDefault; adapter: z.ZodDefault; modelIds: z.ZodDefault>; defaultModelId: z.ZodOptional; environmentRefs: z.ZodDefault>; environmentIds: z.ZodDefault>; sharedMode: z.ZodDefault; allowedCapabilities: z.ZodDefault>>; defaults: z.ZodOptional; reasoningEffort: z.ZodOptional; temperature: z.ZodOptional; maxOutputTokens: z.ZodOptional; }, z.core.$strict>>; execution: z.ZodOptional>; environmentId: z.ZodOptional; resources: z.ZodOptional; memoryMiB: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>; workspaceId: z.ZodOptional; context: z.ZodOptional>; knowledgeBaseIds: z.ZodOptional>; skillIds: z.ZodOptional>; memory: z.ZodOptional; spaceId: z.ZodOptional; write: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; tools: z.ZodOptional>; }, z.core.$strict>>; capabilities: z.ZodOptional>; permissions: z.ZodOptional>; approval: z.ZodOptional>; ruleIds: z.ZodOptional>; }, z.core.$strict>>; limits: z.ZodOptional; runTimeoutMs: z.ZodOptional; approvalTimeoutMs: z.ZodOptional; maxOutputBytes: z.ZodOptional; }, z.core.$strict>>; output: z.ZodOptional; schema: z.ZodOptional>; }, z.core.$strict>>; native: z.ZodOptional; }, z.core.$strict>>; metadata: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>], "mode">>>; workspaces: z.ZodDefault; path: z.ZodString; }, z.core.$strict>, z.ZodObject<{ type: z.ZodLiteral<"volume">; name: z.ZodString; engine: z.ZodDefault>; image: z.ZodString; }, z.core.$strict>], "type">; repositories: z.ZodDefault; }, z.core.$strict>>>; environmentRefs: z.ZodDefault>; gitEnvironmentRefs: z.ZodDefault>; }, z.core.$strict>>>; requestTimeout: z.ZodDefault; promptTimeout: z.ZodDefault; cancelTimeout: z.ZodDefault; maxContentBytes: z.ZodDefault; maxPendingEvents: z.ZodDefault; workerIdleTimeoutMs: z.ZodDefault; }, z.core.$strict>; /** * ACP 初始化配置,已填充超时和只读清单默认值。 * @example * ```ts * import { ACPConfigSchema } from '@h-ai/ai' * import type { ACPConfig } from '@h-ai/ai' * const config: ACPConfig = ACPConfigSchema.parse({ promptTimeout: 300000 }) * ``` */ type ACPConfig = z.output; /** * ACP 初始化输入,省略字段采用 Schema 默认值。 * @example * ```ts * import type { ACPConfigInput } from '@h-ai/ai' * const config: ACPConfigInput = { promptTimeout: 300000 } * ``` */ type ACPConfigInput = z.input; /** * @h-ai/ai — Store 存储抽象类型 * * 定义统一的键值式 CRUD + 查询接口,所有需要状态持久化的子系统通过此接口存取数据。 * @module ai-store-types */ /** * 存储作用域——用于索引列加速查询 * * 在 save 时传入 scope,值将写入独立索引列(object_id / session_id), * 后续 query / removeBy 可通过 StoreFilter.objectId / sessionId 使用索引过滤。 * * @example * ```ts * import type { AIRelStore, StoreScope } from '@h-ai/ai' * async function saveOwned(store: AIRelStore<{ title: string }>, userId: string) { * const scope: StoreScope = { objectId: userId, sessionId: 'session-1' } * await store.save('record-1', { title: '指南' }, scope) * } * ``` */ interface StoreScope { /** 交互主体 ID(写入 object_id 索引列) */ objectId?: string; /** 会话 ID(写入 session_id 索引列) */ sessionId?: string; /** 状态(写入 status 索引列) */ status?: string; /** 引用 ID(写入 ref_id 索引列,关联外部实体) */ refId?: string; } /** * where 条件中单个字段的值——纯值表示等值匹配,对象表示操作符 * * @example * ```ts * import type { WhereOperator } from '@h-ai/ai' * const condition: WhereOperator = { $gte: 0.5, $lt: 1 } * const filter = { condition } * ``` */ interface WhereOperator { /** 值在给定列表中(IN 语义) */ $in?: V[]; /** 不等于该值;缺失的字段也匹配。 */ $ne?: V; /** 大于等于 */ $gte?: V; /** 大于 */ $gt?: V; /** 小于等于 */ $lte?: V; /** 小于 */ $lt?: V; } /** * 单字段条件:纯值 = 等值匹配,WhereOperator 对象 = 操作符匹配 * * @example * ```ts * import type { WhereValue } from '@h-ai/ai' * const condition: WhereValue = { $in: ['fact', 'preference'] } * const filter = { condition } * ``` */ type WhereValue = V | WhereOperator; /** * where 子句类型——每个字段可以是等值匹配或操作符对象 * * @example * ```ts * import type { WhereClause } from '@h-ai/ai' * const condition: WhereClause<{ importance: number }> = { importance: { $gte: 0.5 } } * const filter = { condition } * ``` */ type WhereClause = { [K in keyof T]?: WhereValue; }; /** * 存储查询过滤条件 * * @typeParam T - 记录类型 * * @example * ```ts * import type { AIRelStore, StoreFilter } from '@h-ai/ai' * async function queryOwned(store: AIRelStore<{ importance: number }>, userId: string) { * const filter: StoreFilter<{ importance: number }> = { objectId: userId, where: { importance: { $gte: 0.5 } }, limit: 20 } * return await store.query(filter) * } * ``` */ interface StoreFilter { /** 字段匹配条件(等值或操作符) */ where?: WhereClause; /** 按 object_id 索引列过滤(需要 AIRelStoreOptions.hasObjectId 启用) */ objectId?: string; /** 按 session_id 索引列过滤(需要 AIRelStoreOptions.hasSessionId 启用) */ sessionId?: string; /** 按 status 索引列过滤(需要 AIRelStoreOptions.hasStatus 启用,支持单值或多值 IN 匹配) */ status?: string | string[]; /** 按 ref_id 索引列过滤(需要 AIRelStoreOptions.hasRefId 启用) */ refId?: string; /** * 按业务作用域过滤(`data.scope` JSON 字段的 key-value 包含匹配)。 * * 仅在 PostgreSQL 上下推为 `data @> ?::jsonb`(配合 GIN 索引加速); * SQLite / MySQL 上为 no-op(不影响结果,由调用方在内存中完成 scope 匹配)。 */ scope?: Record; /** 排序 */ orderBy?: { field: keyof T; direction: 'asc' | 'desc'; }; /** 数量限制 */ limit?: number; /** 按关系记录最后写入时间过滤,主要用于保留期维护。 */ updatedBefore?: number; /** 按不可变主键继续扫描;提供后查询按主键升序。 */ afterId?: string; } /** * 分页查询结果 * * @example * ```ts * import type { StorePage } from '@h-ai/ai' * const page: StorePage<{ title: string }> = { items: [{ title: '指南' }], total: 1 } * const titles = page.items.map(item => item.title) * ``` */ interface StorePage { /** 当前页数据 */ items: T[]; /** 总记录数 */ total: number; } /** * AIRelStore 配置选项 * * 控制存储实例需要创建哪些索引列(object_id / session_id / status / ref_id)。 * * @example * ```ts * import type { AIStoreProvider, AIRelStoreOptions } from '@h-ai/ai' * async function prepare(provider: AIStoreProvider) { * const options: AIRelStoreOptions = { hasObjectId: true, hasSessionId: true } * const store = provider.createRelStore<{ title: string }>('documents', options) * await provider.initialize() * return store * } * ``` */ interface AIRelStoreOptions { /** 是否创建 object_id 索引列 */ hasObjectId?: boolean; /** 是否创建 session_id 索引列 */ hasSessionId?: boolean; /** 是否创建 status 索引列 */ hasStatus?: boolean; /** 是否创建 ref_id 索引列 */ hasRefId?: boolean; /** * 是否为业务作用域(记录内 `data.scope` JSON 字段)建立索引以加速 scope 过滤。 * * 仅 PostgreSQL 生效:在 JSONB `data` 列上建 GIN 索引,配合 `StoreFilter.scope` * 的 `data @> ?::jsonb` 包含查询下推,避免加载全部候选再在内存过滤。 * SQLite / MySQL 不建索引,`scope` 过滤退回调用方内存匹配(当前行为不变)。 */ hasScopeIndex?: boolean; /** 为存在全局配额的 Store 启用事务串行写入。 */ serializeWrites?: boolean; /** 为按最后更新时间读取记录键的维护任务建索引。 */ hasUpdatedAtIndex?: boolean; /** 为原生记忆维护启用当前向量版本索引。 */ hasMemoryVectorIndex?: boolean; } /** * 同一次读取的记录及不可复用的存储版本。 * * @example * ```ts * import type { AIVersionedRecord } from '@h-ai/ai' * function nextVersion(snapshot: AIVersionedRecord<{ count: number }>) { * return { expectedVersion: snapshot.version, data: { count: snapshot.data.count + 1 } } * } * ``` */ interface AIVersionedRecord { /** 每次写入都会更换的版本;不得把业务 ID 或时间戳用作版本。 */ version: string; /** 该版本的独立数据快照,修改它不会隐式写入 Store。 */ data: T; } /** * 单记录的原子条件写入;不跨表承诺事务。 * * @example * ```ts * import type { AIRelStore, AIRelStoreCompareAndSwap } from '@h-ai/ai' * async function increment(store: AIRelStore<{ count: number }>, id: string) { * const previous = await store.readVersioned(id) * const change: AIRelStoreCompareAndSwap<{ count: number }> = { expectedVersion: previous?.version, data: { count: (previous?.data.count ?? 0) + 1 }, notAfter: await store.currentTime() + 1000 } * const version = await store.compareAndSwap(id, change) * if (!version) throw new Error('Conflict or deadline expired') * return version * } * ``` */ interface AIRelStoreCompareAndSwap { /** undefined 只允许新建;已有记录必须精确匹配读取到的版本。 */ expectedVersion: string | undefined; /** 成功时替换的数据;需要撤销时持久化业务墓碑,避免删除后 missing ABA。 */ data: T; /** 与数据同一次条件提交的索引列;未传时保留已有索引。 */ scope?: StoreScope; /** 可选 Unix 毫秒截止时间;执行写入时由存储端时钟原子检查,等于截止时间也拒绝。 */ notAfter?: number; } /** * AI 关系存储适配器 * * 提供统一的 KV 式 CRUD + 查询能力,由 AIStoreProvider 创建具体实现。 * 这是内部适配边界:读取/写入故障抛错,不能伪装为缺失、空结果或完成; * 最近的非流式业务 API 负责转换为失败 HaiResult,流迭代保留抛错契约。 * * @typeParam T - 记录类型 * * @example * ```ts * import type { AIRelStore } from '@h-ai/ai' * // 存储异常保留抛错;业务边界负责转 HaiResult,不能当作缺失。 * async function claim(store: AIRelStore<{ owner: string }>, id: string, owner: string) { * const current = await store.readVersioned(id) * const deadline = await store.currentTime() + 30_000 * return await store.compareAndSwap(id, { expectedVersion: current?.version, data: { owner }, notAfter: deadline }) * } * ``` */ interface AIRelStore { /** 在共享存储事务中串行执行配额读取和写入,回调使用事务内 Store。 */ withWriteLock?: (write: (store: AIRelStore) => Promise) => Promise; /** 持同一个写锁,在同一事务中提交当前和另一个关系 Store 的改动。 */ withRelatedWriteLock?: (related: AIRelStore, write: (store: AIRelStore, related: AIRelStore) => Promise) => Promise; /** 核对有向量的记忆版本 ID,包含仍用业务 ID 存储向量的旧记录。 */ getMemoryVectorIds?: (ids: string[]) => Promise; /** 从已提交的关系记录按不可变主键读取一批需重建索引的记忆,读取失败须抛错。 */ readMemoryVectorPage?: (afterId: string, limit: number) => Promise; /** 按更新时间和主键升序获取小批记录键,避免加载业务 JSON。 */ queryKeys?: (filter: StoreFilter, cursor?: { updatedAt: number; id: string; }) => Promise>; /** 只删除指定版本,防止过期维护删除同时更新的记录。 */ removeIfUnchanged?: (id: string, version: string) => Promise; /** * 存储端 Unix 毫秒时钟;共享租约以它计算期限,不依赖各节点墙钟同步。 */ currentTime: () => Promise; /** * 读取记录与版本的同一快照;失败抛错,不能把故障当作缺失。 */ readVersioned: (id: string) => Promise | undefined>; /** * 原子条件替换;成功返回新版本,冲突/截止返回 undefined,存储故障抛错。 */ compareAndSwap: (id: string, input: AIRelStoreCompareAndSwap) => Promise; /** 保存一条记录(upsert 语义) */ save: (id: string, data: T, scope?: StoreScope) => Promise; /** 批量保存 */ saveMany: (items: Array<{ id: string; data: T; scope?: StoreScope; }>) => Promise; /** 按 ID 获取 */ get: (id: string) => Promise; /** 按条件查询 */ query: (filter: StoreFilter) => Promise; /** 分页查询 */ queryPage: (filter: StoreFilter, page: { offset: number; limit: number; }) => Promise>; /** 删除一条记录 */ remove: (id: string) => Promise; /** 按条件删除 */ removeBy: (filter: StoreFilter) => Promise; /** 计数 */ count: (filter?: StoreFilter) => Promise; /** 清空(可选按条件) */ clear: (filter?: StoreFilter) => Promise; } /** * AI 向量存储适配器 * * 专用于需要向量检索的场景(如 Memory),由 AIStoreProvider 创建具体实现。 * * @example * ```ts * import type { AIVectorStore } from '@h-ai/ai' * async function searchTenant(store: AIVectorStore, vector: number[], tenant: string) { * // 向量维度须与集合一致,Provider 过滤能力也须满足部署后端契约。 * return await store.search(vector, { topK: 5, filter: { tenant } }) * } * ``` */ interface AIVectorStore { /** 存储向量 */ upsert: (id: string, vector: number[], metadata?: Record) => Promise; /** 批量存储同一集合的向量,允许安全重试。 */ upsertMany?: (entries: Array<{ id: string; vector: number[]; metadata?: Record; }>) => Promise; /** * 向量相似度检索。默认 DB Store 的 filter 透传底层 Provider,失败抛错,由领域 API 转为 HaiResult。 * LanceDB 只支持顶层 string/有限 number/boolean/null 的 AND 匹配,不支持嵌套结构。 */ search: (vector: number[], options?: { topK?: number; minScore?: number; filter?: Record; }) => Promise; }>>; /** 删除向量 */ remove: (id: string) => Promise; /** 分页读取专用集合的向量键,游标由向量后端生成。 */ scan?: (options: { cursor?: string; limit: number; }) => Promise<{ items: Array<{ id: string; }>; nextCursor?: string; }>; /** 按键批量删除向量,重复删除安全。 */ removeMany?: (ids: string[]) => Promise; /** 清空 */ clear: (filter?: Record) => Promise; } /** * 交互主体引用 * * 代表"和谁"交互 — 可以是人、AI Agent、或系统自身。 * * @example * ```ts * import type { ObjectRef } from '@h-ai/ai' * const value: ObjectRef = { objectId: 'agent-1', objectType: 'agent' } * const output = value.objectId * ``` */ interface ObjectRef { /** 主体唯一 ID */ objectId: string; /** 主体类型 */ objectType?: 'human' | 'agent' | 'system'; } /** * 完整的交互作用域 = Object + Session * * @example * ```ts * import type { InteractionScope } from '@h-ai/ai' * const value: InteractionScope = { objectId: 'user-1', sessionId: 'session-1' } * const output = `${value.objectId}/${value.sessionId}` * ``` */ interface InteractionScope { /** 交互主体 ID */ objectId: string; /** 会话 ID */ sessionId: string; } /** * 会话信息;目录更新必须保留并发标题及删除标记。 * * @example * ```ts * import type { SessionInfo } from '@h-ai/ai' * const value: SessionInfo = { objectId: 'user-1', sessionId: 'session-1', title: '部署咨询', createdAt: Date.now(), updatedAt: Date.now() } * const output = value.deleted ? undefined : value.title * ``` */ interface SessionInfo { /** 会话 ID */ sessionId: string; /** 所属主体 ID */ objectId: string; /** 会话标题 */ title?: string; /** 创建时间(Unix 毫秒) */ createdAt: number; /** 更新时间(Unix 毫秒) */ updatedAt: number; /** 附加元数据 */ metadata?: Record; /** 永久删除标记;同一主体的 sessionId 不再复用,迟到生成不得重建目录。 */ deleted?: boolean; } /** * 一次完整准备、尚未发布的文档版本;chunk 和实体关联必须使用本版本的唯一 ID。 * * @example * ```ts * import type { KnowledgeDocumentRevision } from '@h-ai/ai' * const value: KnowledgeDocumentRevision = { documentId: 'guide', collection: 'docs', revision: crypto.randomUUID(), chunks: [{ id: 'revision-chunk-1', content: '共享数据库', vector: [0.1, 0.2], metadata: { documentId: 'guide' } }], entities: [], createdAt: Date.now() } * const output = value.chunks.map(chunk => chunk.id) * ``` */ interface KnowledgeDocumentRevision { /** 业务文档 ID。 */ documentId: string; /** 逻辑集合名。 */ collection: string; /** 每次导入生成的不可复用版本。 */ revision: string; /** 标题。 */ title?: string; /** 信源地址。 */ url?: string; /** 本次版本的创建时间,Unix 毫秒。 */ createdAt: number; /** 本版本全部分块;向量只在暂存阶段写入,发布快照不保留向量数组。 */ chunks: Array<{ id: string; vector: number[]; content: string; metadata: Record; }>; /** 本版本全部实体及命中分块,不与其他文档共享可变实体行。 */ entities: Array<{ id: string; name: string; type: string; aliases: string[]; description?: string; chunkIds: string[]; }>; } /** * 有界补偿扫描的进度;调用方以 offset + processed 继续,直到覆盖 total。 * * @example * ```ts * import type { KnowledgeRepairProgress } from '@h-ai/ai' * const value: KnowledgeRepairProgress = { processed: 100, total: 250 } * const output = value.processed < value.total * ``` */ interface KnowledgeRepairProgress { /** 本页检查的文档墓碑/清单数。 */ processed: number; /** 集合内清单总数,包含已删除文档的补偿墓碑。 */ total: number; } /** * 来自同一已发布快照的文档摘要,实体数不会与另一个 revision 拼接。 * * @example * ```ts * import type { KnowledgeDocumentMetadata } from '@h-ai/ai' * const value: KnowledgeDocumentMetadata = { documentId: 'guide', collection: 'docs', revision: 'revision-1', title: '指南', url: null, chunkCount: 2, entityCount: 1, createdAt: Date.now() } * const output = value.title ?? value.documentId * ``` */ interface KnowledgeDocumentMetadata { /** 业务文档 ID。 */ documentId: string; /** 逻辑集合名。 */ collection: string; /** 当前发布版本。 */ revision: string; /** 可选标题,缺失为 null。 */ title: string | null; /** 可选信源地址,缺失为 null。 */ url: string | null; /** 同版本分块数。 */ chunkCount: number; /** 同版本实体数。 */ entityCount: number; /** 版本创建时间,Unix 毫秒。 */ createdAt: number; } /** * Knowledge 专用存储接口 * * 封装知识库的实体索引、文档元数据和向量操作。 * 默认实现使用 reldb 单文档版本清单 CAS + vecdb 向量检索; * SaaS 实现可对接远端知识库 API。 * * @example * ```ts * import type { KnowledgeStore, KnowledgeDocumentRevision } from '@h-ai/ai' * async function publish(store: KnowledgeStore, document: KnowledgeDocumentRevision) { * await store.initialize(document.collection, document.chunks[0]?.vector.length ?? 2) * const result = await store.replaceDocument(document) * if (result.cleanupPending) { * let offset = 0 * while (true) { * const progress = await store.repair(document.collection, { offset, limit: 100 }) * offset += progress.processed * if (offset >= progress.total || progress.processed === 0) break * } * } * } * ``` */ interface KnowledgeStore { /** 初始化存储(建表 / 建集合 / 建索引,幂等) */ initialize: (collection: string, dimension: number) => Promise; /** * 先持久化暂存清单,再写向量,最后原子发布完整版本;失败保留原可见版本和补偿记录。 * 同一文档正在导入时拒绝并发写入。cleanupPending 表示发布成功但旧数据清理需重试。 */ replaceDocument: (document: KnowledgeDocumentRevision) => Promise<{ cleanupPending: boolean; }>; /** * 恢复过期暂存并清理记录在案的旧向量;故障抛错,不以空结果伪装成功。 * 被遗弃暂存的墓碑保留,重复扫描可清理旧节点迟到的外部写入。 */ repair: (collection: string, options?: { offset?: number; limit?: number; }) => Promise; /** 按名称模糊搜索实体(匹配 name 和 aliases,可按 collection 过滤) */ findEntitiesByName: (keyword: string, collection?: string) => Promise>; /** 列出实体(支持 collection / 类型 / 关键词搜索) */ listEntities: (options?: { collection?: string; type?: string; keyword?: string; limit?: number; }) => Promise>; /** 按实体 ID 列表查询关联文档 */ findDocumentsByEntityIds: (entityIds: string[], collection?: string) => Promise>; /** 按实体名称查询实体及其关联文档 */ findByEntityName: (entityName: string, options?: { collection?: string; type?: string; }) => Promise; }>>; /** 按 documentId + collection 获取单个文档元数据 */ getDocument: (documentId: string, collection: string) => Promise; /** 列出文档元数据 */ listDocuments: (collection: string, options?: { offset?: number; limit?: number; }) => Promise; /** 原子撤销文档版本并删除清单中向量;清理失败抛错,持久墓碑允许 repair 重试。 */ removeDocument: (documentId: string, collection: string) => Promise; /** * 向量相似度检索。默认 DB Store 将 filter 透传底层 Provider,校验/查询失败抛错,不当作空结果。 * LanceDB 仅支持顶层 string/有限 number/boolean/null 的 AND 匹配,null 与字段缺失不同。 */ searchVectors: (collection: string, vector: number[], options?: { topK?: number; minScore?: number; filter?: Record; }) => Promise; }>>; /** 确保向量集合存在 */ ensureCollection: (collection: string, dimension: number) => Promise; /** 注册 collection(setup 时持久化,幂等) */ registerCollection: (collection: string, dimension: number) => Promise; /** 检查 collection 是否已在注册表中存在(跨节点/重启后仍有效) */ collectionExists: (collection: string) => Promise; /** * 撤销 collection 可见代际并清理向量,保留物理集合与补偿墓碑供迟到写入的重复清理。 * 内部按页清理,失败抛错后由 repair 恢复;collection 不存在时幂等成功。 */ deleteCollection: (collection: string) => Promise; } /** * 向量库后端连接信息 * * 由 Provider 暴露底层向量库的原始连接,供需要复用同一后端的格式适配器(如 Mem0 数据格式存储) * 直连。字段按后端类型填充;包含凭证,仅供同进程内集成使用。 * * @example * ```ts * import type { AIVectorBackend } from '@h-ai/ai' * const value: AIVectorBackend = { type: 'qdrant', url: 'https://vector.example.com:6333' } * const output = value.type * ``` */ interface AIVectorBackend { /** 后端类型(如 'qdrant'、'pgvector'、'lancedb'、'chroma') */ type: string; /** 服务 URL(qdrant / chroma) */ url?: string; /** API Key(qdrant / chroma) */ apiKey?: string; /** 主机(pgvector) */ host?: string; /** 端口(pgvector / chroma) */ port?: number; /** 数据库名(pgvector) */ database?: string; /** 用户名(pgvector) */ user?: string; /** 密码(pgvector) */ password?: string; /** 连接串(pgvector) */ connectionString?: string; /** 本地路径(lancedb / chroma 嵌入式) */ path?: string; } /** * AI 存储 Provider 接口 * * 负责创建 AIRelStore / AIVectorStore 实例,并管理存储层生命周期。 * reldb + vecdb 已初始化时默认使用 DB 实现;仅开发或明确 E2E 可使用临时实现,生产要求 shared; * 也可对接 SaaS API 或其他后端。 * * @example * ```ts * import { ai, type AIStoreProvider, type AIConfigInput } from '@h-ai/ai' * // provider 的 shared 声明必须由真实共享后端支撑;AI 关闭时调用其 close。 * async function start(config: AIConfigInput, provider: AIStoreProvider) { * const result = await ai.init(config, { storeProvider: provider }) * if (!result.success) throw new Error(result.error.message) * } * ``` */ interface AIStoreProvider { /** 关系状态与向量后端是否跨主机共享;自定义Provider必须如实声明,生产拒绝local。 */ readonly stateScope: 'local' | 'shared'; /** Provider 名称(如 'db'、'api') */ readonly name: string; /** 创建关系数据存储实例 */ createRelStore: (name: string, options?: AIRelStoreOptions) => AIRelStore; /** 创建向量数据存储实例。原生记忆在关系 Store 初始化并读出集合名称后调用。 */ createVectorStore: (name: string) => AIVectorStore; /** * 暴露底层向量库后端连接(可选) * * 供需要直连同一向量库的格式适配器(如 Mem0 数据格式存储)复用后端。未初始化或不支持时返回 * `undefined`。返回值含凭证,仅供同进程内集成使用,禁止写入日志。 */ getVectorBackend?: () => AIVectorBackend | undefined; /** * 创建 knowledge 专用存储(可选) * * 如果 Provider 不提供此方法,knowledge 子系统将不可用。 * 默认 db Provider 提供基于 reldb 归一化表 + vecdb 的高效实现。 */ createKnowledgeStore?: () => KnowledgeStore; /** * 初始化所有已创建的存储(建表、建连接等) * * 由 ai.init() 在创建完关系 Store 实例后调用。 */ initialize: () => Promise; /** 关闭所有存储(释放连接等),由 ai.close() 调用 */ close?: () => Promise; } /** * @h-ai/ai — MCP 子功能类型 * * 定义 MCP 工具、资源、提示词的注册与调用接口。 * @module ai-mcp-types */ /** * MCP 工具定义(注册工具时的元数据) * * @example * ```ts * import { ai, type MCPToolDefinition } from '@h-ai/ai' * // 应用启动已成功初始化 ai;echo 为无外部副作用的示例工具。 * const definition: MCPToolDefinition = { name: 'echo', description: '返回输入', inputSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: false } } * const registered = ai.mcp.registerTool(definition, (input: { text: string }) => ({ text: input.text })) * if (!registered.success) throw new Error(registered.error.message) * ``` */ interface MCPToolDefinition { /** 工具名称(需唯一) */ name: string; /** 工具功能描述 */ description: string; /** 输入参数的 JSON Schema */ inputSchema: Record; } /** * MCP 工具处理器,接收输入参数和执行上下文 * * @example * ```ts * import type { MCPToolHandler } from '@h-ai/ai' * const echo: MCPToolHandler<{ text: string }, { text: string }> = (input, context) => ({ text: `${context.requestId ?? 'request'}: ${input.text}` }) * const output = await echo({ text: '你好' }, { requestId: 'request-1' }) * ``` */ type MCPToolHandler = (input: TInput, context: MCPContext) => Promise | TOutput; /** * MCP 执行上下文,携带请求元数据 * * @example * ```ts * import type { MCPContext } from '@h-ai/ai' * const value: MCPContext = { requestId: 'request-1', clientInfo: { name: 'assistant', version: '1.0.0' } } * const correlationId = value.requestId * ``` */ interface MCPContext { /** 请求唯一标识(未传入时自动生成 UUID) */ requestId?: string; /** 客户端信息(可选) */ clientInfo?: { name: string; version: string; }; /** 自定义元数据(可选) */ metadata?: Record; } /** * MCP 资源描述(注册资源时的元数据) * * @example * ```ts * import type { MCPResource } from '@h-ai/ai' * const value: MCPResource = { uri: 'config://public/features', name: '公开特性', mimeType: 'application/json' } * const resourceName = value.name * ``` */ interface MCPResource { /** 资源 URI(唯一标识) */ uri: string; /** 资源名称 */ name: string; /** 资源描述(可选) */ description?: string; /** MIME 类型(可选,如 `'application/json'`) */ mimeType?: string; } /** * MCP 资源内容(readResource 的返回值) * * @example * ```ts * import type { MCPResourceContent } from '@h-ai/ai' * const value: MCPResourceContent = { uri: 'config://public/features', mimeType: 'application/json', text: JSON.stringify({ enabled: true }) } * const text = value.text * ``` */ interface MCPResourceContent { /** 资源 URI */ uri: string; /** MIME 类型(可选) */ mimeType?: string; /** 文本内容(与 blob 二选一) */ text?: string; /** Base64 编码的二进制内容(与 text 二选一) */ blob?: string; } /** * MCP 提示词模板描述 * * @example * ```ts * import type { MCPPrompt } from '@h-ai/ai' * const value: MCPPrompt = { name: 'explain', description: '解释主题', arguments: [{ name: 'topic', required: true }] } * const required = value.arguments?.filter(argument => argument.required) * ``` */ interface MCPPrompt { /** 提示词名称(唯一标识) */ name: string; /** 提示词描述(可选) */ description?: string; /** 参数定义列表(可选) */ arguments?: MCPPromptArgument[]; } /** * MCP 提示词参数定义 * * @example * ```ts * import type { MCPPromptArgument } from '@h-ai/ai' * const value: MCPPromptArgument = { name: 'topic', description: '要解释的主题', required: true } * const field = value.name * ``` */ interface MCPPromptArgument { /** 参数名称 */ name: string; /** 参数描述(可选) */ description?: string; /** 是否必填(默认 `false`) */ required?: boolean; } /** * MCP 提示词消息,直接复用 SDK 的完整判别联合(含图片、音频与嵌入资源) * * @example * ```ts * import type { MCPPromptMessage } from '@h-ai/ai' * const value: MCPPromptMessage = { role: 'user', content: { type: 'text', text: '请解释共享状态' } } * const role = value.role * ``` */ type MCPPromptMessage = PromptMessage; /** * MCP 提示词内容;按 type 缩窄后访问对应字段 * * @example * ```ts * import type { MCPPromptContent } from '@h-ai/ai' * function textContent(content: MCPPromptContent): string | undefined { * return content.type === 'text' ? content.text : undefined * } * ``` */ type MCPPromptContent = PromptMessage['content']; /** * MCP 服务器创建选项 * * @example * ```ts * import { createMcpServer, type McpServerOptions } from '@h-ai/ai' * const options: McpServerOptions = { name: 'public-tools', version: '1.0.0' } * const server = createMcpServer(options) * // 应用停止接入请求后关闭 SDK server。 * await server.close() * ``` */ interface McpServerOptions { /** 服务器名称 */ name: string; /** 服务器版本(默认 `'1.0.0'`) */ version?: string; } /** * MCP 操作接口(通过 `ai.mcp` 访问) * * 需要先调用 `ai.init()` 初始化,否则所有方法返回 `NOT_INITIALIZED` 错误。 * * @example * ```ts * import { ai, type MCPOperations } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * const mcp: MCPOperations = ai.mcp * const registered = mcp.registerTool({ name: 'echo', description: '返回输入', inputSchema: { type: 'string' } }, (input: string) => input) * if (!registered.success) throw new Error(registered.error.message) * const called = await mcp.callTool('echo', '你好', { requestId: 'request-1' }) * if (!called.success) throw new Error(called.error.message) * ``` */ interface MCPOperations { /** 注册工具并编译 JSON Schema;非法 Schema 返回 MCP_TOOL_ERROR,同名注册覆盖 */ registerTool: (definition: MCPToolDefinition, handler: MCPToolHandler) => HaiResult; /** 注册资源加载器;读取时校验 text/blob 输出 */ registerResource: (resource: MCPResource, handler: () => Promise) => HaiResult; /** 注册提示词;调用时校验必填参数和 SDK 消息格式 */ registerPrompt: (prompt: MCPPrompt, handler: (args: Record) => Promise) => HaiResult; /** 校验输入后执行工具;自动补齐缺失的 requestId */ callTool: (name: string, args: unknown, context?: MCPContext) => Promise>; /** 读取资源,输出必须恰好含一个有效 text 或 blob */ readResource: (uri: string) => Promise>; /** 渲染提示词;必填参数必须是自身属性,且提供的已声明参数必须是字符串 */ getPrompt: (name: string, args: Record) => Promise>; } /** * 按目录 ID 调用工具,连接设置始终由服务端清单提供。 * @example * ```ts * import type { MCPServiceRequest } from '@h-ai/ai' * const request: MCPServiceRequest = { serviceId: 'docs', tool: 'search', arguments: { query: 'manual' } } * ``` */ interface MCPServiceRequest { serviceId: string; tool: string; arguments?: CallToolRequest['params']['arguments']; } /** * 由可信应用从认证态和业务授权构造的调用上下文。 * @example * ```ts * import type { MCPServiceAuthorization } from '@h-ai/ai' * const authorization: MCPServiceAuthorization = { * principal: { tenantId: 'team', userId: 'ada' }, * authorize: ({ principal, serviceId, tool }) => principal.tenantId === 'team' && serviceId === 'docs' && tool === 'search', * } * ``` */ interface MCPServiceAuthorization { /** 从 IAM 会话或可信服务身份取得的主体,不能从模型或工具参数构造。 */ principal: { tenantId: string; userId: string; }; /** 可信调用方绑定的业务任务 ID;通过 Broker 调用时由绑定提供。 */ taskId?: string; /** 根据主体、工具和实际参数检查资料访问权限及操作权限。 */ authorize: (input: MCPServiceRequest & { principal: MCPServiceAuthorization['principal']; signal: AbortSignal; }) => boolean | Promise; /** 在请求开始前或执行中取消;远端已完成的操作由业务核对。 */ signal?: AbortSignal; } /** * 作业执行者在读取授权对象或提交暂存产物时使用的可信业务绑定。 * @example * ```ts * import type { MCPJobFileContext } from '@h-ai/ai' * function owner(context: MCPJobFileContext) { return context.principal.tenantId } * ``` */ interface MCPJobFileContext { principal: MCPServiceAuthorization['principal']; taskId?: string; jobId: string; signal: AbortSignal; } /** * 应用提供对象 ACL 与存储接入。文件内容只在作业节点暂存,队列仅保存对象 ID。 * @example * ```ts * import { err, type HaiResult } from '@h-ai/core' * import { HaiAIError, type MCPJobFiles } from '@h-ai/ai' * function denied(): HaiResult { return err(HaiAIError.MCP_TOOL_FORBIDDEN, 'File is not authorized') } * const files: MCPJobFiles = { read: async () => denied(), publish: async () => denied() } * ``` */ interface MCPJobFiles { /** 在读取前验证主体、任务状态、对象归属和读取授权。 */ read: (input: MCPJobFileContext & { fileId: string; }) => Promise>; /** 重新验证主体与任务,提交带归属、可按 jobId 回收的暂存对象。 */ publish: (input: MCPJobFileContext & { name: string; base64: string; }) => Promise>; } /** * 通过现有合并目录调用受控的第三方 Streamable HTTP 工具。 * @example * ```ts * import { ai, type MCPServiceAuthorization } from '@h-ai/ai' * async function search(context: MCPServiceAuthorization) { * const result = await ai.mcp.services.invoke({ serviceId: 'docs', tool: 'search', arguments: { query: 'manual' } }, context) * if (!result.success) return result * return result.data.content * } * ``` */ interface MCPServiceOperations { /** 解析当前清单和授权后连接远端,返回标准 MCP 工具内容或本地化失败。 */ invoke: (request: MCPServiceRequest, authorization: MCPServiceAuthorization) => Promise>; /** 在执行节点创建受信 HTTP 工具入口。 */ createBroker: (options: MCPServiceBrokerOptions) => HaiResult; } /** * 工具入口固定地址及每次调用的实时业务授权。 * @example * ```ts * import type { MCPServiceBrokerOptions } from '@h-ai/ai' * const broker: MCPServiceBrokerOptions = { * url: 'https://executor.example.com/mcp', * authorize: ({ principal, serviceId, taskId }) => principal.tenantId === 'team' && serviceId === 'docs' && taskId === 'run-1', * } * ``` */ interface MCPServiceBrokerOptions { /** Agent 容器可访问的固定工具端点。 */ url: string; /** 可信应用每次核验任务仍运行、主体和实际参数仍允许。 */ authorize: (input: Parameters[0] & { taskId: string; }) => boolean | Promise; } /** * 任务授权、模型可见工具名及应用提供的输入契约。 * @example * ```ts * import type { MCPServiceBindingRequest } from '@h-ai/ai' * const binding: MCPServiceBindingRequest = { * principal: { tenantId: 'team', userId: 'ada' }, * taskId: 'run-1', * tools: [{ id: 'docs_search', serviceId: 'docs', tool: 'search', description: 'Search manuals', inputSchema: { type: 'object' } }], * } * ``` */ interface MCPServiceBindingRequest { principal: MCPServiceAuthorization['principal']; taskId: string; tools: Array<{ id: string; serviceId: string; tool: string; description: string; inputSchema: Record; }>; /** 有效期,缺省 15 分钟,最多 24 小时。 */ ttlMs?: number; /** 执行结束或失租时撤销此绑定。 */ signal?: AbortSignal; } /** * 只向当前执行代次提供的 MCP 连接和撤销句柄。 * @example * ```ts * import type { MCPServiceBinding } from '@h-ai/ai' * function stop(binding: MCPServiceBinding) { binding.revoke() } * ``` */ interface MCPServiceBinding { /** 仅传给当前 Agent,含短期 Bearer。 */ servers: Array>; revoke: () => void; /** 此绑定到期、撤销或上层关闭时取消;受管 ACP 用它判定何时结束原生会话。 */ signal?: AbortSignal; } /** * 执行节点挂载的任务工具入口。 * @example * ```ts * import { createServer } from 'node:http' * import type { MCPServiceBroker } from '@h-ai/ai' * function mount(broker: MCPServiceBroker) { return createServer((req, res) => void broker.handleRequest(req, res)) } * ``` */ interface MCPServiceBroker { bind: (request: MCPServiceBindingRequest) => Promise>; handleRequest: (request: IncomingMessage, response: ServerResponse) => Promise; close: () => void; } /** * 将可信管理员登记的 MCP 输入契约连接到中立工具目录。 * @example * ```ts * import type { McpToolOptions } from '@h-ai/ai' * function count(options: McpToolOptions) { return options.definitions.length } * ``` */ interface McpToolOptions { context: ToolServiceContext; definitions: (ToolDefinition$1 & { serviceId: string; tool: string; })[]; authorize: MCPServiceAuthorization['authorize']; } /** * MCP 连接、凭据和调用限额继续由已有服务管理。 * @example 模块内部上下文 * ```ts * function build(options: McpToolOptions, services: () => MCPServiceOperations) { return createMcpTools(options, services) } * ``` */ declare function createMcpTools(options: McpToolOptions, services: () => MCPServiceOperations): HaiResult; /** * 由资源服务核验归属之后返回的文件或产物。 * @example * ```ts * import type { BuiltinArtifact } from '@h-ai/ai' * function size(file: BuiltinArtifact) { return file.data.byteLength } * ``` */ type BuiltinArtifact = ToolArtifact; /** * 业务资源引用,文件字节不会进入模型消息或 Runner 结果。 * @example * ```ts * import type { BuiltinArtifactReference } from '@h-ai/ai' * function id(reference: BuiltinArtifactReference) { return reference.id } * ``` */ type BuiltinArtifactReference = ToolArtifactReference; /** * 宿主资源访问接口;读取和提交均需复核身份、任务及资源权限。 * @example * ```ts * import type { BuiltinArtifactAccess } from '@h-ai/ai' * function reader(access: BuiltinArtifactAccess) { return access.read } * ``` */ type BuiltinArtifactAccess = ToolArtifactAccess; /** * 内置工具的可信执行绑定。 * @example * ```ts * import type { BuiltinToolOptions } from '@h-ai/ai' * function owner(options: BuiltinToolOptions) { return options.context.scope.userId } * ``` */ interface BuiltinToolOptions { context: ToolServiceContext; files: BuiltinArtifactAccess; /** 调用同一工具服务的固定容器作业;省略时不登记网址视频工作流。 */ executeJob?: (request: ToolSubmitRequest, context: ToolServiceContext) => Promise>; } /** * 本地工具服务与现有短期 MCP Broker 的装配。 * @example * ```ts * import type { BuiltinToolBrokerOptions } from '@h-ai/ai' * function endpoint(options: BuiltinToolBrokerOptions) { return options.url } * ``` */ interface BuiltinToolBrokerOptions { service: ToolService; url: string; } /** * 本地服务绑定只指定允许的工具名,Schema 来自服务当前目录。 * @example * ```ts * import type { BuiltinToolBinding } from '@h-ai/ai' * const binding: BuiltinToolBinding = { scope: { tenantId: 'team', userId: 'alice' }, sessionId: 'task-1', tools: ['image_generate'] } * ``` */ interface BuiltinToolBinding { scope: ToolServiceContext['scope']; sessionId: string; tools: readonly string[]; /** 绑定有效期毫秒;省略为 900000,范围 1..86400000,较短父信号及撤销仍优先。 */ ttlMs?: MCPServiceBindingRequest['ttlMs']; signal?: AbortSignal; } /** * 与现有 MCP HTTP 入口相同的挂载方式,不关闭借入的工具服务。 * @example * ```ts * import type { BuiltinToolBroker } from '@h-ai/ai' * function stop(broker: BuiltinToolBroker) { broker.close() } * ``` */ interface BuiltinToolBroker { bind: (input: BuiltinToolBinding) => Promise>; handleRequest: MCPServiceBroker['handleRequest']; close: () => void; } /** * 内置工具构造函数的公开签名。 * @example * ```ts * import type { CreateBuiltinTools } from '@h-ai/ai' * function build(factory: CreateBuiltinTools, options: Parameters[0]) { return factory(options) } * ``` */ type CreateBuiltinTools = (options: BuiltinToolOptions) => ToolSet; /** * @h-ai/ai — LLM 子功能类型 * * 定义 LLM 消息、请求、响应、流、工具等公共类型。 * @module ai-llm-types */ /** * 消息角色枚举:`'system'` | `'developer'` | `'user'` | `'assistant'` | `'tool'` * * @example * ```ts * import type { MessageRole } from '@h-ai/ai' * * const value: MessageRole = 'developer' * ``` */ type MessageRole = 'system' | 'developer' | 'user' | 'assistant' | 'tool'; /** * 文本内容块(多模态消息中的纯文本部分) * * @example * ```ts * import type { TextContent } from '@h-ai/ai' * * const value: TextContent = { type: 'text', text: '请说明这张图的主要内容。' } * ``` */ type TextContent = OpenAI.Chat.Completions.ChatCompletionContentPartText; /** * 图片内容块(多模态消息中的图片部分) * * @example * ```ts * import type { ImageContent } from '@h-ai/ai' * * const value: ImageContent = { type: 'image_url', image_url: { url: 'https://images.example.com/diagram.png', detail: 'low' } } * ``` */ type ImageContent = OpenAI.Chat.Completions.ChatCompletionContentPartImage; /** * 消息内容(纯文本字符串,或由内容块组成的多模态数组) * * @example * ```ts * import type { MessageContent } from '@h-ai/ai' * * const value: MessageContent = [{ type: 'text', text: '提取图中的标题' }, { type: 'image_url', image_url: { url: 'https://images.example.com/title.png' } }] * ``` */ type MessageContent = string | OpenAI.Chat.Completions.ChatCompletionContentPart[]; /** * 系统消息,用于设定对话的行为规则 * * @example * ```ts * import type { SystemMessage } from '@h-ai/ai' * * const value: SystemMessage = { role: 'system', content: '仅依据提供的订单数据回答。' } * ``` */ type SystemMessage = OpenAI.Chat.Completions.ChatCompletionSystemMessageParam; /** * 开发者消息(高优先级运行时约束) * * @example * ```ts * import type { DeveloperMessage } from '@h-ai/ai' * * const value: DeveloperMessage = { role: 'developer', content: '调用工具前先验证订单访问权限。' } * ``` */ interface DeveloperMessage { role: 'developer'; content: string | TextContent[]; name?: string; } /** * 用户消息 * * @example * ```ts * import type { UserMessage } from '@h-ai/ai' * * const value: UserMessage = { role: 'user', content: '订单 o-1 的状态是什么?' } * ``` */ type UserMessage = OpenAI.Chat.Completions.ChatCompletionUserMessageParam; /** * 工具调用描述,由助手消息中的 `tool_calls` 字段携带 * * @example * ```ts * import type { ToolCall } from '@h-ai/ai' * * const value: ToolCall = { id: 'call-order-1', type: 'function', function: { name: 'order_status', arguments: JSON.stringify({ orderId: 'o-1' }) } } * ``` */ type ToolCall = OpenAI.Chat.Completions.ChatCompletionMessageToolCall; /** * 助手消息(模型生成的回复,或传入对话上下文的助手轮次) * * @example * ```ts * import type { AssistantMessage } from '@h-ai/ai' * * const value: AssistantMessage = { role: 'assistant', content: null, tool_calls: [{ id: 'call-order-1', type: 'function', function: { name: 'order_status', arguments: JSON.stringify({ orderId: 'o-1' }) } }] } * ``` */ type AssistantMessage = OpenAI.Chat.Completions.ChatCompletionAssistantMessageParam & { /** * 推理模型额外返回的思维链内容。 * * DeepSeek thinking mode 在 function calling 多轮续写时要求回传该字段。 */ reasoning_content?: string | null; }; /** * 工具消息(工具执行结果,用于回传给模型) * * @example * ```ts * import type { ToolMessage } from '@h-ai/ai' * * const value: ToolMessage = { role: 'tool', tool_call_id: 'call-order-1', content: JSON.stringify({ status: 'shipped' }) } * ``` */ type ToolMessage = OpenAI.Chat.Completions.ChatCompletionToolMessageParam; /** * 聊天消息联合类型,涵盖对话中所有角色的消息 * * @example * ```ts * import type { ChatMessage } from '@h-ai/ai' * * const value: ChatMessage = { role: 'user', content: '请总结本周进展。' } * ``` */ type ChatMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | DeveloperMessage; /** * OpenAI function calling 工具定义格式 * * @example * ```ts * import type { ToolDefinition } from '@h-ai/ai' * * const value: ToolDefinition = { type: 'function', function: { name: 'sum', description: '计算两个数之和', parameters: { type: 'object', properties: { a: { type: 'number' }, b: { type: 'number' } }, required: ['a', 'b'] } } } * ``` */ type ToolDefinition = OpenAI.Chat.Completions.ChatCompletionTool; /** * 临时模型配置 * * 单次请求级别的临时模型端点,绕过配置中注册的模型与场景映射, * 直接指定 API Key / Base URL / 模型名等参数。适用于运行时动态切换模型、 * 多租户各自携带凭据等场景。其客户端实例按 TTL 缓存(见 `LLMConfig.tempModelCacheTtl`), * 与常驻模型客户端缓存隔离。 * * 未指定的字段回退到全局 LLM 配置:`apiKey` / `baseUrl` 回退全局值或环境变量, * `maxTokens` / `temperature` / `timeout` 回退全局默认值。 * * @example * ```ts * import type { TempModelConfig } from '@h-ai/ai' * * const value: TempModelConfig = { model: 'gpt-4o-mini', protocol: 'chat', timeout: 15_000 } * ``` */ interface TempModelConfig { /** 模型名称(传给 API 的实际模型名) */ model: string; /** API 协议(未指定时回退全局 `protocol`,再回退 `chat`;决定走 Chat Completions / Responses / Anthropic) */ protocol?: ApiType; /** API Key(未指定时回退全局配置 / 环境变量) */ apiKey?: string; /** API 基础 URL(未指定时回退全局配置 / 环境变量 / 默认 OpenAI) */ baseUrl?: string; /** 最大 Token 数(未指定时回退全局配置;请求显式指定 `max_tokens` 时以请求为准) */ maxTokens?: number; /** 采样温度(未指定时回退全局配置;请求显式指定 `temperature` 时以请求为准) */ temperature?: number; /** 请求超时时间(毫秒,未指定时回退全局配置) */ timeout?: number; } /** * 聊天完成请求参数 * * 继承 OpenAI SDK 全部标准请求字段,并扩展框架专属字段(`objectId`、`sessionId`)。 * `model` 改为可选(未指定时使用配置中的默认模型)。 * `stream` 字段由框架内部控制,不对外暴露。 * * @example * ```ts * import type { ChatCompletionRequest } from '@h-ai/ai' * * const value: ChatCompletionRequest = { messages: [{ role: 'user', content: '给出三个待办事项。' }], objectId: 'user-42', sessionId: 'weekly', temperature: 0.2, signal: new AbortController().signal } * ``` */ type ChatCompletionRequest = Omit & { /** 对话消息列表 */ messages: ChatMessage[]; /** 模型名称(可选,未指定时使用配置中的默认模型) */ model?: string; /** 交互主体 ID(传入后 LLM 会自动关联到该主体) */ objectId?: string; /** 会话 ID(传入后 LLM 会自动关联到该会话) */ sessionId?: string; /** 是否持久化对话记录(默认 true;传入 false 时跳过记录,适用于内部调用如实体提取) */ enablePersist?: boolean; /** 临时模型配置(传入后绕过配置注册的模型,使用临时端点;优先级高于 `model`) */ tempModel?: TempModelConfig; /** * 请求取消信号 * * 传入后透传给底层 SDK(OpenAI / Anthropic)的请求取消参数。主持人打断、 * 用户切换等场景可 `abortController.abort()` 立即停止上游生成与计费。 */ signal?: AbortSignal; }; /** * Token 使用统计 * * @example * ```ts * import type { TokenUsage } from '@h-ai/ai' * * const value: TokenUsage = { prompt_tokens: 20, completion_tokens: 10, total_tokens: 30 } * ``` */ type TokenUsage = OpenAI.CompletionUsage; /** * 聊天完成响应中的单个选择 * * @example * ```ts * import type { ChatCompletionChoice } from '@h-ai/ai' * * function responseText(choice: ChatCompletionChoice): string { * return choice.message.content ?? '' * } * ``` */ type ChatCompletionChoice = OpenAI.Chat.ChatCompletion.Choice; /** * 聊天完成响应(非流式) * * @example * ```ts * import type { ChatCompletionResponse } from '@h-ai/ai' * * function responseText(response: ChatCompletionResponse): string { * return response.choices[0]?.message.content ?? '' * } * ``` */ type ChatCompletionResponse = OpenAI.Chat.ChatCompletion; /** * 流式增量内容(每个 chunk 中的变化部分) * * @example * ```ts * import type { ChatCompletionDelta } from '@h-ai/ai' * * const value: ChatCompletionDelta = { content: '已发货' } * ``` */ type ChatCompletionDelta = OpenAI.Chat.ChatCompletionChunk.Choice.Delta; /** * 流式响应块(SSE 传输的单个数据帧) * * @example * ```ts * import type { ChatCompletionChunk } from '@h-ai/ai' * * const value: ChatCompletionChunk = { id: 'chatcmpl-example', object: 'chat.completion.chunk', created: 0, model: 'gpt-4o-mini', choices: [{ index: 0, delta: { content: '你好' }, finish_reason: null }] } * ``` */ type ChatCompletionChunk = OpenAI.Chat.ChatCompletionChunk; /** * 流处理结果(完整消费流后的累积数据) * * @example * ```ts * import type { StreamResult } from '@h-ai/ai' * * function completedMessage(result: StreamResult): string { * return result.finishReason === 'stop' ? result.content : '输出尚未完整结束' * } * ``` */ interface StreamResult { /** 累积的完整文本内容 */ content: string; /** 累积的完整 reasoning 内容 */ reasoningContent: string; /** 累积的完整工具调用列表 */ toolCalls: ToolCall[]; /** 完成原因(流未结束时为 `null`) */ finishReason: string | null; } /** * 流处理器接口 * * 逐 chunk 喂入,内部累积文本和工具调用,支持 reset 复用。 * * @example * ```ts * import { ai } from '@h-ai/ai' * * const processor = ai.stream.createProcessor() * processor.process({ id: 'chatcmpl-example', object: 'chat.completion.chunk', created: 0, model: 'gpt-4o-mini', choices: [{ index: 0, delta: { content: '你好' }, finish_reason: 'stop' }] }) * const message = processor.toAssistantMessage() * ``` */ interface StreamProcessor { /** 处理单个 chunk,返回增量 delta;空 choices 时返回 `null` */ process: (chunk: ChatCompletionChunk) => ChatCompletionDelta | null; /** 获取当前累积结果(不重置状态) */ getResult: () => StreamResult; /** 将累积结果转换为 AssistantMessage(有 tool_calls 时 content 为 `null`) */ toAssistantMessage: () => AssistantMessage; /** 重置内部状态,可重新处理新一轮流 */ reset: () => void; } /** * SSE(Server-Sent Events)事件结构 * * @example * ```ts * import type { SSEEvent } from '@h-ai/ai' * * const value: SSEEvent = { id: 'event-1', event: 'delta', data: JSON.stringify({ text: '你好' }), retry: 1000 } * ``` */ interface SSEEvent { /** 事件类型(`event:` 字段) */ event?: string; /** 事件 ID(`id:` 字段);解码继承最近有效值,空字符串显式清空,NUL 字段忽略。 */ id?: string; /** 重连间隔(毫秒,非负安全整数);解码保留最近有效值,但不会自动执行重连。 */ retry?: number; /** 数据载荷(`data:` 字段,多行数据以 `\n` 合并) */ data?: string; } /** * SSE 解码器接口 * * 内部维护行与事件缓冲区,支持跨 chunk 的 LF/CRLF/CR 和多行 data。 * 仅移除冒号后的一个 ASCII 空格;只派发有 data 字段且已收到空行的事件。 * EOF 不补空行;新连接或放弃未完成输入时调用 reset,清除旧 id/retry 与剩余数据。 * * @example * ```ts * import { ai } from '@h-ai/ai' * * const decoder = ai.stream.createSSEDecoder() * const first = [...decoder.decode('data: hel')] * const second = [...decoder.decode('lo\n\n')] * // first 为空,second 的首个事件 data 为 hello。 * ``` */ interface SSEDecoder { /** 追加 UTF-8 解码后的文本并解码完整事件;未完成的部分留在缓冲区。 */ decode: (text: string) => Iterable; /** 清空所有缓冲区及连接级元数据;不会派发残余的不完整事件。 */ reset: () => void; } /** * 流式 JSON 文本预览的字符上限,均以 UTF-16 单元计。 * @example * ```ts * import type { JsonFieldPreviewOptions } from '@h-ai/ai' * const options: JsonFieldPreviewOptions = { maxLength: 1000, maxInputLength: 20000 } * ``` */ interface JsonFieldPreviewOptions { /** 预览字段的上限,默认 12000。 */ maxLength?: number; /** 累计输入的上限,默认 1000000。 */ maxInputLength?: number; } /** * 针对一次模型回复的预览器。只预览指定的顶层字符串字段,最终结果仍需校验完整 JSON。 * @example * ```ts * import { ai } from '@h-ai/ai' * const preview = ai.stream.createJsonFieldPreview('text') * const prefix = preview.push('{"text":"已记录') * ``` */ interface JsonFieldPreview { /** 输入下一段 JSON。返回累计前缀,未变时返回 undefined。累计输入超限时抛出 RangeError。 */ push: (fragment: string) => string | undefined; } /** * 流处理操作接口(通过 `ai.stream` 访问,纯函数,无需初始化) * * @example * ```ts * import { ai } from '@h-ai/ai' * * // 纯协议处理无需初始化 ai。 * const wire = ai.stream.encodeSSE({ event: 'delta', data: '你好' }) * const events = [...ai.stream.createSSEDecoder().decode(wire)] * ``` */ interface StreamOperations { /** 创建顶层字符串字段的增量预览器。字段名或上限无效时抛出 RangeError。 */ createJsonFieldPreview: (field: string, options?: JsonFieldPreviewOptions) => JsonFieldPreview; /** 创建新的流处理器实例 */ createProcessor: () => StreamProcessor; /** 完整消费流并返回累积结果 */ collect: (stream: AsyncIterable) => Promise; /** 创建新的 SSE 解码器实例 */ createSSEDecoder: () => SSEDecoder; /** 将 SSE 事件编码为符合规范的文本(以 `\n\n` 结尾) */ encodeSSE: (event: SSEEvent) => string; } /** * 模型工具协议适配器,只负责编解码并委托中立注册表执行。 * * 定义、注册、授权、超时和取消由 `@h-ai/tools` 负责;执行失败保留原始 Tools 错误。 * @example * ```ts * import { ai } from '@h-ai/ai' * import { tools } from '@h-ai/tools' * import { z } from 'zod' * const registry = tools.createRegistry() * const registered = registry.register(tools.define({ name: 'echo', description: '返回文本', parameters: z.object({ text: z.string() }), handler: input => input.text })) * if (!registered.success) throw new Error(registered.error.message) * const modelTools = ai.tools.adapt(registry) * const result = await modelTools.execute({ id: 'call-1', type: 'function', function: { name: 'echo', arguments: '{"text":"你好"}' } }) * if (!result.success) throw new Error(result.error.message) * ``` */ interface ToolRegistryOperations { /** 读取当前中立注册表,转换为模型 function calling 定义。 */ getDefinitions: () => ToolDefinition[]; /** 解码 JSON 入参并执行;Tools 业务错误直接透传,协议错误属于 AI。 */ execute: (toolCall: ToolCall, options?: ToolExecutionOptions) => Promise>; /** 先检查所有调用格式,再由中立注册表串行或显式并行执行,按输入顺序编码消息。 */ executeAll: (toolCalls: ToolCall[], options?: ToolExecutionOptions & { parallel?: boolean; }) => Promise>; } /** * AI 的工具协议接入,纯适配,无需初始化。 * @example * ```ts * import { ai } from '@h-ai/ai' * import { tools } from '@h-ai/tools' * const registry = tools.createRegistry() * const modelTools = ai.tools.adapt(registry) * const definitions = modelTools.getDefinitions() * ``` */ interface ToolsOperations { /** 将已登记 MCP 服务接入同一工具目录及执行管道。 */ createMcpTools: (options: Parameters[0]) => ReturnType; /** 组合现有模型能力为带资源授权的工具定义,不执行模型请求。 */ createBuiltinTools: CreateBuiltinTools; /** 通过现有短期 MCP Broker 向原生 Agent 开放本地工具服务。 */ createBroker: (options: BuiltinToolBrokerOptions) => HaiResult; /** 使用同一份工具注册表;不复制工具或授权状态。 */ adapt: (registry: ToolRegistryOperations$1) => ToolRegistryOperations; } /** * 对话记录查询选项 * * @example * ```ts * import type { ChatHistoryOptions } from '@h-ai/ai' * * const value: ChatHistoryOptions = { limit: 20, order: 'desc' } * ``` */ interface ChatHistoryOptions { /** 返回数量限制 */ limit?: number; /** 排序方向(默认 `'desc'` 最新在前) */ order?: 'asc' | 'desc'; } /** * ask/askStream 便捷方法选项 * * @example * ```ts * import type { AskOptions } from '@h-ai/ai' * * const value: AskOptions = { systemPrompt: '回答保持简洁。', objectId: 'user-42', sessionId: 'weekly', temperature: 0.2 } * ``` */ interface AskOptions { /** 系统提示词 */ systemPrompt?: string; /** 使用的模型 */ model?: string; /** 交互主体 ID */ objectId?: string; /** 会话 ID */ sessionId?: string; /** 温度(0~2) */ temperature?: number; /** 是否持久化对话记录(默认 true;传入 false 时跳过记录) */ enablePersist?: boolean; /** 临时模型配置(传入后绕过配置注册的模型,使用临时端点;优先级高于 `model`) */ tempModel?: TempModelConfig; /** 请求取消信号(透传给底层 SDK,支持主动打断上游生成) */ signal?: AbortSignal; } /** * 对话记录 * * 每次 `llm.chat()` 调用在传入 `objectId` 时自动保存的请求+响应快照。 * * @example * ```ts * import type { ChatRecord } from '@h-ai/ai' * * function elapsedLabel(record: ChatRecord): string { * return `${record.sessionId}: ${record.duration}ms, ${record.response.usage.total_tokens} tokens` * } * ``` */ interface ChatRecord { /** 记录唯一 ID */ id: string; /** 交互主体 ID */ objectId: string; /** 会话 ID */ sessionId: string; /** 请求摘要 */ request: { model: string; messages: ChatMessage[]; }; /** 响应摘要 */ response: { content: string; toolCalls?: ToolCall[]; finishReason: string; usage: TokenUsage; }; /** 创建时间(Unix 毫秒) */ createdAt: number; /** 耗时(毫秒) */ duration: number; } /** * 结构化输出请求 * * 给定 Zod schema,要求模型返回 JSON,并在应用本地验证结构。 * 解析失败时自动带错误修复重试,避免调用方手写 `JSON.parse` 的不稳定性。 * * @example * ```ts * import type { GenerateObjectRequest } from '@h-ai/ai' * import { z } from 'zod' * * const request: GenerateObjectRequest<{ title: string }> = { * schema: z.object({ title: z.string() }), * messages: [{ role: 'user', content: '为本次会议生成标题。' }], * maxRepairs: 1, * } * ``` */ interface GenerateObjectRequest { /** 输出结构的 Zod schema */ schema: ZodType; /** 对话消息 */ messages: ChatMessage[]; /** 模型名(可选,不传时使用默认模型) */ model?: string; /** 系统提示词(可选,追加为首条 system 消息) */ systemPrompt?: string; /** 温度覆盖 */ temperature?: number; /** 临时模型配置 */ tempModel?: TempModelConfig; /** schema 名称(用于 json_schema response_format,默认 `result`) */ schemaName?: string; /** 上游响应格式,默认 `json_schema`。只支持 JSON 模式的 Chat 网关可使用 `json_object`,本地仍会校验 schema。 */ responseFormat?: 'json_schema' | 'json_object'; /** 解析失败时的修复重试次数(默认 1) */ maxRepairs?: number; /** 单次生成的最大输出 token 数。 */ maxTokens?: number; /** 选用流式调用,预览只包含指定顶层字段。失败尝试的内容经空串清除。 */ preview?: JsonFieldPreviewOptions & { field: string; onPrefix: (text: string) => void | Promise; }; /** 取消信号 */ signal?: AbortSignal; } /** * LLM 操作接口(通过 `ai.llm` 访问) * * 需要先调用 `ai.init()` 初始化,否则返回 `NOT_INITIALIZED` 错误。 * * @example * ```ts * import { ai } from '@h-ai/ai' * * // 应用启动已成功初始化 ai;scope 由可信会话绑定。 * async function summarizeWeek() { * const result = await ai.llm.chat({ messages: [{ role: 'user', content: '总结本周待办。' }], objectId: 'user-42', sessionId: 'weekly' }) * if (!result.success) * return result * return result.data.choices[0]?.message.content ?? '' * } * ``` */ interface LLMOperations { /** 发送聊天请求,返回 `HaiResult` */ chat: (request: ChatCompletionRequest) => Promise>; /** 发送流式聊天请求,逐 chunk 产出 `ChatCompletionChunk` */ chatStream: (request: ChatCompletionRequest) => AsyncIterable; /** 获取可用模型名称列表 */ listModels: () => Promise>; /** 查询对话历史记录(需传入 objectId;可选 sessionId 以按会话过滤) */ getHistory: (scope: InteractionScope, options?: ChatHistoryOptions) => Promise>; /** 列出指定 objectId 下的所有会话 */ listSessions: (objectId: string) => Promise>; /** * 便捷方法:发送纯文本问题,返回回复文本 * * 内部构建 ChatCompletionRequest 并调用 `chat()`,只返回第一个 choice 的文本。 * * @param question - 用户问题文本 * @param options - 可选的模型、systemPrompt、objectId、sessionId 等 * @returns 回复文本 */ ask: (question: string, options?: AskOptions) => Promise>; /** * 便捷方法:流式发送纯文本问题,返回文本片段异步迭代器 * * @param question - 用户问题文本 * @param options - 可选配置 * @returns 文本片段的异步迭代器 */ askStream: (question: string, options?: AskOptions) => AsyncIterable; /** * 结构化输出:按 Zod schema 约束模型输出并解析为对象 * * 默认使用 `json_schema` 约束输出。使用 `json_object` 时由提示提供 Schema,两种模式均本地校验并按配置修复重试。 * * @param request - 包含 schema、messages 及可选模型/修复次数等 * @returns 符合 schema 的对象;多次重试仍无法解析时返回 `INVALID_REQUEST` */ generateObject: (request: GenerateObjectRequest) => Promise>; } /** * @h-ai/ai — Compress 子功能类型 * * 定义上下文压缩操作的类型接口:滑动窗口、摘要、混合三种策略。 * 在对话超出模型上下文窗口时,自动压缩历史消息以保持对话连续性。 * @module ai-compress-types */ /** * 压缩策略枚举 * * @example * ```ts * import { CompressionStrategySchema } from '@h-ai/ai' * const parsed = CompressionStrategySchema.safeParse('sliding-window') * if (!parsed.success) throw parsed.error * const selected = parsed.data * ``` */ declare const CompressionStrategySchema: z.ZodEnum<{ summary: "summary"; "sliding-window": "sliding-window"; hybrid: "hybrid"; }>; /** * 压缩策略类型 * * @example * ```ts * import type { CompressionStrategy } from '@h-ai/ai' * const value: CompressionStrategy = 'sliding-window' * const usesSummary = value !== 'sliding-window' * ``` */ type CompressionStrategy = z.infer; /** * 上下文压缩选项 * * @example * ```ts * import { ai, type CompressOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * async function run(options: CompressOptions) { * const result = await ai.compress.tryCompress([{ role: 'user', content: '你好' }], options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface CompressOptions { /** 压缩策略(默认使用配置的 defaultStrategy) */ strategy?: CompressionStrategy; /** 目标 token 数(默认使用配置的 defaultMaxTokens,0 表示取模型 maxTokens 的 80%) */ maxTokens?: number; /** 保留 system 消息(默认 true) */ preserveSystem?: boolean; /** 保留最近 N 条消息不压缩(默认使用配置的 preserveLastN) */ preserveLastN?: number; /** 摘要用的模型 */ summaryModel?: string; } /** * 上下文压缩结果 * * @example * ```ts * import type { CompressResult } from '@h-ai/ai' * const value: CompressResult = { messages: [{ role: 'user', content: '你好' }], originalTokens: 2, compressedTokens: 2, removedCount: 0 } * const text = value.messages.map(message => message.content).join('\n') * ``` */ interface CompressResult { /** 压缩后的消息列表 */ messages: ChatMessage[]; /** 原始消息的估算 token 数 */ originalTokens: number; /** 压缩后的估算 token 数 */ compressedTokens: number; /** 被移除/合并的消息数 */ removedCount: number; /** 生成的摘要文本(仅 summary/hybrid 策略有值) */ summary?: string; } /** * Compress 操作接口 * * 管理对话消息的压缩,支持三种策略: * - `sliding-window`:移除最旧的消息,保留最近 N 条 * - `summary`:使用 LLM 生成摘要替换旧消息 * - `hybrid`:先滑动窗口,不够则回退到摘要 * * @example * ```ts * import { ai, type CompressOperations } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * const operations: CompressOperations = ai.compress * const result = await operations.tryCompress([{ role: 'user', content: '你好' }], { strategy: 'sliding-window', maxTokens: 100 }) * if (!result.success) throw new Error(result.error.message) * const withinBudget = result.data.compressedTokens <= 100 * ``` */ interface CompressOperations { /** * 尝试压缩消息列表,使其不超过指定 Token 预算 * * 如果当前 token 数未超限则直接返回(不压缩),因此命名为 tryCompress。 * 如果受保护的 system、最近消息或最新 user 输入自身已超过预算,返回 * `HaiAIError.CONTEXT_BUDGET_EXCEEDED`,不会删除受保护内容或返回超预算的成功结果。 * * @param messages - 消息列表 * @param options - 压缩选项 * @returns 满足预算的压缩结果,或无法满足预算时的显式错误 */ tryCompress: (messages: ChatMessage[], options?: CompressOptions) => Promise>; } /** * @h-ai/ai — Retrieval 子功能类型 * * 定义检索操作的类型接口,支持向量检索和混合检索。 * @module ai-retrieval-types */ /** * 信源引用——结构化描述检索结果的来源信息 * * 用于在 RAG 回答中追踪每段内容的出处。 * * @example * ```ts * import type { Citation } from '@h-ai/ai' * const value: Citation = { documentId: 'guide', title: '部署指南', url: 'https://docs.example.com/guide', position: 'section:2', chunkId: 'guide-2' } * const output = value.title ?? value.documentId * ``` */ interface Citation { /** 原始文档 ID(入库时的文档级唯一标识) */ documentId?: string; /** 原始文档标题 */ title?: string; /** 原始文档 URL / 路径 */ url?: string; /** 位置信息(页码、段落、section 等) */ position?: string; /** 分块 ID(对应 vecdb 中的向量记录 ID) */ chunkId?: string; /** 信源集合名 */ collection?: string; } /** * 检索源——描述一个可查询的知识来源 * * @example * ```ts * import { ai, type RetrievalSource } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: RetrievalSource) { * const result = await ai.retrieval.addSource(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface RetrievalSource { /** 来源唯一标识 */ id: string; /** collection / table 名称 */ collection: string; /** 信源显示名(用于 UI 展示) */ name?: string; /** 信源 URL / 路径 */ url?: string; /** 最大返回条数(默认 5) */ topK?: number; /** 最低相似度(低于此值的结果被过滤) */ minScore?: number; /** 元数据过滤条件 */ filter?: Record; } /** * 检索请求参数 * * @example * ```ts * import { ai, type RetrievalRequest } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: RetrievalRequest) { * const result = await ai.retrieval.retrieve(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface RetrievalRequest { /** 查询文本 */ query: string; /** 使用的检索源(不指定则使用全部已注册源) */ sources?: string[]; /** 全局 topK 覆盖 */ topK?: number; /** 全局 minScore 覆盖 */ minScore?: number; /** 是否启用 Rerank 重排序(需要已初始化 ai.rerank) */ enableRerank?: boolean; /** Rerank 使用的模型名称覆盖 */ rerankModel?: string; } /** * 单条检索结果 * * @example * ```ts * import type { RetrievalResultItem } from '@h-ai/ai' * const value: RetrievalResultItem = { id: 'chunk-1', content: '共享数据库', score: 0.9, sourceId: 'docs' } * const output = `${value.sourceId}: ${value.content}` * ``` */ interface RetrievalResultItem { /** 文档 ID */ id: string; /** 内容文本 */ content: string; /** 相似度分数 [0, 1] */ score: number; /** 来源 id */ sourceId: string; /** 元数据 */ metadata?: Record; /** 结构化信源引用 */ citation?: Citation; } /** * 检索结果 * * @example * ```ts * import type { RetrievalResult } from '@h-ai/ai' * const value: RetrievalResult = { items: [{ id: 'chunk-1', content: '共享数据库', score: 0.9, sourceId: 'docs' }], query: '如何部署', duration: 12 } * const output = value.items.map(item => item.content) * ``` */ interface RetrievalResult { /** 检索结果列表(按分数降序) */ items: RetrievalResultItem[]; /** 查询文本 */ query: string; /** 查询耗时(毫秒) */ duration: number; } /** * 检索操作接口 * * @example * ```ts * import { ai, type RetrievalOperations } from '@h-ai/ai' * // 应用启动已成功初始化 ai,docs 为已注册检索源。 * const operations: RetrievalOperations = ai.retrieval * const result = await operations.retrieve({ query: '部署要求', sources: ['docs'], topK: 3 }) * if (!result.success) throw new Error(result.error.message) * const citations = result.data.items.map(item => item.citation) * ``` */ interface RetrievalOperations { /** * 注册一个检索源(持久化到 DB) * * @param source - 检索源配置 * @returns 成功返回 ok,重复 id 返回错误 */ addSource: (source: RetrievalSource) => Promise>; /** * 移除一个检索源(从 DB 删除) * * @param sourceId - 检索源 ID * @returns 成功返回 ok,未找到返回错误 */ removeSource: (sourceId: string) => Promise>; /** * 列出所有已注册的检索源(从 DB 读取,分布式一致) */ listSources: () => Promise; /** * 执行检索 * * @param request - 检索请求 * @returns 检索结果 */ retrieve: (request: RetrievalRequest) => Promise>; } /** * @h-ai/ai — Knowledge 子功能类型 * * 定义知识库操作的类型接口:文档导入、实体索引、信源追踪检索。 * @module ai-knowledge-types */ /** * 内置实体类型枚举(预设值,可通过配置 `entityTypes` 扩展) * * @example * ```ts * import { EntityTypeSchema } from '@h-ai/ai' * const parsed = EntityTypeSchema.safeParse('project') * if (!parsed.success) throw parsed.error * const builtIn = parsed.data * ``` */ declare const EntityTypeSchema: z.ZodEnum<{ person: "person"; project: "project"; concept: "concept"; organization: "organization"; location: "location"; event: "event"; other: "other"; }>; /** * 实体类型(字符串,支持内置类型及用户自定义类型) * * @example * ```ts * import type { EntityType } from '@h-ai/ai' * const value: EntityType = 'product' * const output = value.toLowerCase() * ``` */ type EntityType = string; /** * 知识实体 * * 表示从文档中提取的命名实体(人名、项目名、概念等), * 存储在 KnowledgeStore 中用于倒排索引查询。 * * @example * ```ts * import type { KnowledgeEntity } from '@h-ai/ai' * const value: KnowledgeEntity = { id: 'entity-1', name: 'HAI', type: 'project', aliases: ['hai-framework'] } * const output = [value.name, ...(value.aliases ?? [])].join(', ') * ``` */ interface KnowledgeEntity { /** 实体唯一标识 */ id: string; /** 实体名称 */ name: string; /** 实体类型 */ type: EntityType; /** 别名列表(可选) */ aliases?: string[]; /** 描述(可选) */ description?: string; /** 创建时间 */ createdAt?: string; /** 更新时间 */ updatedAt?: string; } /** * 文档-实体关联记录 * * 倒排索引中的一条记录,记录实体与文档/分块的关联关系。 * * @example * ```ts * import type { EntityDocumentRelation } from '@h-ai/ai' * const value: EntityDocumentRelation = { entityId: 'entity-1', documentId: 'guide', chunkId: 'guide-1', collection: 'docs', relevance: 1 } * const output = `${value.collection}/${value.documentId}` * ``` */ interface EntityDocumentRelation { /** 实体 ID */ entityId: string; /** 文档 ID(对应向量存储中的 documentId) */ documentId: string; /** 分块 ID(对应向量存储中的向量记录 ID) */ chunkId?: string; /** 集合名 */ collection: string; /** 关联强度 [0, 1](默认 1.0) */ relevance?: number; /** 实体在该文档中的上下文片段(可选) */ context?: string; /** 创建时间 */ createdAt?: string; } /** * 知识库初始化选项 * * @example * ```ts * import { ai, type KnowledgeSetupOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: KnowledgeSetupOptions) { * const result = await ai.knowledge.setup(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface KnowledgeSetupOptions { /** 集合名(可选,默认使用配置中的 collection) */ collection?: string; /** 向量维度(可选,默认使用配置中的 dimension) */ dimension?: number; } /** * 文档导入输入 * * @example * ```ts * import { ai, type KnowledgeIngestInput } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: KnowledgeIngestInput) { * const result = await ai.knowledge.ingest(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface KnowledgeIngestInput { /** 文档唯一标识(必填,用于关联信源和实体) */ documentId: string; /** 文档原始内容文本 */ content: string; /** 文档标题(可选,存入 metadata 用于信源展示) */ title?: string; /** 文档 URL / 路径(可选,存入 metadata 用于信源展示) */ url?: string; /** 集合名(可选,默认使用配置中的 collection) */ collection?: string; /** 附加元数据(可选,合并到每个 chunk 的 metadata 中) */ metadata?: Record; /** 是否启用实体提取(可选,覆盖全局配置) */ enableEntityExtraction?: boolean; /** * 文本清洗选项(可选,覆盖全局配置默认值) * * 字段含义与 @h-ai/datapipe CleanOptionsInput 一致。 * 知识库默认关闭 normalizeWhitespace 和 trim,调用时可以显式开启。 */ cleanOptions?: CleanOptionsInput; /** * 分块选项(可选,覆盖全局配置默认值) * * 字段含义与 @h-ai/datapipe ChunkOptionsInput 完全一致, * 支持 mode、maxSize、overlap、separator、markdownMinLevel 等完整选项。 */ chunkOptions?: ChunkOptionsInput; } /** * 文档导入结果 * * @example * ```ts * import type { KnowledgeIngestResult, KnowledgeOperations } from '@h-ai/ai' * async function reconcile(knowledge: KnowledgeOperations, value: KnowledgeIngestResult) { * if (!value.cleanupPending) return value.revision * let offset = 0 * while (true) { * const repaired = await knowledge.repair({ offset, limit: 100 }) * if (!repaired.success) throw new Error(repaired.error.message) * offset += repaired.data.processed * if (offset >= repaired.data.total || repaired.data.processed === 0) break * } * return value.revision * } * ``` */ interface KnowledgeIngestResult { /** 文档 ID */ documentId: string; /** 已完整发布的唯一文档版本;分块 ID 也包含此版本。 */ revision: string; /** 新版本已可见,但旧向量删除失败;调用 repair 重试,不能忽略此标志。 */ cleanupPending: boolean; /** 生成的分块数量 */ chunkCount: number; /** 提取的实体列表(未启用实体提取时为空数组) */ entities: KnowledgeEntity[]; /** 处理耗时(毫秒) */ duration: number; } /** * 分页恢复暂存和向量清理;删除集合后也允许调用。 * * @example * ```ts * import { ai, type KnowledgeRepairOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: KnowledgeRepairOptions) { * const result = await ai.knowledge.repair(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface KnowledgeRepairOptions { /** 集合名,默认使用 knowledge.collection。 */ collection?: string; /** 清单偏移,包含已删除文档的墓碑,默认 0。 */ offset?: number; /** 本页最多检查 1–1000 份清单,默认 100。 */ limit?: number; } /** * 本页补偿扫描进度;失败以 HaiResult 返回,补偿记录仍保留。 * * @example * ```ts * import type { KnowledgeRepairResult } from '@h-ai/ai' * const value: KnowledgeRepairResult = { processed: 50, total: 120 } * const output = value.processed < value.total * ``` */ interface KnowledgeRepairResult { /** 本页检查的清单数量。 */ processed: number; /** 集合内清单总数,包含永久补偿墓碑。 */ total: number; } /** * 知识检索选项 * * @example * ```ts * import { ai, type KnowledgeRetrieveOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: KnowledgeRetrieveOptions) { * const result = await ai.knowledge.retrieve('部署要求', options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface KnowledgeRetrieveOptions { /** 集合名(可选,默认使用配置中的 collection) */ collection?: string; /** 返回的最大结果数(默认 10) */ topK?: number; /** 最低相似度(默认无限制) */ minScore?: number; /** 是否启用实体增强检索(默认 true) */ enableEntityBoost?: boolean; /** * 透传给向量 Provider 的元数据过滤条件;LanceDB 仅支持顶层 string/有限 number/boolean/null 的 AND 匹配,null 不匹配缺失字段。 * 对象、数组及 undefined 不受 LanceDB 支持,过滤失败返回 KNOWLEDGE_RETRIEVE_FAILED;其它后端语义须单独核对。 */ filter?: Record; } /** * 知识检索结果项 * * @example * ```ts * import type { KnowledgeRetrieveItem } from '@h-ai/ai' * const value: KnowledgeRetrieveItem = { id: 'chunk-1', content: '共享数据库', score: 0.9, citation: { documentId: 'guide', chunkId: 'chunk-1' }, matchedEntities: ['HAI'] } * const output = value.citation.documentId * ``` */ interface KnowledgeRetrieveItem { /** 分块 ID */ id: string; /** 分块内容 */ content: string; /** 综合得分(向量相似度 + 实体加权) */ score: number; /** 结构化信源引用 */ citation: Citation; /** 元数据 */ metadata?: Record; /** 命中的实体名称列表(实体增强检索时填充) */ matchedEntities?: string[]; } /** * 知识检索结果 * * @example * ```ts * import type { KnowledgeRetrieveResult } from '@h-ai/ai' * const value: KnowledgeRetrieveResult = { items: [], citations: [], query: '部署要求', duration: 12 } * const output = value.items.map(item => item.content) * ``` */ interface KnowledgeRetrieveResult { /** 检索结果列表(按综合分数降序) */ items: KnowledgeRetrieveItem[]; /** 去重后的信源引用列表 */ citations: Citation[]; /** 查询文本 */ query: string; /** 查询耗时(毫秒) */ duration: number; } /** * 知识问答选项 * * @example * ```ts * import { ai, type KnowledgeAskOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: KnowledgeAskOptions) { * const result = await ai.knowledge.ask('如何部署?', options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface KnowledgeAskOptions extends KnowledgeRetrieveOptions { /** LLM 模型名称覆盖 */ model?: string; /** 系统提示词覆盖 */ systemPrompt?: string; /** 温度覆盖 */ temperature?: number; /** 消息历史(多轮对话) */ messages?: ChatMessage[]; } /** * 知识问答结果 * * @example * ```ts * import type { KnowledgeAskResult } from '@h-ai/ai' * const value: KnowledgeAskResult = { answer: '使用共享数据库', context: [], citations: [], query: '部署要求', model: 'configured-model' } * const output = value.answer * ``` */ interface KnowledgeAskResult { /** LLM 生成的回答 */ answer: string; /** 使用的上下文 */ context: KnowledgeRetrieveItem[]; /** 去重后的信源引用列表 */ citations: Citation[]; /** 查询文本 */ query: string; /** 使用的模型 */ model: string; /** Token 使用统计 */ usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; } /** * 实体查询选项 * * @example * ```ts * import { ai, type EntityQueryOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: EntityQueryOptions) { * const result = await ai.knowledge.findByEntity('HAI', options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface EntityQueryOptions { /** 集合名(可选,默认使用配置中的 collection) */ collection?: string; /** 实体类型过滤 */ type?: EntityType; } /** * 实体关联文档结果 * * @example * ```ts * import type { EntityDocumentResult } from '@h-ai/ai' * const value: EntityDocumentResult = { entity: { id: 'entity-1', name: 'HAI', type: 'project' }, documents: [{ documentId: 'guide', collection: 'docs', relevance: 1 }] } * const output = value.documents.map(document => document.documentId) * ``` */ interface EntityDocumentResult { /** 实体信息 */ entity: KnowledgeEntity; /** 关联文档列表 */ documents: Array<{ documentId: string; chunkId?: string; collection: string; relevance: number; context?: string; }>; } /** * 实体列表查询选项 * * @example * ```ts * import { ai, type EntityListOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: EntityListOptions) { * const result = await ai.knowledge.listEntities(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface EntityListOptions { /** 集合名过滤(不指定则返回所有 collection 的实体) */ collection?: string; /** 实体类型过滤 */ type?: EntityType; /** 关键词搜索(模糊匹配实体名称和别名) */ keyword?: string; /** 最大返回数 */ limit?: number; } /** * 文件导入输入(从文件路径读取内容后自动 ingest) * * 仅 Node.js 端可用。 * * @example * ```ts * import { ai, type KnowledgeIngestFileInput } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: KnowledgeIngestFileInput) { * const result = await ai.knowledge.ingestFile(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface KnowledgeIngestFileInput { /** 文件路径(绝对路径或相对路径) */ filePath: string; /** 文档唯一标识(可选,默认从文件名派生) */ documentId?: string; /** 文档标题(可选,默认为文件名) */ title?: string; /** 文件编码(默认 'utf-8') */ encoding?: BufferEncoding; /** 集合名(可选,默认使用配置中的 collection) */ collection?: string; /** 附加元数据 */ metadata?: Record; /** 是否启用实体提取 */ enableEntityExtraction?: boolean; /** 清洗选项 */ cleanOptions?: CleanOptionsInput; /** 分块选项 */ chunkOptions?: ChunkOptionsInput; } /** * 文档信息(列表展示用) * * @example * ```ts * import type { KnowledgeDocumentInfo } from '@h-ai/ai' * const value: KnowledgeDocumentInfo = { documentId: 'guide', revision: 'revision-1', title: '指南', chunkCount: 2, entityCount: 1, createdAt: Date.now() } * const output = `${value.title}: ${value.chunkCount}` * ``` */ interface KnowledgeDocumentInfo { /** 当前完整发布版本。 */ revision: string; /** 文档 ID */ documentId: string; /** 文档标题 */ title?: string; /** 文档来源 URL / 路径 */ url?: string; /** 分块数量 */ chunkCount: number; /** 关联实体数 */ entityCount: number; /** 创建时间(Unix 毫秒) */ createdAt: number; } /** * 文档列表查询选项 * * @example * ```ts * import { ai, type KnowledgeDocumentListOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: KnowledgeDocumentListOptions) { * const result = await ai.knowledge.listDocuments(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface KnowledgeDocumentListOptions { /** 集合名覆盖(不指定则使用配置中的 default) */ collection?: string; /** 偏移量 */ offset?: number; /** 每页数量(默认 20) */ limit?: number; } /** * 文档删除选项 * * @example * ```ts * import { ai, type KnowledgeDocumentRemoveOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai,且目标知识集合已 setup。 * async function run(options: KnowledgeDocumentRemoveOptions) { * const result = await ai.knowledge.removeDocument('guide', options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface KnowledgeDocumentRemoveOptions { /** 集合名覆盖 */ collection?: string; } /** * 批量导入进度回调参数 * * @example * ```ts * import type { KnowledgeIngestBatchProgress } from '@h-ai/ai' * function progress(value: KnowledgeIngestBatchProgress): string { * if (value.error) return `${value.currentDocumentId}: ${value.error.message}` * return `${value.completed}/${value.total}` * } * ``` */ interface KnowledgeIngestBatchProgress { /** 已完成数量 */ completed: number; /** 总数量 */ total: number; /** 当前文档 ID */ currentDocumentId: string; /** 当前文档导入结果(失败时为 undefined) */ result?: KnowledgeIngestResult; /** 当前文档导入错误(成功时为 undefined) */ error?: HaiError; } /** * 批量导入结果 * * @example * ```ts * import type { KnowledgeIngestBatchResult } from '@h-ai/ai' * function failedDocuments(value: KnowledgeIngestBatchResult): string[] { * return value.results.filter(item => item.error !== undefined).map(item => item.documentId) * } * ``` */ interface KnowledgeIngestBatchResult { /** 成功导入的文档数 */ successCount: number; /** 失败的文档数 */ failureCount: number; /** 各文档导入结果 */ results: Array<{ documentId: string; result?: KnowledgeIngestResult; error?: HaiError; }>; /** 总耗时(毫秒) */ duration: number; } /** * Knowledge 操作接口(通过 `ai.knowledge` 访问)。 * * 每个 collection 使用前须独立 setup。导入以版本清单原子发布;成功中的 cleanupPending * 表示仍需分页 repair 清理旧向量,不能把补偿失败视作已清理。业务授权由调用层按主体执行。 * * @example * ```ts * import { ai } from '@h-ai/ai' * // 应用启动已成功初始化 ai。每个逻辑集合先单独 setup。 * const ready = await ai.knowledge.setup({ collection: 'docs' }) * if (!ready.success) throw new Error(ready.error.message) * const published = await ai.knowledge.ingest({ collection: 'docs', documentId: 'guide', content: '# 部署指南\n使用共享数据库。' }) * if (!published.success) throw new Error(published.error.message) * if (published.data.cleanupPending) { * // 生产维护任务须按 processed/total 分页扫描,失败保留清单供重试。 * const repaired = await ai.knowledge.repair({ collection: 'docs', offset: 0, limit: 100 }) * if (!repaired.success) throw new Error(repaired.error.message) * } * const answer = await ai.knowledge.ask('部署需要什么?', { collection: 'docs' }) * if (!answer.success) throw new Error(answer.error.message) * ``` */ interface KnowledgeOperations { /** * 初始化知识库(幂等,支持多次调用以初始化不同 collection) * * 创建向量集合和文档版本清单。每个 collection 需独立调用本方法, * 未 setup 的 collection 执行以下操作时均会返回 `KNOWLEDGE_NOT_SETUP` 错误: * `ingest` / `ingestFile` / `ingestBatch` / `retrieve` / `ask` / * `findByEntity` / `listDocuments` / `removeDocument`。 * * @param options - 初始化选项(collection 名称、向量维度) * @returns 成功返回 ok(undefined) */ setup: (options?: KnowledgeSetupOptions) => Promise>; /** * 导入文档 * * 执行流程:clean → chunk → embed/实体准备 → 持久暂存 → 写入向量 → CAS 发布完整版本。 * 清洗或分块失败时返回 KNOWLEDGE_INGEST_FAILED,保留原始错误,不继续生成向量或发布。 * 成功包含 revision 与 cleanupPending;旧数据清理失败时检查标志并安排 repair。 * * @param input - 文档导入输入 * @returns 导入结果(分块数、实体列表等) */ ingest: (input: KnowledgeIngestInput) => Promise>; /** * 知识检索(带实体增强 + 信源追踪) * * @param query - 查询文本 * @param options - 检索选项 * @returns 检索结果(带 citations) */ retrieve: (query: string, options?: KnowledgeRetrieveOptions) => Promise>; /** * 知识问答(RAG + 信源引用) * * @param query - 用户问题 * @param options - 问答选项 * @returns 问答结果(回答 + 信源) */ ask: (query: string, options?: KnowledgeAskOptions) => Promise>; /** * 按实体查询关联文档 * * @param entityName - 实体名称 * @param options - 查询选项 * @returns 实体关联文档列表 */ findByEntity: (entityName: string, options?: EntityQueryOptions) => Promise>; /** * 列出所有实体 * * @param options - 列表选项 * @returns 实体列表 */ listEntities: (options?: EntityListOptions) => Promise>; /** * 列出已导入的文档列表 * * @param options - 列表选项 * @returns 文档信息列表 */ listDocuments: (options?: KnowledgeDocumentListOptions) => Promise>; /** * 删除已导入的文档(同时删除向量和实体关联) * * @param documentId - 文档 ID * @param options - 删除选项 * @returns 成功返回 ok(undefined) */ removeDocument: (documentId: string, options?: KnowledgeDocumentRemoveOptions) => Promise>; /** * 有界恢复过期暂存、重试失败的旧向量清理。setup 自动扫描前 100 份清单,大集合需定期分页调用。 * 暂存租约为存储端时钟的 5 分钟;过期 owner 即使恢复也不能发布。 * 被遗弃写入的补偿墓碑永久保留,重复扫描用于清理迟到的外部写入。 */ repair: (options?: KnowledgeRepairOptions) => Promise>; /** * 从文件路径导入文档(仅 Node.js 端可用) * * 读取文件内容后自动调用 ingest() 完成导入。 * * @param input - 文件导入输入 * @returns 导入结果 */ ingestFile: (input: KnowledgeIngestFileInput) => Promise>; /** * 批量导入文档 * * 依次执行 ingest(),通过 onProgress 回调报告进度,单个文档失败不中断整体流程。 * * @param inputs - 文档导入输入列表 * @param onProgress - 每完成一个文档后的回调 * @returns 批量导入汇总结果 */ ingestBatch: (inputs: KnowledgeIngestInput[], onProgress?: (progress: KnowledgeIngestBatchProgress) => void) => Promise>; /** * 删除整个 collection(幂等) * * 先撤销整个代际的可见性,再清理已登记向量,保留物理集合与补偿墓碑。 * 内部按页清理,失败返回错误后可用 repair 恢复;重新 setup 使用新代际。 * * @param collection - 要删除的 collection 名称,默认使用 config.collection * @returns 成功返回 ok(undefined);store 不可用时返回 `KNOWLEDGE_SETUP_FAILED` */ deleteCollection: (collection?: string) => Promise>; } /** * @h-ai/ai — Memory 子功能类型 * * 定义记忆管理操作的类型接口:提取、存储、检索、注入。 * 支持从对话中自动提取关键事实、偏好、事件等记忆,并在后续对话中检索注入。 * @module ai-memory-types */ /** * 记忆类型枚举 Schema * * 定义系统支持的五种记忆类型,用于对提取和存储的记忆进行分类: * - `fact` — 客观事实(如「用户是后端工程师」「项目使用 TypeScript」) * - `preference` — 用户偏好(如「喜欢简洁的代码风格」「偏好中文回复」) * - `event` — 事件/时间线信息(如「上周部署了 v2.0」「昨天修复了登录 Bug」) * - `entity` — 命名实体(如人名、产品名、组织名等,便于后续实体关联) * - `instruction` — 用户给出的持久指令(如「以后都用函数式写法」「回复不超过 200 字」) * * @example * ```ts * import { MemoryTypeSchema } from '@h-ai/ai' * const parsed = MemoryTypeSchema.safeParse('preference') * if (!parsed.success) throw parsed.error * const selected = parsed.data * ``` */ declare const MemoryTypeSchema: z.ZodEnum<{ event: "event"; fact: "fact"; preference: "preference"; entity: "entity"; instruction: "instruction"; }>; /** * 记忆类型 * * @example * ```ts * import type { MemoryType } from '@h-ai/ai' * const value: MemoryType = 'preference' * const filter = { types: [value] } * ``` */ type MemoryType = z.infer; /** * 记忆条目输入(手动添加时使用) * * @example * ```ts * import { ai, type MemoryEntryInput } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * async function run(options: MemoryEntryInput) { * const result = await ai.memory.add(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface MemoryEntryInput { /** 记忆内容 */ content: string; /** 记忆类型 */ type: MemoryType; /** 重要性评分 [0, 1](可选,默认 0.5) */ importance?: number; /** 所属主体 ID(不指定时为全局记忆) */ objectId?: string; /** 作用域(JSON 对象,key-value 匹配过滤。用于子 session 记忆隔离等场景) */ scope?: Record; /** 附加元数据 */ metadata?: Record; } /** * 完整的记忆条目 * * @example * ```ts * import type { MemoryEntry } from '@h-ai/ai' * const value: MemoryEntry = { id: 'memory-1', objectId: 'user-1', type: 'preference', content: '偏好中文', importance: 0.8, createdAt: Date.now(), lastAccessedAt: Date.now(), accessCount: 0 } * const preview = value.content.slice(0, 20) * ``` */ interface MemoryEntry { /** 记忆唯一标识 */ id: string; /** 记忆内容 */ content: string; /** 记忆类型 */ type: MemoryType; /** 重要性评分 [0, 1] */ importance: number; /** 所属主体 ID */ objectId?: string; /** 作用域(JSON 对象,key-value 匹配过滤。用于子 session 记忆隔离等场景) */ scope?: Record; /** 附加元数据 */ metadata?: Record; /** 向量(embedding 已计算时填充) */ vector?: number[]; /** 创建时间(Unix 毫秒) */ createdAt: number; /** 最近访问时间(Unix 毫秒) */ lastAccessedAt: number; /** 被检索次数 */ accessCount: number; } /** * 记忆提取选项 * * @example * ```ts * import { ai, type MemoryExtractOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * async function run(options: MemoryExtractOptions) { * const result = await ai.memory.extract([{ role: 'user', content: '以后请用中文' }], options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface MemoryExtractOptions { /** 只提取指定类型 */ types?: MemoryType[]; /** 指定提取用的模型 */ model?: string; /** 自定义提取 systemPrompt(覆盖模块配置与内置默认提示词) */ systemPrompt?: string; /** 过滤低重要性条目(默认 0) */ minImportance?: number; /** 所属主体 ID(关联到提取结果) */ objectId?: string; /** 作用域(JSON 对象,提取的记忆将关联此 scope) */ scope?: Record; /** * 临时模型配置(携带凭据的模型请求)。 * * 用于传递运行时解析的 apiKey / baseUrl 等凭证, * 避免回退到全局 .env 配置。优先级高于全局 config.models 查找。 */ tempModel?: TempModelConfig; /** 取消整条记忆提取链(包括事实抽取与 native 对账 LLM 调用) */ signal?: AbortSignal; } /** * 记忆检索选项 * * @example * ```ts * import { ai, type MemoryRecallOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * async function run(options: MemoryRecallOptions) { * const result = await ai.memory.recall('语言偏好', options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface MemoryRecallOptions { /** 返回数量(默认使用配置的 defaultTopK) */ topK?: number; /** * 候选池倍数(覆盖配置的 candidateMultiplier) * * 检索时先取回 `topK × candidateMultiplier` 条候选再按 scope / 类型 / 重要性过滤, * 最后截取 topK。scope 过滤较严(如按 topic / persona 隔离)时应调大,避免漏召回。 */ candidateMultiplier?: number; /** 过滤类型 */ types?: MemoryType[]; /** 最低重要性 */ minImportance?: number; /** 时间衰减权重 [0, 1](0 = 不考虑时间,1 = 仅按时间排序) */ recencyWeight?: number; /** 限定主体 ID */ objectId?: string; /** 限定作用域(key-value 匹配过滤,用于子 session 记忆隔离等场景) */ scope?: Record; } /** * 记忆注入选项(`injectMemories` 使用) * * 控制记忆注入行为:检索数量、Token 预算、注入位置等。 * * @example * ```ts * import { ai, type MemoryInjectionOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * async function run(options: MemoryInjectionOptions) { * const result = await ai.memory.injectMemories([{ role: 'user', content: '你好' }], options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface MemoryInjectionOptions { /** 注入的记忆数量(默认 5) */ topK?: number; /** * 候选池倍数(覆盖配置的 candidateMultiplier) * * 透传给底层 `recall`,scope 过滤较严时应调大以避免漏召回。 */ candidateMultiplier?: number; /** 记忆占用的最大 token 预算(默认不限) */ maxTokens?: number; /** 注入位置:system = 追加到 system 消息末尾,before-last = 插入在最后一条用户消息之前 */ position?: 'system' | 'before-last'; /** 限定主体 ID */ objectId?: string; /** 限定作用域(key-value 匹配过滤,用于子 session 记忆隔离等场景) */ scope?: Record; /** 限定记忆类型 */ types?: MemoryType[]; /** 最低重要性阈值 */ minImportance?: number; } /** * 记忆列表选项 * * @example * ```ts * import { ai, type MemoryListOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * async function run(options: MemoryListOptions) { * const result = await ai.memory.list(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface MemoryListOptions { /** 过滤类型 */ types?: MemoryType[]; /** 限定主体 ID */ objectId?: string; /** 限定作用域(key-value 匹配过滤,用于子 session / 主题 / 角色记忆隔离等场景) */ scope?: Record; /** 最大返回数 */ limit?: number; } /** * 记忆分页选项 * * @example * ```ts * import { ai, type MemoryListPageOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * async function run(options: MemoryListPageOptions) { * const result = await ai.memory.listPage(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface MemoryListPageOptions { /** 过滤类型 */ types?: MemoryType[]; /** 限定主体 ID */ objectId?: string; /** 限定作用域(key-value 匹配过滤,用于子 session / 主题 / 角色记忆隔离等场景) */ scope?: Record; /** 偏移量 */ offset?: number; /** 每页数量(默认 20) */ limit?: number; } /** * 记忆清空选项 * * 安全语义:公共 clear 拒绝空过滤,全局清空仅限显式管理接口;传入 objectId / types / scope 时 * 仅删除同时匹配所有给定条件的记忆,避免误删其他主体或类型的记忆。 * * @example * ```ts * import { ai, type MemoryClearOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * async function run(options: MemoryClearOptions) { * const result = await ai.memory.clear(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface MemoryClearOptions { /** 仅清空指定类型 */ types?: MemoryType[]; /** 仅清空指定主体 */ objectId?: string; /** 仅清空匹配指定作用域的记忆(key-value 匹配过滤) */ scope?: Record; } /** * 记忆条目更新输入 * * 所有字段均为可选,仅传入需要更新的字段。 * * @example * ```ts * import { ai, type MemoryUpdateInput } from '@h-ai/ai' * async function updateOwnedMemory(memoryId: string, userId: string) { * const input: MemoryUpdateInput = { importance: 0.9, metadata: { source: 'confirmed' } } * const result = await ai.memory.update(memoryId, input, { objectId: userId }) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface MemoryUpdateInput { /** 更新记忆内容(同时重新计算向量) */ content?: string; /** 更新记忆类型 */ type?: MemoryType; /** 更新重要性 */ importance?: number; /** 更新元数据 */ metadata?: Record; } /** * 按 ID 访问单条记忆(get / update / remove)时的归属校验作用域。 * * 传入后,Provider 先读取记忆再校验:`entry.objectId` 必须等于 `objectId`,且 `entry.scope` * 包含 `scope` 的全部 key-value;不匹配时统一返回 `MEMORY_NOT_FOUND`(避免通过错误差异 * 枚举其他主体的记忆)。不传时仅供受信内部操作;处理不可信输入的 memoryId 时必须传入。 * * @example * ```ts * import { ai, type MemoryAccessScope } from '@h-ai/ai' * async function readOwnedMemory(memoryId: string, trustedUserId: string) { * const scope: MemoryAccessScope = { objectId: trustedUserId, scope: { topicId: 'profile' } } * const result = await ai.memory.get(memoryId, scope) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface MemoryAccessScope { /** 归属主体 ID(必须与记忆 entry.objectId 一致) */ objectId: string; /** 业务作用域(entry.scope 必须包含这些 key-value) */ scope?: Record; } /** * 记忆作用域绑定(`ai.memory.scoped()` 使用) * * 绑定后,所有操作自动携带 `objectId` 与 `scope`,无需每次手动传入, * 从根本上避免「忘记传 objectId 导致跨租户越权」的安全隐患。 * * @example * ```ts * import { ai, type ScopedMemoryBinding } from '@h-ai/ai' * const binding: ScopedMemoryBinding = { objectId: 'user-1', scope: { topicId: 'profile' } } * const memory = ai.memory.scoped(binding) * const result = await memory.list({ limit: 10 }) * if (!result.success) throw new Error(result.error.message) * ``` */ interface ScopedMemoryBinding { /** 归属主体 ID(所有操作自动绑定) */ objectId: string; /** 业务作用域(所有操作自动绑定并作为归属校验的一部分,如 `{ topicId, personaId }`) */ scope?: Record; } /** * 全局清空选项(`ai.memory.admin.clearAll()` 使用) * * 危险操作:清空整个记忆后端的全部数据。必须显式传入 `confirm: true`, * 防止误调用;普通 `clear()` 不再支持通过省略参数隐式清空全局。 * * @example * ```ts * import type { MemoryAdminOperations, MemoryClearAllOptions } from '@h-ai/ai' * // 仅由已经通过管理权限校验的维护入口调用。 * async function clearConfirmed(admin: MemoryAdminOperations) { * const options: MemoryClearAllOptions = { confirm: true } * const result = await admin.clearAll(options) * if (!result.success) throw new Error(result.error.message) * } * ``` */ interface MemoryClearAllOptions { /** 必须显式为 `true`,否则拒绝执行 */ confirm: true; } /** * 记忆管理接口(`ai.memory.admin`) * * 承载危险的全局操作,与业务作用域操作明确分离。 * * @example * ```ts * import type { MemoryAdminOperations } from '@h-ai/ai' * // 管理接口不直接交给普通业务请求。 * async function clearAfterAuthorization(admin: MemoryAdminOperations) { * const result = await admin.clearAll({ confirm: true }) * if (!result.success) throw new Error(result.error.message) * } * ``` */ interface MemoryAdminOperations { /** * 清空整个记忆后端的全部数据(跨所有主体 / 作用域) * * @param options - 必须传入 `{ confirm: true }` * @returns 成功返回 ok(undefined);未确认返回 MEMORY_STORE_FAILED */ clearAll: (options: MemoryClearAllOptions) => Promise>; } /** * 记忆核心操作(Provider 实现层) * * 各 Provider(native / mem0)实现这一组操作。公共入口 `ai.memory` 在其基础上 * 叠加作用域绑定(`scoped`)与管理接口(`admin`),并对 `clear` 施加空过滤保护。 * * @example * ```ts * import type { MemoryCoreOperations } from '@h-ai/ai' * async function addWithProvider(core: MemoryCoreOperations, trustedUserId: string) { * const result = await core.add({ objectId: trustedUserId, type: 'fact', content: '已验证的业务事实' }) * if (!result.success) throw new Error(result.error.message) * return result.data.id * } * ``` */ interface MemoryCoreOperations { /** * 从对话消息中自动提取记忆条目 * * 使用 LLM 分析对话内容,提取值得记住的事实、偏好、事件等。 * 提取的记忆会自动持久化到 Store(含向量计算)。 * * @param messages - 对话消息列表 * @param options - 提取选项 * @returns 提取到的记忆条目列表 */ extract: (messages: ChatMessage[], options?: MemoryExtractOptions) => Promise>; /** * 根据查询检索最相关的记忆 * * 综合向量相似度、重要性、时间衰减进行排序。 * * @param query - 查询文本 * @param options - 检索选项 * @returns 相关记忆列表 */ recall: (query: string, options?: MemoryRecallOptions) => Promise>; /** * 将相关记忆注入到消息列表中 * * 工作流程: * 1. 从消息列表中提取最后一条用户消息作为检索查询 * 2. 调用 `recall` 检索最相关的记忆条目 * 3. 将记忆格式化为文本块,按指定位置注入消息列表 * * @param messages - 原始消息列表 * @param options - 注入选项(数量、位置、Token 预算等) * @returns 注入记忆后的新消息列表(不修改原数组) */ injectMemories: (messages: ChatMessage[], options?: MemoryInjectionOptions) => Promise>; /** * 手动添加一条记忆 * * 记忆会自动持久化到 Store(含向量计算)。 * * @param entry - 记忆条目输入 * @returns 存储后的完整记忆条目 */ add: (entry: MemoryEntryInput) => Promise>; /** * 更新一条已有记忆 * * 仅更新传入的字段,其余字段保持不变。 * 若 content 被更新,会重新计算向量。 * 更新结果自动持久化到 Store。 * * @param memoryId - 记忆 ID * @param updates - 需要更新的字段 * @param accessScope - 可选归属校验(不匹配返回 MEMORY_NOT_FOUND) * @returns 更新后的完整记忆条目 */ update: (memoryId: string, updates: MemoryUpdateInput, accessScope?: MemoryAccessScope) => Promise>; /** * 按 ID 获取单条记忆 * * @param memoryId - 记忆 ID * @param accessScope - 可选归属校验(不匹配返回 MEMORY_NOT_FOUND) * @returns 记忆条目,不存在时返回 MEMORY_NOT_FOUND */ get: (memoryId: string, accessScope?: MemoryAccessScope) => Promise>; /** * 删除单条记忆 * * 同时从 Store 中移除持久化数据。 * * @param memoryId - 记忆 ID * @param accessScope - 可选归属校验(不匹配返回 MEMORY_NOT_FOUND) * @returns 成功返回 ok(undefined) */ remove: (memoryId: string, accessScope?: MemoryAccessScope) => Promise>; /** * 获取记忆列表 * * @param options - 列表选项 * @returns 记忆条目列表 */ list: (options?: MemoryListOptions) => Promise>; /** * 分页获取记忆列表 * * @param options - 分页选项 * @returns 分页结果 */ listPage: (options?: MemoryListPageOptions) => Promise>>; /** * 清空记忆 * * 同时从 Store 中移除持久化数据。 * * @param options - 清空选项(可按类型/主体过滤) */ clear: (options?: MemoryClearOptions) => Promise>; } /** * 作用域绑定的记忆操作(`ai.memory.scoped()` 返回) * * 所有操作自动携带绑定的 `objectId` 与 `scope`,无需重复传入;`get` / `update` / `remove` * 自动施加归属校验(跨租户访问返回 `MEMORY_NOT_FOUND`);`clear` 仅清空绑定作用域内的记忆, * 永远不会误清全局。 * * @example * ```ts * import { ai, type ScopedMemoryOperations } from '@h-ai/ai' * const memory: ScopedMemoryOperations = ai.memory.scoped({ objectId: 'user-1', scope: { topicId: 'profile' } }) * const result = await memory.add({ content: '偏好中文', type: 'preference' }) * if (!result.success) throw new Error(result.error.message) * ``` */ interface ScopedMemoryOperations { /** 从对话中提取记忆(自动绑定 objectId / scope) */ extract: (messages: ChatMessage[], options?: Omit) => Promise>; /** 检索相关记忆(自动绑定 objectId / scope) */ recall: (query: string, options?: Omit) => Promise>; /** 注入相关记忆(自动绑定 objectId / scope) */ injectMemories: (messages: ChatMessage[], options?: Omit) => Promise>; /** 添加记忆(自动绑定 objectId / scope) */ add: (entry: Omit) => Promise>; /** 更新记忆(自动施加归属校验) */ update: (memoryId: string, updates: MemoryUpdateInput) => Promise>; /** 按 ID 获取记忆(自动施加归属校验) */ get: (memoryId: string) => Promise>; /** 删除记忆(自动施加归属校验) */ remove: (memoryId: string) => Promise>; /** 列出记忆(自动绑定 objectId / scope) */ list: (options?: Omit) => Promise>; /** 分页列出记忆(自动绑定 objectId / scope) */ listPage: (options?: Omit) => Promise>>; /** 清空绑定作用域内的记忆(自动绑定 objectId / scope,不会误清全局) */ clear: (options?: Omit) => Promise>; } /** * 公共记忆操作接口(通过 `ai.memory` 访问) * * 在核心操作基础上增加: * - `scoped(binding)`:返回自动绑定 objectId / scope 的安全实例(多租户推荐入口); * - `admin`:承载危险的全局操作(如 `clearAll`); * - `clear`:拒绝空过滤调用(无 objectId / types / scope 时返回错误),防止误清全局。 * * @example * ```ts * import { ai, type MemoryOperations } from '@h-ai/ai' * const operations: MemoryOperations = ai.memory * const result = await operations.scoped({ objectId: 'user-1' }).recall('语言偏好', { topK: 3 }) * if (!result.success) throw new Error(result.error.message) * const texts = result.data.map(memory => memory.content) * ``` */ interface MemoryOperations extends MemoryCoreOperations { /** * 创建绑定作用域的记忆实例 * * @param binding - 作用域绑定(objectId + 可选 scope) * @returns 所有操作自动携带该作用域的记忆实例 * @throws objectId 缺失、为空或只有空白时抛 TypeError;工厂不创建未绑定的实例。 */ scoped: (binding: ScopedMemoryBinding) => ScopedMemoryOperations; /** 管理接口(危险的全局操作,需显式确认) */ admin: MemoryAdminOperations; } /** * 可选密钥 Schema。 * * 配置文件中的空插值、空白字符串或 YAML null 都表示“未配置”,输出统一为 undefined; * 非空密钥保持原值,避免模块调用方重复编写兼容清洗逻辑。 * * @example * ```ts * import { OptionalSecretSchema } from '@h-ai/ai' * * const result = OptionalSecretSchema.safeParse(null) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const OptionalSecretSchema: z.ZodOptional, z.ZodTransform>>; /** * 模型场景枚举 * * 预定义的模型使用场景,用于自动选择合适的模型。 * * - `default` — 默认场景(兜底) * - `chat` — 对话场景 * - `reasoning` — 推理场景(ReAct、CoT,需要强逻辑能力) * - `plan` — Plan-Execute 规划阶段(需要强推理) * - `execute` — Plan-Execute 执行阶段(需要工具调用能力) * - `extraction` — 信息提取场景(记忆提取、实体抽取) * - `summary` — 摘要/压缩场景(上下文摘要) * - `embedding` — 向量嵌入场景 * - `rerank` — 文档重排序场景 * - `ocr` — 图片 OCR 识别场景(视觉模型) * - `fast` — 快速响应场景(低延迟优先) * * @example * ```ts * import { ModelScenarioSchema } from '@h-ai/ai' * * const result = ModelScenarioSchema.safeParse('summary') * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const ModelScenarioSchema: z.ZodEnum<{ default: "default"; chat: "chat"; reasoning: "reasoning"; plan: "plan"; execute: "execute"; extraction: "extraction"; summary: "summary"; embedding: "embedding"; rerank: "rerank"; ocr: "ocr"; fast: "fast"; }>; /** * 模型场景类型 * * @example * ```ts * import type { ModelScenario } from '@h-ai/ai' * import { ModelScenarioSchema } from '@h-ai/ai' * * const config: ModelScenario = ModelScenarioSchema.parse('summary') * ``` */ type ModelScenario = z.infer; /** * LLM API 协议枚举 * * 决定底层通过哪种 API 协议与模型交互(对使用方透明,公共请求/响应形状保持一致): * * - `chat` — OpenAI Chat Completions API(`/v1/chat/completions`,默认,兼容绝大多数厂商) * - `responses` — OpenAI Responses API(`/v1/responses`,新一代有状态接口) * - `anthropic` — Anthropic Messages API(Claude 原生协议,使用 fetch 直接调用) * * @example * ```ts * import { ApiTypeSchema } from '@h-ai/ai' * * const result = ApiTypeSchema.safeParse('anthropic') * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const ApiTypeSchema: z.ZodEnum<{ chat: "chat"; responses: "responses"; anthropic: "anthropic"; }>; /** * LLM API 协议类型 * * @example * ```ts * import type { ApiType } from '@h-ai/ai' * import { ApiTypeSchema } from '@h-ai/ai' * * const config: ApiType = ApiTypeSchema.parse('anthropic') * ``` */ type ApiType = z.infer; /** * 模型能力元数据;缺省字段表示未知,不从调用预算推断容量。 * @example * ```ts * import { ModelCapabilitiesSchema } from '@h-ai/ai' * const capabilities = ModelCapabilitiesSchema.parse({ contextWindow: 128000, toolCalling: true }) * ``` */ declare const ModelCapabilitiesSchema: z.ZodObject<{ contextWindow: z.ZodOptional; maxOutputTokens: z.ZodOptional; inputModalities: z.ZodOptional>>; outputModalities: z.ZodOptional>>; toolCalling: z.ZodOptional; reasoning: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>; /** * 模型条目 Schema * * 定义单个模型的配置信息,包含唯一 ID、模型名称和可选参数覆盖。 * * @example * ```ts * import { ModelEntrySchema } from '@h-ai/ai' * * const result = ModelEntrySchema.safeParse({ id: 'chat', model: 'gpt-4o-mini', temperature: 0.2 }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const ModelEntrySchema: z.ZodObject<{ id: z.ZodString; capabilities: z.ZodOptional; maxOutputTokens: z.ZodOptional; inputModalities: z.ZodOptional>>; outputModalities: z.ZodOptional>>; toolCalling: z.ZodOptional; reasoning: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; model: z.ZodString; protocol: z.ZodOptional>; apiKey: z.ZodOptional, z.ZodTransform>>; baseUrl: z.ZodOptional; maxTokens: z.ZodOptional; temperature: z.ZodOptional; timeout: z.ZodOptional; }, z.core.$strict>; /** * 模型条目类型 * * @example * ```ts * import type { ModelEntry } from '@h-ai/ai' * import { ModelEntrySchema } from '@h-ai/ai' * * const config: ModelEntry = ModelEntrySchema.parse({ id: 'chat', model: 'gpt-4o-mini', temperature: 0.2 }) * ``` */ type ModelEntry = z.infer; /** * LLM 配置 Schema * * 配置大模型调用参数:模型名称、API Key、Base URL、温度等。 * 支持多模型注册和场景映射。 * * 顶层 `apiKey`、`baseUrl`、`maxTokens`、`temperature`、`timeout` 作为全局默认值, * 当 `models` 条目中未指定对应字段时,自动回退到这些全局默认值。 * 通过 `resolveModelEntry()` 统一解析。 * * @example * ```ts * import { LLMConfigSchema } from '@h-ai/ai' * * const result = LLMConfigSchema.safeParse({ apiKey: process.env.HAI_AI_LLM_APIKEY, models: [{ id: 'fast', model: 'gpt-4o-mini' }], scenarios: { chat: 'fast', summary: 'fast' } }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const LLMConfigSchema: z.ZodObject<{ apiKey: z.ZodOptional, z.ZodTransform>>; baseUrl: z.ZodOptional; model: z.ZodDefault>; protocol: z.ZodDefault>>; maxTokens: z.ZodDefault>; temperature: z.ZodDefault>; timeout: z.ZodDefault>; tempModelCacheTtl: z.ZodDefault>; models: z.ZodOptional; maxOutputTokens: z.ZodOptional; inputModalities: z.ZodOptional>>; outputModalities: z.ZodOptional>>; toolCalling: z.ZodOptional; reasoning: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; model: z.ZodString; protocol: z.ZodOptional>; apiKey: z.ZodOptional, z.ZodTransform>>; baseUrl: z.ZodOptional; maxTokens: z.ZodOptional; temperature: z.ZodOptional; timeout: z.ZodOptional; }, z.core.$strict>>>; scenarios: z.ZodOptional; chat: z.ZodOptional; reasoning: z.ZodOptional; plan: z.ZodOptional; execute: z.ZodOptional; extraction: z.ZodOptional; summary: z.ZodOptional; embedding: z.ZodOptional; rerank: z.ZodOptional; ocr: z.ZodOptional; fast: z.ZodOptional; }, z.core.$strip>>; }, z.core.$strict>; /** * LLM 配置类型 * * @example * ```ts * import type { LLMConfig } from '@h-ai/ai' * import { LLMConfigSchema } from '@h-ai/ai' * * const config: LLMConfig = LLMConfigSchema.parse({ apiKey: process.env.HAI_AI_LLM_APIKEY, models: [{ id: 'fast', model: 'gpt-4o-mini' }], scenarios: { chat: 'fast', summary: 'fast' } }) * ``` */ type LLMConfig = z.infer; /** * 已解析的模型配置 * * 由 `resolveModelEntry()` 返回,包含模型名称和完整的参数配置(已合并全局默认值和环境变量)。 * * @example * ```ts * import type { ResolvedModelConfig } from '@h-ai/ai' * * // 展示模型选择,不输出配置中的 apiKey。 * function label(config: ResolvedModelConfig): string { * return `${config.protocol}/${config.model}, timeout=${config.timeout}ms` * } * ``` */ interface ResolvedModelConfig { /** 已确认的模型能力 */ capabilities?: z.infer; /** 模型名称(传给 API 的实际模型名) */ model: string; /** API 协议(模型条目 > 全局配置 > `chat`) */ protocol: ApiType; /** API Key(模型条目 > 全局配置 > 环境变量) */ apiKey: string | undefined; /** API 基础 URL(模型条目 > 全局配置 > 环境变量 > 默认 OpenAI) */ baseUrl: string; /** 最大 Token 数(模型条目 > 全局配置) */ maxTokens: number; /** 采样温度(模型条目 > 全局配置) */ temperature: number; /** 请求超时时间(毫秒)(模型条目 > 全局配置) */ timeout: number; } /** * 必需模型解析选项 * * @example * ```ts * import type { ResolveRequiredModelEntryOptions } from '@h-ai/ai' * * const value: ResolveRequiredModelEntryOptions = { missingApiKeyMessage: '请在服务端私有配置中提供模型凭据。' } * ``` */ interface ResolveRequiredModelEntryOptions { /** 缺少 API Key 时的自定义错误消息 */ missingApiKeyMessage?: string; } /** * 根据场景解析完整模型配置,并要求必须存在 API Key * * 用于需要访问远程模型 API 的场景,避免各子模块重复编写 * `if (!resolved.apiKey)` 之类的配置校验逻辑。 * * @param llmConfig - LLM 配置 * @param scenario - 使用场景 * @param explicit - 调用方显式指定的模型名称(最高优先级) * @param options - 必需校验选项 * @returns 成功返回已解析模型配置,失败返回 `CONFIGURATION_ERROR` * * @example * ```ts * import { LLMConfigSchema, resolveModelEntry } from '@h-ai/ai' * * const config = LLMConfigSchema.parse({ apiKey: process.env.HAI_AI_LLM_APIKEY, models: [{ id: 'fast', model: 'gpt-4o-mini' }], scenarios: { summary: 'fast' } }) * const result = resolveModelEntry(config, 'summary') * if (result.success) { * const modelName = result.data.model * } * ``` */ declare function resolveModelEntry(llmConfig: LLMConfig, scenario: ModelScenario, explicit?: string, options?: ResolveRequiredModelEntryOptions): HaiResult; /** * 解析某次 chat 请求应使用的 API 协议(不校验 API Key) * * 供 LLM Provider 路由层选择底层实现使用:优先取显式模型条目的 `protocol`, * 其次全局 `protocol`,最后回退 `chat`。临时模型的 `protocol` 由调用方单独传入优先。 * * @param llmConfig - LLM 配置 * @param explicitModel - 显式指定的模型名/ID(可选) * @param tempApi - 临时模型显式指定的 API 协议(可选,最高优先级) * @returns 解析出的 API 协议 * * @example * ```ts * import { LLMConfigSchema, resolveModelApi } from '@h-ai/ai' * * const config = LLMConfigSchema.parse({ models: [{ id: 'claude', model: 'claude-sonnet-4', protocol: 'anthropic' }] }) * const protocol = resolveModelApi(config, 'claude') * ``` */ declare function resolveModelApi(llmConfig: LLMConfig, explicitModel?: string, tempApi?: ApiType): ApiType; /** * MCP 服务器能力 Schema * * @example * ```ts * import { MCPServerCapabilitiesSchema } from '@h-ai/ai' * * const result = MCPServerCapabilitiesSchema.safeParse({ tools: true, resources: false, prompts: true }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const MCPServerCapabilitiesSchema: z.ZodObject<{ tools: z.ZodDefault>; resources: z.ZodDefault>; prompts: z.ZodDefault>; }, z.core.$strip>; /** * MCP 服务器能力类型 * * @example * ```ts * import type { MCPServerCapabilities } from '@h-ai/ai' * import { MCPServerCapabilitiesSchema } from '@h-ai/ai' * * const config: MCPServerCapabilities = MCPServerCapabilitiesSchema.parse({ tools: true, resources: false, prompts: true }) * ``` */ type MCPServerCapabilities = z.infer; /** * MCP 服务器配置 Schema * * @example * ```ts * import { MCPServerConfigSchema } from '@h-ai/ai' * * const result = MCPServerConfigSchema.safeParse({ name: 'support-tools', version: '1.0.0', capabilities: { tools: true, resources: false, prompts: false } }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const MCPServerConfigSchema: z.ZodObject<{ name: z.ZodString; version: z.ZodDefault>; capabilities: z.ZodOptional>; resources: z.ZodDefault>; prompts: z.ZodDefault>; }, z.core.$strip>>; }, z.core.$strip>; /** * MCP 服务器配置类型 * * @example * ```ts * import type { MCPServerConfig } from '@h-ai/ai' * import { MCPServerConfigSchema } from '@h-ai/ai' * * const config: MCPServerConfig = MCPServerConfigSchema.parse({ name: 'support-tools', version: '1.0.0', capabilities: { tools: true, resources: false, prompts: false } }) * ``` */ type MCPServerConfig = z.infer; /** * 外部 MCP 服务清单项;凭据仅保存环境变量引用,可供 ACP 会话选择。 * @example * ```ts * import { MCPExternalServerSchema } from '@h-ai/ai' * const server = MCPExternalServerSchema.parse({ id: 'docs', name: 'Docs', transport: 'http', url: 'https://mcp.example.com' }) * ``` */ declare const MCPExternalServerSchema: z.ZodObject<{ id: z.ZodString; name: z.ZodString; transport: z.ZodEnum<{ http: "http"; stdio: "stdio"; sse: "sse"; job: "job"; }>; environmentId: z.ZodOptional; command: z.ZodOptional; args: z.ZodDefault>; url: z.ZodOptional; environmentRefs: z.ZodDefault>; headerEnv: z.ZodDefault>; allowedTools: z.ZodOptional>; timeoutMs: z.ZodOptional; pool: z.ZodOptional; maxTotal: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>; /** * 外部 MCP 服务配置。 * @example * ```ts * import type { MCPExternalServer } from '@h-ai/ai' * function serverId(server: MCPExternalServer) { return server.id } * ``` */ type MCPExternalServer = z.infer; /** * MCP 配置 Schema * * 配置 MCP(Model Context Protocol)服务器参数。 * * @example * ```ts * import { MCPConfigSchema } from '@h-ai/ai' * * const result = MCPConfigSchema.safeParse({ server: { name: 'support-tools', version: '1.0.0' } }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const MCPConfigSchema: z.ZodObject<{ servers: z.ZodOptional; environmentId: z.ZodOptional; command: z.ZodOptional; args: z.ZodDefault>; url: z.ZodOptional; environmentRefs: z.ZodDefault>; headerEnv: z.ZodDefault>; allowedTools: z.ZodOptional>; timeoutMs: z.ZodOptional; pool: z.ZodOptional; maxTotal: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>>; server: z.ZodOptional>; capabilities: z.ZodOptional>; resources: z.ZodDefault>; prompts: z.ZodDefault>; }, z.core.$strip>>; }, z.core.$strip>>; }, z.core.$strip>; /** * MCP 配置类型 * * @example * ```ts * import type { MCPConfig } from '@h-ai/ai' * import { MCPConfigSchema } from '@h-ai/ai' * * const config: MCPConfig = MCPConfigSchema.parse({ server: { name: 'support-tools', version: '1.0.0' } }) * ``` */ type MCPConfig = z.infer; /** * Embedding 配置 Schema * * 配置文本向量化参数。 * 模型通过 LLMConfigSchema.scenarios.embedding 解析, * apiKey / baseUrl 统一使用 LLM 配置。 * * @example * ```ts * import { EmbeddingConfigSchema } from '@h-ai/ai' * * const result = EmbeddingConfigSchema.safeParse({ dimensions: 1536, batchSize: 20 }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const EmbeddingConfigSchema: z.ZodObject<{ dimensions: z.ZodOptional; batchSize: z.ZodDefault; }, z.core.$strip>; /** * Embedding 配置类型 * * @example * ```ts * import type { EmbeddingConfig } from '@h-ai/ai' * import { EmbeddingConfigSchema } from '@h-ai/ai' * * const config: EmbeddingConfig = EmbeddingConfigSchema.parse({ dimensions: 1536, batchSize: 20 }) * ``` */ type EmbeddingConfig = z.infer; /** * Knowledge 配置 Schema * * 配置知识库管理参数:向量集合、分块策略、实体提取等。 * 模型通过 LLMConfigSchema.scenarios 解析, * apiKey / baseUrl 统一使用 LLM 配置。 * * @example * ```ts * import { KnowledgeConfigSchema } from '@h-ai/ai' * * const result = KnowledgeConfigSchema.safeParse({ collection: 'product_docs', dimension: 1536, enableEntityExtraction: true, chunkOptions: { mode: 'markdown', maxSize: 1500, overlap: 200 } }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const KnowledgeConfigSchema: z.ZodObject<{ collection: z.ZodDefault; dimension: z.ZodDefault; enableEntityExtraction: z.ZodDefault; cleanOptions: z.ZodDefault; removeUrls: z.ZodDefault; removeEmails: z.ZodDefault; customReplacements: z.ZodOptional>>; normalizeWhitespace: z.ZodDefault; trim: z.ZodDefault; }, z.core.$strip>>; chunkOptions: z.ZodDefault; maxSize: z.ZodDefault; overlap: z.ZodDefault; separator: z.ZodOptional; markdownMinLevel: z.ZodDefault; markdownKeepTitle: z.ZodDefault; }, z.core.$strip>>; entityBoostWeight: z.ZodDefault; entityTypes: z.ZodOptional>; systemPrompt: z.ZodOptional; }, z.core.$strip>; /** * Knowledge 配置类型 * * @example * ```ts * import type { KnowledgeConfig } from '@h-ai/ai' * import { KnowledgeConfigSchema } from '@h-ai/ai' * * const config: KnowledgeConfig = KnowledgeConfigSchema.parse({ collection: 'product_docs', dimension: 1536, enableEntityExtraction: true, chunkOptions: { mode: 'markdown', maxSize: 1500, overlap: 200 } }) * ``` */ type KnowledgeConfig = z.infer; /** * Memory 配置 Schema * * 配置对话记忆的提取、存储与检索参数。两种 provider 均为嵌入式,复用同一套 * vecdb / reldb / LLM / Embedding;模型通过 LLMConfigSchema.scenarios.extraction * 解析,apiKey / baseUrl 统一使用 LLM 配置。 * * @example * ```ts * import { MemoryConfigSchema } from '@h-ai/ai' * * const result = MemoryConfigSchema.safeParse({ provider: 'native', maxEntriesPerObject: 500, defaultTopK: 5 }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const MemoryConfigSchema: z.ZodObject<{ provider: z.ZodDefault>; vectorNamespace: z.ZodDefault; allowEphemeralFallback: z.ZodDefault; maxEntriesPerObject: z.ZodDefault; maxEntriesGlobal: z.ZodDefault; systemPrompt: z.ZodOptional; recencyDecay: z.ZodDefault; embeddingEnabled: z.ZodDefault; defaultTopK: z.ZodDefault; candidateMultiplier: z.ZodDefault; writebackRelatedTopK: z.ZodDefault; }, z.core.$strip>; /** * Memory 配置类型 * * @example * ```ts * import type { MemoryConfig } from '@h-ai/ai' * import { MemoryConfigSchema } from '@h-ai/ai' * * const config: MemoryConfig = MemoryConfigSchema.parse({ provider: 'native', maxEntriesPerObject: 500, defaultTopK: 5 }) * ``` */ type MemoryConfig = z.infer; /** * Token 配置 Schema * * 配置 Token 估算参数。 * * @example * ```ts * import { TokenConfigSchema } from '@h-ai/ai' * * const result = TokenConfigSchema.safeParse({ tokenRatio: 0.25 }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const TokenConfigSchema: z.ZodObject<{ tokenRatio: z.ZodDefault; }, z.core.$strip>; /** * Token 配置类型 * * @example * ```ts * import type { TokenConfig } from '@h-ai/ai' * import { TokenConfigSchema } from '@h-ai/ai' * * const config: TokenConfig = TokenConfigSchema.parse({ tokenRatio: 0.25 }) * ``` */ type TokenConfig = z.infer; /** * Summary 配置 Schema * * 配置摘要生成参数。 * 模型通过 LLMConfigSchema.scenarios.summary 解析, * apiKey / baseUrl 统一使用 LLM 配置。 * * @example * ```ts * import { SummaryConfigSchema } from '@h-ai/ai' * * const result = SummaryConfigSchema.safeParse({ systemPrompt: '保留已确认决策与未完成事项。' }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const SummaryConfigSchema: z.ZodObject<{ systemPrompt: z.ZodOptional; }, z.core.$strip>; /** * Summary 配置类型 * * @example * ```ts * import type { SummaryConfig } from '@h-ai/ai' * import { SummaryConfigSchema } from '@h-ai/ai' * * const config: SummaryConfig = SummaryConfigSchema.parse({ systemPrompt: '保留已确认决策与未完成事项。' }) * ``` */ type SummaryConfig = z.infer; /** * Compress 配置 Schema * * 配置上下文压缩参数:压缩策略、Token 预算、保留消息数。 * * @example * ```ts * import { CompressConfigSchema } from '@h-ai/ai' * * const result = CompressConfigSchema.safeParse({ defaultStrategy: 'hybrid', defaultMaxTokens: 4000, preserveLastN: 4 }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const CompressConfigSchema: z.ZodObject<{ defaultStrategy: z.ZodDefault>; defaultMaxTokens: z.ZodDefault; preserveLastN: z.ZodDefault; }, z.core.$strip>; /** * Compress 配置类型 * * @example * ```ts * import type { CompressConfig } from '@h-ai/ai' * import { CompressConfigSchema } from '@h-ai/ai' * * const config: CompressConfig = CompressConfigSchema.parse({ defaultStrategy: 'hybrid', defaultMaxTokens: 4000, preserveLastN: 4 }) * ``` */ type CompressConfig = z.infer; /** * File 配置 Schema * * 配置文件解析参数:OCR 提示词。 * OCR 使用的视觉模型通过 `llm.scenarios.ocr` 指定。 * * @example * ```ts * import { FileConfigSchema } from '@h-ai/ai' * * const result = FileConfigSchema.safeParse({ systemPrompt: '忠实提取图片中的可见文字,不补写缺失内容。' }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const FileConfigSchema: z.ZodObject<{ systemPrompt: z.ZodOptional; }, z.core.$strip>; /** * File 配置类型 * * @example * ```ts * import type { FileConfig } from '@h-ai/ai' * import { FileConfigSchema } from '@h-ai/ai' * * const config: FileConfig = FileConfigSchema.parse({ systemPrompt: '忠实提取图片中的可见文字,不补写缺失内容。' }) * ``` */ type FileConfig = z.infer; /** * 检索源配置 Schema * * 与 `RetrievalSource` 接口字段对齐,支持在 `ai.init()` 中预注册检索源。 * * @example * ```ts * import { RetrievalSourceSchema } from '@h-ai/ai' * * const result = RetrievalSourceSchema.safeParse({ id: 'docs', collection: 'product_docs', name: '产品文档', topK: 5, minScore: 0.7 }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const RetrievalSourceSchema: z.ZodObject<{ id: z.ZodString; collection: z.ZodString; name: z.ZodOptional; url: z.ZodOptional; topK: z.ZodOptional; minScore: z.ZodOptional; filter: z.ZodOptional>; }, z.core.$strip>; /** * 检索源配置类型 * * @example * ```ts * import type { RetrievalSourceConfig } from '@h-ai/ai' * import { RetrievalSourceSchema } from '@h-ai/ai' * * const config: RetrievalSourceConfig = RetrievalSourceSchema.parse({ id: 'docs', collection: 'product_docs', name: '产品文档', topK: 5, minScore: 0.7 }) * ``` */ type RetrievalSourceConfig = z.infer; /** * Retrieval 配置 Schema * * 在 `ai.init()` 时预注册检索源,等价于初始化后逐条调用 `ai.retrieval.addSource()`。 * * @example * ```ts * import { RetrievalConfigSchema } from '@h-ai/ai' * * const result = RetrievalConfigSchema.safeParse({ sources: [{ id: 'docs', collection: 'product_docs', topK: 5 }] }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const RetrievalConfigSchema: z.ZodObject<{ sources: z.ZodOptional; url: z.ZodOptional; topK: z.ZodOptional; minScore: z.ZodOptional; filter: z.ZodOptional>; }, z.core.$strip>>>; }, z.core.$strip>; /** * Retrieval 配置类型 * * @example * ```ts * import type { RetrievalConfig } from '@h-ai/ai' * import { RetrievalConfigSchema } from '@h-ai/ai' * * const config: RetrievalConfig = RetrievalConfigSchema.parse({ sources: [{ id: 'docs', collection: 'product_docs', topK: 5 }] }) * ``` */ type RetrievalConfig = z.infer; /** * A2A Agent Skill 配置 Schema * * @example * ```ts * import { A2ASkillConfigSchema } from '@h-ai/ai' * * const result = A2ASkillConfigSchema.safeParse({ id: 'support', name: '产品支持', tags: ['documentation'] }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const A2ASkillConfigSchema: z.ZodObject<{ id: z.ZodString; name: z.ZodString; description: z.ZodOptional; tags: z.ZodOptional>; }, z.core.$strip>; /** * A2A 配置 Schema * * 配置 Agent-to-Agent 协议参数:Agent Card、认证等。 * * @example * ```ts * import { A2AConfigSchema } from '@h-ai/ai' * * const result = A2AConfigSchema.safeParse({ agentCard: { name: 'support', url: 'https://agent.example.com/a2a', skills: [{ id: 'help', name: '产品帮助' }] }, security: { apiKey: { in: 'header', name: 'x-api-key' } } }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const A2AConfigSchema: z.ZodObject<{ execution: z.ZodPrefault; pollIntervalMs: z.ZodDefault; maxExecutionMs: z.ZodDefault; }, z.core.$strip>>; agentCard: z.ZodObject<{ name: z.ZodString; description: z.ZodOptional; url: z.ZodString; version: z.ZodOptional; skills: z.ZodOptional; tags: z.ZodOptional>; }, z.core.$strip>>>; }, z.core.$strip>; security: z.ZodOptional>; name: z.ZodDefault; }, z.core.$strip>>; }, z.core.$strip>>; }, z.core.$strip>; /** * A2A 配置类型 * * @example * ```ts * import type { A2AConfig } from '@h-ai/ai' * import { A2AConfigSchema } from '@h-ai/ai' * * const config: A2AConfig = A2AConfigSchema.parse({ agentCard: { name: 'support', url: 'https://agent.example.com/a2a', skills: [{ id: 'help', name: '产品帮助' }] }, security: { apiKey: { in: 'header', name: 'x-api-key' } } }) * ``` */ type A2AConfig = z.infer; /** * 语音平台枚举 * * 决定 `ai.audio` 底层调用哪个厂商 / 协议(对使用方透明,公共请求/响应形状保持一致): * * - `openai` — OpenAI Audio API(transcriptions / speech) * - `mimo` — 小米 MiMo(Chat Completions 风格 ASR / TTS) * - `qwen` — 阿里云百炼 Qwen Realtime(DashScope WebSocket ASR / TTS) * - `doubao` — 火山引擎豆包语音(二进制 WebSocket ASR / TTS) * - `whisper` — hai-framework Whisper Service 协议(HTTP 文件识别,可自托管) * - `indextts` — hai-framework IndexTTS Service 协议(HTTP 合成,可自托管) * * 平台仅表示「用哪种协议调用」,不表示服务部署在哪里;`whisper` / `indextts` 需显式配置 `baseUrl`。 * * @example * ```ts * import { AudioProviderSchema } from '@h-ai/ai' * * const result = AudioProviderSchema.safeParse('indextts') * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const AudioProviderSchema: z.ZodEnum<{ openai: "openai"; mimo: "mimo"; qwen: "qwen"; doubao: "doubao"; whisper: "whisper"; indextts: "indextts"; }>; /** * 语音平台类型 * * @example * ```ts * import type { AudioProviderName } from '@h-ai/ai' * import { AudioProviderSchema } from '@h-ai/ai' * * const config: AudioProviderName = AudioProviderSchema.parse('indextts') * ``` */ type AudioProviderName = z.infer; /** * 单个语音操作类型 * * @example * ```ts * import { AudioOperationSchema } from '@h-ai/ai' * * const result = AudioOperationSchema.safeParse('synthesize') * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const AudioOperationSchema: z.ZodEnum<{ transcribe: "transcribe"; synthesize: "synthesize"; }>; /** * 语音操作类型 * * @example * ```ts * import type { AudioOperation } from '@h-ai/ai' * import { AudioOperationSchema } from '@h-ai/ai' * * const config: AudioOperation = AudioOperationSchema.parse('synthesize') * ``` */ type AudioOperation = z.infer; /** * 语音模型允许的操作列表 * * 至少一项,且不允许重复。 * * @example * ```ts * import { AudioOperationsSchema } from '@h-ai/ai' * * const result = AudioOperationsSchema.safeParse(['transcribe', 'synthesize']) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const AudioOperationsSchema: z.ZodArray>; /** * 语音模型条目 Schema * * 定义单个语音模型:唯一 ID、所属平台、厂商模型名及凭据。凭据未提供时回退到对应平台的环境变量。 * * @example * ```ts * import { AudioModelEntrySchema } from '@h-ai/ai' * * const result = AudioModelEntrySchema.safeParse({ id: 'local-tts', provider: 'indextts', model: 'indextts2', operations: ['synthesize'], baseUrl: 'http://127.0.0.1:8000' }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const AudioModelEntrySchema: z.ZodObject<{ id: z.ZodString; provider: z.ZodEnum<{ openai: "openai"; mimo: "mimo"; qwen: "qwen"; doubao: "doubao"; whisper: "whisper"; indextts: "indextts"; }>; model: z.ZodString; operations: z.ZodArray>; apiKey: z.ZodOptional, z.ZodTransform>>; baseUrl: z.ZodOptional; appKey: z.ZodOptional, z.ZodTransform>>; accessKey: z.ZodOptional, z.ZodTransform>>; resourceId: z.ZodOptional; workspaceId: z.ZodOptional; timeout: z.ZodOptional; }, z.core.$strip>; /** * 语音模型条目类型 * * @example * ```ts * import type { AudioModelEntry } from '@h-ai/ai' * import { AudioModelEntrySchema } from '@h-ai/ai' * * const config: AudioModelEntry = AudioModelEntrySchema.parse({ id: 'local-tts', provider: 'indextts', model: 'indextts2', operations: ['synthesize'], baseUrl: 'http://127.0.0.1:8000' }) * ``` */ type AudioModelEntry = z.infer; /** * Audio 配置 Schema * * 注册语音模型并映射默认识别 / 合成模型。调用方通常无需指定模型,仅在临时切换时通过 `request.model` 覆盖。 * * @example * ```ts * import { AudioConfigSchema } from '@h-ai/ai' * * const result = AudioConfigSchema.safeParse({ models: [{ id: 'local-tts', provider: 'indextts', model: 'indextts2', operations: ['synthesize'], baseUrl: 'http://127.0.0.1:8000' }], synthesizeModel: 'local-tts', inheritLlmApiKey: false }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const AudioConfigSchema: z.ZodObject<{ models: z.ZodOptional; model: z.ZodString; operations: z.ZodArray>; apiKey: z.ZodOptional, z.ZodTransform>>; baseUrl: z.ZodOptional; appKey: z.ZodOptional, z.ZodTransform>>; accessKey: z.ZodOptional, z.ZodTransform>>; resourceId: z.ZodOptional; workspaceId: z.ZodOptional; timeout: z.ZodOptional; }, z.core.$strip>>>; inheritLlmApiKey: z.ZodDefault; transcribeModel: z.ZodOptional; synthesizeModel: z.ZodOptional; maxAudioBytes: z.ZodDefault; maxStreamDurationMs: z.ZodDefault; }, z.core.$strip>; /** * Audio 配置类型 * * @example * ```ts * import type { AudioConfig } from '@h-ai/ai' * import { AudioConfigSchema } from '@h-ai/ai' * * const config: AudioConfig = AudioConfigSchema.parse({ models: [{ id: 'local-tts', provider: 'indextts', model: 'indextts2', operations: ['synthesize'], baseUrl: 'http://127.0.0.1:8000' }], synthesizeModel: 'local-tts', inheritLlmApiKey: false }) * ``` */ type AudioConfig = z.infer; /** * 已解析的语音模型配置 * * 由 `resolveAudioModel()` 返回,凭据已按模型条目、显式 LLM 继承、平台环境变量的顺序解析, * 端点已应用平台默认值。 * * @example * ```ts * import type { ResolvedAudioModel } from '@h-ai/ai' * * // 凭据只供请求使用,不写入面向用户的模型标签。 * function label(model: ResolvedAudioModel): string { * return `${model.provider}/${model.model}, timeout=${model.timeout}ms` * } * ``` */ interface ResolvedAudioModel { /** 模型条目 ID */ id: string; /** 所属平台 */ provider: AudioProviderName; /** 厂商模型名 */ model: string; /** API Key(模型条目 > 显式启用的 LLM 密钥继承 > 平台环境变量) */ apiKey: string | undefined; /** 端点(条目 > 平台默认) */ baseUrl: string; /** 火山引擎 App Key */ appKey: string | undefined; /** 火山引擎 Access Key */ accessKey: string | undefined; /** 火山引擎资源 ID(条目 > 平台默认) */ resourceId: string; /** 阿里云百炼业务空间 ID */ workspaceId: string | undefined; /** 请求超时(毫秒) */ timeout: number; } /** * 解析语音操作应使用的模型配置 * * 解析优先级:请求显式 `model` > 场景默认(transcribe/synthesize);凭据回退到平台环境变量。 * * @param audioConfig - Audio 配置 * @param operation - 操作类型(识别 / 合成),决定使用哪个默认模型 * @param explicit - 请求显式指定的模型 ID(最高优先级) * @param llmApiKey - LLM 全局密钥,仅在 `inheritLlmApiKey` 启用时参与解析 * @returns 成功返回已解析模型;无匹配模型返回 `AUDIO_MODEL_NOT_FOUND`;缺少凭据返回 `CONFIGURATION_ERROR` * * @example * ```ts * import { AudioConfigSchema, resolveAudioModel } from '@h-ai/ai' * * const config = AudioConfigSchema.parse({ models: [{ id: 'tts', provider: 'indextts', model: 'indextts2', operations: ['synthesize'], baseUrl: 'http://127.0.0.1:8000' }], synthesizeModel: 'tts' }) * const result = resolveAudioModel(config, 'synthesize') * if (result.success) { * const endpoint = result.data.baseUrl * } * ``` */ declare function resolveAudioModel(audioConfig: AudioConfig, operation: 'transcribe' | 'synthesize', explicit?: string, llmApiKey?: string): HaiResult; /** * 校验已解析模型是否具备该平台协议所需的凭据 * * 凭据是否必需由平台协议决定:自托管的 `whisper` / `indextts` 可无凭据;豆包允许 API Key * 或 App/Access Key 组合;其余云平台必须提供 API Key。仅在真正发起识别 / 合成前调用, * 能力查询(`getCapabilities`)不需要凭据。 * * @param model - 已解析模型 * @returns 缺少必需凭据时返回 `CONFIGURATION_ERROR`,否则返回 `null` * * @example * ```ts * import { AudioConfigSchema, ensureAudioCredential, resolveAudioModel } from '@h-ai/ai' * * const config = AudioConfigSchema.parse({ models: [{ id: 'asr', provider: 'openai', model: 'whisper-1', operations: ['transcribe'] }], transcribeModel: 'asr' }) * const result = resolveAudioModel(config, 'transcribe') * if (result.success) { * const missingCredential = ensureAudioCredential(result.data) * if (missingCredential) { * const code = missingCredential.code * } * } * ``` */ declare function ensureAudioCredential(model: ResolvedAudioModel): HaiError | null; /** * 文生图平台枚举 * * - `openai` — OpenAI GPT Image(Image API) * - `google` — Google Gemini Image / Nano Banana(Generate Content API) * - `qwen` — 阿里云百炼 Qwen-Image 2.0 / 3.0 * - `seedream` — 火山方舟 Seedream 4.x / 5.x * - `pollinations` — Pollinations 免费额度图片 API * * @example * ```ts * import { ImageProviderSchema } from '@h-ai/ai' * * const result = ImageProviderSchema.safeParse('openai') * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const ImageProviderSchema: z.ZodEnum<{ openai: "openai"; qwen: "qwen"; google: "google"; seedream: "seedream"; pollinations: "pollinations"; }>; /** * 文生图平台类型 * * @example * ```ts * import type { ImageProviderName } from '@h-ai/ai' * import { ImageProviderSchema } from '@h-ai/ai' * * const config: ImageProviderName = ImageProviderSchema.parse('openai') * ``` */ type ImageProviderName = z.infer; /** * 文生图模型条目 Schema * * @example * ```ts * import { ImageModelEntrySchema } from '@h-ai/ai' * * const result = ImageModelEntrySchema.safeParse({ id: 'image', provider: 'openai', model: 'gpt-image-1', apiKey: process.env.HAI_AI_IMAGE_OPENAI_APIKEY }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const ImageModelEntrySchema: z.ZodObject<{ id: z.ZodString; provider: z.ZodEnum<{ openai: "openai"; qwen: "qwen"; google: "google"; seedream: "seedream"; pollinations: "pollinations"; }>; model: z.ZodString; apiKey: z.ZodOptional, z.ZodTransform>>; baseUrl: z.ZodOptional; workspaceId: z.ZodOptional; timeout: z.ZodDefault; }, z.core.$strip>; /** * 文生图模型条目类型 * * @example * ```ts * import type { ImageModelEntry } from '@h-ai/ai' * import { ImageModelEntrySchema } from '@h-ai/ai' * * const config: ImageModelEntry = ImageModelEntrySchema.parse({ id: 'image', provider: 'openai', model: 'gpt-image-1', apiKey: process.env.HAI_AI_IMAGE_OPENAI_APIKEY }) * ``` */ type ImageModelEntry = z.infer; /** * 文生图配置 Schema;资源限制对所有厂商路径生效。 * * @example * ```ts * import { ImageConfigSchema } from '@h-ai/ai' * * const result = ImageConfigSchema.safeParse({ models: [{ id: 'image', provider: 'openai', model: 'gpt-image-1', apiKey: process.env.HAI_AI_IMAGE_OPENAI_APIKEY }], generateModel: 'image', maxImages: 2, maxImageBytes: 20971520 }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const ImageConfigSchema: z.ZodObject<{ maxImageBytes: z.ZodDefault; maxImages: z.ZodDefault; models: z.ZodOptional; model: z.ZodString; apiKey: z.ZodOptional, z.ZodTransform>>; baseUrl: z.ZodOptional; workspaceId: z.ZodOptional; timeout: z.ZodDefault; }, z.core.$strip>>>; generateModel: z.ZodOptional; }, z.core.$strip>; /** * 文生图配置类型 * * @example * ```ts * import type { ImageConfig } from '@h-ai/ai' * import { ImageConfigSchema } from '@h-ai/ai' * * const config: ImageConfig = ImageConfigSchema.parse({ models: [{ id: 'image', provider: 'openai', model: 'gpt-image-1', apiKey: process.env.HAI_AI_IMAGE_OPENAI_APIKEY }], generateModel: 'image', maxImages: 2, maxImageBytes: 20971520 }) * ``` */ type ImageConfig = z.infer; /** * 已解析的文生图模型 * * @example * ```ts * import type { ResolvedImageModel } from '@h-ai/ai' * * function label(model: ResolvedImageModel): string { * return `${model.provider}/${model.model}` * } * ``` */ interface ResolvedImageModel { id: string; provider: ImageProviderName; model: string; apiKey: string; baseUrl: string; workspaceId?: string; timeout: number; } /** * 解析文生图模型配置 * * @param imageConfig - 文生图配置 * @param explicit - 请求显式模型 ID 或厂商模型名 * @returns 已解析模型;模型或凭据缺失时返回 HaiResult 错误 * * @example * ```ts * import { ImageConfigSchema, resolveImageModel } from '@h-ai/ai' * * const config = ImageConfigSchema.parse({ models: [{ id: 'image', provider: 'openai', model: 'gpt-image-1', apiKey: process.env.HAI_AI_IMAGE_OPENAI_APIKEY }], generateModel: 'image' }) * const result = resolveImageModel(config) * if (result.success) { * const modelName = result.data.model * } * ``` */ declare function resolveImageModel(imageConfig: ImageConfig, explicit?: string): HaiResult; /** * AI 配置 Schema * * 统一 AI 模块配置:LLM、MCP、Embedding、Knowledge、Retrieval、Memory、Token、Summary、Compress、File。 * 模型通过 LLM.scenarios 映射场景,子系统不再独立配置 apiKey / baseUrl / model。 * * @example * ```ts * import { AIConfigSchema } from '@h-ai/ai' * * const result = AIConfigSchema.safeParse({ llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY }, token: { tokenRatio: 0.25 }, compress: { defaultStrategy: 'hybrid', preserveLastN: 4 } }) * if (!result.success) { * const issues = result.error.issues * } * else { * const config = result.data * } * ``` */ declare const AIConfigSchema: z.ZodObject<{ acp: z.ZodOptional; transport: z.ZodEnum<{ http: "http"; ws: "ws"; }>; url: z.ZodURL; headerEnv: z.ZodDefault>; supportedTransports: z.ZodArray>; id: z.ZodString; name: z.ZodString; enabled: z.ZodDefault; adapter: z.ZodDefault; modelIds: z.ZodDefault>; defaultModelId: z.ZodOptional; environmentRefs: z.ZodDefault>; environmentIds: z.ZodDefault>; sharedMode: z.ZodDefault; allowedCapabilities: z.ZodDefault>>; defaults: z.ZodOptional; reasoningEffort: z.ZodOptional; temperature: z.ZodOptional; maxOutputTokens: z.ZodOptional; }, z.core.$strict>>; execution: z.ZodOptional>; environmentId: z.ZodOptional; resources: z.ZodOptional; memoryMiB: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>; workspaceId: z.ZodOptional; context: z.ZodOptional>; knowledgeBaseIds: z.ZodOptional>; skillIds: z.ZodOptional>; memory: z.ZodOptional; spaceId: z.ZodOptional; write: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; tools: z.ZodOptional>; }, z.core.$strict>>; capabilities: z.ZodOptional>; permissions: z.ZodOptional>; approval: z.ZodOptional>; ruleIds: z.ZodOptional>; }, z.core.$strict>>; limits: z.ZodOptional; runTimeoutMs: z.ZodOptional; approvalTimeoutMs: z.ZodOptional; maxOutputBytes: z.ZodOptional; }, z.core.$strict>>; output: z.ZodOptional; schema: z.ZodOptional>; }, z.core.$strict>>; native: z.ZodOptional; }, z.core.$strict>>; metadata: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>, z.ZodObject<{ mode: z.ZodLiteral<"embedded">; transport: z.ZodDefault>; command: z.ZodOptional; args: z.ZodOptional>; id: z.ZodString; name: z.ZodString; enabled: z.ZodDefault; adapter: z.ZodDefault; modelIds: z.ZodDefault>; defaultModelId: z.ZodOptional; environmentRefs: z.ZodDefault>; environmentIds: z.ZodDefault>; sharedMode: z.ZodDefault; allowedCapabilities: z.ZodDefault>>; defaults: z.ZodOptional; reasoningEffort: z.ZodOptional; temperature: z.ZodOptional; maxOutputTokens: z.ZodOptional; }, z.core.$strict>>; execution: z.ZodOptional>; environmentId: z.ZodOptional; resources: z.ZodOptional; memoryMiB: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>; workspaceId: z.ZodOptional; context: z.ZodOptional>; knowledgeBaseIds: z.ZodOptional>; skillIds: z.ZodOptional>; memory: z.ZodOptional; spaceId: z.ZodOptional; write: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; tools: z.ZodOptional>; }, z.core.$strict>>; capabilities: z.ZodOptional>; permissions: z.ZodOptional>; approval: z.ZodOptional>; ruleIds: z.ZodOptional>; }, z.core.$strict>>; limits: z.ZodOptional; runTimeoutMs: z.ZodOptional; approvalTimeoutMs: z.ZodOptional; maxOutputBytes: z.ZodOptional; }, z.core.$strict>>; output: z.ZodOptional; schema: z.ZodOptional>; }, z.core.$strict>>; native: z.ZodOptional; }, z.core.$strict>>; metadata: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>, z.ZodObject<{ mode: z.ZodLiteral<"builtin-service">; transport: z.ZodDefault>; image: z.ZodString; engine: z.ZodDefault>; command: z.ZodOptional; args: z.ZodOptional>; id: z.ZodString; name: z.ZodString; enabled: z.ZodDefault; adapter: z.ZodDefault; modelIds: z.ZodDefault>; defaultModelId: z.ZodOptional; environmentRefs: z.ZodDefault>; environmentIds: z.ZodDefault>; sharedMode: z.ZodDefault; allowedCapabilities: z.ZodDefault>>; defaults: z.ZodOptional; reasoningEffort: z.ZodOptional; temperature: z.ZodOptional; maxOutputTokens: z.ZodOptional; }, z.core.$strict>>; execution: z.ZodOptional>; environmentId: z.ZodOptional; resources: z.ZodOptional; memoryMiB: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>; workspaceId: z.ZodOptional; context: z.ZodOptional>; knowledgeBaseIds: z.ZodOptional>; skillIds: z.ZodOptional>; memory: z.ZodOptional; spaceId: z.ZodOptional; write: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; tools: z.ZodOptional>; }, z.core.$strict>>; capabilities: z.ZodOptional>; permissions: z.ZodOptional>; approval: z.ZodOptional>; ruleIds: z.ZodOptional>; }, z.core.$strict>>; limits: z.ZodOptional; runTimeoutMs: z.ZodOptional; approvalTimeoutMs: z.ZodOptional; maxOutputBytes: z.ZodOptional; }, z.core.$strict>>; output: z.ZodOptional; schema: z.ZodOptional>; }, z.core.$strict>>; native: z.ZodOptional; }, z.core.$strict>>; metadata: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>], "mode">>>; workspaces: z.ZodDefault; path: z.ZodString; }, z.core.$strict>, z.ZodObject<{ type: z.ZodLiteral<"volume">; name: z.ZodString; engine: z.ZodDefault>; image: z.ZodString; }, z.core.$strict>], "type">; repositories: z.ZodDefault; }, z.core.$strict>>>; environmentRefs: z.ZodDefault>; gitEnvironmentRefs: z.ZodDefault>; }, z.core.$strict>>>; requestTimeout: z.ZodDefault; promptTimeout: z.ZodDefault; cancelTimeout: z.ZodDefault; maxContentBytes: z.ZodDefault; maxPendingEvents: z.ZodDefault; workerIdleTimeoutMs: z.ZodDefault; }, z.core.$strict>>; llm: z.ZodDefault, z.ZodTransform>>; baseUrl: z.ZodOptional; model: z.ZodDefault>; protocol: z.ZodDefault>>; maxTokens: z.ZodDefault>; temperature: z.ZodDefault>; timeout: z.ZodDefault>; tempModelCacheTtl: z.ZodDefault>; models: z.ZodOptional; maxOutputTokens: z.ZodOptional; inputModalities: z.ZodOptional>>; outputModalities: z.ZodOptional>>; toolCalling: z.ZodOptional; reasoning: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; model: z.ZodString; protocol: z.ZodOptional>; apiKey: z.ZodOptional, z.ZodTransform>>; baseUrl: z.ZodOptional; maxTokens: z.ZodOptional; temperature: z.ZodOptional; timeout: z.ZodOptional; }, z.core.$strict>>>; scenarios: z.ZodOptional; chat: z.ZodOptional; reasoning: z.ZodOptional; plan: z.ZodOptional; execute: z.ZodOptional; extraction: z.ZodOptional; summary: z.ZodOptional; embedding: z.ZodOptional; rerank: z.ZodOptional; ocr: z.ZodOptional; fast: z.ZodOptional; }, z.core.$strip>>; }, z.core.$strict>>; mcp: z.ZodOptional; environmentId: z.ZodOptional; command: z.ZodOptional; args: z.ZodDefault>; url: z.ZodOptional; environmentRefs: z.ZodDefault>; headerEnv: z.ZodDefault>; allowedTools: z.ZodOptional>; timeoutMs: z.ZodOptional; pool: z.ZodOptional; maxTotal: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>>; server: z.ZodOptional>; capabilities: z.ZodOptional>; resources: z.ZodDefault>; prompts: z.ZodDefault>; }, z.core.$strip>>; }, z.core.$strip>>; }, z.core.$strip>>; embedding: z.ZodOptional; batchSize: z.ZodDefault; }, z.core.$strip>>; knowledge: z.ZodOptional; dimension: z.ZodDefault; enableEntityExtraction: z.ZodDefault; cleanOptions: z.ZodDefault; removeUrls: z.ZodDefault; removeEmails: z.ZodDefault; customReplacements: z.ZodOptional>>; normalizeWhitespace: z.ZodDefault; trim: z.ZodDefault; }, z.core.$strip>>; chunkOptions: z.ZodDefault; maxSize: z.ZodDefault; overlap: z.ZodDefault; separator: z.ZodOptional; markdownMinLevel: z.ZodDefault; markdownKeepTitle: z.ZodDefault; }, z.core.$strip>>; entityBoostWeight: z.ZodDefault; entityTypes: z.ZodOptional>; systemPrompt: z.ZodOptional; }, z.core.$strip>>; memory: z.ZodOptional>; vectorNamespace: z.ZodDefault; allowEphemeralFallback: z.ZodDefault; maxEntriesPerObject: z.ZodDefault; maxEntriesGlobal: z.ZodDefault; systemPrompt: z.ZodOptional; recencyDecay: z.ZodDefault; embeddingEnabled: z.ZodDefault; defaultTopK: z.ZodDefault; candidateMultiplier: z.ZodDefault; writebackRelatedTopK: z.ZodDefault; }, z.core.$strip>>; token: z.ZodOptional; }, z.core.$strip>>; summary: z.ZodOptional; }, z.core.$strip>>; compress: z.ZodOptional>; defaultMaxTokens: z.ZodDefault; preserveLastN: z.ZodDefault; }, z.core.$strip>>; retrieval: z.ZodOptional; url: z.ZodOptional; topK: z.ZodOptional; minScore: z.ZodOptional; filter: z.ZodOptional>; }, z.core.$strip>>>; }, z.core.$strip>>; file: z.ZodOptional; }, z.core.$strip>>; a2a: z.ZodOptional; pollIntervalMs: z.ZodDefault; maxExecutionMs: z.ZodDefault; }, z.core.$strip>>; agentCard: z.ZodObject<{ name: z.ZodString; description: z.ZodOptional; url: z.ZodString; version: z.ZodOptional; skills: z.ZodOptional; tags: z.ZodOptional>; }, z.core.$strip>>>; }, z.core.$strip>; security: z.ZodOptional>; name: z.ZodDefault; }, z.core.$strip>>; }, z.core.$strip>>; }, z.core.$strip>>; audio: z.ZodOptional; model: z.ZodString; operations: z.ZodArray>; apiKey: z.ZodOptional, z.ZodTransform>>; baseUrl: z.ZodOptional; appKey: z.ZodOptional, z.ZodTransform>>; accessKey: z.ZodOptional, z.ZodTransform>>; resourceId: z.ZodOptional; workspaceId: z.ZodOptional; timeout: z.ZodOptional; }, z.core.$strip>>>; inheritLlmApiKey: z.ZodDefault; transcribeModel: z.ZodOptional; synthesizeModel: z.ZodOptional; maxAudioBytes: z.ZodDefault; maxStreamDurationMs: z.ZodDefault; }, z.core.$strip>>; image: z.ZodOptional; maxImages: z.ZodDefault; models: z.ZodOptional; model: z.ZodString; apiKey: z.ZodOptional, z.ZodTransform>>; baseUrl: z.ZodOptional; workspaceId: z.ZodOptional; timeout: z.ZodDefault; }, z.core.$strip>>>; generateModel: z.ZodOptional; }, z.core.$strip>>; }, z.core.$strip>; /** * AI 配置类型(校验后的完整类型) * * @example * ```ts * import type { AIConfig } from '@h-ai/ai' * import { AIConfigSchema } from '@h-ai/ai' * * const config: AIConfig = AIConfigSchema.parse({ llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY }, token: { tokenRatio: 0.25 }, compress: { defaultStrategy: 'hybrid', preserveLastN: 4 } }) * ``` */ type AIConfig = z.infer; /** * AI 配置输入类型(允许部分字段) * * @example * ```ts * import type { AIConfigInput } from '@h-ai/ai' * * const value: AIConfigInput = { llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_APIKEY }, embedding: { dimensions: 1536 } } * ``` */ type AIConfigInput = z.input; /** * 已授权的 Git 提交文件树,包含规范 Base64 数据。 * @example * ```ts * import type { ACPProjectSnapshot } from '@h-ai/ai' * function revision(snapshot: ACPProjectSnapshot) { return snapshot.revision } * ``` */ interface ACPProjectSnapshot { revision: string; files: Record; } /** * 当前文件树相对于授权提交的改动。 * @example * ```ts * import type { ACPProjectChanges } from '@h-ai/ai' * const empty: ACPProjectChanges = { patch: '', paths: [] } * ``` */ interface ACPProjectChanges { patch: string; paths: string[]; } /** * 从可信仓库目录读取指定提交的有界普通文件树。 * @example 模块内部上下文 * ```ts * async function read(directory: string) { return readGitSnapshot({ directory, revision: 'refs/heads/main' }) } * ``` */ declare function readGitSnapshot(input: { directory: string; revision: string; maxBytes?: number; }, signal?: AbortSignal): Promise; /** * 应用确认后的发布条件,目标分支固定在 agent/ 下。 * @example * ```ts * import type { ACPPublishSnapshot } from '@h-ai/ai' * function branch(input: ACPPublishSnapshot) { return input.branch } * ``` */ interface ACPPublishSnapshot { directory: string; remote: string; revision: string; patch: string; branch: string; date: string; author: { name: string; email: string; }; } /** * 在独立 Git 目录中应用已验权的补丁,仅向任务分支执行普通 push。 * @example 模块内部上下文 * ```ts * async function confirmed(input: ACPPublishSnapshot) { return publishSnapshot(input) } * ``` */ declare function publishSnapshot(input: ACPPublishSnapshot, signal?: AbortSignal): Promise<{ branch: string; commit: string; }>; /** * @h-ai/ai — A2A(Agent-to-Agent)子功能类型 * * 定义 A2A 协议集成所需的类型、SDK 类型再导出、操作接口。 * @module ai-a2a-types */ /** * 可直接用于 HTTP 发现响应的 A2A 1.0 ProtoJSON 文档;不暴露 SDK 内部 oneof 结构。 * @example * ```ts * import { ai } from '@h-ai/ai' * const card = ai.a2a.getAgentCard() * if (card.success) Response.json(card.data) * ``` */ interface A2AAgentCardDocument { name: string; description: string; version: string; supportedInterfaces: Array<{ url: string; protocolBinding: string; protocolVersion: string; }>; defaultInputModes: string[]; defaultOutputModes: string[]; capabilities: { streaming: boolean; pushNotifications: boolean; }; skills: Array<{ id: string; name: string; description: string; tags: string[]; }>; securitySchemes?: Record; securityRequirements?: Array<{ schemes: Record; }>; } /** * A2A 调用方身份信息 * * @example * ```ts * import type { A2ACallerIdentity } from '@h-ai/ai' * function principal(identity: A2ACallerIdentity) { * return identity.agentId // 只接受可信认证器返回的身份,不接受 JSON-RPC 参数自报。 * } * ``` */ interface A2ACallerIdentity { /** 调用方 Agent ID(如 AgentCard.name 或自定义标识) */ agentId: string; /** 调用方显示名 */ name?: string; /** 调用方 URL(AgentCard 地址) */ url?: string; } /** * A2A 消息记录(存储每条 A2A 交互) * * @example * ```ts * import type { A2AMessageRecord } from '@h-ai/ai' * function text(record: A2AMessageRecord) { * return { taskId: record.taskId, role: record.role, parts: record.parts } * } * ``` */ interface A2AMessageRecord { /** 记录 ID(自动生成) */ id: string; /** 关联的 A2A Task ID */ taskId: string; /** 所属会话上下文 ID(历史记录可能缺失) */ contextId?: string; /** 消息角色:user(入站请求)/ agent(出站响应) */ role: 'user' | 'agent'; /** 消息内容(JSON 序列化的 Part[] 数组) */ parts: unknown[]; /** 调用方身份信息(仅 role=user 时) */ caller?: A2ACallerIdentity; /** 创建时间戳(毫秒) */ createdAt: number; } /** * A2A 上下文信息(对话/会话级别) * * @example * ```ts * import type { A2AContextInfo } from '@h-ai/ai' * function lastActivity(context: A2AContextInfo) { * return new Date(context.updatedAt).toISOString() * } * ``` */ interface A2AContextInfo { /** 上下文 ID(对应 SDK 的 contextId) */ id: string; /** 关联的 Agent 标识 */ agentId?: string; /** 上下文标题(可选) */ title?: string; /** 创建时间戳 */ createdAt: number; /** 最后更新时间戳 */ updatedAt: number; } /** * A2A 认证器接口 * * 纯接口设计,由应用层实现,Kit 模块做胶水集成。 * 用于验证入站 A2A 请求的身份。 * * @example * ```ts * import type { A2AAuthenticator, A2ACallerIdentity } from '@h-ai/ai' * import type { HaiResult } from '@h-ai/core' * function authenticator(verify: (headers: Record) => Promise>): A2AAuthenticator { * return { authenticate: headers => verify(headers) } * } * ``` */ interface A2AAuthenticator { /** * 验证入站请求 * * @param headers - HTTP 请求头 * @returns 成功返回调用方身份信息,失败返回错误 */ authenticate: (headers: Record) => Promise>; } /** * A2A 任务查询过滤器 * * @example * ```ts * import { ai } from '@h-ai/ai' * import type { A2ATaskFilter } from '@h-ai/ai' * const filter: A2ATaskFilter = { callerId: 'agent-1', contextId: 'context-1', status: 'user', limit: 20 } * const result = await ai.a2a.listMessages(filter) * if (result.success) { * const messages = result.data.items * } * ``` */ interface A2ATaskFilter { /** 按消息角色过滤(user / agent),不是任务生命周期状态 */ status?: string | string[]; /** 按上下文 ID 过滤 */ contextId?: string; /** 按调用方 Agent ID 过滤 */ callerId?: string; /** 时间范围起始(毫秒) */ since?: number; /** 最大返回数 */ limit?: number; /** 偏移量 */ offset?: number; } /** * A2A 操作接口 * * 提供 Agent-to-Agent 协议能力:Agent Card 管理、请求处理、客户端调用。 * * @example * ```ts * import { ai } from '@h-ai/ai' * import type { AgentExecutor } from '@h-ai/ai' * function register(executor: AgentExecutor) { * const registered = ai.a2a.registerExecutor(executor) * if (!registered.success) return registered * const card = ai.a2a.getAgentCard() * if (!card.success) return card * return card.data * } * ``` */ interface A2AOperations { /** * 注册 Agent 执行器 * * 需要先调用 `ai.init()` 并配置 `a2a` 后才能注册。 * 注册后 `handleRequest()`、`listMessages()` 等方法即可使用。 * * @param executor - Agent 执行器(由应用层实现) * @returns 注册成功返回 `ok(undefined)`;未配置/未初始化返回 `err(HaiAIError.*)` */ registerExecutor: (executor: AgentExecutor) => HaiResult; /** * 获取当前 Agent Card * * 配置了 a2a 后即可使用,无需注册 executor。 * * @returns 可直接用于 HTTP 发现响应的 A2A 1.0 ProtoJSON Agent Card(含能力与安全方案) */ getAgentCard: () => HaiResult; /** * 处理入站 JSON-RPC 请求 * * 将 HTTP 请求体路由到 SDK 的 JsonRpcTransportHandler。 * * @param requestBody - JSON-RPC 请求体 * @param context - 可信 HTTP 层认证上下文;agentId 映射为 SDK user.userName * @returns JSON-RPC 响应(单条或流式);未初始化也返回 JSON-RPC 错误,不混入 HaiResult */ handleRequest: (requestBody: unknown, context?: Record) => Promise; /** * 查询 A2A 消息列表(服务端管理接口,不自动推断调用方权限) * * @param filter - 查询过滤器 * @returns 分页消息;存储失败返回 A2A_LIST_MESSAGES_FAILED,不暴露原始连接错误。 * 日志不是交付回执,业务结果须结合 Task 的 requiresEffectReconciliation 判断。 */ listMessages: (filter: A2ATaskFilter) => Promise>>; /** * 作为客户端调用远端 Agent * * remoteUrl 只应来自受信配置。框架校验协议和内嵌凭据,应用仍须按部署环境实施来源白名单与出口策略。 * * @param remoteUrl - 远端 Agent 的 A2A 端点 URL * @param message - 发送的消息文本 * @param options - 调用选项 * @returns 远端响应 */ callRemoteAgent: (remoteUrl: string, message: string, options?: A2ACallOptions) => Promise>; } /** * A2A API Key 安全配置 * * @example * ```ts * import type { A2AApiKeySecurity } from '@h-ai/ai' * const security: A2AApiKeySecurity = { in: 'header', name: 'X-Agent-Key' } * const headerName = security.name // 描述传递方式;实际验证仍由应用实现。 * ``` */ interface A2AApiKeySecurity { /** API Key 的传递位置 */ in: 'header' | 'query'; /** 参数名 */ name: string; } /** * A2A 安全认证配置 * * @example * ```ts * import type { A2AAgentCardConfig, A2ASecurityConfig } from '@h-ai/ai' * const security: A2ASecurityConfig = { apiKey: { in: 'header', name: 'X-Agent-Key' } } * const card: A2AAgentCardConfig = { name: 'guide', url: 'https://example.com/a2a', security } * ``` */ interface A2ASecurityConfig { /** API Key 认证配置 */ apiKey?: A2AApiKeySecurity; } /** * Agent Card 配置(应用层提供) * * @example * ```ts * import type { A2AAgentCardConfig } from '@h-ai/ai' * const config: A2AAgentCardConfig = { name: 'guide', url: 'https://example.com/a2a', version: '1.0.0', skills: [{ id: 'help', name: '帮助', tags: ['docs'] }] } * const skillNames = config.skills?.map(skill => skill.name) ?? [] * ``` */ interface A2AAgentCardConfig { /** Agent 名称 */ name: string; /** Agent 描述 */ description?: string; /** Agent URL(对外可访问的 base URL) */ url: string; /** Agent 版本 */ version?: string; /** Agent 能力声明 */ skills?: Array<{ id: string; name: string; description?: string; tags?: string[]; }>; /** 安全认证配置(体现在 Agent Card 的 securitySchemes / securityRequirements 字段) */ security?: A2ASecurityConfig; } /** * 处理结果(单条或流式) * * @example * ```ts * import type { A2AHandleResult } from '@h-ai/ai' * async function consume(result: A2AHandleResult) { * if (result.streaming && result.stream) { * const events: unknown[] = [] * for await (const event of result.stream) events.push(event) * return events * } * return result.body * } * ``` */ interface A2AHandleResult { /** 是否为流式响应 */ streaming: boolean; /** 单条 JSON-RPC 响应体(非流式时) */ body?: unknown; /** 流式 JSON-RPC 响应迭代器(流式时) */ stream?: AsyncGenerator; } /** * 远端调用选项 * * @example * ```ts * import { ai } from '@h-ai/ai' * import type { A2ACallOptions } from '@h-ai/ai' * const options: A2ACallOptions = { timeout: 30_000 } * const result = await ai.a2a.callRemoteAgent('https://trusted-agent.example.com/a2a', '项目介绍', options) * if (result.success) { * const answer = result.data.responseText * } * ``` */ interface A2ACallOptions { /** 超时时间(毫秒),默认 60 秒。 */ timeout?: number; /** 额外请求头,按大小写不敏感的同名字段覆盖;远端 HTTP 重定向被拒绝。 */ headers?: Record; } /** * 远端调用结果 * * @example * ```ts * import type { A2ACallResult } from '@h-ai/ai' * function answer(result: A2ACallResult) { * return { taskId: result.taskId, state: result.taskState, text: result.responseText ?? '' } * } * ``` */ interface A2ACallResult { /** 远端任务 ID */ taskId?: string; /** 任务最终状态 */ taskState?: TaskState; /** 响应消息文本 */ responseText?: string; /** 响应消息 Part 数组 */ responseParts?: unknown[]; } /** * 计划或持续会话的参数。 * @example 模块内部上下文 * ```ts * const request = platformRequestSchema.parse({ agentId: 'assistant' }) * ``` */ declare const platformRequestSchema: z.ZodObject<{ model: z.ZodOptional; reasoningEffort: z.ZodOptional; temperature: z.ZodOptional; maxOutputTokens: z.ZodOptional; }, z.core.$strict>>; execution: z.ZodOptional>; environmentId: z.ZodOptional; resources: z.ZodOptional; memoryMiB: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>>; workspaceId: z.ZodOptional; context: z.ZodOptional>; knowledgeBaseIds: z.ZodOptional>; skillIds: z.ZodOptional>; memory: z.ZodOptional; spaceId: z.ZodOptional; write: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; tools: z.ZodOptional>; }, z.core.$strict>>; capabilities: z.ZodOptional>; permissions: z.ZodOptional>; approval: z.ZodOptional>; ruleIds: z.ZodOptional>; }, z.core.$strict>>; limits: z.ZodOptional; runTimeoutMs: z.ZodOptional; approvalTimeoutMs: z.ZodOptional; maxOutputBytes: z.ZodOptional; }, z.core.$strict>>; output: z.ZodOptional; schema: z.ZodOptional>; }, z.core.$strict>>; native: z.ZodOptional; }, z.core.$strict>>; metadata: z.ZodOptional>; agentId: z.ZodString; }, z.core.$strict>; declare const submitTurnSchema: z.ZodObject<{ output: z.ZodOptional; schema: z.ZodOptional>; }, z.core.$strict>>; context: z.ZodOptional>; knowledgeBaseIds: z.ZodOptional>; skillIds: z.ZodOptional>; memory: z.ZodOptional; spaceId: z.ZodOptional; write: z.ZodOptional>; }, z.core.$strict>>; }, z.core.$strict>>; limits: z.ZodOptional; runTimeoutMs: z.ZodOptional; approvalTimeoutMs: z.ZodOptional; maxOutputBytes: z.ZodOptional; }, z.core.$strict>>; prompt: z.ZodUnion>]>; idempotencyKey: z.ZodString; }, z.core.$strict>; /** * 应用核验主体和任务所请求的高权限选项。 * @example * ```ts * import type { ACPPlatformPolicy } from '@h-ai/ai' * const policy: ACPPlatformPolicy = { allowFullAccess: scope => scope.userId === 'operator' } * ``` */ interface ACPPlatformPolicy { /** 只接受已由应用确认的主体和 Agent。默认禁止完全访问。 */ allowFullAccess?: (scope: RunnerScope, agentId: string) => boolean | Promise; /** 自动模式下明确允许同一用户复用独占 Worker。 */ preferUserWorker?: (scope: RunnerScope, agentId: string) => boolean | Promise; /** 检查当前主体是否能使用选定工具,每轮重新校验。 */ allowTools?: (scope: RunnerScope, agentId: string, toolIds: readonly string[]) => boolean | Promise; /** 创建应用控制的 HTTP MCP 入口。传入 Worker 生命周期,返回 signal 通知绑定到期或撤销。 */ bindTools?: (scope: RunnerScope, sessionId: string, toolIds: readonly string[], signal: AbortSignal) => Promise<{ servers: McpServer[]; revoke: () => void | Promise; signal?: AbortSignal; }>; /** 在计划和执行时验证知识库、文件与记忆选择的权限。 */ allowContext?: (scope: RunnerScope, agentId: string, context: NonNullable) => boolean | Promise; /** 以当前主体检查只读工作区快照的访问权限。 */ allowWorkspace?: (scope: RunnerScope, workspaceId: string) => boolean | Promise; /** 在执行节点读取已授权的工作区文件。最多 8 个平铺普通文件,总量受执行环境和 16 MiB 上限约束。 */ resolveWorkspace?: (scope: RunnerScope, workspaceId: string, signal: AbortSignal) => Promise>>; /** 在工作区授权之后读取部署方登记的普通文件项目快照。 */ resolveProject?: (scope: RunnerScope, workspaceId: string, signal: AbortSignal) => Promise; /** 在成功轮次后发布补丁;只向浏览器交付已绑定主体的产物引用。 */ publishProject?: (input: { scope: RunnerScope; workspaceId: string; sessionId: string; turnId: string; revision: string; changes: ACPProjectChanges; }, signal: AbortSignal) => Promise<{ id: string; name: string; }>; /** 在当前轮次装配经授权的知识片段、记忆及附件。只读;不共享宿主路径。 */ resolveContext?: (scope: RunnerScope, request: ACPPlatformRequest, prompt: readonly ContentBlock[], signal: AbortSignal) => Promise; /** 提交用户记忆。应用按 turnId 幂等写入,或登记人工确认。 */ commitMemory?: (input: { scope: RunnerScope; sessionId: string; turnId: string; context: NonNullable; text: string; }, signal: AbortSignal) => Promise; /** 解析已授权技能的正文或原生指令。 */ resolveSkills?: (scope: RunnerScope, agentId: string, skillIds: readonly string[], signal: AbortSignal) => Promise; /** 核对当前 ACL 和原生操作,返回绑定真实对象与操作的规则键。返回 undefined 时拒绝。 */ resolvePermission?: (scope: RunnerScope, sessionId: string, tool: RequestPermissionRequest['toolCall']) => { key: string; summary: string; } | undefined | Promise<{ key: string; summary: string; } | undefined>; } /** * 审批有效期或拒绝本次操作。 * @example * ```ts * import type { ACPApprovalDecision } from '@h-ai/ai' * const decision: ACPApprovalDecision = 'allow-once' * ``` */ type ACPApprovalDecision = 'allow-once' | 'allow-session' | 'always-allow' | 'deny'; /** * 与当前轮次实际使用的资料一起返回的应用引用。 * @example * ```ts * import type { ACPCitation } from '@h-ai/ai' * const source: ACPCitation = { id: 'guide', title: 'Team guide', excerpt: 'Use Node.js.' } * ``` */ interface ACPCitation { id: string; title: string; excerpt?: string; } /** * 受管会话及计划的调用参数。 * @example * ```ts * import type { ACPPlatformRequest } from '@h-ai/ai' * const request: ACPPlatformRequest = { agentId: 'assistant', execution: { mode: 'auto' } } * ``` */ type ACPPlatformRequest = z.input; /** * 一次请求的业务输入。 * @example * ```ts * import type { ACPRunRequest } from '@h-ai/ai' * const request: ACPRunRequest = { agentId: 'assistant', prompt: '总结', idempotencyKey: 'message-1' } * ``` */ type ACPRunRequest = ACPPlatformRequest & { prompt: string | ContentBlock[]; idempotencyKey?: string; }; /** * API 侧的观察器和显式取消信号。 * @example * ```ts * import type { ACPRunObserver } from '@h-ai/ai' * const observer: ACPRunObserver = { signal: new AbortController().signal } * ``` */ interface ACPRunObserver { signal?: AbortSignal; onEvent?: (event: RunnerJson) => void; } /** * 可在当前轮次调整的时限、输出和事件观察选项。 * @example * ```ts * import type { ACPTurnOptions } from '@h-ai/ai' * const options: ACPTurnOptions = { limits: { runTimeoutMs: 10000 }, output: { format: 'json' } } * ``` */ type ACPTurnOptions = ACPRunObserver & Pick; /** * 独立提交一轮。提交回执和执行进度可由各自的 HTTP 请求获取。 * @example * ```ts * import type { ACPSubmitTurn } from '@h-ai/ai' * const turn: ACPSubmitTurn = { prompt: 'Summarize the document.', idempotencyKey: 'request-1' } * ``` */ type ACPSubmitTurn = z.input; /** * @h-ai/ai — RAG(Retrieval-Augmented Generation)子功能类型 * * 定义 RAG 操作的类型接口:检索 + 生成。 * @module ai-rag-types */ /** * RAG 选项 * * @example * ```ts * import { ai, type RagOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * async function run(options: RagOptions) { * const result = await ai.rag.query('如何部署?', options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface RagOptions { /** 交互主体 ID */ objectId?: string; /** 会话 ID */ sessionId?: string; /** 使用的检索源(不指定则使用全部已注册源) */ sources?: string[]; /** 返回的上下文条数(默认 5) */ topK?: number; /** 最低相似度 */ minScore?: number; /** 是否启用 Rerank 重排序 */ enableRerank?: boolean; /** Rerank 使用的模型名称覆盖 */ rerankModel?: string; /** LLM 模型名称覆盖 */ model?: string; /** 系统提示词(可选,会自动注入检索上下文) */ systemPrompt?: string; /** 温度覆盖 */ temperature?: number; /** 自定义上下文格式化函数 */ formatContext?: (items: RagContextItem[]) => string; /** 是否保留消息历史(用于多轮对话) */ messages?: ChatMessage[]; /** 是否启用内部 LLM 调用的持久化(默认 true;Context 层调用时传 false 避免重复记录) */ enablePersist?: boolean; /** 请求取消信号(透传给内部 LLM 调用,支持中途取消生成) */ signal?: AbortSignal; } /** * RAG 上下文项 * * @example * ```ts * import type { RagContextItem } from '@h-ai/ai' * const value: RagContextItem = { content: '使用共享数据库', score: 0.9, sourceId: 'docs' } * const fragment = `[${value.sourceId}] ${value.content}` * ``` */ interface RagContextItem { /** 文档内容 */ content: string; /** 相似度分数 */ score: number; /** 来源 */ sourceId: string; /** 元数据 */ metadata?: Record; /** 结构化信源引用 */ citation?: Citation; } /** * RAG 结果 * * @example * ```ts * import type { RagResult } from '@h-ai/ai' * const value: RagResult = { answer: '请使用共享数据库。', context: [], citations: [], query: '如何部署?', model: 'configured-model' } * const answer = value.answer * ``` */ interface RagResult { /** LLM 生成的回答 */ answer: string; /** 使用的上下文 */ context: RagContextItem[]; /** 去重后的信源引用列表(方便 UI 展示引用栏) */ citations: Citation[]; /** 查询文本 */ query: string; /** 使用的模型 */ model: string; /** Token 使用统计 */ usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; } /** * RAG 流式事件 * * queryStream 产出的事件序列: * 1. `context` — 检索结果就绪,携带上下文列表 * 2. `delta` — LLM 增量文本 * 3. `done` — 生成完成,携带完整结果汇总 * * @example * ```ts * import type { RagStreamEvent } from '@h-ai/ai' * function render(event: RagStreamEvent): string { * return event.type === 'delta' ? event.text : event.type === 'done' ? event.answer : '' * } * ``` */ type RagStreamEvent = { type: 'context'; items: RagContextItem[]; citations: Citation[]; } | { type: 'delta'; text: string; } | { type: 'done'; answer: string; model: string; usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; }; /** * RAG 操作接口 * * @example * ```ts * import { ai, type RagOperations } from '@h-ai/ai' * // 应用启动已成功初始化 ai,并注册 docs 检索源。 * const operations: RagOperations = ai.rag * const result = await operations.query('如何部署?', { objectId: 'user-1', sources: ['docs'], topK: 3 }) * if (!result.success) throw new Error(result.error.message) * const answer = result.data.answer * ``` */ interface RagOperations { /** * 执行 RAG(检索增强生成) * * 1. 将查询文本向量化 * 2. 从已注册的检索源中检索相关文档 * 3. 将检索上下文注入 LLM 提示词 * 4. 调用 LLM 生成回答 * * @param query - 用户查询文本 * @param options - RAG 选项 * @returns RAG 结果 */ query: (query: string, options?: RagOptions) => Promise>; /** * 流式 RAG 查询 * * 产出事件序列:context → delta* → done * * @param query - 用户查询文本 * @param options - RAG 选项 * @returns 异步可迭代的 RagStreamEvent */ queryStream: (query: string, options?: RagOptions) => AsyncIterable; } /** * @h-ai/ai — Reasoning 子功能类型 * * 定义推理策略和推理操作的类型接口。 * 支持 ReAct、Chain-of-Thought(CoT)、Plan-and-Execute 三种策略。 * @module ai-reasoning-types */ /** * 推理策略类型 * * - `react` — ReAct(Reasoning + Acting):交替 思考→行动→观察 循环 * - `cot` — Chain-of-Thought:将问题分解为思维链逐步推理 * - `plan-execute` — Plan-and-Execute:先生成计划再逐步执行 * * @example * ```ts * import type { ReasoningStrategy } from '@h-ai/ai' * const value: ReasoningStrategy = 'cot' * const options = { strategy: value, maxRounds: 3 } * ``` */ type ReasoningStrategy = 'react' | 'cot' | 'plan-execute'; /** * 推理执行选项 * * @example * ```ts * import { ai, type ReasoningOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * async function run(options: ReasoningOptions) { * const result = await ai.reasoning.run('解释这项设计的权衡', options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface ReasoningOptions { /** 交互主体 ID */ objectId?: string; /** 会话 ID */ sessionId?: string; /** 推理策略(默认 `'react'`) */ strategy?: ReasoningStrategy; /** 最大推理轮次(默认 10) */ maxRounds?: number; /** 使用的模型 ID 或名称(可选,默认使用 reasoning 场景的模型) */ model?: string; /** Plan-Execute 规划阶段模型(可选,默认回退到 `model` → 场景 `plan` → 场景 `reasoning`) */ planModel?: string; /** Plan-Execute 执行阶段模型(可选,默认回退到 `model` → 场景 `execute` → 场景 `reasoning`) */ executeModel?: string; /** 系统提示词(可选,覆盖默认的策略提示词) */ systemPrompt?: string; /** 是否启用内部 LLM 调用的持久化(默认 true;Context 层调用时传 false 避免重复记录) */ enablePersist?: boolean; /** * 前置对话上下文(可选) * * 插入到系统提示词之后、当前问题之前,用于注入: * - 历史对话轮次(连续对话场景) * - `ai.memory.injectMemories()` 处理后的记忆增强消息 * - RAG 检索到的内容片段(构造为 system 消息) * * @example * ```ts * // 将记忆注入推理上下文 * const withMemory = await ai.memory.injectMemories( * [{ role: 'user', content: query }], * { objectId: 'user-001' }, * ) * await ai.reasoning.run(query, { messages: withMemory.data }) * ``` */ messages?: ChatMessage[]; /** 可用工具注册表(可选,ReAct 和 Plan-Execute 策略可用) */ tools?: ToolRegistryOperations; /** 温度覆盖 */ temperature?: number; /** 请求取消信号(透传给内部 LLM 调用,支持中途取消推理) */ signal?: AbortSignal; } /** * 推理步骤类型 * * @example * ```ts * import type { ReasoningStepType } from '@h-ai/ai' * const value: ReasoningStepType = 'answer' * const isFinal = value === 'answer' * ``` */ type ReasoningStepType = 'thought' | 'action' | 'observation' | 'plan' | 'answer'; /** * 单个推理步骤 * * @example * ```ts * import type { ReasoningStep } from '@h-ai/ai' * const value: ReasoningStep = { type: 'answer', content: '选择共享数据库。', index: 0 } * const display = value.content * ``` */ interface ReasoningStep { /** 步骤类型 */ type: ReasoningStepType; /** 步骤内容 */ content: string; /** 工具调用信息(仅 action 类型) */ toolCall?: { name: string; arguments: Record; result?: string; }; /** 步骤索引(从 0 开始) */ index: number; } /** * 推理执行结果 * * @example * ```ts * import type { ReasoningResult } from '@h-ai/ai' * const value: ReasoningResult = { answer: '选择共享数据库。', steps: [{ type: 'answer', content: '选择共享数据库。', index: 0 }], strategy: 'cot', rounds: 1, messages: [] } * const answer = value.answer * ``` */ interface ReasoningResult { /** 最终答案 */ answer: string; /** 推理步骤列表 */ steps: ReasoningStep[]; /** 使用的策略 */ strategy: ReasoningStrategy; /** 总推理轮次 */ rounds: number; /** 完整的消息历史 */ messages: ChatMessage[]; } /** * 推理流式事件 * * runStream 产出的事件序列: * - `step` — 推理步骤完成(思考/行动/观察/计划) * - `delta` — LLM 增量文本(最终答案的流式输出) * - `done` — 推理完成,携带完整结果 * * @example * ```ts * import type { ReasoningStreamEvent } from '@h-ai/ai' * function render(event: ReasoningStreamEvent): string { * return event.type === 'delta' ? event.text : event.type === 'done' ? event.result.answer : event.step.content * } * ``` */ type ReasoningStreamEvent = { type: 'step'; step: ReasoningStep; } | { type: 'delta'; text: string; } | { type: 'done'; result: ReasoningResult; }; /** * 推理操作接口(通过 `ai.reasoning` 访问) * * 需要先调用 `ai.init()` 初始化后使用。 * * @example * ```ts * import { ai, type ReasoningOperations } from '@h-ai/ai' * // 应用启动已成功初始化 ai。 * const operations: ReasoningOperations = ai.reasoning * const result = await operations.run('解释为何需要共享状态', { strategy: 'cot', maxRounds: 3 }) * if (!result.success) throw new Error(result.error.message) * const answer = result.data.answer * ``` */ interface ReasoningOperations { /** * 执行推理 * * @param query - 用户问题或任务描述 * @param options - 推理选项 * @returns 推理结果 */ run: (query: string, options?: ReasoningOptions) => Promise>; /** * 流式推理(逐步产出推理步骤 + 最终答案增量文本) * * 产出事件序列:step* → delta* → done * * @param query - 用户问题或任务描述 * @param options - 推理选项 * @returns 异步可迭代的 ReasoningStreamEvent */ runStream: (query: string, options?: ReasoningOptions) => AsyncIterable; } /** * @h-ai/ai — Summary 子功能类型 * * 定义摘要生成操作的类型接口:使用 LLM 对对话消息生成摘要,支持增量摘要。 * @module ai-summary-types */ /** * 摘要生成选项 * * @example * ```ts * import type { SummaryOptions } from '@h-ai/ai' * * const value: SummaryOptions = { previousSummary: '用户选择按周发布。', systemPrompt: '保留决策与未完成事项。', temperature: 0.2 } * ``` */ interface SummaryOptions { /** 摘要用的模型 */ model?: string; /** 温度覆盖 */ temperature?: number; /** 自定义摘要 systemPrompt(覆盖模块配置与内置默认提示词) */ systemPrompt?: string; /** 前序摘要文本(用于增量摘要) */ previousSummary?: string; } /** * 摘要生成结果 * * @example * ```ts * import type { SummaryResult } from '@h-ai/ai' * * function describeCoverage(summary: SummaryResult): string { * return `${summary.coveredMessages} 条消息,约 ${summary.tokenCount} tokens:${summary.summary}` * } * ``` */ interface SummaryResult { /** 摘要文本 */ summary: string; /** 摘要的估算 Token 数 */ tokenCount: number; /** 覆盖的原始消息数 */ coveredMessages: number; } /** * Summary 操作接口 * * 使用 LLM 对消息列表生成摘要,支持全量摘要与增量摘要。 * * @example * ```ts * import { ai } from '@h-ai/ai' * * // 应用启动已成功初始化 ai;这里是业务服务函数。 * async function run() { * const result = await ai.summary.summarize([{ role: 'user', content: '每周一发布周报。' }]) * if (!result.success) * return result * return result.data.summary * } * ``` */ interface SummaryOperations { /** * 生成摘要文本 * * @param messages - 消息列表 * @param options - 摘要选项 * @returns 摘要文本 */ generate: (messages: ChatMessage[], options?: SummaryOptions) => Promise>; /** * 生成摘要(含元数据) * * @param messages - 消息列表 * @param options - 摘要选项 * @returns 摘要结果(含 Token 数、覆盖消息数) */ summarize: (messages: ChatMessage[], options?: SummaryOptions) => Promise>; } /** * @h-ai/ai — Context 子功能类型 * * 定义上下文管理操作的类型接口。 * Context 是全部子模块的聚合层,提供有状态的 ContextManager: * 多轮对话自动压缩 + 可选 LLM / Memory / RAG / Reasoning / Tools 编排。 * @module ai-context-types */ /** * 会话固化选项(`ContextManager.consolidate` 使用) * * 把「短期会话记忆 + 摘要」固化为「长期记忆」,形成 * `Session Memory → Summary → Long-term Memory` 的生命周期闭环。 * * @example * ```ts * import type { ContextManager, ConsolidateOptions } from '@h-ai/ai' * async function finish(manager: ContextManager, options: ConsolidateOptions) { * const result = await manager.consolidate(options) * if (!result.success) throw new Error(result.error.message) * return result.data.memories * } * ``` */ interface ConsolidateOptions { /** * 长期记忆作用域。 * * 默认使用管理器 `memory.scope`。通常应传入**不含 sessionId** 的作用域 * (如 `{ userId, personaId }`),使固化后的记忆跨会话持久,而非绑定单次会话。 */ scope?: Record; /** 固化提取的记忆类型限制 */ types?: MemoryType[]; /** 摘要 / 提取使用的模型 */ model?: string; /** 固化提取的自定义 systemPrompt */ extractionSystemPrompt?: string; } /** * 会话固化结果 * * @example * ```ts * import type { ConsolidateResult } from '@h-ai/ai' * const value: ConsolidateResult = { summary: '用户偏好中文', memories: [] } * const summary = value.summary.trim() * ``` */ interface ConsolidateResult { /** 本次会话的整合摘要 */ summary: string; /** 固化到长期记忆的条目 */ memories: MemoryEntry[]; } /** * 对话轮次状态 * * 描述一次 assistant 生成从「模型产出」到「真实进入对话」的生命周期: * - `generating` — 模型正在/已生成,但尚未确定实际对外表达的内容 * - `speaking` — 已进入下游表达(如 TTS 合成 / 播放) * - `completed` — 已提交,完整生成文本即为真实文本 * - `interrupted` — 被打断,仅实际表达出去的部分(committed)进入对话 * * @example * ```ts * import type { ConversationTurnStatus } from '@h-ai/ai' * function mayCommit(status: ConversationTurnStatus): boolean { * return status === 'generating' || status === 'speaking' * } * ``` */ type ConversationTurnStatus = 'generating' | 'speaking' | 'completed' | 'interrupted'; /** * 对话轮次 * * 区分「模型生成的文本」与「真实进入对话的文本」,解决多智能体 / 语音访谈等场景中 * 「AI 说到一半被打断,下一轮所有参与者应看到真实发生了什么」的问题。 * * @example * ```ts * import type { ConversationTurn } from '@h-ai/ai' * const value: ConversationTurn = { id: 'turn-1', speaker: 'assistant', generated: '完整回复', committed: '完整', status: 'interrupted', createdAt: Date.now(), committedAt: Date.now() } * const displayedText = value.committed * ``` */ interface ConversationTurn { /** 轮次唯一标识 */ id: string; /** 发言者 */ speaker: 'user' | 'assistant'; /** 模型生成的完整文本 */ generated: string; /** 实际提交进入上下文的文本(`completed` 时通常等于 generated;`interrupted` 时为真实表达部分) */ committed: string; /** 轮次状态 */ status: ConversationTurnStatus; /** 创建时间(Unix 毫秒) */ createdAt: number; /** 提交时间(Unix 毫秒,未提交时为 undefined) */ committedAt?: number; } /** * 提交 / 打断轮次的输入 * * @example * ```ts * import type { ContextManager, CommitTurnInput } from '@h-ai/ai' * async function recordPlayback(manager: ContextManager, turnId: string) { * const input: CommitTurnInput = { text: '实际已经播放的片段' } * const result = await manager.interruptTurn(turnId, input) * if (!result.success) throw new Error(result.error.message) * } * ``` */ interface CommitTurnInput { /** * 实际进入对话的文本。 * * - `commitTurn` 不传时默认使用模型生成的完整文本(generated)。 * - `interruptTurn` 不传时默认视为「未表达任何内容」(空串,不写入上下文)。 */ text?: string; } /** * 有状态上下文管理器配置 * * 通过嵌套子对象直接引用各子模块的配置类型,避免字段重复声明。 * * @example * ```ts * import { ai, type ContextManagerOptions } from '@h-ai/ai' * // 应用启动已成功初始化 ai;身份来自可信认证会话。 * const options: ContextManagerOptions = { scope: { objectId: 'user-1', sessionId: 'session-1' }, turnCommit: 'manual', concurrency: 'reject' } * const result = ai.context.createManager(options) * if (!result.success) throw new Error(result.error.message) * ``` */ interface ContextManagerOptions { /** 必填交互作用域(objectId + sessionId);所有节点共享同一生成与提交屏障。 */ scope: InteractionScope; /** 系统提示词(创建时作为首条 system 消息追加) */ systemPrompt?: string; /** LLM 模型名覆盖 */ model?: string; /** 温度覆盖 */ temperature?: number; /** * 对话提交模式(默认 `auto`) * * - `auto`:`chat` / `chatStream` 生成结束后,自动把**模型生成的完整文本**写入上下文并触发记忆提取。 * - `manual`:生成结束后**不写入**上下文,仅登记一个待提交轮次并返回 `turnId`;由调用方在确定 * 「实际发生了什么」后,通过 `commitTurn` / `interruptTurn` 写入**真实文本**。 * * 用于「模型生成 → TTS 合成 → 实际播放」链路:AI 说到一半被打断时,只有真正播放出去的 * 部分才应进入下一轮所有参与者可见的对话状态,而不是模型本想说完的全文。 */ turnCommit?: 'auto' | 'manual'; /** * 并发生成策略(默认 `reject`) * * ContextManager 默认实行**单活动生成**:同一 scope 的所有管理器/节点同一时刻只允许一个未完成的 * `chat` / `chatStream` 轮次,避免「上一轮 AI 尚未退出,下一轮 user 消息先写入」 * 导致的消息乱序(user1 → user2 → assistant1)。 * * - `reject`:已有活动生成时,新的 `chat` / `chatStream` 立即返回 `CONTEXT_BUSY` 错误。 * - `queue`:新请求可取消地轮询(不承诺 FIFO),等待前一轮次进入终态(`completed` / `interrupted`)后再开始。 * * `manual` 提交模式下,屏障持续到 `commitTurn` / `interruptTurn` 提交真实文本为止, * 因此「打断当前轮次 → 立即发起下一轮」也能保证顺序正确。 */ concurrency?: 'reject' | 'queue'; /** * 压缩配置(覆盖全局 compress 配置) * * 直接引用 CompressOptions,加上 auto 开关。 */ compress?: CompressOptions & { /** 是否自动触发压缩(默认 true) */ auto?: boolean; }; /** * 记忆配置 * * 控制记忆注入与提取。`scope` / `types` / `minImportance` 会完整透传给 Memory 的 * `injectMemories` 与 `extract`,用于表达「用户 + 主题 + 角色」等多维隔离 * (如 `{ userId, topicId, personaId }`)。 */ memory?: { /** 是否启用记忆注入(默认 false) */ enable?: boolean; /** 是否启用自动记忆提取(默认 false) */ enableExtract?: boolean; /** 业务作用域(透传给 injectMemories / extract,key-value 匹配隔离) */ scope?: Record; /** 注入 / 提取时限定的记忆类型 */ types?: MemoryType[]; /** 注入时的最低重要性阈值 */ minImportance?: number; /** 注入的记忆数量 */ topK?: number; /** 注入记忆占用的最大 token 预算 */ maxTokens?: number; /** 注入位置:system 追加或最后一条用户消息前插入 */ position?: 'system' | 'before-last'; /** 记忆提取使用的模型(覆盖默认提取模型) */ extractionModel?: string; /** 记忆提取的自定义 systemPrompt */ extractionSystemPrompt?: string; }; /** * RAG 配置 * * 引用 RagOptions 中检索相关的字段。 */ rag?: Pick & { /** 是否启用 RAG 检索增强(默认 false) */ enable?: boolean; }; /** * 推理配置 * * 引用 ReasoningOptions 中策略相关的字段。 */ reasoning?: Pick & { /** 是否启用推理引擎替代普通 LLM(默认 false) */ enable?: boolean; }; /** 工具注册表(传入后 chat/chatStream 支持 function calling) */ tools?: ToolRegistryOperations; /** * 工具调用最大轮次(默认 10) * * 当 LLM 返回 tool_calls 时,自动执行工具并将结果回传 LLM, * 重复此过程直到 LLM 给出文本回复或达到最大轮次。 */ maxToolRounds?: number; } /** * 重置管理器选项(`ContextManager.reset` 使用) * * @example * ```ts * import type { ContextManager, ContextResetOptions } from '@h-ai/ai' * async function run(manager: ContextManager) { * const options: ContextResetOptions = { preserveSystemPrompt: true, waitForMemoryTasks: true } * const result = await manager.reset(options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface ContextResetOptions { /** * 是否保留系统提示词(默认 `true`) * * 系统提示词(Persona / System Prompt)只在创建时追加一次;重置若不保留, * 会连同对话历史一起清空。默认重新写入系统提示词,避免 Persona 语义丢失。 */ preserveSystemPrompt?: boolean; /** * 是否终止活动轮次(默认 `true`) * * 为 `true` 时:中断内部生成信号,使所有非终态轮次进入 `interrupted` 终态, * 释放并发屏障,并阻止这些旧轮次在重置后被再次 `commitTurn` / `interruptTurn`。 */ cancelActiveTurn?: boolean; /** * 是否等待后台记忆提取任务完成后再清空(默认 `false`) * * 为 `true` 时先 `flush()`,失败即返回且不清空上下文;否则不等待。 * 已在途提取仍可能写入外部记忆,异常/失败仍由之后的 flush 报告,不自动重放。 */ waitForMemoryTasks?: boolean; } /** * 单次 chat/chatStream 请求的覆盖选项 * * @example * ```ts * import type { ContextManager, ContextChatOptions } from '@h-ai/ai' * async function run(manager: ContextManager) { * const options: ContextChatOptions = { signal: new AbortController().signal } * const result = await manager.chat('你好', options) * if (!result.success) throw new Error(result.error.message) * return result.data * } * ``` */ interface ContextChatOptions { /** LLM 模型名覆盖 */ model?: string; /** 温度覆盖 */ temperature?: number; /** 是否启用本次 LLM 调用的持久化(默认 false,Context 自行管理状态) */ enablePersist?: boolean; /** * 请求取消信号 * * 透传给底层 LLM 调用;打断、用户切换等场景可 `abortController.abort()` * 立即停止上游生成与计费。 */ signal?: AbortSignal; } /** * chat() 返回的结果 * * @example * ```ts * import type { ContextChatResult } from '@h-ai/ai' * const value: ContextChatResult = { reply: '你好', model: 'configured-model', turnId: 'turn-1' } * const pendingTurnId = value.turnId * ``` */ interface ContextChatResult { /** LLM 回复内容 */ reply: string; /** 使用的模型 */ model: string; /** * 本次生成对应的对话轮次 ID * * `turnCommit: 'manual'` 时,用于后续 `commitTurn` / `interruptTurn` 提交真实文本; * `auto` 模式下该轮已自动提交(`completed`)。 */ turnId: string; /** Token 使用统计 */ usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; } /** * chatStream() 产出的事件 * * 事件序列:`turn_started` → `delta`* → `done`;中途取消(AbortSignal)时为 * `turn_started` → `delta`* → `cancelled`。`cancelled` 保留 turnId 与已生成文本, * 调用方可用真实内容调用 `commitTurn` / `interruptTurn` 提交。 * * @example * ```ts * import type { ContextStreamEvent } from '@h-ai/ai' * function render(event: ContextStreamEvent): string { * if (event.type === 'delta') return event.text * if (event.type === 'cancelled') return event.generated * return '' * } * ``` */ type ContextStreamEvent = { type: 'turn_started'; turnId: string; } | { type: 'delta'; text: string; } | { type: 'tool_call'; name: string; arguments: string; } | { type: 'tool_result'; name: string; content: string; success: boolean; } | { type: 'done'; reply: string; model: string; turnId: string; usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; } | { type: 'cancelled'; turnId: string; generated: string; }; /** * 有状态上下文管理器接口 * * 适用于多轮对话场景。追加消息并在超限时自动压缩; * 若传入 deps.llm 则可直接通过 chat/chatStream 进行对话编排。 * * @example * ```ts * import { ai } from '@h-ai/ai' * // 应用启动已成功初始化 ai;手动提交只记录实际表达的文本。 * const created = ai.context.createManager({ scope: { objectId: 'user-1', sessionId: 'session-1' }, turnCommit: 'manual' }) * if (!created.success) throw new Error(created.error.message) * const generated = await created.data.chat('你好') * if (!generated.success) throw new Error(generated.error.message) * const committed = await created.data.commitTurn(generated.data.turnId, { text: generated.data.reply }) * if (!committed.success) throw new Error(committed.error.message) * const flushed = await created.data.flush() * if (!flushed.success) throw new Error(flushed.error.message) * ``` */ interface ContextManager { /** 当前必填作用域的独立副本。 */ readonly scope: InteractionScope; /** * 追加消息 * * 自动在超限时触发压缩(如果启用了 compress.auto)。 * * 活动生成或 pending 期间拒绝追加;先提交真实轮次或 reset。 * @param message - 要追加的消息 * @returns 成功返回 ok(undefined) */ addMessage: (message: ChatMessage) => Promise>; /** * 获取当前消息列表(压缩后) * * @returns 当前消息列表 */ getMessages: () => HaiResult; /** * 重新读取共享快照。同步 getters 仅返回本管理器最近一次成功读写的副本。 */ reload: () => Promise>; /** * 获取当前 token 使用量 * * @returns 当前 token 数和预算 */ getTokenUsage: () => HaiResult<{ current: number; budget: number; }>; /** * 获取历史摘要列表 * * @returns 每次压缩产生的摘要 */ getSummaries: () => HaiResult; /** * 刷新共享快照并同步会话目录;所有消息与轮次变更已经即时 CAS 持久化。 * * 内部会先 `flush()` 等待本节点后台记忆任务;不承诺外部记忆与消息跨系统原子提交。 */ save: () => Promise>; /** * 等待所有后台记忆提取任务完成 * * chat/chatStream 的自动记忆提取是「即发即忘」的后台任务;在开始下一轮召回、 * 生成总结或关闭前调用 `flush()`,可避免「上一轮记忆尚未写完」的时序问题(issue #14)。 * * 同轮并发调用共享结果;异常或失败 HaiResult 均返回 MEMORY_EXTRACT_FAILED(含失败数量)。 * 返回即确认本批报告,后续 flush 只观察新任务;不会自动重放可能已部分执行的副作用。 * 只等待当前管理器所在节点的任务,不是分布式队列或跨系统事务。 * * @returns 本批全部成功返回 ok(undefined);失败须由调用方核对实际记忆状态。 */ flush: () => Promise>; /** * 当前挂起的后台记忆提取任务数量 * * 供应用侧观测;为 0 只表示没有在途任务,历史失败仍需通过 flush() 观察。 */ readonly pendingMemoryTasks: number; /** * 重置管理器 * * 默认行为:终止活动轮次(进入终态并释放并发屏障)、清空消息 / 摘要 / 轮次 / * 待提交轮次,并重新写入系统提示词。可通过选项调整。 * * @param options - 重置选项(保留系统提示词 / 终止活动轮次 / 等待记忆任务) * @returns 成功返回 ok(undefined) */ reset: (options?: ContextResetOptions) => Promise>; /** * 获取对话轮次列表(Conversation Commit Layer) * * 记录每次 chat/chatStream 生成的轮次及其 `generated` / `committed` / `status`, * 供应用侧观测「模型生成」与「真实进入对话」的差异。 * * @returns 轮次列表(按发生顺序) */ getTurns: () => HaiResult; /** * 标记某轮次进入「表达中」(如 TTS 开始播放) * * 仅更新状态用于观测,不改变上下文内容。 * * @param turnId - 轮次 ID * @returns 成功返回 ok(undefined);轮次不存在返回 CONTEXT_TURN_NOT_FOUND */ markTurnSpeaking: (turnId: string) => Promise>; /** * 提交轮次(`turnCommit: 'manual'` 场景) * * 把真实文本写入上下文并触发记忆提取;`text` 缺省时使用模型生成的完整文本。 * 提交后该轮 `status` 变为 `completed`,可由任意节点按同一 turnId 提交。 * * @param turnId - 轮次 ID * @param input - 提交内容(可覆盖为真实表达文本) * @returns 相同终态与文本重复提交仍成功;不存在、过期或内容冲突返回错误 */ commitTurn: (turnId: string, input?: CommitTurnInput) => Promise>; /** * 打断轮次(`turnCommit: 'manual'` 场景) * * 只把「实际表达出去的部分」写入上下文;`text` 缺省时视为未表达任何内容(不写入)。 * 打断后该轮 `status` 变为 `interrupted`。 * * @param turnId - 轮次 ID * @param input - 实际表达出去的文本 * @returns 相同终态与文本重复提交仍成功;不存在、过期或内容冲突返回错误 */ interruptTurn: (turnId: string, input?: CommitTurnInput) => Promise>; /** * 将当前会话固化为长期记忆(Memory 生命周期) * * 流程:整合会话摘要(历史摘要 + 当前消息)→ 从摘要中提取长期记忆 → 以持久作用域写入。 * 需要 deps.summary + deps.memory 可用。用于会话结束时把「短期会话记忆」沉淀为 * 「跨会话长期记忆」,形成 Session → Summary → Long-term Memory 闭环。 * * @param options - 固化选项(长期作用域、类型、模型等) * @returns 会话摘要与固化的记忆条目 */ consolidate: (options?: ConsolidateOptions) => Promise>; /** * 发送消息并获取回复(需 deps.llm 可用) * * 流程:追加用户消息 → 自动压缩 → 注入记忆(可选) → RAG(可选) → LLM/Reasoning → 追加助手消息 → 提取记忆(可选) * * @param message - 用户消息文本 * @param options - 单次请求覆盖选项 * @returns 对话结果 */ chat: (message: string, options?: ContextChatOptions) => Promise>; /** * 流式发送消息并获取回复(需 deps.llm 可用) * * 产出事件序列:turn_started → delta* → done(中途取消时 → cancelled) * * @param message - 用户消息文本 * @param options - 单次请求覆盖选项 * @returns 异步可迭代的 ContextStreamEvent */ chatStream: (message: string, options?: ContextChatOptions) => AsyncIterable; } /** * Context 操作接口(通过 `ai.context` 访问) * * 提供有状态的 ContextManager,管理多轮对话的消息追加、自动压缩与对话编排。 * 原子操作(token / summary / compress)已独立暴露在 `ai.token`、`ai.summary`、`ai.compress`。 * 需要先调用 `ai.init()` 初始化后使用。 * * @example * ```ts * import { ai, type ContextOperations } from '@h-ai/ai' * // 应用启动已成功初始化 ai;跨节点读取使用 restore/reload。 * const operations: ContextOperations = ai.context * const restored = await operations.restoreManager({ objectId: 'user-1', sessionId: 'session-1' }) * if (!restored.success) throw new Error(restored.error.message) * const messages = restored.data.getMessages() * if (!messages.success) throw new Error(messages.error.message) * const count = messages.data.length * ``` */ interface ContextOperations { /** * 创建有状态上下文管理器 * * @param options - 管理器配置 * @returns 管理器实例 */ createManager: (options: ContextManagerOptions) => HaiResult; /** * 从持久化恢复上下文管理器 * * @param scope - 交互作用域 * @param options - 管理器配置覆盖 * @returns 恢复的管理器实例 */ restoreManager: (scope: InteractionScope, options?: Omit) => Promise>; /** * 列出指定主体的所有会话 * * @param objectId - 主体 ID * @returns 会话信息列表 */ listSessions: (objectId: string) => Promise>; /** * 重命名会话 * * @param scope - 交互作用域(objectId + sessionId,用于多租户隔离) * @param title - 新标题 * @returns 成功返回 ok(undefined) */ renameSession: (scope: InteractionScope, title: string) => Promise>; /** * 删除正文并保留永久墓碑;同一 scope 不再复用,迟到节点不能重建。 * * @param scope - 交互作用域(objectId + sessionId,用于多租户隔离) * @returns 成功返回 ok(undefined) */ removeSession: (scope: InteractionScope) => Promise>; } /** * @h-ai/ai — Embedding 子功能类型 * * 定义向量嵌入操作的类型接口。 * @module ai-embedding-types */ /** * Embedding 请求参数 * * @example * ```ts * import type { EmbeddingRequest } from '@h-ai/ai' * * const value: EmbeddingRequest = { input: ['退款申请', '退款进度'], dimensions: 1024 } * ``` */ interface EmbeddingRequest { /** 输入文本(单条或批量) */ input: string | string[]; /** 模型名称(可选,未指定时使用配置中的默认模型) */ model?: string; /** 向量维度(可选,部分模型支持) */ dimensions?: number; } /** * 单条 Embedding 结果 * * @example * ```ts * import type { EmbeddingItem } from '@h-ai/ai' * * const value: EmbeddingItem = { index: 0, embedding: [0.12, -0.08, 0.31] } * ``` */ interface EmbeddingItem { /** 在输入列表中的索引 */ index: number; /** 向量数据 */ embedding: number[]; } /** * Embedding 响应 * * @example * ```ts * import type { EmbeddingResponse } from '@h-ai/ai' * * function firstVector(response: EmbeddingResponse): number[] | undefined { * return response.data.find(item => item.index === 0)?.embedding * } * ``` */ interface EmbeddingResponse { /** 模型名称 */ model: string; /** Embedding 结果列表 */ data: EmbeddingItem[]; /** Token 使用统计 */ usage: { prompt_tokens: number; total_tokens: number; }; } /** * Embedding 操作接口(通过 `ai.embedding` 访问) * * 需要先调用 `ai.init()` 初始化后使用。 * * @example * ```ts * import { ai } from '@h-ai/ai' * * // 应用启动已成功初始化 ai;这里是业务服务函数。 * async function run() { * const result = await ai.embedding.embed({ input: ['退款申请', '退款进度'] }) * if (!result.success) * return result * return result.data.data.map(item => item.embedding) * } * ``` */ interface EmbeddingOperations { /** * 生成向量嵌入 * * @param request - Embedding 请求 * @returns Embedding 响应 */ embed: (request: EmbeddingRequest) => Promise>; /** * 便捷方法:嵌入单条文本,直接返回向量 * * @param text - 输入文本 * @returns 向量数组 */ embedText: (text: string) => Promise>; /** * 便捷方法:批量嵌入文本,返回向量列表 * * @param texts - 输入文本列表 * @returns 向量数组列表(与输入顺序一致) */ embedBatch: (texts: string[]) => Promise>; } /** * @h-ai/ai — Persona 子功能类型 * * 定义「AI 角色人格」的持久化与组合接口。Persona 解决的是「AI 是谁」的问题: * 多智能体场景(如多位专家同台访谈)中,每个 AI 有稳定的系统提示词、性格特征与 * 长期人格。它与 Memory 正交——Memory 用 `objectId` / `scope` 回答「谁的记忆」, * Persona 回答「这个 AI 的身份与人设」,二者通过 `scope: { personaId }` 关联。 * @module ai-persona-types */ /** * Persona 档案输入(创建 / 覆盖保存时使用) * * @example * ```ts * import type { PersonaProfileInput } from '@h-ai/ai' * * const value: PersonaProfileInput = { id: 'support', objectId: 'tenant-1', name: '客服助手', systemPrompt: '根据已验证的订单信息回答。', traits: ['简洁', '先核对证据'] } * ``` */ interface PersonaProfileInput { /** 角色唯一标识(业务侧稳定 ID,如 `xiaop`) */ id: string; /** * 所属主体 ID(多租户隔离) * * 不同主体可创建同名角色而互不覆盖;不传时归为平台内置角色 `system`。 */ objectId?: string; /** 角色显示名(如「小P」) */ name?: string; /** 角色系统提示词(定义身份、职责、语气) */ systemPrompt: string; /** 性格 / 风格特征(组合进系统提示词,如「谨慎」「喜欢引用案例」) */ traits?: string[]; /** 附加元数据 */ metadata?: Record; } /** * 完整的 Persona 档案 * * @example * ```ts * import type { PersonaProfile } from '@h-ai/ai' * * function label(profile: PersonaProfile): string { * return `${profile.objectId}/${profile.id}: ${profile.name ?? profile.id}` * } * ``` */ interface PersonaProfile { /** 角色唯一标识 */ id: string; /** 所属主体 ID(多租户隔离;平台内置角色为 `system`) */ objectId: string; /** 角色显示名 */ name?: string; /** 角色系统提示词 */ systemPrompt: string; /** 性格 / 风格特征 */ traits: string[]; /** 附加元数据 */ metadata?: Record; /** 创建时间(Unix 毫秒) */ createdAt: number; /** 更新时间(Unix 毫秒) */ updatedAt: number; } /** * Persona 档案更新输入 * * 所有字段可选,仅更新传入的字段。 * * @example * ```ts * import type { PersonaProfileUpdate } from '@h-ai/ai' * * const value: PersonaProfileUpdate = { traits: ['简洁', '引用来源'] } * ``` */ interface PersonaProfileUpdate { /** 更新显示名 */ name?: string; /** 更新系统提示词 */ systemPrompt?: string; /** 更新特征列表(整体替换) */ traits?: string[]; /** 更新元数据 */ metadata?: Record; } /** * Persona 操作接口(通过 `ai.persona` 访问) * * 管理 AI 角色人格的持久化与系统提示词组合。需要先调用 `ai.init()` 初始化后使用。 * * @example * ```ts * import { ai } from '@h-ai/ai' * * // 应用启动已成功初始化 ai;这里是业务服务函数。 * async function run() { * const result = await ai.persona.save({ id: 'support', objectId: 'tenant-1', systemPrompt: '先核对订单状态再回答。' }) * if (!result.success) * return result * const composed = await ai.persona.compose(result.data.id, { objectId: result.data.objectId }) * if (!composed.success) * return composed * return composed.data * } * ``` */ interface PersonaOperations { /** * 创建或覆盖保存一个角色档案(upsert 语义) * * @param profile - 角色档案输入 * @returns 保存后的完整档案 */ save: (profile: PersonaProfileInput) => Promise>; /** * 按 ID 获取角色档案 * * @param id - 角色 ID * @returns 角色档案,不存在时返回 PERSONA_NOT_FOUND */ get: (id: string, options?: PersonaScopeOptions) => Promise>; /** * 更新角色档案(仅更新传入字段) * * @param id - 角色 ID * @param updates - 需要更新的字段 * @param options - 主体作用域(默认 `system`) * @returns 更新后的完整档案 */ update: (id: string, updates: PersonaProfileUpdate, options?: PersonaScopeOptions) => Promise>; /** * 删除角色档案 * * @param id - 角色 ID * @param options - 主体作用域(默认 `system`) * @returns 成功返回 ok(undefined) */ remove: (id: string, options?: PersonaScopeOptions) => Promise>; /** * 列出指定主体的角色档案 * * @param options - 主体作用域(默认 `system`) * @returns 角色档案列表 */ list: (options?: PersonaScopeOptions) => Promise>; /** * 组合角色的完整系统提示词 * * 将 `systemPrompt` 与 `traits` 拼装为一段可直接作为 system 消息的文本, * 供 `ai.context.createManager({ scope, systemPrompt })` 使用。 * * @param id - 角色 ID * @param options - 主体作用域(默认 `system`) * @returns 组合后的系统提示词,角色不存在时返回 PERSONA_NOT_FOUND */ compose: (id: string, options?: PersonaScopeOptions) => Promise>; } /** * Persona 操作的主体作用域选项 * * @example * ```ts * import type { PersonaScopeOptions } from '@h-ai/ai' * * const value: PersonaScopeOptions = { objectId: 'tenant-1' } * ``` */ interface PersonaScopeOptions { /** 所属主体 ID(不传时归为平台内置角色 `system`) */ objectId?: string; } /** * @h-ai/ai — 文生图公共类型 * * 公共契约只暴露业务需要的提示词、尺寸和标准化图片字节。 * 厂商请求字段、临时 URL 与响应中间态由 Provider 内部处理。 * @module image/ai-image-types */ /** * 图片像素尺寸 * * @example * ```ts * import type { ImageSize } from '@h-ai/ai' * * const value: ImageSize = { width: 1024, height: 1024 } * ``` */ interface ImageSize { /** 宽度(像素) */ width: number; /** 高度(像素) */ height: number; } /** * 可选参考图;Provider 会转换为对应厂商的传输格式 * * @example * ```ts * import type { ReferenceImage } from '@h-ai/ai' * import { readFile } from 'node:fs/promises' * * const reference: ReferenceImage = { data: await readFile('reference.png'), mimeType: 'image/png' } * ``` */ interface ReferenceImage { /** 图片二进制内容 */ data: Uint8Array; /** 图片 MIME 类型,例如 `image/png`、`image/jpeg` */ mimeType: string; } /** * 文生图请求 * * @example * ```ts * import type { GenerateImageRequest } from '@h-ai/ai' * * const value: GenerateImageRequest = { prompt: '水墨山水,留白构图', size: { width: 1024, height: 1024 }, signal: new AbortController().signal } * ``` */ interface GenerateImageRequest { /** 图片内容与风格提示词 */ prompt: string; /** 模型 ID;不传时使用配置中的默认文生图模型 */ model?: string; /** 输出像素尺寸;不传时由模型决定 */ size?: ImageSize; /** 用于图生图、编辑或风格参考的一张或多张图片 */ referenceImages?: ReferenceImage[]; /** 取消整个厂商请求和图片下载;模型 timeout 同时限制总耗时。 */ signal?: AbortSignal; } /** * 标准化后的单张图片 * * @example * ```ts * import type { GeneratedImage } from '@h-ai/ai' * * function imageBlob(image: GeneratedImage): Blob { * return new Blob([Uint8Array.from(image.data)], { type: image.mimeType }) * } * ``` */ interface GeneratedImage { /** 图片二进制内容 */ data: Uint8Array; /** 经魔数核验的栅格图片 MIME:PNG、JPEG、GIF、WebP。 */ mimeType: string; /** 宽度提示,来自请求或厂商;未通过完整图片解码核验。 */ width?: number; /** 高度提示,来自请求或厂商;未通过完整图片解码核验。 */ height?: number; } /** * 文生图结果 * * @example * ```ts * import type { GenerateImageResult } from '@h-ai/ai' * * function imageCount(result: GenerateImageResult): number { * return result.images.length * } * ``` */ interface GenerateImageResult { /** 厂商实际返回的图片;通常为一张 */ images: GeneratedImage[]; } /** * 文生图操作接口(通过 `ai.image` 访问) * * @example * ```ts * import { ai } from '@h-ai/ai' * * // 应用启动已成功初始化 ai;这里是业务服务函数。 * async function run() { * const result = await ai.image.generate({ prompt: '水墨山水,留白构图' }) * if (!result.success) * return result * return result.data.images[0] * } * ``` */ interface ImageOperations { /** * 根据文本提示生成有界的图片字节;先判断 success,下载/超限/超时错误不返回部分结果。 */ generate: (request: GenerateImageRequest) => Promise>; } /** * 清单项与来源;配置来源不可修改,version 仅用于数据库乐观并发更新。 * @example * ```ts * import type { AIResourceEntry, ModelEntry } from '@h-ai/ai' * function editable(entry: AIResourceEntry) { return entry.source === 'database' } * ``` */ interface AIResourceEntry { /** 原始配置;返回独立副本,修改副本不会修改清单。 */ value: T; /** config 来自初始化配置,database 来自 AIStoreProvider。 */ source: 'config' | 'database'; /** get 返回的数据库版本;更新/删除时可传回以拒绝过期写入。 */ version?: string; } /** * 配置与数据库合并的资源清单。相同 ID 配置优先,配置记录永不写回数据库。 * @example * ```ts * import { ai } from '@h-ai/ai' * async function listModels() { const result = await ai.llm.models.list(); if (!result.success) return result; return result.data.map(item => ({ id: item.value.id, source: item.source })) } * ``` */ interface AIResourceRegistry { /** * 读取合并清单;保留配置顺序,追加未被遮蔽的数据库项。 * @returns 包含 value/source 的去重列表;列表项无数据库版本。 * @example * ```ts * import { ai } from '@h-ai/ai' * const result = await ai.llm.models.list() * if (result.success) { const entries = result.data } * ``` */ list: () => Promise[]>>; /** * 按 ID 读取来源、配置和数据库版本。 * @param id - 资源 ID。 * @returns 包含 value/source/version 的资源条目,未找到时返回失败。 * @example * ```ts * import { ai } from '@h-ai/ai' * const result = await ai.llm.models.get('coding') * if (result.success) { const source = result.data.source } * ``` */ get: (id: string) => Promise>>; /** * 新建数据库记录;ID 已存在或属于配置时拒绝。 * @param input - 完整资源配置。 * @returns 新建条目及版本的 HaiResult,配置同 ID 返回只读错误。 * @example * ```ts * import { ai } from '@h-ai/ai' * const result = await ai.llm.models.register({ id: 'coding', model: 'example-model', protocol: 'responses' }) * if (!result.success) { const code = result.error.code } * ``` */ register: (input: Input) => Promise>>; /** * 完整替换数据库记录;配置来源只读。版本不匹配时不写入。 * @param input - 同 ID 的完整新配置。 * @param expectedVersion - 可选的 get 版本。 * @returns 替换后的条目及版本;过期版本返回资源冲突。 * @example * ```ts * import { ai } from '@h-ai/ai' * const current = await ai.llm.models.get('coding') * if (current.success && current.data.source === 'database') { * const result = await ai.llm.models.update({ ...current.data.value, temperature: 0.2 }, current.data.version) * if (!result.success) { const code = result.error.code } * } * ``` */ update: (input: Input, expectedVersion?: string) => Promise>>; /** * 删除数据库记录,采用 CAS 墓碑避免与并发更新相互覆盖;不删除外部文件。 * @param id - 资源 ID。 * @param expectedVersion - 可选的 get 版本。 * @returns 删除完成的 HaiResult;配置只读、版本冲突或记录不存在时失败。 * @example * ```ts * import { ai } from '@h-ai/ai' * const result = await ai.llm.models.remove('temporary') * if (!result.success) { const code = result.error.code } * ``` */ remove: (id: string, expectedVersion?: string) => Promise>; } /** * 包含配置/数据库资源维护的 llm 操作接口。 * @example * ```ts * import { ai } from '@h-ai/ai' * const result = await ai.llm.models.list() * if (result.success) { const resources = result.data } * ``` */ interface ManagedLLMOperations extends LLMOperations { /** 配置只读、数据库可维护的合并清单。 */ models: AIResourceRegistry, z.input>; } /** * 包含配置/数据库资源维护的 audio 操作接口。 * @example * ```ts * import { ai } from '@h-ai/ai' * const result = await ai.audio.models.list() * if (result.success) { const resources = result.data } * ``` */ interface ManagedAudioOperations extends AudioOperations { /** 配置只读、数据库可维护的合并清单。 */ models: AIResourceRegistry, z.input>; } /** * 包含配置/数据库资源维护的 image 操作接口。 * @example * ```ts * import { ai } from '@h-ai/ai' * const result = await ai.image.models.list() * if (result.success) { const resources = result.data } * ``` */ interface ManagedImageOperations extends ImageOperations { /** 配置只读、数据库可维护的合并清单。 */ models: AIResourceRegistry, z.input>; } /** * 包含配置/数据库资源维护的 mcp 操作接口。 * @example * ```ts * import { ai } from '@h-ai/ai' * const result = await ai.mcp.servers.list() * if (result.success) { const resources = result.data } * ``` */ interface ManagedMCPOperations extends MCPOperations { /** 按业务身份调用合并清单中已显式开放的工具。 */ services: MCPServiceOperations; /** 配置只读、数据库可维护的合并清单。 */ servers: AIResourceRegistry, z.input>; } /** * 包含配置/数据库资源维护的 retrieval 操作接口。 * @example * ```ts * import { ai } from '@h-ai/ai' * const result = await ai.retrieval.sources.list() * if (result.success) { const resources = result.data } * ``` */ interface ManagedRetrievalOperations extends RetrievalOperations { /** 配置只读、数据库可维护的合并清单。 */ sources: AIResourceRegistry, z.input>; } /** * @h-ai/ai — Rerank 子功能类型 * * 定义文档重排序操作的类型接口。 * @module ai-rerank-types */ /** * 单条待排序文档 * * @example * ```ts * import type { RerankDocument } from '@h-ai/ai' * * const value: RerankDocument = { id: 'refund-policy', text: '订单完成后七天内可申请退款。' } * ``` */ interface RerankDocument { /** 文档唯一标识(可选,便于结果追踪) */ id?: string; /** 文档文本内容 */ text: string; } /** * Rerank 请求参数 * * @example * ```ts * import type { RerankRequest } from '@h-ai/ai' * * const value: RerankRequest = { query: '如何退款', documents: [{ id: 'refund-policy', text: '七天内申请退款。' }], topN: 1, returnDocuments: true } * ``` */ interface RerankRequest { /** 查询文本 */ query: string; /** 待排序文档列表(字符串数组或带 id 的文档对象数组) */ documents: string[] | RerankDocument[]; /** 模型名称(可选,未指定时使用配置中的默认模型) */ model?: string; /** 返回结果数量(可选,默认返回全部文档) */ topN?: number; /** 是否在结果中返回文档原文(默认 false) */ returnDocuments?: boolean; } /** * 单条 Rerank 结果 * * @example * ```ts * import type { RerankItem } from '@h-ai/ai' * * const value: RerankItem = { index: 0, id: 'refund-policy', relevanceScore: 0.92, document: '七天内申请退款。' } * ``` */ interface RerankItem { /** 文档在原始输入中的索引 */ index: number; /** 文档 ID(当输入为带 id 的文档对象时) */ id?: string; /** 相关性分数(越高越相关) */ relevanceScore: number; /** 文档原文(当 returnDocuments 为 true 时) */ document?: string; } /** * Rerank 响应 * * @example * ```ts * import type { RerankResponse } from '@h-ai/ai' * * function winningDocument(response: RerankResponse) { * return response.results[0]?.document * } * ``` */ interface RerankResponse { /** 使用的模型名称 */ model: string; /** 重排序结果列表(按相关性分数降序排列) */ results: RerankItem[]; } /** * Rerank 操作接口(通过 `ai.rerank` 访问) * * 需要先调用 `ai.init()` 初始化后使用。 * 通过专用 Rerank API(兼容 Cohere 格式)对文档进行相关性重排序。 * * @example * ```ts * import { ai } from '@h-ai/ai' * * // 应用启动已成功初始化 ai;这里是业务服务函数。 * async function run() { * const result = await ai.rerank.rerank({ query: '如何退款', documents: ['七天内申请退款。', '支持信用卡付款。'], topN: 1 }) * if (!result.success) * return result * return result.data.results * } * ``` */ interface RerankOperations { /** * 对文档列表进行相关性重排序 * * @param request - Rerank 请求 * @returns 重排序响应,结果按相关性分数降序排列 */ rerank: (request: RerankRequest) => Promise>; /** * 便捷方法:对文本数组重排序,直接返回结果列表 * * @param query - 查询文本 * @param texts - 待排序文本列表 * @param topN - 返回条数(可选) * @returns RerankItem 列表,按相关性分数降序排列 */ rerankTexts: (query: string, texts: string[], topN?: number) => Promise>; } /** * @h-ai/ai — Token 子功能类型 * * 定义 Token 估算操作的类型接口:文本与消息级别的 Token 数估算。 * 使用 CJK 感知的字符级估算算法,无需外部分词库依赖。 * @module ai-token-types */ /** * Token 操作接口 * * 提供 Token 估算能力,使用配置的 `tokenRatio` 做估算。 * * @example * ```ts * import { ai } from '@h-ai/ai' * * // 应用已成功初始化 ai;消息估算包含协议字段与角色开销。 * const textTokens = ai.token.estimateText('Hello 世界') * const messageTokens = ai.token.estimateMessages([{ role: 'user', content: 'Hello 世界' }]) * ``` */ interface TokenOperations { /** * 估算单条文本的 Token 数 * * 使用字符级估算:中文约每字 1.5 token,英文约每 4 字符 1 token。 * * @param text - 文本内容 * @returns 估算 Token 数 */ estimateText: (text: string) => number; /** * 估算消息列表的总 Token 数 * * 包含消息结构开销(每条消息约 4 token 用于角色标记和分隔)。 * * @param messages - 消息列表 * @returns 估算 Token 总数 */ estimateMessages: (messages: ChatMessage[]) => number; } /** * AI 模块标准错误定义。通过错误码比较分支,用户文案由业务边界本地化。 * * @example * ```ts * import { HaiAIError } from '@h-ai/ai' * import { err } from '@h-ai/core' * const result = err(HaiAIError.NOT_INITIALIZED, 'AI is not initialized') * if (!result.success) { * const status = result.error.httpStatus * const code = result.error.code * } * ``` */ declare const HaiAIError: { readonly INTERNAL_ERROR: _h_ai_core.HaiErrorDef; readonly ACP_GIT_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly ACP_OPERATION_FAILED: _h_ai_core.HaiErrorDef; readonly ACP_INVALID_REQUEST: _h_ai_core.HaiErrorDef; readonly ACP_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly ACP_BUSY: _h_ai_core.HaiErrorDef; readonly ACP_UNSUPPORTED: _h_ai_core.HaiErrorDef; readonly ACP_CANCELLED: _h_ai_core.HaiErrorDef; readonly ACP_TIMEOUT: _h_ai_core.HaiErrorDef; readonly ACP_OUTPUT_INVALID: _h_ai_core.HaiErrorDef; readonly ACP_CONFLICT: _h_ai_core.HaiErrorDef; readonly ACP_PARTIAL_FAILURE: _h_ai_core.HaiErrorDef; readonly ACP_CLOSED: _h_ai_core.HaiErrorDef; readonly ACP_RUNTIME_UNAVAILABLE: _h_ai_core.HaiErrorDef; readonly ACP_MODEL_INCOMPATIBLE: _h_ai_core.HaiErrorDef; readonly ACP_CLEANUP_FAILED: _h_ai_core.HaiErrorDef; readonly NOT_INITIALIZED: _h_ai_core.HaiErrorDef; readonly CONFIGURATION_ERROR: _h_ai_core.HaiErrorDef; readonly INIT_IN_PROGRESS: _h_ai_core.HaiErrorDef; readonly RERANK_API_ERROR: _h_ai_core.HaiErrorDef; readonly RERANK_INVALID_REQUEST: _h_ai_core.HaiErrorDef; readonly API_ERROR: _h_ai_core.HaiErrorDef; readonly INVALID_REQUEST: _h_ai_core.HaiErrorDef; readonly RATE_LIMITED: _h_ai_core.HaiErrorDef; readonly TIMEOUT: _h_ai_core.HaiErrorDef; readonly MODEL_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly CONTEXT_LENGTH_EXCEEDED: _h_ai_core.HaiErrorDef; readonly LLM_RECORD_FAILED: _h_ai_core.HaiErrorDef; readonly LLM_HISTORY_FAILED: _h_ai_core.HaiErrorDef; readonly MCP_CONNECTION_ERROR: _h_ai_core.HaiErrorDef; readonly MCP_PROTOCOL_ERROR: _h_ai_core.HaiErrorDef; readonly MCP_TOOL_ERROR: _h_ai_core.HaiErrorDef; readonly MCP_RESOURCE_ERROR: _h_ai_core.HaiErrorDef; readonly MCP_SERVER_ERROR: _h_ai_core.HaiErrorDef; readonly MCP_TOOL_FORBIDDEN: _h_ai_core.HaiErrorDef; readonly MCP_TOOL_CANCELLED: _h_ai_core.HaiErrorDef; readonly EMBEDDING_API_ERROR: _h_ai_core.HaiErrorDef; readonly EMBEDDING_MODEL_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly EMBEDDING_INPUT_TOO_LONG: _h_ai_core.HaiErrorDef; readonly TOOL_PROTOCOL_ERROR: _h_ai_core.HaiErrorDef; readonly TOOL_RESULT_ERROR: _h_ai_core.HaiErrorDef; readonly REASONING_FAILED: _h_ai_core.HaiErrorDef; readonly REASONING_MAX_ROUNDS: _h_ai_core.HaiErrorDef; readonly REASONING_STRATEGY_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly RETRIEVAL_FAILED: _h_ai_core.HaiErrorDef; readonly RETRIEVAL_SOURCE_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly RAG_FAILED: _h_ai_core.HaiErrorDef; readonly RAG_CONTEXT_BUILD_FAILED: _h_ai_core.HaiErrorDef; readonly KNOWLEDGE_SETUP_FAILED: _h_ai_core.HaiErrorDef; readonly KNOWLEDGE_INGEST_FAILED: _h_ai_core.HaiErrorDef; readonly KNOWLEDGE_RETRIEVE_FAILED: _h_ai_core.HaiErrorDef; readonly KNOWLEDGE_ENTITY_EXTRACT_FAILED: _h_ai_core.HaiErrorDef; readonly KNOWLEDGE_NOT_SETUP: _h_ai_core.HaiErrorDef; readonly KNOWLEDGE_COLLECTION_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly MEMORY_EXTRACT_FAILED: _h_ai_core.HaiErrorDef; readonly MEMORY_STORE_FAILED: _h_ai_core.HaiErrorDef; readonly MEMORY_RECALL_FAILED: _h_ai_core.HaiErrorDef; readonly MEMORY_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly MEMORY_ENRICH_FAILED: _h_ai_core.HaiErrorDef; readonly MEMORY_PROMOTE_FAILED: _h_ai_core.HaiErrorDef; readonly MEMORY_LIST_INCOMPLETE: _h_ai_core.HaiErrorDef; readonly PERSONA_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly PERSONA_SAVE_FAILED: _h_ai_core.HaiErrorDef; readonly FILE_PARSE_FAILED: _h_ai_core.HaiErrorDef; readonly FILE_UNSUPPORTED_FORMAT: _h_ai_core.HaiErrorDef; readonly FILE_OCR_FAILED: _h_ai_core.HaiErrorDef; readonly FILE_INVALID_CONTENT: _h_ai_core.HaiErrorDef; readonly FILE_LOCAL_BUSY: _h_ai_core.HaiErrorDef; readonly FILE_LOCAL_CANCELLED: _h_ai_core.HaiErrorDef; readonly FILE_LOCAL_TIMEOUT: _h_ai_core.HaiErrorDef; readonly AUDIO_INVALID_REQUEST: _h_ai_core.HaiErrorDef; readonly AUDIO_MODEL_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly AUDIO_PROVIDER_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly AUDIO_UNSUPPORTED_INPUT: _h_ai_core.HaiErrorDef; readonly AUDIO_UPSTREAM_ERROR: _h_ai_core.HaiErrorDef; readonly AUDIO_PROTOCOL_ERROR: _h_ai_core.HaiErrorDef; readonly AUDIO_CONNECTION_FAILED: _h_ai_core.HaiErrorDef; readonly AUDIO_TIMEOUT: _h_ai_core.HaiErrorDef; readonly AUDIO_INPUT_TOO_LARGE: _h_ai_core.HaiErrorDef; readonly AUDIO_CANCELLED: _h_ai_core.HaiErrorDef; readonly IMAGE_INVALID_REQUEST: _h_ai_core.HaiErrorDef; readonly IMAGE_MODEL_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly IMAGE_PROVIDER_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly IMAGE_UPSTREAM_ERROR: _h_ai_core.HaiErrorDef; readonly IMAGE_PROTOCOL_ERROR: _h_ai_core.HaiErrorDef; readonly IMAGE_CANCELLED: _h_ai_core.HaiErrorDef; readonly IMAGE_DOWNLOAD_BLOCKED: _h_ai_core.HaiErrorDef; readonly IMAGE_TOO_LARGE: _h_ai_core.HaiErrorDef; readonly IMAGE_TIMEOUT: _h_ai_core.HaiErrorDef; readonly RESOURCE_READ_ONLY: _h_ai_core.HaiErrorDef; readonly RESOURCE_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly RESOURCE_CONFLICT: _h_ai_core.HaiErrorDef; readonly RESOURCE_INVALID: _h_ai_core.HaiErrorDef; readonly RESOURCE_OPERATION_FAILED: _h_ai_core.HaiErrorDef; readonly CONTEXT_COMPRESS_FAILED: _h_ai_core.HaiErrorDef; readonly CONTEXT_SUMMARIZE_FAILED: _h_ai_core.HaiErrorDef; readonly CONTEXT_TOKEN_ESTIMATE_FAILED: _h_ai_core.HaiErrorDef; readonly CONTEXT_BUDGET_EXCEEDED: _h_ai_core.HaiErrorDef; readonly CONTEXT_TURN_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly CONTEXT_TURN_INVALID_STATE: _h_ai_core.HaiErrorDef; readonly CONTEXT_BUSY: _h_ai_core.HaiErrorDef; readonly STORE_FAILED: _h_ai_core.HaiErrorDef; readonly STORE_NOT_AVAILABLE: _h_ai_core.HaiErrorDef; readonly SESSION_NOT_FOUND: _h_ai_core.HaiErrorDef; readonly SESSION_FAILED: _h_ai_core.HaiErrorDef; readonly A2A_NOT_CONFIGURED: _h_ai_core.HaiErrorDef; readonly A2A_HANDLE_FAILED: _h_ai_core.HaiErrorDef; readonly A2A_REMOTE_CALL_FAILED: _h_ai_core.HaiErrorDef; readonly A2A_AUTH_FAILED: _h_ai_core.HaiErrorDef; readonly A2A_LIST_MESSAGES_FAILED: _h_ai_core.HaiErrorDef; }; /** * AI 初始化运行时选项 * * 用于传入运行时对象(如自定义 StoreProvider), * 这些对象无法通过 Zod 配置 Schema 传递。 * * @example * ```ts * import { ai, type AIConfigInput, type AIInitOptions, type AIStoreProvider } from '@h-ai/ai' * async function start(config: AIConfigInput, storeProvider: AIStoreProvider) { * const options: AIInitOptions = { storeProvider } * const result = await ai.init(config, options) * if (!result.success) throw new Error(result.error.message) * } * ``` */ interface AIInitOptions { /** 由应用初始化和关闭的受管执行实例。 */ runner?: RunnerFunctions; /** 应用对受管 ACP 请求执行的可信授权。 */ acpPolicy?: ACPPlatformPolicy; /** 在作业领取者上验证文件权限、读入对象和暂存结果。 */ mcpJobFiles?: MCPJobFiles; /** 可信服务端扩展:为其他 ACP 智能体生成原生配置。 */ acpAdapters?: Record; /** * 自定义存储 Provider * * 提供后 AI 模块将使用此 Provider,而不采用自动选择的存储实现。 * 未提供时:reldb + vecdb 已初始化则使用持久化 DB Provider,否则使用进程内临时 Provider。 */ storeProvider?: AIStoreProvider; } /** * AI 服务接口(通过 `ai` 对象访问) * * 所有 AI 功能的统一入口,需先调用 `init()` 初始化后才能使用 `llm`、`mcp` 操作。 * `tools` 和 `stream` 为纯函数,无需初始化即可使用。 * * @example * ```ts * import { ai, type AIConfigInput, type AIInitOptions } from '@h-ai/ai' * // 一次性脚本示例;服务应用在启动阶段 init,在停止接入请求后 close。 * async function run(config: AIConfigInput, options: AIInitOptions) { * const ready = await ai.init(config, options) * if (!ready.success) throw new Error(ready.error.message) * try { * const answer = await ai.llm.ask('你好', { objectId: 'user-1' }) * if (!answer.success) throw new Error(answer.error.message) * return answer.data * } * finally { * await ai.close() * } * } * ``` */ interface AIFunctions { /** * 初始化 AI 服务 * * 使用 Zod Schema 校验配置,失败返回 `CONFIGURATION_ERROR`。 * 重复调用会先关闭旧实例再重新初始化。 * * @param config - AI 配置(可选,默认使用空对象并应用 Schema 默认值) * @param options - 运行时选项(可选,用于传入自定义 StoreProvider 等运行时对象) * @returns 成功返回 `ok(undefined)`;配置校验失败返回 `err(HaiAIError.CONFIGURATION_ERROR)` */ init: (config?: AIConfigInput, options?: AIInitOptions) => Promise>; /** * 关闭 AI 服务,释放内部状态 * * 关闭后 `llm`、`mcp` 操作将返回 `NOT_INITIALIZED` 错误。 * 重复关闭不会报错。 */ close: () => Promise; /** 当前脱敏后的配置快照(未初始化时为 `null`) */ readonly config: AIConfig | null; /** 是否已初始化(`init()` 成功后为 `true`,`close()` 后为 `false`) */ readonly isInitialized: boolean; /** LLM 操作(聊天、流式、模型列表),需要先调用 `init()` */ readonly llm: ManagedLLMOperations; /** ACP 智能体、工作区与原生会话,需要先调用 `init()`。 */ readonly acp: ACPOperations; /** MCP 本地函数注册及配置/数据库外部服务清单,需要先调用 `init()`。 */ readonly mcp: ManagedMCPOperations; /** 模型工具协议适配,工具定义和执行复用 @h-ai/tools;无需初始化 */ readonly tools: ToolsOperations; /** 流处理操作(流处理器、SSE 编解码),纯函数,无需初始化 */ readonly stream: StreamOperations; /** Embedding 操作(向量嵌入),需要先调用 `init()` */ readonly embedding: EmbeddingOperations; /** 推理操作(ReAct / CoT / Plan-Execute),需要先调用 `init()` */ readonly reasoning: ReasoningOperations; /** 检索操作(向量检索),需要先调用 `init()` */ readonly retrieval: ManagedRetrievalOperations; /** RAG 操作(检索增强生成),需要先调用 `init()` */ readonly rag: RagOperations; /** Knowledge 操作(知识库管理与检索),需要先调用 `init()` 和 `knowledge.setup()` */ readonly knowledge: KnowledgeOperations; /** Memory 操作(记忆提取、存储、检索、注入),需要先调用 `init()` */ readonly memory: MemoryOperations; /** Persona 操作(AI 角色人格档案与系统提示词组合),需要先调用 `init()` */ readonly persona: PersonaOperations; /** Token 操作(Token 估算),需要先调用 `init()` */ readonly token: TokenOperations; /** Summary 操作(消息摘要生成),需要先调用 `init()` */ readonly summary: SummaryOperations; /** Compress 操作(上下文压缩),需要先调用 `init()` */ readonly compress: CompressOperations; /** Context 操作(有状态上下文管理器,编排 LLM + Memory + RAG + Reasoning),需要先调用 `init()` */ readonly context: ContextOperations; /** Rerank 操作(文档重排序),需要先调用 `init()` */ readonly rerank: RerankOperations; /** File 操作(文件内容解析),需要先调用 `init()` */ readonly file: FileOperations; /** A2A 操作(Agent-to-Agent 协议),需要先调用 `init()` 并配置 `a2a` */ readonly a2a: A2AOperations; /** Audio 操作(语音识别 / 语音合成),需要先调用 `init()` 并配置 `audio` */ readonly audio: ManagedAudioOperations; /** Image 操作(文生图),需要先调用 `init()` 并配置 `image` */ readonly image: ManagedImageOperations; } /** @h-ai/ai — 音频播放负载序列化 */ /** * 将标准音频内容转换为浏览器可直接播放的 Base64 负载。 * * `synthesize` 只负责统一供应商输出的字节与格式;裸 PCM 没有容器头, * 因此这里负责补齐 WAV 头。MP3/WAV 则只进行 Base64 编码,不重新封装。 * * @example * ```ts * import { serializePlayableAudio } from '@h-ai/ai' * const result = serializePlayableAudio({ data: new Uint8Array(320), format: 'pcm16', sampleRate: 16000, channels: 1 }) * if (result.success) { * const source = 'data:' + result.data.mimeType + ';base64,' + result.data.audioBase64 * } * ``` */ declare function serializePlayableAudio(audio: AudioContent): HaiResult; /** * 统一语音入口的默认路径(相对 API 前缀) * * @example * ```ts * import { AUDIO_WS_PATH } from '@h-ai/ai' * const url = new URL('/api/v1' + AUDIO_WS_PATH, 'https://example.com') * url.protocol = 'wss:' * ``` */ declare const AUDIO_WS_PATH = "/ai/audio"; /** * 会话起始消息(客户端首个 JSON 帧) * * 表达本次语音操作:识别或合成,及可选的模型 / 语言 / 音色 / 格式等参数。 * * @example * ```ts * import type { AudioWsStartMessage } from '@h-ai/ai' * const start: AudioWsStartMessage = { type: 'start', operation: 'transcribe', stream: true, format: 'pcm16', sampleRate: 16000 } * const frame = JSON.stringify(start) * ``` */ interface AudioWsStartMessage { type: 'start'; /** 操作类型 */ operation: 'transcribe' | 'synthesize'; /** * 是否流式返回增量结果 * * 识别操作:`true` 时服务端桥接为持续音频输入并流式返回临时结果; * `false`(默认)时服务端缓冲完整音频后返回单条最终结果。 */ stream?: boolean; /** 模型 ID(不传时使用服务端默认模型) */ model?: string; /** 识别语言提示 */ language?: string; /** 领域提示词 / 热词(识别) */ contextHints?: string[]; /** 合成音色 */ voice?: string; /** 合成自然语言风格指令 */ instruction?: string; /** 音频格式(识别时为输入格式,合成时为输出格式) */ format?: AudioFormat; /** 采样率 */ sampleRate?: number; /** 声道数 */ channels?: 1 | 2; } /** * 文本输入帧(合成操作时携带待合成文本) * * @example * ```ts * import type { AudioWsTextMessage } from '@h-ai/ai' * const input: AudioWsTextMessage = { type: 'text', segmentId: 'segment-1', text: '你好' } * const frame = JSON.stringify(input) * ``` */ interface AudioWsTextMessage { type: 'text'; /** 调用方分配的稳定文本段 ID */ segmentId: string; /** 待合成文本片段 */ text: string; } /** * 输入结束帧(音频 / 文本输入全部发送完毕) * * @example * ```ts * import type { AudioWsDoneMessage } from '@h-ai/ai' * const done: AudioWsDoneMessage = { type: 'done' } * const frame = JSON.stringify(done) // 所有输入发送完毕后发送一次。 * ``` */ interface AudioWsDoneMessage { type: 'done'; } /** * 客户端 JSON 控制消息(音频输入以二进制帧发送,不走 JSON) * * @example * ```ts * import { AudioWsClientMessageSchema } from '@h-ai/ai' * import type { AudioWsClientMessage } from '@h-ai/ai' * function validate(input: unknown): AudioWsClientMessage | undefined { * const result = AudioWsClientMessageSchema.safeParse(input) * return result.success ? result.data : undefined * } * ``` */ type AudioWsClientMessage = AudioWsStartMessage | AudioWsTextMessage | AudioWsDoneMessage; /** * 合法音频格式 * * @example * ```ts * import { AudioFormatSchema } from '@h-ai/ai' * const result = AudioFormatSchema.safeParse('pcm16') * if (result.success) { * const message = result.data * } * ``` */ declare const AudioFormatSchema: zod.ZodEnum<{ pcm16: "pcm16"; wav: "wav"; mp3: "mp3"; opus: "opus"; }>; /** * 会话起始帧 Schema * * @example * ```ts * import { AudioWsStartMessageSchema } from '@h-ai/ai' * const result = AudioWsStartMessageSchema.safeParse({ type: 'start', operation: 'synthesize', format: 'mp3' }) * if (result.success) { * const message = result.data * } * ``` */ declare const AudioWsStartMessageSchema: zod.ZodObject<{ type: zod.ZodLiteral<"start">; operation: zod.ZodEnum<{ transcribe: "transcribe"; synthesize: "synthesize"; }>; stream: zod.ZodOptional; model: zod.ZodOptional; language: zod.ZodOptional; contextHints: zod.ZodOptional>; voice: zod.ZodOptional; instruction: zod.ZodOptional; format: zod.ZodOptional>; sampleRate: zod.ZodOptional; channels: zod.ZodOptional, zod.ZodLiteral<2>]>>; }, zod_v4_core.$strip>; /** * 文本输入帧 Schema(segmentId 非空且长度受限) * * @example * ```ts * import { AudioWsTextMessageSchema } from '@h-ai/ai' * const result = AudioWsTextMessageSchema.safeParse({ type: 'text', segmentId: 'segment-1', text: '你好' }) * if (result.success) { * const message = result.data * } * ``` */ declare const AudioWsTextMessageSchema: zod.ZodObject<{ type: zod.ZodLiteral<"text">; segmentId: zod.ZodString; text: zod.ZodString; }, zod_v4_core.$strip>; /** * 输入结束帧 Schema * * @example * ```ts * import { AudioWsDoneMessageSchema } from '@h-ai/ai' * const result = AudioWsDoneMessageSchema.safeParse({ type: 'done' }) * if (result.success) { * const message = result.data * } * ``` */ declare const AudioWsDoneMessageSchema: zod.ZodObject<{ type: zod.ZodLiteral<"done">; }, zod_v4_core.$strip>; /** * 客户端 JSON 控制消息 Schema(按 type 判别) * * @example * ```ts * import { AudioWsClientMessageSchema } from '@h-ai/ai' * const result = AudioWsClientMessageSchema.safeParse({ type: 'start', operation: 'transcribe', format: 'pcm16', sampleRate: 16000 }) * if (result.success) { * const message = result.data * } * ``` */ declare const AudioWsClientMessageSchema: zod.ZodDiscriminatedUnion<[zod.ZodObject<{ type: zod.ZodLiteral<"start">; operation: zod.ZodEnum<{ transcribe: "transcribe"; synthesize: "synthesize"; }>; stream: zod.ZodOptional; model: zod.ZodOptional; language: zod.ZodOptional; contextHints: zod.ZodOptional>; voice: zod.ZodOptional; instruction: zod.ZodOptional; format: zod.ZodOptional>; sampleRate: zod.ZodOptional; channels: zod.ZodOptional, zod.ZodLiteral<2>]>>; }, zod_v4_core.$strip>, zod.ZodObject<{ type: zod.ZodLiteral<"text">; segmentId: zod.ZodString; text: zod.ZodString; }, zod_v4_core.$strip>, zod.ZodObject<{ type: zod.ZodLiteral<"done">; }, zod_v4_core.$strip>], "type">; /** * 语音起止事件(识别操作时服务端 VAD 检测到语音开始 / 结束) * * @example * ```ts * import type { AudioWsSpeechMessage } from '@h-ai/ai' * function isSpeaking(event: AudioWsSpeechMessage) { * return event.type === 'speech_started' * } * ``` */ interface AudioWsSpeechMessage { type: 'speech_started' | 'speech_stopped'; } /** * 识别结果帧(识别操作时返回当前语句的完整文本) * * @example * ```ts * import type { AudioWsTranscriptMessage } from '@h-ai/ai' * function transcript(event: AudioWsTranscriptMessage) { * return { text: event.text, complete: event.final } // text 替换上一条临时识别文本。 * } * ``` */ interface AudioWsTranscriptMessage { type: 'transcript'; /** 当前语句的完整识别文本 */ text: string; /** 是否为该语句的最终结果 */ final: boolean; } /** * 合成文本段开始;后续二进制帧均属于该段,直到收到对应的 `segment_done`。 * * 携带服务端解析 Provider 后的真实输出音频参数,供浏览器正确标注音频格式。 * * @example * ```ts * import type { AudioWsSegmentStartedMessage } from '@h-ai/ai' * function decoderOptions(event: AudioWsSegmentStartedMessage) { * return { format: event.format, sampleRate: event.sampleRate, channels: event.channels ?? 1 } * } * ``` */ interface AudioWsSegmentStartedMessage { type: 'segment_started'; segmentId: string; text: string; /** 真实输出音频格式(来自服务端解析后的 Provider 输出,非客户端请求参数) */ format: AudioFormat; /** 采样率(Hz);pcm16 等裸音频必填 */ sampleRate?: number; /** 声道数(默认单声道) */ channels?: 1 | 2; } /** * 合成文本段的音频已全部发送。 * * @example * ```ts * import type { AudioWsSegmentDoneMessage } from '@h-ai/ai' * function generated(event: AudioWsSegmentDoneMessage) { * return event.segmentId // 仅标记生成完成;播放完成由终端另行确认。 * } * ``` */ interface AudioWsSegmentDoneMessage { type: 'segment_done'; segmentId: string; } /** * 错误帧(领域语义错误码,不暴露厂商协议细节) * * @example * ```ts * import type { AudioWsErrorMessage } from '@h-ai/ai' * function failure(event: AudioWsErrorMessage) { * return { code: event.code, message: event.message } * } * ``` */ interface AudioWsErrorMessage { type: 'error'; /** 领域错误码(如 `hai:ai:054`) */ code: string; /** 错误消息 */ message: string; } /** * 结束帧(服务端已发送全部结果,随后关闭连接) * * @example * ```ts * import type { AudioWsEndMessage } from '@h-ai/ai' * const end: AudioWsEndMessage = { type: 'end' } * const frame = JSON.stringify(end) // 服务端结果发送结束,随后关闭连接。 * ``` */ interface AudioWsEndMessage { type: 'end'; } /** * 服务端 JSON 消息(合成音频以二进制帧返回,不走 JSON) * * @example * ```ts * import type { AudioWsServerMessage } from '@h-ai/ai' * function result(event: AudioWsServerMessage) { * if (event.type === 'error') throw new Error(event.message) * if (event.type === 'transcript') return event.text * return undefined * } * ``` */ type AudioWsServerMessage = AudioWsSpeechMessage | AudioWsTranscriptMessage | AudioWsSegmentStartedMessage | AudioWsSegmentDoneMessage | AudioWsErrorMessage | AudioWsEndMessage; /** * ACP 子系统;资源占用通过 CAS 持久化,不以超时推断失联进程已停止。 * @param provider - 与 AI 模块共享的持久存储;工厂创建表后由调用方统一初始化。 * @param config - 经 AIConfigSchema 校验的模块配置,包括只读智能体和工作区。 * @param extensions - 可信原生配置适配器,可覆盖同名内置适配器。 * @param modelConfig - 获取包含数据库模型的实时配置;默认使用初始化配置。 * @param mcpLookup - 将合并清单 ID 解析为原生 MCP 定义,启动时解析环境变量。 * @returns 智能体、工作区、会话管理器和低层连接入口;业务失败返回 HaiResult。 * @example * ```ts * // 模块内部上下文;存储在工厂创建所有表后统一初始化。 * async function assemble(provider: AIStoreProvider, config: AIConfig) { const acp = createACPOperations(provider, config); await provider.initialize(); return acp } * ``` */ declare function createACPOperations(provider: AIStoreProvider, config: AIConfig, extensions?: Record, modelConfig?: () => Promise, mcpLookup?: (ids: string[]) => Promise, runner?: RunnerFunctions, policy?: ACPPlatformPolicy): { scoped: (rawScope: _h_ai_runner.RunnerScope) => { plan: (request: ACPPlatformRequest) => Promise>; agents: { describe: (id: string) => Promise>; }; approvals: { rules: (offset?: number, limit?: number) => Promise>; revoke: (id: string) => Promise>; respond: (approvalId: string, decision: ACPApprovalDecision) => Promise>; }; tasks: { findSubmission: (sessionId: string, idempotencyKey: string) => Promise>; get: (id: string) => Promise>; events: (id: string, after?: number, limit?: number) => Promise>; cancel: (id: string) => Promise>; }; sessions: { create: (request: ACPPlatformRequest, options?: { idempotencyKey?: string; historySummary?: string; }) => Promise Promise>; submit: (request: ACPSubmitTurn) => Promise>; prompt: (content: ACPRunRequest["prompt"], observer?: ACPTurnOptions) => Promise>; close: () => Promise>; stream(content: ACPRunRequest["prompt"], options?: ACPTurnOptions): AsyncGenerator<_h_ai_runner.RunnerJson>; changeExecution: (execution: NonNullable & { acceptNewSession: true; historySummary?: string; }) => Promise>; }>>; get: (id: string) => Promise Promise>; submit: (request: ACPSubmitTurn) => Promise>; prompt: (content: ACPRunRequest["prompt"], observer?: ACPTurnOptions) => Promise>; close: () => Promise>; stream(content: ACPRunRequest["prompt"], options?: ACPTurnOptions): AsyncGenerator<_h_ai_runner.RunnerJson>; changeExecution: (execution: NonNullable & { acceptNewSession: true; historySummary?: string; }) => Promise>; }>>; }; run: (raw: ACPRunRequest, observer?: ACPRunObserver) => Promise>; }; registerManagedExecutors: () => void; agents: { /** * 校验模型与适配器后新增数据库智能体;配置同名条目只读。 * @param input - 完整智能体定义,必须引用已有 Hai 模型 ID。 * @returns 带 source/version 的新增条目;配置同 ID 返回只读错误。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.agents.register({ id: 'coder', name: 'Coder', mode: 'embedded', adapter: 'codex', modelIds: ['coding'] }) * ``` */ register: (input: z.input) => Promise; supportedTransports: ("http" | "ws")[]; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; } | { mode: "embedded"; transport: "stdio"; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; command?: string | undefined; args?: string[] | undefined; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; } | { mode: "builtin-service"; transport: "stdio"; image: string; engine: "auto" | "podman" | "docker"; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; command?: string | undefined; args?: string[] | undefined; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; }>>>; /** * 按 ID 读取合并清单条目;source 区分配置与数据库,数据库 get 返回 version。 * @param id - 智能体 ID。 * @returns 合并后的资源条目;未找到时返回资源不存在错误。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.agents.get('coder') * ``` */ get: (id: string) => Promise; supportedTransports: ("http" | "ws")[]; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; } | { mode: "embedded"; transport: "stdio"; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; command?: string | undefined; args?: string[] | undefined; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; } | { mode: "builtin-service"; transport: "stdio"; image: string; engine: "auto" | "podman" | "docker"; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; command?: string | undefined; args?: string[] | undefined; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; }>>>; /** * 列出配置与数据库合并后的智能体;同 ID 配置优先。 * @returns 去重后的智能体条目列表;列表项不带数据库 version。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.agents.list() * ``` */ list: () => Promise; supportedTransports: ("http" | "ws")[]; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; } | { mode: "embedded"; transport: "stdio"; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; command?: string | undefined; args?: string[] | undefined; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; } | { mode: "builtin-service"; transport: "stdio"; image: string; engine: "auto" | "podman" | "docker"; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; command?: string | undefined; args?: string[] | undefined; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; }>[]>>; /** * 整体替换数据库智能体;可传入 get 返回的版本防止覆盖并发修改,配置条目不可改。 * @param input - 包含原 ID 的完整替换定义。 * @param version - get 返回的数据库版本;传入时校验并发修改。 * @returns 更新后的资源条目;配置只读、版本冲突均返回失败。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // definition 为完整替换定义;entry 为 get 成功返回的条目。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.agents.update(definition, entry.version) * ``` */ update: (input: z.input, version?: string) => Promise; supportedTransports: ("http" | "ws")[]; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; } | { mode: "embedded"; transport: "stdio"; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; command?: string | undefined; args?: string[] | undefined; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; } | { mode: "builtin-service"; transport: "stdio"; image: string; engine: "auto" | "podman" | "docker"; id: string; name: string; enabled: boolean; adapter: string; modelIds: string[]; environmentRefs: Record; environmentIds: string[]; sharedMode: boolean; allowedCapabilities: string[]; command?: string | undefined; args?: string[] | undefined; defaultModelId?: string | undefined; defaults?: { model?: { id?: string | undefined; reasoningEffort?: string | undefined; temperature?: number | undefined; maxOutputTokens?: number | undefined; } | undefined; execution?: { mode?: "auto" | "shared" | "user" | "task" | undefined; environmentId?: string | undefined; resources?: { cpu?: number | undefined; memoryMiB?: number | undefined; } | undefined; } | undefined; workspaceId?: string | undefined; context?: { fileIds?: string[] | undefined; knowledgeBaseIds?: string[] | undefined; skillIds?: string[] | undefined; memory?: { scope: "user" | "none" | "space"; spaceId?: string | undefined; write?: "none" | "confirm" | "on-success" | undefined; } | undefined; } | undefined; tools?: { allow?: string[] | undefined; } | undefined; capabilities?: string[] | undefined; permissions?: { profile?: "read-only" | "workspace" | "full-access" | undefined; approval?: "never" | "on-request" | undefined; ruleIds?: string[] | undefined; } | undefined; limits?: { queueTimeoutMs?: number | undefined; runTimeoutMs?: number | undefined; approvalTimeoutMs?: number | undefined; maxOutputBytes?: number | undefined; } | undefined; output?: { format: "text" | "json"; schema?: Record | undefined; } | undefined; native?: { adapter: string; options: Record; } | undefined; metadata?: Record | undefined; } | undefined; }>>>; /** * 删除无会话引用的数据库智能体定义;不删除镜像或外部服务。 * @param id - 数据库智能体 ID。 * @param version - 可选的期望版本。 * @returns 删除完成的 HaiResult;存在会话引用时返回 ACP_BUSY。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // entry 为 get 成功返回的数据库条目。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.agents.remove('coder', entry.version) * ``` */ remove: (id: string, version?: string) => Promise>; /** * 解析模型和原生配置,验证适配器是否兼容;不持久保存模型凭据。 * @param id - 已登记智能体 ID。 * @param modelId - 可选模型 ID,须在智能体 modelIds 中。 * @returns 智能体模式与绑定模型摘要;不返回凭据或原生配置内容。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.agents.initialize('coder') * ``` */ initialize: (id: string, modelId?: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: { agentId: string; mode: "custom-service"; modelIds: never[]; } | { agentId: string; mode: "embedded" | "builtin-service"; modelIds: string[]; }; }>; /** * 实际启动并握手后关闭连接,返回智能体能力;托管模式需指定工作区。 * @param id - 已登记智能体 ID。 * @param options - 回调、能力及工作区;托管模式必须传 workspaceId。 * @returns 原生初始化结果(智能体能力、认证方法等)的 HaiResult。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.agents.check('coder', { workspaceId: 'project' }) * ``` */ check: (id: string, options?: ACPClientOptions & { workspaceId?: string; }) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: _agentclientprotocol_sdk.InitializeResponse; }>; }; workspaces: { /** 从受信仓库的一次提交读取有界普通文件快照。 */ readGitSnapshot: (input: Parameters[0], signal?: AbortSignal) => Promise>; /** 比较快照并生成可下载的补丁。 */ diffSnapshot: (before: Record, after: Record, signal?: AbortSignal) => Promise>; /** 应用重新验权后,向独立任务分支提交并普通推送。 */ publishSnapshot: (input: Parameters[0], signal?: AbortSignal) => Promise>; /** * 新增数据库工作区并归一化存储位置;拒绝目录重叠或同一 volume 重复登记。 * @param input - 工作区存储位置、显式 Git 主分支和环境变量引用。 * @returns 带来源和版本的工作区条目;重叠位置返回冲突错误。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.workspaces.register({ id: 'project', storage: { type: 'directory', path: '/srv/project' } }) * ``` */ register: (input: z.input) => Promise; gitEnvironmentRefs: Record; }>>>; /** * 读取工作区定义及来源;配置条目无数据库版本。 * @param id - 工作区 ID。 * @returns 工作区资源条目;未找到时返回资源不存在错误。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.workspaces.get('project') * ``` */ get: (id: string) => Promise; gitEnvironmentRefs: Record; }>>>; /** * 列出配置与数据库合并后的工作区;不创建路径或克隆工程。 * @returns 去重后的工作区列表;列表项不含数据库 version。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.workspaces.list() * ``` */ list: () => Promise; gitEnvironmentRefs: Record; }>[]>>; /** * 整体替换无会话引用的数据库工作区,重新检查存储位置重叠;配置条目不可修改。 * @param input - 包含原 ID 的完整替换定义。 * @param version - 可选的数据库期望版本。 * @returns 更新后的工作区;有会话引用、位置冲突或版本冲突时失败。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // definition 为完整替换定义;entry 为 get 成功返回的条目。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.workspaces.update(definition, entry.version) * ``` */ update: (input: z.input, version?: string) => Promise; gitEnvironmentRefs: Record; }>>>; /** * 创建目录并克隆缺失工程;已有内容不自动 pull 或覆盖,Git 不存在时返回明确错误。 * @param id - 已登记工作区 ID。 * @returns 准备后的 main 绝对目录;克隆失败保留现场供检查。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.workspaces.prepare('project') * ``` */ prepare: (id: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: string; }>; /** * 将有限大小的文件写入 main/files,拒绝覆盖、路径逃逸和符号链接;失败前已写入文件会保留。 * @param id - 已登记工作区 ID。 * @param files - 相对路径和 UTF-8 文本或二进制;不允许覆盖或路径逃逸。 * @returns 已导入相对路径列表;写入中途失败不回滚已有文件。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.workspaces.importFiles('project', [{ path: 'notes.txt', content: '需求' }]) * ``` */ importFiles: (id: string, files: Array<{ path: string; content: string | Uint8Array; }>) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: { imported: string[]; }; }>; /** * 移除无会话引用的数据库定义,保留磁盘目录、Git 检出和 volume。 * @param id - 数据库工作区 ID。 * @param version - 可选的数据库期望版本。 * @returns 删除定义的 HaiResult;引用存在时失败,文件始终保留。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // entry 为 get 成功返回的数据库条目。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.workspaces.remove('project', entry.version) * ``` */ remove: (id: string, version?: string) => Promise>; }; sessions: { /** * 绑定模型、工作区和 MCP,准备目录后建立原生会话;newWorktree 可选择独立工程分支。 * @param options - 智能体、工作区、可选会话仓库、模型、MCP 及可信回调;newWorktree 默认 false。 * @returns 可用于 prompt/stream/publish 的会话句柄;启动失败保留失败记录。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.sessions.create({ agentId: 'coder', workspaceId: 'project', repositoryId: 'api', newWorktree: true }) * ``` */ create: (options: ACPCreateSessionOptions) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: { id: string; /** * 读取持久会话信息,包括状态、原生 ID 和当前容器。 * @returns 包含 ACPSessionInfo 的 HaiResult;记录不存在时返回失败。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.info() * ``` */ info: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: ACPSessionInfo; }>; /** * 发送一轮内容,等待最终停止原因、最终消息文本和完整事件;同一会话不允许并发轮次。 * @param content - 原生 ACP 内容块,不允许同一会话并发执行。 * @param signal - 本轮取消信号;取消超时会关闭连接。 * @returns 最终文本、停止原因和事件的 HaiResult。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.prompt([{ type: 'text', text: '检查工程' }]) * ``` */ prompt: (content: ContentBlock[], signal?: AbortSignal) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: { text: string; events: SessionNotification[]; stopReason: _agentclientprotocol_sdk.StopReason; _meta?: { [key: string]: unknown; } | null; }; }>; /** * 仅接受正常结束的一份 JSON(允许完整 JSON 代码围栏),再按 schema 校验;前后夹杂文本视为失败。 * @param content - 要求返回结构化 JSON 的原生内容块。 * @param schema - 最终 JSON 的 Zod 校验器。 * @param signal - 可选的本轮取消信号。 * @returns 经过 schema 校验的数据;输出不合法时返回 ACP_OUTPUT_INVALID。 * @example * ```ts * import { z } from 'zod' * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.promptStructured([{ type: 'text', text: '返回 JSON' }], z.object({ ok: z.boolean() })) * ``` */ promptStructured: (content: ContentBlock[], schema: z.ZodType, signal?: AbortSignal) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: Awaited; }>; /** * 迭代本轮 ACP 事件;中途退出迭代会取消本轮,失败会抛错,调用方需 try/finally 清理。 * @param content - 本轮原生内容块。 * @param signal - 可选取消信号;结束迭代同样会取消本轮。 * @returns 异步事件迭代器;流式失败抛出异常,需在调用方捕获。 * @throws 连接关闭、取消超时、输出超限或原生请求失败。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * for await (const event of session.stream([{ type: 'text', text: '检查工程' }])) { const update = event.update } * ``` */ stream(content: ContentBlock[], signal?: AbortSignal): AsyncGenerator; /** * 请求取消正在执行的一轮;超时未停止时关闭所拥有的传输。 * @returns 取消完成的 HaiResult;超时或清理失败返回错误。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.cancel() * ``` */ cancel: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: void; }>; /** * 选择智能体公布的原生模式 ID;不兼容时返回协议失败。 * @param mode - 握手或事件中公布的原生模式 ID。 * @returns 原生模式设置结果的 HaiResult。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.setMode('code') * ``` */ setMode: (mode: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: _agentclientprotocol_sdk.SetSessionModeResponse; }>; /** * 设置智能体公布的原生配置选项;值必须符合该智能体的选项定义。 * @param key - 原生配置选项 ID。 * @param value - 该选项允许的值。 * @returns 原生配置更新结果的 HaiResult。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.setConfigOption('model', 'coding') * ``` */ setConfigOption: (key: string, value: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: _agentclientprotocol_sdk.SetSessionConfigOptionResponse; }>; /** * 先关闭会话执行环境,再 fetch 并仅快进各工程明确配置的主分支;不修改会话分支。 * @returns 各仓更新报告;部分失败时报告位于 error.cause.reports。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.updateMain() * ``` */ updateMain: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: ACPGitReport[]; }>; /** * 关闭执行环境后逐仓提交并推送;仅支持受管理的独立会话,部分失败保留各仓报告,禁止强推。 * @param request - 发布模式、提交说明和作者;仅支持受管理的独立会话。 * @returns 各仓提交/推送报告;部分失败时报告位于 error.cause.reports。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.publish({ mode: 'merge-main', message: '完成任务', author: { name: 'Developer', email: 'dev@example.com' } }) * ``` */ publish: (request: z.input) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: ACPGitReport[]; }>; /** * 停止拥有的进程或容器,释放占用;保留工作目录和原生状态,供后续显式恢复。 * @returns 关闭完成的 HaiResult;清理失败时不释放仍在占用的资源。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.close() * ``` */ close: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: void; }>; }; }>; /** * 获取持久会话的管理句柄;已关闭会话需要 resume 后才能执行 prompt。 * @param id - 框架会话 ID,不是智能体原生 ID。 * @returns 管理句柄的 HaiResult;不会自动重新启动智能体。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.sessions.get('task-1') * ``` */ get: (id: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: { id: string; /** * 读取持久会话信息,包括状态、原生 ID 和当前容器。 * @returns 包含 ACPSessionInfo 的 HaiResult;记录不存在时返回失败。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.info() * ``` */ info: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: ACPSessionInfo; }>; /** * 发送一轮内容,等待最终停止原因、最终消息文本和完整事件;同一会话不允许并发轮次。 * @param content - 原生 ACP 内容块,不允许同一会话并发执行。 * @param signal - 本轮取消信号;取消超时会关闭连接。 * @returns 最终文本、停止原因和事件的 HaiResult。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.prompt([{ type: 'text', text: '检查工程' }]) * ``` */ prompt: (content: ContentBlock[], signal?: AbortSignal) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: { text: string; events: SessionNotification[]; stopReason: _agentclientprotocol_sdk.StopReason; _meta?: { [key: string]: unknown; } | null; }; }>; /** * 仅接受正常结束的一份 JSON(允许完整 JSON 代码围栏),再按 schema 校验;前后夹杂文本视为失败。 * @param content - 要求返回结构化 JSON 的原生内容块。 * @param schema - 最终 JSON 的 Zod 校验器。 * @param signal - 可选的本轮取消信号。 * @returns 经过 schema 校验的数据;输出不合法时返回 ACP_OUTPUT_INVALID。 * @example * ```ts * import { z } from 'zod' * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.promptStructured([{ type: 'text', text: '返回 JSON' }], z.object({ ok: z.boolean() })) * ``` */ promptStructured: (content: ContentBlock[], schema: z.ZodType, signal?: AbortSignal) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: Awaited; }>; /** * 迭代本轮 ACP 事件;中途退出迭代会取消本轮,失败会抛错,调用方需 try/finally 清理。 * @param content - 本轮原生内容块。 * @param signal - 可选取消信号;结束迭代同样会取消本轮。 * @returns 异步事件迭代器;流式失败抛出异常,需在调用方捕获。 * @throws 连接关闭、取消超时、输出超限或原生请求失败。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * for await (const event of session.stream([{ type: 'text', text: '检查工程' }])) { const update = event.update } * ``` */ stream(content: ContentBlock[], signal?: AbortSignal): AsyncGenerator; /** * 请求取消正在执行的一轮;超时未停止时关闭所拥有的传输。 * @returns 取消完成的 HaiResult;超时或清理失败返回错误。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.cancel() * ``` */ cancel: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: void; }>; /** * 选择智能体公布的原生模式 ID;不兼容时返回协议失败。 * @param mode - 握手或事件中公布的原生模式 ID。 * @returns 原生模式设置结果的 HaiResult。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.setMode('code') * ``` */ setMode: (mode: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: _agentclientprotocol_sdk.SetSessionModeResponse; }>; /** * 设置智能体公布的原生配置选项;值必须符合该智能体的选项定义。 * @param key - 原生配置选项 ID。 * @param value - 该选项允许的值。 * @returns 原生配置更新结果的 HaiResult。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.setConfigOption('model', 'coding') * ``` */ setConfigOption: (key: string, value: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: _agentclientprotocol_sdk.SetSessionConfigOptionResponse; }>; /** * 先关闭会话执行环境,再 fetch 并仅快进各工程明确配置的主分支;不修改会话分支。 * @returns 各仓更新报告;部分失败时报告位于 error.cause.reports。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.updateMain() * ``` */ updateMain: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: ACPGitReport[]; }>; /** * 关闭执行环境后逐仓提交并推送;仅支持受管理的独立会话,部分失败保留各仓报告,禁止强推。 * @param request - 发布模式、提交说明和作者;仅支持受管理的独立会话。 * @returns 各仓提交/推送报告;部分失败时报告位于 error.cause.reports。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.publish({ mode: 'merge-main', message: '完成任务', author: { name: 'Developer', email: 'dev@example.com' } }) * ``` */ publish: (request: z.input) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: ACPGitReport[]; }>; /** * 停止拥有的进程或容器,释放占用;保留工作目录和原生状态,供后续显式恢复。 * @returns 关闭完成的 HaiResult;清理失败时不释放仍在占用的资源。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.close() * ``` */ close: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: void; }>; }; }>; /** * 列出持久会话,可按工作区 ID 过滤。 * @param workspaceId - 可选工作区筛选条件;省略返回全部会话。 * @returns 持久 ACPSessionInfo 列表的 HaiResult。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.sessions.list('project') * ``` */ list: (workspaceId?: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: ACPSessionInfo[]; }>; /** * 默认使用原生会话 ID 和原状态恢复。可信宿主确认首轮尚未派发时,可在原隔离工作树重开。 * @param id - 已关闭或失败的框架会话 ID。 * @param options - 本次连接选项和可信宿主可显式启用的 restartNative。 * @returns 恢复后的会话句柄;占用、工作树失效、原生操作失败或配置变化时返回失败。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.sessions.resume('task-1') * ``` */ resume: (id: string, options?: ACPClientOptions & { /** 可信宿主持有任务执行租约或等价的独占执行权,并确认首轮尚未派发时可设为 true。默认 false。 */ restartNative?: boolean; }) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: { id: string; /** * 读取持久会话信息,包括状态、原生 ID 和当前容器。 * @returns 包含 ACPSessionInfo 的 HaiResult;记录不存在时返回失败。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.info() * ``` */ info: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: ACPSessionInfo; }>; /** * 发送一轮内容,等待最终停止原因、最终消息文本和完整事件;同一会话不允许并发轮次。 * @param content - 原生 ACP 内容块,不允许同一会话并发执行。 * @param signal - 本轮取消信号;取消超时会关闭连接。 * @returns 最终文本、停止原因和事件的 HaiResult。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.prompt([{ type: 'text', text: '检查工程' }]) * ``` */ prompt: (content: ContentBlock[], signal?: AbortSignal) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: { text: string; events: SessionNotification[]; stopReason: _agentclientprotocol_sdk.StopReason; _meta?: { [key: string]: unknown; } | null; }; }>; /** * 仅接受正常结束的一份 JSON(允许完整 JSON 代码围栏),再按 schema 校验;前后夹杂文本视为失败。 * @param content - 要求返回结构化 JSON 的原生内容块。 * @param schema - 最终 JSON 的 Zod 校验器。 * @param signal - 可选的本轮取消信号。 * @returns 经过 schema 校验的数据;输出不合法时返回 ACP_OUTPUT_INVALID。 * @example * ```ts * import { z } from 'zod' * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.promptStructured([{ type: 'text', text: '返回 JSON' }], z.object({ ok: z.boolean() })) * ``` */ promptStructured: (content: ContentBlock[], schema: z.ZodType, signal?: AbortSignal) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: Awaited; }>; /** * 迭代本轮 ACP 事件;中途退出迭代会取消本轮,失败会抛错,调用方需 try/finally 清理。 * @param content - 本轮原生内容块。 * @param signal - 可选取消信号;结束迭代同样会取消本轮。 * @returns 异步事件迭代器;流式失败抛出异常,需在调用方捕获。 * @throws 连接关闭、取消超时、输出超限或原生请求失败。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * for await (const event of session.stream([{ type: 'text', text: '检查工程' }])) { const update = event.update } * ``` */ stream(content: ContentBlock[], signal?: AbortSignal): AsyncGenerator; /** * 请求取消正在执行的一轮;超时未停止时关闭所拥有的传输。 * @returns 取消完成的 HaiResult;超时或清理失败返回错误。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.cancel() * ``` */ cancel: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: void; }>; /** * 选择智能体公布的原生模式 ID;不兼容时返回协议失败。 * @param mode - 握手或事件中公布的原生模式 ID。 * @returns 原生模式设置结果的 HaiResult。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.setMode('code') * ``` */ setMode: (mode: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: _agentclientprotocol_sdk.SetSessionModeResponse; }>; /** * 设置智能体公布的原生配置选项;值必须符合该智能体的选项定义。 * @param key - 原生配置选项 ID。 * @param value - 该选项允许的值。 * @returns 原生配置更新结果的 HaiResult。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.setConfigOption('model', 'coding') * ``` */ setConfigOption: (key: string, value: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: _agentclientprotocol_sdk.SetSessionConfigOptionResponse; }>; /** * 先关闭会话执行环境,再 fetch 并仅快进各工程明确配置的主分支;不修改会话分支。 * @returns 各仓更新报告;部分失败时报告位于 error.cause.reports。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.updateMain() * ``` */ updateMain: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: ACPGitReport[]; }>; /** * 关闭执行环境后逐仓提交并推送;仅支持受管理的独立会话,部分失败保留各仓报告,禁止强推。 * @param request - 发布模式、提交说明和作者;仅支持受管理的独立会话。 * @returns 各仓提交/推送报告;部分失败时报告位于 error.cause.reports。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.publish({ mode: 'merge-main', message: '完成任务', author: { name: 'Developer', email: 'dev@example.com' } }) * ``` */ publish: (request: z.input) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: ACPGitReport[]; }>; /** * 停止拥有的进程或容器,释放占用;保留工作目录和原生状态,供后续显式恢复。 * @returns 关闭完成的 HaiResult;清理失败时不释放仍在占用的资源。 * @example * ```ts * // session 为 sessions.create/get/resume 成功返回的 data。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await session.close() * ``` */ close: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: void; }>; }; }>; /** * 关闭本进程拥有的会话并释放锁,不删除历史和工程内容。 * @param id - 框架会话 ID。 * @returns 关闭完成的 HaiResult;不允许关闭其他进程拥有的执行环境。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.sessions.close('task-1') * ``` */ close: (id: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: void; }>; /** * 回收停止后由框架登记的干净工作树;调用方须先停止独立预览。 * @param id - 框架会话 ID;仅支持记录了归属的独立 Git 会话。 * @returns 回收完成的 HaiResult;可重试,保留分支、普通文件及原生历史。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:已关闭 Agent,已停止预览并提交或另存修改。 * const result = await ai.acp.sessions.reclaimWorktree('task-1') * if (!result.success) throw new Error(result.error.message) * ``` */ reclaimWorktree: (id: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: void; }>; /** * 仅删除已关闭或失败的会话记录;不删除工作树及原生文件,不替代 Git worktree 清理。 * @param id - 框架会话 ID。 * @returns 删除完成的 HaiResult;活动会话返回忙碌错误。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.sessions.remove('task-1') * ``` */ remove: (id: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: void; }>; }; /** * 连接原生 stdio/HTTP/WS 服务;不创建工作区或提供传输兼容桥。 * @param transport - 智能体实际支持的原生传输与命令或地址。 * @param options - 可信回调、声明能力和初始化取消信号。 * @returns 低层连接句柄的 HaiResult;连接失败不自动转换传输。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * const result = await ai.acp.connect({ type: 'http', url: 'https://agent.example.com/acp' }) * ``` */ connect: (transport: ACPTransport, options?: ACPClientOptions) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: { info: _agentclientprotocol_sdk.InitializeResponse; /** * 选择对端握手公布的认证方法,返回 HaiResult。 * @param method - initialize 返回的认证方法 ID。 * @returns 认证响应的 HaiResult。 * @example * ```ts * // connection/session 为已成功连接或创建的句柄,先检查 result.success。 * const result = await connection.authenticate('api-key') * ``` */ authenticate: (method: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: _agentclientprotocol_sdk.AuthenticateResponse; }>; /** * 在对端可见的绝对 cwd 创建原生会话,返回 prompt/cancel 句柄。 * @param cwd - 对端文件系统可见的绝对工作目录。 * @param mcpServers - 可选原生 MCP 定义;调用方负责凭据与授权。 * @returns 原生会话句柄;不创建框架持久会话记录。 * @example * ```ts * // connection/session 为已成功连接或创建的句柄,先检查 result.success。 * const result = await connection.createSession('/srv/project', []) * ``` */ createSession: (cwd: string, mcpServers?: McpServer[]) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: { id: string; /** * 发送一轮原生内容,返回最终文本、停止原因和事件。 * @param content - 原生 ACP 内容块。 * @param signal - 可选本轮取消信号。 * @returns 最终文本、停止原因和事件的 HaiResult。 * @example * ```ts * // connection/session 为已成功连接或创建的句柄,先检查 result.success。 * const result = await session.prompt([{ type: 'text', text: '检查工程' }]) * ``` */ prompt: (content: ContentBlock[], signal?: AbortSignal) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: { text: string; events: SessionNotification[]; stopReason: _agentclientprotocol_sdk.StopReason; _meta?: { [key: string]: unknown; } | null; }; }>; /** * 取消当前轮次,超时则关闭连接。 * @returns 取消完成的 HaiResult。 * @example * ```ts * // connection/session 为已成功连接或创建的句柄,先检查 result.success。 * const result = await session.cancel() * ``` */ cancel: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: void; }>; }; }>; /** * 读取对端原生会话列表;未声明相应能力时返回错误。 * @param cursor - 上一次原生列表响应中的分页游标。 * @returns 原生分页响应的 HaiResult。 * @example * ```ts * // connection/session 为已成功连接或创建的句柄,先检查 result.success。 * const result = await connection.listSessions() * ``` */ listSessions: (cursor?: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: _agentclientprotocol_sdk.ListSessionsResponse; }>; /** * 按原生 ID 删除远端会话;不会删除框架数据库会话记录。 * @param id - 对端返回的原生会话 ID。 * @returns 原生删除响应的 HaiResult;不支持时返回协议错误。 * @example * ```ts * // connection/session 为已成功连接或创建的句柄,先检查 result.success。 * const result = await connection.deleteSession('native-id') * ``` */ deleteSession: (id: string) => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: _agentclientprotocol_sdk.DeleteSessionResponse; }>; /** * 关闭连接和拥有的子进程;不删除远端文件或持久状态。 * @returns 关闭完成的 HaiResult;可重复关闭。 * @example * ```ts * // connection/session 为已成功连接或创建的句柄,先检查 result.success。 * const result = await connection.close() * ``` */ close: () => Promise<{ success: false; error: _h_ai_core.HaiError; } | { success: true; data: void; }>; }; }>; /** * 关闭子系统及拥有的资源;由 ai.close 生命周期调用。 * @returns 所有已接受操作结束和拥有资源完成清理后的 Promise。 * @throws 清理进程或容器失败时抛出 ACPFailure,由 ai.close 统一处理。 * @example * ```ts * import { ai } from '@h-ai/ai' * // 前提:ai 已成功初始化。 * // 普通 API 先检查 result.success,再读取 data 或 error。 * await ai.close() * ``` */ close(): Promise; }; /** * 原生传输参数;HTTP/WS 使用锁定版本的官方实验传输,不进行隐式转换。 * @example * ```ts * import type { ACPTransport } from '@h-ai/ai' * const transport: ACPTransport = { type: 'stdio', command: 'codex-acp' } * ``` */ type ACPTransport = { /** 通过独占子进程 stdin/stdout 传输 ACP。 */ type: 'stdio'; /** 直接执行的程序路径,不通过 shell。 */ command: string; /** 原生参数数组。 */ args?: string[]; /** 子进程工作目录。 */ cwd?: string; /** 传给子进程的环境变量,与最小宿主环境合并。 */ env?: Record; } | { /** 原生远程传输;对端必须支持相同 SDK 协议版本。 */ type: 'http' | 'ws'; /** ACP 服务地址,协议应与 type 一致。 */ url: string; /** 当前连接的认证请求头,仅保存在内存。 */ headers?: Record; }; /** * 可信宿主回调。声明能力必须提供对应实现;默认拒绝权限请求。 * @example * ```ts * import type { ACPClientOptions } from '@h-ai/ai' * const options: ACPClientOptions = { handlers: { 'session/request_permission': () => ({ outcome: { outcome: 'cancelled' } }) } } * ``` */ interface ACPClientOptions { /** 接收原生会话事件,包括 session/new 完成前的事件;抛错将关闭连接。 */ onEvent?: (event: SessionNotification) => void; /** 可信客户端回调实现;未提供权限回调时默认拒绝。 */ handlers?: Partial; /** 向智能体声明的能力;声明的文件、终端和 elicitation 能力必须配齐回调。 */ capabilities?: ClientCapabilities; /** 初始化连接的取消信号;每轮 prompt 的取消信号独立传入。 */ signal?: AbortSignal; } /** * 可信原生配置扩展;返回值只传给进程,不写入 Agent 定义存储。 * @example * ```ts * import type { ACPAgentAdapter } from '@h-ai/ai' * const adapter: ACPAgentAdapter = { configure: () => ({ command: 'my-agent', args: ['--acp'], env: {} }) } * ``` */ interface ACPAgentAdapter { /** 仅已验证无原生越权入口、能安全隔离并关闭会话的适配器可声明。 */ sharedSessions?: true; /** 验证原生扩展并返回实际生效的选项。 */ nativeOptions?: z.ZodType>; /** * 生成当前会话的原生启动参数;实现可以异步,不应在此启动进程或持久保存密钥。 * @param input - 智能体、已解析模型与独立状态目录。 * @returns 原生可执行文件、参数、临时环境和可选配置文件。 * @example * ```ts * const adapter: ACPAgentAdapter = { configure: ({ statePath }) => ({ command: 'my-agent', args: ['--acp'], env: { AGENT_HOME: statePath } }) } * ``` */ configure: (input: ACPAgentAdapterInput) => ACPAgentLaunch | Promise; } /** * 原生适配器输入;模型来源由框架统一解析,适配器不维护独立模型清单。 * @example * ```ts * import type { ACPAgentAdapterInput } from '@h-ai/ai' * function selected(input: ACPAgentAdapterInput) { return input.models.find(model => model.id === input.modelId) } * ``` */ interface ACPAgentAdapterInput { /** 合并清单中的智能体定义。 */ agent: z.infer; /** 智能体绑定的全部模型及已解析协议、凭据、容量和模态信息。 */ models: Array<{ id: string; config: ResolvedModelConfig; }>; /** 本次会话选择的模型 ID。 */ modelId?: string; /** 已创建的专属状态目录;托管容器内使用 /state/<会话 ID>。 */ statePath: string; /** 受管任务请求的权限范围。 */ permissionProfile?: 'read-only' | 'workspace' | 'full-access'; /** 为经过隔离验证的原生适配器启用只读共享启动配置。 */ shared?: boolean; /** 已由适配器 Schema 校验的原生扩展选项。 */ nativeOptions?: Record; /** 模型声明支持且适配器可落实的推理级别。 */ reasoningEffort?: string; } /** * 单次启动的原生配置;env 可能含凭据,不可向浏览器或日志直接公开。 * @example * ```ts * import type { ACPAgentLaunch } from '@h-ai/ai' * const launch: ACPAgentLaunch = { command: 'my-agent', args: ['--acp'], env: {} } * ``` */ interface ACPAgentLaunch { /** 直接执行的程序,禁止拼接 shell 命令。 */ command: string; /** 原生参数数组。 */ args: string[]; /** 仅向当前执行环境注入的变量。 */ env: Record; /** 状态目录下的普通配置文件,文件名不允许路径分隔符。 */ files?: Record; } /** * 已准备的工程位置,供同一节点上的可信预览或检查进程使用。 * @example * ```ts * import type { ACPSessionWorkspace } from '@h-ai/ai' * function webPath(workspace: ACPSessionWorkspace) { return workspace.repositories.find(repo => repo.id === 'web')?.path } * ``` */ interface ACPSessionWorkspace { /** 本机真实目录,或实际使用的引擎、源码卷和容器挂载点。 */ storage: { type: 'directory'; path: string; } | { type: 'volume'; engine: 'podman' | 'docker'; name: string; mountPath: string; }; /** 当前会话的聚合目录,位于上述宿主目录或容器挂载点内。 */ path: string; /** 登记仓库在同一文件系统中的绝对路径。 */ repositories: Array<{ id: string; path: string; }>; } /** * 持久会话绑定;原生 ID 不等于框架 ID,工作目录只能由登记信息生成。 * @example * ```ts * import type { ACPSessionInfo } from '@h-ai/ai' * function sessionStatus(session: ACPSessionInfo) { return session.status } * ``` */ interface ACPSessionInfo { /** 框架会话 ID,与智能体返回的 nativeId 分开维护。 */ id: string; /** 合并清单中的智能体 ID。 */ agentId: string; /** 受管理工作区 ID;远程自定义服务可省略。 */ workspaceId?: string; /** 作为会话工作目录的已登记仓库;省略时使用聚合目录。 */ repositoryId?: string; /** 智能体实际可见的绝对工作目录。 */ cwd: string; /** 是否使用独立检出目录;false 表示共享工作区主目录。 */ newWorktree: boolean; /** 独立会话中所有工程共用的分支名。 */ branch?: string; /** 受管目录交接信息;创建失败时可能只有部分工作树,旧记录或远程会话可能没有该字段。 */ workspace?: ACPSessionWorkspace; /** 显式回收已开始或完成。此时 workspace 仅供历史追溯,不可恢复会话或发布工作树。 */ worktreeStatus?: 'reclaiming' | 'reclaimed'; /** 启动时选定的 Hai 模型 ID。 */ modelId?: string; /** 模型非密钥配置的摘要;用于阻止不兼容的会话恢复。 */ modelSignature?: string; /** 当前原生会话 ID。默认恢复时原样传回,显式重开成功后更新。 */ nativeId?: string; /** 打开中、运行中、已关闭或打开失败。 */ status: 'opening' | 'active' | 'closed' | 'failed'; /** 创建会话时的智能体定义快照。 */ agent: z.infer; /** 直接绑定的原生 MCP 参数;可能含凭据,仅供可信服务端管理。 */ mcpServers: McpServer[]; /** 从 MCP 合并清单选择的服务 ID;凭据在启动时解析。 */ mcpServerIds?: string[]; /** 当前拥有的容器;关闭后清空,volume 内容仍保留。 */ resource?: { engine?: 'podman' | 'docker'; container: string; }; } /** * 创建会话参数;远程服务使用它自身可见的绝对路径。 * @example * ```ts * import type { ACPCreateSessionOptions } from '@h-ai/ai' * const options: ACPCreateSessionOptions = { agentId: 'coder', workspaceId: 'project', newWorktree: true } * ``` */ interface ACPCreateSessionOptions extends ACPClientOptions { /** 可选业务会话 ID;省略时生成 UUID。 */ id?: string; /** 合并清单中的智能体 ID。 */ agentId: string; /** 托管模式必填的工作区 ID。 */ workspaceId?: string; /** 以已登记仓库的根目录启动与恢复;不改变 worktree 和 Git 发布的仓库范围。 */ repositoryId?: string; /** 自定义远程服务可见的绝对路径;托管模式由工作区计算。 */ cwd?: string; /** 默认 false;true 时从每个工程当前本地主分支创建 worktree。 */ newWorktree?: boolean; /** 独立会话分支名;默认 acp/<会话 ID>。 */ branch?: string; /** 本次会话的模型 ID,必须在智能体 modelIds 内。 */ modelId?: string; /** 直接传给智能体的 MCP 定义;与 mcpServerIds 合并。 */ mcpServers?: McpServer[]; /** 从 ai.mcp.servers 选择的登记服务。 */ mcpServerIds?: string[]; } /** * 每个工程分别报告,保留失败前已发生的提交和推送结果。 * @example * ```ts * import type { ACPGitReport } from '@h-ai/ai' * function failedRepositories(reports: ACPGitReport[]) { return reports.filter(report => !report.success).map(report => report.repositoryId) } * ``` */ interface ACPGitReport { /** 工作区中声明的工程 ID。 */ repositoryId: string; /** 该工程是否完成全部请求操作。 */ success: boolean; /** 成功时为 done;失败时标明停止阶段。 */ phase: 'check' | 'commit' | 'fetch' | 'merge' | 'push' | 'done'; /** 已创建或发布的提交 SHA;失败前可能已经产生提交。 */ commit?: string; /** 脱敏的失败原因,不包含 Git stderr 或认证资料。 */ error?: string; } /** * ACP 操作入口。 * @example * ```ts * import { ai } from '@h-ai/ai' * async function listAgents() { const result = await ai.acp.agents.list(); if (!result.success) return result; return result.data } * ``` */ type ACPOperations = ReturnType; export { AudioFormatSchema as $, ACPPublishSchema as B, ACPRepositorySchema as C, ACPWorkspaceSchema as F, AIConfigSchema as I, AUDIO_WS_PATH as U, ApiTypeSchema as W, AudioConfigSchema as _, AudioModelEntrySchema as a1, AudioOperationSchema as a3, AudioOperationsSchema as a4, AudioProviderSchema as a6, AudioWsClientMessageSchema as a8, CompressionStrategySchema as aC, EmbeddingConfigSchema as aQ, EntityTypeSchema as a_, AudioWsDoneMessageSchema as aa, AudioWsStartMessageSchema as ai, AudioWsTextMessageSchema as ak, CompressConfigSchema as ax, FileConfigSchema as b0, HaiAIError as b5, ImageConfigSchema as b7, LLMConfigSchema as bF, MCPConfigSchema as bI, MCPExternalServerSchema as bL, MCPServerCapabilitiesSchema as bU, MCPServerConfigSchema as bW, ImageModelEntrySchema as ba, ImageProviderSchema as bd, KnowledgeConfigSchema as bj, MemoryConfigSchema as c8, RetrievalConfigSchema as cW, MemoryTypeSchema as cj, ModelCapabilitiesSchema as cn, ModelEntrySchema as cp, ModelScenarioSchema as cr, OptionalSecretSchema as ct, RetrievalSourceSchema as d1, resolveAudioModel as dA, resolveImageModel as dB, resolveModelApi as dC, resolveModelEntry as dD, serializePlayableAudio as dE, SummaryConfigSchema as de, TokenConfigSchema as dm, ensureAudioCredential as dz, A2AConfigSchema as h, A2ASkillConfigSchema as n, ACPAgentSchema as s, ACPConfigSchema as w }; export type { A2AAgentCardConfig as A, ACPSessionInfo as D, ACPTransport as E, AIConfig as G, AIConfigInput as H, AIFunctions as J, AIInitOptions as K, AIRelStore as L, AIRelStoreCompareAndSwap as M, AIRelStoreOptions as N, AIResourceEntry as O, AIResourceRegistry as P, AIStoreProvider as Q, AIVectorBackend as R, AIVectorStore as S, AIVersionedRecord as T, ApiType as V, AskOptions as X, AssistantMessage as Y, AudioConfig as Z, A2AAgentCardDocument as a, FileConfig as a$, AudioModelEntry as a0, AudioOperation as a2, AudioProviderName as a5, AudioWsClientMessage as a7, AudioWsDoneMessage as a9, CompressResult as aA, CompressionStrategy as aB, ConsolidateOptions as aD, ConsolidateResult as aE, ContextChatOptions as aF, ContextChatResult as aG, ContextManager as aH, ContextManagerOptions as aI, ContextOperations as aJ, ContextResetOptions as aK, ContextStreamEvent as aL, ConversationTurn as aM, ConversationTurnStatus as aN, DeveloperMessage as aO, EmbeddingConfig as aP, EmbeddingItem as aR, EmbeddingOperations as aS, EmbeddingRequest as aT, EmbeddingResponse as aU, EntityDocumentRelation as aV, EntityDocumentResult as aW, EntityListOptions as aX, EntityQueryOptions as aY, EntityType as aZ, AudioWsEndMessage as ab, AudioWsErrorMessage as ac, AudioWsSegmentDoneMessage as ad, AudioWsSegmentStartedMessage as ae, AudioWsServerMessage as af, AudioWsSpeechMessage as ag, AudioWsStartMessage as ah, AudioWsTextMessage as aj, AudioWsTranscriptMessage as al, ChatCompletionChoice as am, ChatCompletionChunk as an, ChatCompletionDelta as ao, ChatCompletionRequest as ap, ChatCompletionResponse as aq, ChatHistoryOptions as ar, ChatMessage as as, ChatRecord as at, Citation as au, CommitTurnInput as av, CompressConfig as aw, CompressOperations as ay, CompressOptions as az, A2AApiKeySecurity as b, ManagedLLMOperations as b$, GenerateImageRequest as b1, GenerateImageResult as b2, GenerateObjectRequest as b3, GeneratedImage as b4, ImageConfig as b6, ImageContent as b8, ImageModelEntry as b9, KnowledgeRetrieveOptions as bA, KnowledgeRetrieveResult as bB, KnowledgeSetupOptions as bC, KnowledgeStore as bD, LLMConfig as bE, LLMOperations as bG, MCPConfig as bH, MCPContext as bJ, MCPExternalServer as bK, MCPOperations as bM, MCPPrompt as bN, MCPPromptArgument as bO, MCPPromptContent as bP, MCPPromptMessage as bQ, MCPResource as bR, MCPResourceContent as bS, MCPServerCapabilities as bT, MCPServerConfig as bV, MCPToolDefinition as bX, MCPToolHandler as bY, ManagedAudioOperations as bZ, ManagedImageOperations as b_, ImageOperations as bb, ImageProviderName as bc, ImageSize as be, InteractionScope as bf, KnowledgeAskOptions as bg, KnowledgeAskResult as bh, KnowledgeConfig as bi, KnowledgeDocumentInfo as bk, KnowledgeDocumentListOptions as bl, KnowledgeDocumentMetadata as bm, KnowledgeDocumentRemoveOptions as bn, KnowledgeDocumentRevision as bo, KnowledgeEntity as bp, KnowledgeIngestBatchProgress as bq, KnowledgeIngestBatchResult as br, KnowledgeIngestFileInput as bs, KnowledgeIngestInput as bt, KnowledgeIngestResult as bu, KnowledgeOperations as bv, KnowledgeRepairOptions as bw, KnowledgeRepairProgress as bx, KnowledgeRepairResult as by, KnowledgeRetrieveItem as bz, A2AAuthenticator as c, RetrievalSource as c$, ManagedMCPOperations as c0, ManagedRetrievalOperations as c1, McpServerOptions as c2, MemoryAccessScope as c3, MemoryAdminOperations as c4, MemoryClearAllOptions as c5, MemoryClearOptions as c6, MemoryConfig as c7, MemoryCoreOperations as c9, RagOperations as cA, RagOptions as cB, RagResult as cC, RagStreamEvent as cD, ReasoningOperations as cE, ReasoningOptions as cF, ReasoningResult as cG, ReasoningStep as cH, ReasoningStepType as cI, ReasoningStrategy as cJ, ReasoningStreamEvent as cK, ReferenceImage as cL, RerankDocument as cM, RerankItem as cN, RerankOperations as cO, RerankRequest as cP, RerankResponse as cQ, ResolveRequiredModelEntryOptions as cR, ResolvedAudioModel as cS, ResolvedImageModel as cT, ResolvedModelConfig as cU, RetrievalConfig as cV, RetrievalOperations as cX, RetrievalRequest as cY, RetrievalResult as cZ, RetrievalResultItem as c_, MemoryEntry as ca, MemoryEntryInput as cb, MemoryExtractOptions as cc, MemoryInjectionOptions as cd, MemoryListOptions as ce, MemoryListPageOptions as cf, MemoryOperations as cg, MemoryRecallOptions as ch, MemoryType as ci, MemoryUpdateInput as ck, MessageContent as cl, MessageRole as cm, ModelEntry as co, ModelScenario as cq, ObjectRef as cs, PersonaOperations as cu, PersonaProfile as cv, PersonaProfileInput as cw, PersonaProfileUpdate as cx, PersonaScopeOptions as cy, RagContextItem as cz, A2ACallOptions as d, MCPJobFileContext as d$, RetrievalSourceConfig as d0, SSEDecoder as d2, SSEEvent as d3, ScopedMemoryBinding as d4, ScopedMemoryOperations as d5, SessionInfo as d6, StoreFilter as d7, StorePage as d8, StoreScope as d9, ACPApprovalDecision as dF, ACPCitation as dG, ACPPlatformPolicy as dH, ACPPlatformRequest as dI, ACPProjectChanges as dJ, ACPProjectSnapshot as dK, ACPPublishSnapshot as dL, ACPRunObserver as dM, ACPRunRequest as dN, ACPSessionWorkspace as dO, ACPSubmitTurn as dP, ACPTurnOptions as dQ, BuiltinArtifact as dR, BuiltinArtifactAccess as dS, BuiltinArtifactReference as dT, BuiltinToolBinding as dU, BuiltinToolBroker as dV, BuiltinToolBrokerOptions as dW, BuiltinToolOptions as dX, CreateBuiltinTools as dY, JsonFieldPreview as dZ, JsonFieldPreviewOptions as d_, StreamOperations as da, StreamProcessor as db, StreamResult as dc, SummaryConfig as dd, SummaryOperations as df, SummaryOptions as dg, SummaryResult as dh, SystemMessage as di, TempModelConfig as dj, TextContent as dk, TokenConfig as dl, TokenOperations as dn, TokenUsage as dp, ToolCall as dq, ToolDefinition as dr, ToolMessage as ds, ToolRegistryOperations as dt, ToolsOperations as du, UserMessage as dv, WhereClause as dw, WhereOperator as dx, WhereValue as dy, A2ACallResult as e, MCPJobFiles as e0, MCPServiceAuthorization as e1, MCPServiceBinding as e2, MCPServiceBindingRequest as e3, MCPServiceBroker as e4, MCPServiceBrokerOptions as e5, MCPServiceOperations as e6, MCPServiceRequest as e7, McpToolOptions as e8, A2ACallerIdentity as f, A2AConfig as g, A2AContextInfo as i, A2AHandleResult as j, A2AMessageRecord as k, A2AOperations as l, A2ASecurityConfig as m, A2ATaskFilter as o, ACPAgentAdapter as p, ACPAgentAdapterInput as q, ACPAgentLaunch as r, ACPClientOptions as t, ACPConfig as u, ACPConfigInput as v, ACPCreateSessionOptions as x, ACPGitReport as y, ACPOperations as z };