@h-ai/ai 0.1.0-alpha9 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,118 @@
1
+ import { core } from '@h-ai/core';
2
+
3
+ // src/ai-types.ts
4
+ var AIErrorInfo = {
5
+ // 通用 (000-009)
6
+ INTERNAL_ERROR: "000:500",
7
+ // 初始化 (010-019)
8
+ NOT_INITIALIZED: "010:500",
9
+ CONFIGURATION_ERROR: "011:500",
10
+ INIT_IN_PROGRESS: "012:500",
11
+ RERANK_API_ERROR: "020:502",
12
+ RERANK_INVALID_REQUEST: "021:400",
13
+ // LLM (100-199)
14
+ API_ERROR: "100:502",
15
+ INVALID_REQUEST: "101:400",
16
+ RATE_LIMITED: "102:429",
17
+ TIMEOUT: "103:504",
18
+ MODEL_NOT_FOUND: "104:404",
19
+ CONTEXT_LENGTH_EXCEEDED: "105:400",
20
+ LLM_RECORD_FAILED: "106:500",
21
+ LLM_HISTORY_FAILED: "107:500",
22
+ // MCP (200-299)
23
+ MCP_CONNECTION_ERROR: "200:502",
24
+ MCP_PROTOCOL_ERROR: "201:502",
25
+ MCP_TOOL_ERROR: "202:500",
26
+ MCP_RESOURCE_ERROR: "203:500",
27
+ MCP_SERVER_ERROR: "204:502",
28
+ // Embedding (300-399)
29
+ EMBEDDING_API_ERROR: "300:502",
30
+ EMBEDDING_MODEL_NOT_FOUND: "301:404",
31
+ EMBEDDING_INPUT_TOO_LONG: "302:400",
32
+ // 工具 (400-499)
33
+ TOOL_NOT_FOUND: "400:404",
34
+ TOOL_VALIDATION_FAILED: "401:400",
35
+ TOOL_EXECUTION_FAILED: "402:500",
36
+ TOOL_TIMEOUT: "403:504",
37
+ TOOL_ALREADY_REGISTERED: "404:409",
38
+ TOOL_FORBIDDEN: "405:403",
39
+ // Reasoning (500-599)
40
+ REASONING_FAILED: "500:500",
41
+ REASONING_MAX_ROUNDS: "501:400",
42
+ REASONING_STRATEGY_NOT_FOUND: "502:404",
43
+ // Retrieval (600-699)
44
+ RETRIEVAL_FAILED: "600:500",
45
+ RETRIEVAL_SOURCE_NOT_FOUND: "601:404",
46
+ // RAG (700-799)
47
+ RAG_FAILED: "700:500",
48
+ RAG_CONTEXT_BUILD_FAILED: "701:500",
49
+ // Knowledge (800-899)
50
+ KNOWLEDGE_SETUP_FAILED: "800:500",
51
+ KNOWLEDGE_INGEST_FAILED: "801:500",
52
+ KNOWLEDGE_RETRIEVE_FAILED: "802:500",
53
+ KNOWLEDGE_ENTITY_EXTRACT_FAILED: "803:500",
54
+ KNOWLEDGE_NOT_SETUP: "804:500",
55
+ KNOWLEDGE_COLLECTION_NOT_FOUND: "805:404",
56
+ // Memory (900-949)
57
+ MEMORY_EXTRACT_FAILED: "900:500",
58
+ MEMORY_STORE_FAILED: "901:500",
59
+ MEMORY_RECALL_FAILED: "902:500",
60
+ MEMORY_NOT_FOUND: "903:404",
61
+ MEMORY_ENRICH_FAILED: "904:500",
62
+ MEMORY_PROMOTE_FAILED: "905:500",
63
+ MEMORY_LIST_INCOMPLETE: "906:422",
64
+ // Persona (910-919)
65
+ PERSONA_NOT_FOUND: "910:404",
66
+ PERSONA_SAVE_FAILED: "911:500",
67
+ // File (030-049)
68
+ FILE_PARSE_FAILED: "030:500",
69
+ FILE_UNSUPPORTED_FORMAT: "031:400",
70
+ FILE_OCR_FAILED: "032:500",
71
+ FILE_INVALID_CONTENT: "033:400",
72
+ // Audio (050-059)
73
+ AUDIO_INVALID_REQUEST: "050:400",
74
+ AUDIO_MODEL_NOT_FOUND: "051:404",
75
+ AUDIO_PROVIDER_NOT_FOUND: "052:404",
76
+ AUDIO_UNSUPPORTED_INPUT: "053:400",
77
+ AUDIO_UPSTREAM_ERROR: "054:502",
78
+ AUDIO_PROTOCOL_ERROR: "055:502",
79
+ AUDIO_CONNECTION_FAILED: "056:502",
80
+ AUDIO_TIMEOUT: "057:504",
81
+ AUDIO_INPUT_TOO_LARGE: "058:413",
82
+ AUDIO_CANCELLED: "059:499",
83
+ // Image (060-069)
84
+ IMAGE_INVALID_REQUEST: "060:400",
85
+ IMAGE_MODEL_NOT_FOUND: "061:404",
86
+ IMAGE_PROVIDER_NOT_FOUND: "062:404",
87
+ IMAGE_UPSTREAM_ERROR: "063:502",
88
+ IMAGE_PROTOCOL_ERROR: "064:502",
89
+ IMAGE_CANCELLED: "065:499",
90
+ IMAGE_DOWNLOAD_BLOCKED: "066:502",
91
+ IMAGE_TOO_LARGE: "067:413",
92
+ IMAGE_TIMEOUT: "068:504",
93
+ // Context (950-999)
94
+ CONTEXT_COMPRESS_FAILED: "950:500",
95
+ CONTEXT_SUMMARIZE_FAILED: "951:500",
96
+ CONTEXT_TOKEN_ESTIMATE_FAILED: "952:500",
97
+ CONTEXT_BUDGET_EXCEEDED: "953:400",
98
+ CONTEXT_TURN_NOT_FOUND: "954:404",
99
+ CONTEXT_TURN_INVALID_STATE: "955:409",
100
+ CONTEXT_BUSY: "956:409",
101
+ // Store (960-969)
102
+ STORE_FAILED: "960:500",
103
+ STORE_NOT_AVAILABLE: "961:503",
104
+ // Session (970-979)
105
+ SESSION_NOT_FOUND: "970:404",
106
+ SESSION_FAILED: "971:500",
107
+ // A2A (980-999)
108
+ A2A_NOT_CONFIGURED: "980:500",
109
+ A2A_HANDLE_FAILED: "981:500",
110
+ A2A_REMOTE_CALL_FAILED: "982:502",
111
+ A2A_AUTH_FAILED: "983:401",
112
+ A2A_LIST_MESSAGES_FAILED: "984:500"
113
+ };
114
+ var HaiAIError = core.error.buildHaiErrorsDef("ai", AIErrorInfo);
115
+
116
+ export { HaiAIError };
117
+ //# sourceMappingURL=chunk-HYMP57AC.js.map
118
+ //# sourceMappingURL=chunk-HYMP57AC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ai-types.ts"],"names":[],"mappings":"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","file":"chunk-HYMP57AC.js","sourcesContent":["/**\n * @h-ai/ai — 公共类型定义\n *\n * 聚合导出模块根类型和子功能类型,供外部通过 `@h-ai/ai` 一站式引入。\n * @module ai-types\n */\n\nimport type { ErrorInfo, HaiResult } from '@h-ai/core'\nimport type { A2AOperations } from './a2a/ai-a2a-types.js'\n\nimport type { AIConfig, AIConfigInput } from './ai-config.js'\nimport type { AudioOperations } from './audio/ai-audio-types.js'\nimport type { CompressOperations } from './compress/ai-compress-types.js'\nimport type { ContextOperations } from './context/ai-context-types.js'\nimport type { EmbeddingOperations } from './embedding/ai-embedding-types.js'\nimport type { FileOperations } from './file/ai-file-types.js'\nimport type { ImageOperations } from './image/ai-image-types.js'\nimport type { KnowledgeOperations } from './knowledge/ai-knowledge-types.js'\nimport type { LLMOperations, StreamOperations, ToolsOperations } from './llm/ai-llm-types.js'\nimport type { MCPOperations } from './mcp/ai-mcp-types.js'\nimport type { MemoryOperations } from './memory/ai-memory-types.js'\nimport type { PersonaOperations } from './persona/ai-persona-types.js'\nimport type { RagOperations } from './rag/ai-rag-types.js'\nimport type { ReasoningOperations } from './reasoning/ai-reasoning-types.js'\nimport type { RerankOperations } from './rerank/ai-rerank-types.js'\nimport type { RetrievalOperations } from './retrieval/ai-retrieval-types.js'\nimport type { AIStoreProvider } from './store/ai-store-types.js'\nimport type { SummaryOperations } from './summary/ai-summary-types.js'\nimport type { TokenOperations } from './token/ai-token-types.js'\nimport { core } from '@h-ai/core'\n\n// ─── 错误定义(照 @h-ai/core 范式) ───\n\n/**\n * AI 错误信息映射(错误码:HTTP状态码)。\n *\n * 错误码采用 3 位数字格式(000-999),HTTP 状态码遵循标准 HTTP 规范。\n * 完整错误码将自动生成为:`hai:ai:NNN`\n */\nconst AIErrorInfo = {\n // 通用 (000-009)\n INTERNAL_ERROR: '000:500',\n\n // 初始化 (010-019)\n NOT_INITIALIZED: '010:500',\n CONFIGURATION_ERROR: '011:500',\n INIT_IN_PROGRESS: '012:500',\n RERANK_API_ERROR: '020:502',\n RERANK_INVALID_REQUEST: '021:400',\n\n // LLM (100-199)\n API_ERROR: '100:502',\n INVALID_REQUEST: '101:400',\n RATE_LIMITED: '102:429',\n TIMEOUT: '103:504',\n MODEL_NOT_FOUND: '104:404',\n CONTEXT_LENGTH_EXCEEDED: '105:400',\n LLM_RECORD_FAILED: '106:500',\n LLM_HISTORY_FAILED: '107:500',\n\n // MCP (200-299)\n MCP_CONNECTION_ERROR: '200:502',\n MCP_PROTOCOL_ERROR: '201:502',\n MCP_TOOL_ERROR: '202:500',\n MCP_RESOURCE_ERROR: '203:500',\n MCP_SERVER_ERROR: '204:502',\n\n // Embedding (300-399)\n EMBEDDING_API_ERROR: '300:502',\n EMBEDDING_MODEL_NOT_FOUND: '301:404',\n EMBEDDING_INPUT_TOO_LONG: '302:400',\n\n // 工具 (400-499)\n TOOL_NOT_FOUND: '400:404',\n TOOL_VALIDATION_FAILED: '401:400',\n TOOL_EXECUTION_FAILED: '402:500',\n TOOL_TIMEOUT: '403:504',\n TOOL_ALREADY_REGISTERED: '404:409',\n TOOL_FORBIDDEN: '405:403',\n\n // Reasoning (500-599)\n REASONING_FAILED: '500:500',\n REASONING_MAX_ROUNDS: '501:400',\n REASONING_STRATEGY_NOT_FOUND: '502:404',\n\n // Retrieval (600-699)\n RETRIEVAL_FAILED: '600:500',\n RETRIEVAL_SOURCE_NOT_FOUND: '601:404',\n\n // RAG (700-799)\n RAG_FAILED: '700:500',\n RAG_CONTEXT_BUILD_FAILED: '701:500',\n\n // Knowledge (800-899)\n KNOWLEDGE_SETUP_FAILED: '800:500',\n KNOWLEDGE_INGEST_FAILED: '801:500',\n KNOWLEDGE_RETRIEVE_FAILED: '802:500',\n KNOWLEDGE_ENTITY_EXTRACT_FAILED: '803:500',\n KNOWLEDGE_NOT_SETUP: '804:500',\n KNOWLEDGE_COLLECTION_NOT_FOUND: '805:404',\n\n // Memory (900-949)\n MEMORY_EXTRACT_FAILED: '900:500',\n MEMORY_STORE_FAILED: '901:500',\n MEMORY_RECALL_FAILED: '902:500',\n MEMORY_NOT_FOUND: '903:404',\n MEMORY_ENRICH_FAILED: '904:500',\n MEMORY_PROMOTE_FAILED: '905:500',\n MEMORY_LIST_INCOMPLETE: '906:422',\n\n // Persona (910-919)\n PERSONA_NOT_FOUND: '910:404',\n PERSONA_SAVE_FAILED: '911:500',\n\n // File (030-049)\n FILE_PARSE_FAILED: '030:500',\n FILE_UNSUPPORTED_FORMAT: '031:400',\n FILE_OCR_FAILED: '032:500',\n FILE_INVALID_CONTENT: '033:400',\n\n // Audio (050-059)\n AUDIO_INVALID_REQUEST: '050:400',\n AUDIO_MODEL_NOT_FOUND: '051:404',\n AUDIO_PROVIDER_NOT_FOUND: '052:404',\n AUDIO_UNSUPPORTED_INPUT: '053:400',\n AUDIO_UPSTREAM_ERROR: '054:502',\n AUDIO_PROTOCOL_ERROR: '055:502',\n AUDIO_CONNECTION_FAILED: '056:502',\n AUDIO_TIMEOUT: '057:504',\n AUDIO_INPUT_TOO_LARGE: '058:413',\n AUDIO_CANCELLED: '059:499',\n\n // Image (060-069)\n IMAGE_INVALID_REQUEST: '060:400',\n IMAGE_MODEL_NOT_FOUND: '061:404',\n IMAGE_PROVIDER_NOT_FOUND: '062:404',\n IMAGE_UPSTREAM_ERROR: '063:502',\n IMAGE_PROTOCOL_ERROR: '064:502',\n IMAGE_CANCELLED: '065:499',\n IMAGE_DOWNLOAD_BLOCKED: '066:502',\n IMAGE_TOO_LARGE: '067:413',\n IMAGE_TIMEOUT: '068:504',\n\n // Context (950-999)\n CONTEXT_COMPRESS_FAILED: '950:500',\n CONTEXT_SUMMARIZE_FAILED: '951:500',\n CONTEXT_TOKEN_ESTIMATE_FAILED: '952:500',\n CONTEXT_BUDGET_EXCEEDED: '953:400',\n CONTEXT_TURN_NOT_FOUND: '954:404',\n CONTEXT_TURN_INVALID_STATE: '955:409',\n CONTEXT_BUSY: '956:409',\n\n // Store (960-969)\n STORE_FAILED: '960:500',\n STORE_NOT_AVAILABLE: '961:503',\n\n // Session (970-979)\n SESSION_NOT_FOUND: '970:404',\n SESSION_FAILED: '971:500',\n\n // A2A (980-999)\n A2A_NOT_CONFIGURED: '980:500',\n A2A_HANDLE_FAILED: '981:500',\n A2A_REMOTE_CALL_FAILED: '982:502',\n A2A_AUTH_FAILED: '983:401',\n A2A_LIST_MESSAGES_FAILED: '984:500',\n} as const satisfies ErrorInfo\n\n/**\n * AI 模块标准错误定义。通过错误码比较分支,用户文案由业务边界本地化。\n *\n * @example\n * ```ts\n * import { HaiAIError } from '@h-ai/ai'\n * import { err } from '@h-ai/core'\n * const result = err(HaiAIError.NOT_INITIALIZED, 'AI is not initialized')\n * if (!result.success) {\n * const status = result.error.httpStatus\n * const code = result.error.code\n * }\n * ```\n */\nexport const HaiAIError = core.error.buildHaiErrorsDef('ai', AIErrorInfo)\n\n// ─── 初始化选项 ───\n\n/**\n * AI 初始化运行时选项\n *\n * 用于传入运行时对象(如自定义 StoreProvider),\n * 这些对象无法通过 Zod 配置 Schema 传递。\n *\n * @example\n * ```ts\n * import { ai, type AIConfigInput, type AIInitOptions, type AIStoreProvider } from '@h-ai/ai'\n * async function start(config: AIConfigInput, storeProvider: AIStoreProvider) {\n * const options: AIInitOptions = { storeProvider }\n * const result = await ai.init(config, options)\n * if (!result.success) throw new Error(result.error.message)\n * }\n * ```\n */\nexport interface AIInitOptions {\n /**\n * 自定义存储 Provider\n *\n * 提供后 AI 模块将使用此 Provider,而不采用自动选择的存储实现。\n * 未提供时:reldb + vecdb 已初始化则使用持久化 DB Provider,否则使用进程内临时 Provider。\n */\n storeProvider?: AIStoreProvider\n}\n\n// ─── AIFunctions 接口 ───\n\n/**\n * AI 服务接口(通过 `ai` 对象访问)\n *\n * 所有 AI 功能的统一入口,需先调用 `init()` 初始化后才能使用 `llm`、`mcp` 操作。\n * `tools` 和 `stream` 为纯函数,无需初始化即可使用。\n *\n * @example\n * ```ts\n * import { ai, type AIConfigInput, type AIInitOptions } from '@h-ai/ai'\n * // 一次性脚本示例;服务应用在启动阶段 init,在停止接入请求后 close。\n * async function run(config: AIConfigInput, options: AIInitOptions) {\n * const ready = await ai.init(config, options)\n * if (!ready.success) throw new Error(ready.error.message)\n * try {\n * const answer = await ai.llm.ask('你好', { objectId: 'user-1' })\n * if (!answer.success) throw new Error(answer.error.message)\n * return answer.data\n * }\n * finally {\n * await ai.close()\n * }\n * }\n * ```\n */\nexport interface AIFunctions {\n /**\n * 初始化 AI 服务\n *\n * 使用 Zod Schema 校验配置,失败返回 `CONFIGURATION_ERROR`。\n * 重复调用会先关闭旧实例再重新初始化。\n *\n * @param config - AI 配置(可选,默认使用空对象并应用 Schema 默认值)\n * @param options - 运行时选项(可选,用于传入自定义 StoreProvider 等运行时对象)\n * @returns 成功返回 `ok(undefined)`;配置校验失败返回 `err(HaiAIError.CONFIGURATION_ERROR)`\n */\n init: (config?: AIConfigInput, options?: AIInitOptions) => Promise<HaiResult<void>>\n /**\n * 关闭 AI 服务,释放内部状态\n *\n * 关闭后 `llm`、`mcp` 操作将返回 `NOT_INITIALIZED` 错误。\n * 重复关闭不会报错。\n */\n close: () => Promise<void>\n /** 当前脱敏后的配置快照(未初始化时为 `null`) */\n readonly config: AIConfig | null\n /** 是否已初始化(`init()` 成功后为 `true`,`close()` 后为 `false`) */\n readonly isInitialized: boolean\n /** LLM 操作(聊天、流式、模型列表),需要先调用 `init()` */\n readonly llm: LLMOperations\n /** MCP 操作(工具/资源/提示词注册与调用),需要先调用 `init()` */\n readonly mcp: MCPOperations\n /** 工具操作(定义工具与注册表),纯函数,无需初始化 */\n readonly tools: ToolsOperations\n /** 流处理操作(流处理器、SSE 编解码),纯函数,无需初始化 */\n readonly stream: StreamOperations\n /** Embedding 操作(向量嵌入),需要先调用 `init()` */\n readonly embedding: EmbeddingOperations\n /** 推理操作(ReAct / CoT / Plan-Execute),需要先调用 `init()` */\n readonly reasoning: ReasoningOperations\n /** 检索操作(向量检索),需要先调用 `init()` */\n readonly retrieval: RetrievalOperations\n /** RAG 操作(检索增强生成),需要先调用 `init()` */\n readonly rag: RagOperations\n /** Knowledge 操作(知识库管理与检索),需要先调用 `init()` 和 `knowledge.setup()` */\n readonly knowledge: KnowledgeOperations\n /** Memory 操作(记忆提取、存储、检索、注入),需要先调用 `init()` */\n readonly memory: MemoryOperations\n /** Persona 操作(AI 角色人格档案与系统提示词组合),需要先调用 `init()` */\n readonly persona: PersonaOperations\n /** Token 操作(Token 估算),需要先调用 `init()` */\n readonly token: TokenOperations\n /** Summary 操作(消息摘要生成),需要先调用 `init()` */\n readonly summary: SummaryOperations\n /** Compress 操作(上下文压缩),需要先调用 `init()` */\n readonly compress: CompressOperations\n /** Context 操作(有状态上下文管理器,编排 LLM + Memory + RAG + Reasoning),需要先调用 `init()` */\n readonly context: ContextOperations\n /** Rerank 操作(文档重排序),需要先调用 `init()` */\n readonly rerank: RerankOperations\n /** File 操作(文件内容解析),需要先调用 `init()` */\n readonly file: FileOperations\n /** A2A 操作(Agent-to-Agent 协议),需要先调用 `init()` 并配置 `a2a` */\n readonly a2a: A2AOperations\n /** Audio 操作(语音识别 / 语音合成),需要先调用 `init()` 并配置 `audio` */\n readonly audio: AudioOperations\n /** Image 操作(文生图),需要先调用 `init()` 并配置 `image` */\n readonly image: ImageOperations\n}\n"]}
@@ -1,266 +1,98 @@
1
- import { ac as ChatCompletionRequest, ad as ChatCompletionResponse, aa as ChatCompletionChunk, aD as KnowledgeRetrieveResult, aq as KnowledgeAskResult, az as KnowledgeIngestResult, ar as KnowledgeDocumentInfo, aJ as MemoryEntry, be as StorePage, aK as MemoryEntryInput, aR as MemoryUpdateInput, bc as SessionInfo, ag as ChatRecord, aY as RagResult, b0 as ReasoningResult, O as A2AAgentCardConfig, _ as A2AMessageRecord, V as A2ACallResult } from '../ai-reasoning-types-CGUgkLF7.js';
2
- import { HaiResult } from '@h-ai/core';
3
- import '@a2a-js/sdk/server';
4
- import '@h-ai/datapipe';
5
- import 'zod';
6
- import 'openai';
1
+ import { m as TranscriptionRequest, n as TranscriptionResult, p as TranscriptionStreamRequest, T as TranscriptionEvent, h as SynthesisRequest, i as SynthesisResult, j as SynthesisStreamRequest, S as SynthesisEvent } from '../ai-audio-types-4R5yUAVl.js';
2
+ import '@h-ai/core';
7
3
 
8
4
  /**
9
- * @h-ai/ai — 前端 AI 客户端
5
+ * @h-ai/ai/client — 浏览器语音客户端
10
6
  *
11
- * 基于 @h-ai/api-client 的 AI 领域客户端。
12
- * 通过 `createAIClient()` 工厂函数创建,消除自建 HTTP 层,
13
- * 复用 api-client 提供的 Token 管理、超时、拦截器等基础能力。
14
- * @module ai-client
7
+ * 通过统一 WebSocket 连接 `@h-ai/serv` 的语音入口,向浏览器暴露与 Node 端一致的
8
+ * `ai.audio.*` 业务 API。WebSocket 建立、消息编解码等传输细节在此内部完成,
9
+ * 调用方不接触任何厂商原生事件。
10
+ * @module client/ai-audio-client
15
11
  */
16
12
 
17
13
  /**
18
- * AI 客户端所需的 API 调用能力
14
+ * getTicket 收到的当前 Audio 请求摘要
19
15
  *
20
- * 结构兼容 `@h-ai/api-client` 的 `api` 单例(鸭子类型)。
21
- * 传入 `api` 单例即可,无需额外适配。
22
- */
23
- interface AIApiAdapter {
24
- /** POST 请求(返回 HaiResult) */
25
- post: <T>(path: string, body?: unknown) => Promise<HaiResult<T>>;
26
- /** 流式请求(返回 SSE data 行的 AsyncIterable) */
27
- stream: (path: string, body?: unknown) => AsyncIterable<string>;
28
- }
29
- /**
30
- * AI 客户端配置
16
+ * 供应用签发与本次操作严格绑定的能力票据(如 `iam.ticket.issue({ grant })`),
17
+ * 使票据只能用于本次操作 / 模型 / 会话,降低票据被重放的风险。
31
18
  *
32
19
  * @example
33
20
  * ```ts
34
- * import { api } from '@h-ai/api-client'
35
- * import { createAIClient } from '@h-ai/ai/client'
36
- *
37
- * await api.init({ baseUrl: '/api', auth: { ... } })
38
- * const aiClient = createAIClient({ api })
21
+ * import type { AudioTicketRequest } from '@h-ai/ai/client'
22
+ * function grant(request: AudioTicketRequest) {
23
+ * return { operation: request.operation, model: request.model } // 经已登录 HTTP 接口签发并在服务端原子消费。
24
+ * }
39
25
  * ```
40
26
  */
41
- interface AIClientConfig {
42
- /**
43
- * API 调用适配器
44
- *
45
- * 传入 `api` 单例(初始化后)。
46
- * baseUrl、Token 管理、超时等通过 api-client 配置。
47
- */
48
- api: AIApiAdapter;
49
- }
50
- /** 流式响应进度(`onProgress` 回调参数) */
51
- interface StreamProgress {
52
- /** 当前累积的文本内容 */
53
- content: string;
54
- /** 是否已完成 */
55
- done: boolean;
56
- /** 完成原因(仅 `done=true` 时有值,如 `'stop'`) */
57
- finishReason?: string;
58
- }
59
- /** 流式响应选项 */
60
- interface StreamOptions {
61
- /** 进度回调(每次收到 chunk 时触发) */
62
- onProgress?: (progress: StreamProgress) => void;
27
+ interface AudioTicketRequest {
28
+ /** 本次操作类型 */
29
+ operation: 'transcribe' | 'synthesize';
30
+ /** 本次使用的模型 ID(如有指定) */
31
+ model?: string;
63
32
  }
64
33
  /**
65
- * AI 客户端接口
66
- *
67
- * 提供浏览器端调用 AI API 的能力,HTTP 基础设施委托给 @h-ai/api-client。
68
- */
69
- interface AIClient {
70
- /** 发送对话请求(非流式) */
71
- chat: (request: ChatCompletionRequest) => Promise<ChatCompletionResponse>;
72
- /** 发送流式对话请求,返回异步迭代器 */
73
- chatStream: (request: ChatCompletionRequest, options?: StreamOptions) => AsyncIterable<ChatCompletionChunk>;
74
- /** 便捷方法:发送纯文本消息并返回回复文本 */
75
- sendMessage: (message: string, systemPrompt?: string) => Promise<string>;
76
- /** 便捷方法:流式发送纯文本消息并返回完整回复 */
77
- sendMessageStream: (message: string, options?: StreamOptions, systemPrompt?: string) => Promise<string>;
78
- /** 简单问答(单轮,自动构造 messages) */
79
- ask: (question: string, options?: {
80
- systemPrompt?: string;
81
- model?: string;
82
- }) => Promise<string>;
83
- /** 流式简单问答,返回异步文本流 */
84
- askStream: (question: string, options?: {
85
- systemPrompt?: string;
86
- model?: string;
87
- }) => AsyncIterable<string>;
88
- /** 知识检索(向量 + 实体增强) */
89
- knowledgeRetrieve: (query: string, options?: {
90
- topK?: number;
91
- collection?: string;
92
- }) => Promise<KnowledgeRetrieveResult>;
93
- /** 知识问答(RAG + 信源) */
94
- knowledgeAsk: (query: string, options?: {
95
- model?: string;
96
- collection?: string;
97
- }) => Promise<KnowledgeAskResult>;
98
- /** 导入文档 */
99
- knowledgeIngest: (input: {
100
- documentId: string;
101
- content: string;
102
- title?: string;
103
- collection?: string;
104
- metadata?: Record<string, unknown>;
105
- }) => Promise<KnowledgeIngestResult>;
106
- /** 列出已导入文档 */
107
- knowledgeListDocuments: (options?: {
108
- collection?: string;
109
- offset?: number;
110
- limit?: number;
111
- }) => Promise<KnowledgeDocumentInfo[]>;
112
- /** 删除已导入文档 */
113
- knowledgeRemoveDocument: (documentId: string, options?: {
114
- collection?: string;
115
- }) => Promise<void>;
116
- /** 检索相关记忆 */
117
- recallMemories: (query: string, options?: {
118
- topK?: number;
119
- types?: string[];
120
- minImportance?: number;
121
- objectId?: string;
122
- }) => Promise<MemoryEntry[]>;
123
- /** 列出记忆(分页) */
124
- listMemories: (options?: {
125
- types?: string[];
126
- objectId?: string;
127
- offset?: number;
128
- limit?: number;
129
- }) => Promise<StorePage<MemoryEntry>>;
130
- /** 添加记忆 */
131
- addMemory: (entry: MemoryEntryInput) => Promise<MemoryEntry>;
132
- /** 更新记忆 */
133
- updateMemory: (memoryId: string, updates: MemoryUpdateInput) => Promise<MemoryEntry>;
134
- /** 删除记忆 */
135
- removeMemory: (memoryId: string) => Promise<void>;
136
- /** 列出会话 */
137
- listSessions: (objectId: string) => Promise<SessionInfo[]>;
138
- /** 重命名会话 */
139
- renameSession: (sessionId: string, title: string) => Promise<void>;
140
- /** 删除会话 */
141
- removeSession: (sessionId: string) => Promise<void>;
142
- /** 获取对话历史 */
143
- chatHistory: (objectId: string, sessionId: string, options?: {
144
- limit?: number;
145
- order?: 'asc' | 'desc';
146
- }) => Promise<ChatRecord[]>;
147
- /** RAG 查询(检索 + 生成) */
148
- ragQuery: (query: string, options?: {
149
- collection?: string;
150
- topK?: number;
151
- model?: string;
152
- }) => Promise<RagResult>;
153
- /** RAG 流式查询,返回 SSE 数据行 */
154
- ragQueryStream: (query: string, options?: {
155
- collection?: string;
156
- topK?: number;
157
- model?: string;
158
- }) => AsyncIterable<string>;
159
- /** 推理(多步思考) */
160
- reasoningRun: (query: string, options?: {
161
- model?: string;
162
- maxSteps?: number;
163
- }) => Promise<ReasoningResult>;
164
- /** 推理流式,返回 SSE 数据行 */
165
- reasoningRunStream: (query: string, options?: {
166
- model?: string;
167
- maxSteps?: number;
168
- }) => AsyncIterable<string>;
169
- /** 估算文本的 Token 数 */
170
- estimateTokens: (text: string) => Promise<{
171
- tokens: number;
172
- }>;
173
- }
174
- /**
175
- * 创建 AI 客户端
176
- *
177
- * 通过 @h-ai/api-client 的 ApiClient 实例调用后端 AI API。
178
- * HTTP 层(Token、超时、拦截器)全部复用 api-client,本模块仅负责:
179
- * - 非流式 / 流式 ChatCompletion 协议适配
180
- * - SSE 解析与 ChatCompletionChunk 类型化
181
- * - onProgress 进度回调
182
- *
183
- * @param config - 客户端配置
184
- * @returns AI 客户端实例
34
+ * 浏览器语音客户端配置
185
35
  *
186
36
  * @example
187
37
  * ```ts
188
- * import { api } from '@h-ai/api-client'
189
- * import { createAIClient } from '@h-ai/ai/client'
190
- *
191
- * await api.init({ baseUrl: '/api' })
192
- * const client = createAIClient({ api })
193
- * const reply = await client.sendMessage('你好')
38
+ * import { createAudioClient } from '@h-ai/ai/client'
39
+ * import type { AudioTicketRequest } from '@h-ai/ai/client'
40
+ * function connect(issueTicket: (request: AudioTicketRequest) => Promise<string>) {
41
+ * return createAudioClient({ url: 'wss://example.com/api/v1/ai/audio', getTicket: issueTicket })
42
+ * }
194
43
  * ```
195
44
  */
196
- declare function createAIClient(config: AIClientConfig): AIClient;
45
+ interface AudioClientConfig {
46
+ /** 语音 WebSocket 完整 URL(如 `wss://host/api/v1/ai/audio`) */
47
+ url: string;
48
+ /**
49
+ * 获取短期、一次性的 Audio WebSocket ticket
50
+ *
51
+ * ticket 应由已登录 HTTP 请求签发,并在服务端首次校验时原子消费。
52
+ * 收到当前请求摘要(operation / model),可签发与本次操作严格绑定的票据。
53
+ */
54
+ getTicket: (request: AudioTicketRequest) => string | Promise<string>;
55
+ }
197
56
  /**
198
- * 从 fetch Response 中解析 SSE data 字段
57
+ * 浏览器语音操作接口
199
58
  *
200
- * 自动处理分片缓冲和 `[DONE]` 结束标记。
201
- *
202
- * @param response - fetch 响应对象
203
- * @yields SSE data 字符串(不含 `[DONE]`)
59
+ * 与 Node 端 `AudioOperations` 业务形态一致;出错时抛出异常(浏览器 Client 约定)。
204
60
  *
205
61
  * @example
206
62
  * ```ts
207
- * const resp = await fetch('/api/chat', { method: 'POST', body })
208
- * for await (const data of parseSSE(resp)) {
209
- * const chunk = JSON.parse(data) // ChatCompletionChunk
63
+ * import type { AudioClientOperations } from '@h-ai/ai/client'
64
+ * async function speak(audio: AudioClientOperations) {
65
+ * // 浏览器 AudioClient 普通方法也显式抛错,由应用交互边界处理。
66
+ * const result = await audio.synthesize({ text: '你好', format: 'mp3' })
67
+ * return result.data
210
68
  * }
211
69
  * ```
212
70
  */
213
- declare function parseSSE(response: Response): AsyncIterable<string>;
71
+ interface AudioClientOperations {
72
+ /** 将完整音频识别为完整文本 */
73
+ transcribe: (request: TranscriptionRequest) => Promise<TranscriptionResult>;
74
+ /** 持续输入音频或增量返回识别文本(含语音起止事件) */
75
+ transcribeStream: (request: TranscriptionStreamRequest) => AsyncIterable<TranscriptionEvent>;
76
+ /** 将完整文本合成为完整音频 */
77
+ synthesize: (request: SynthesisRequest) => Promise<SynthesisResult>;
78
+ /** 持续输入文本段并按段输出结构化音频事件 */
79
+ synthesizeStream: (request: SynthesisStreamRequest) => AsyncIterable<SynthesisEvent>;
80
+ }
214
81
  /**
215
- * 收集流式响应的完整文本内容
82
+ * 创建浏览器语音客户端
216
83
  *
217
- * 完整消费流并拼接所有 `delta.content` 片段。
218
- *
219
- * @param stream - 聊天响应块流
220
- * @returns 完整文本
84
+ * @param config - 语音客户端配置
85
+ * @returns 浏览器语音操作接口
221
86
  *
222
87
  * @example
223
88
  * ```ts
224
- * const client = createAIClient({ api })
225
- * const stream = client.chatStream({ messages })
226
- * const fullText = await collectStreamContent(stream)
89
+ * import { createAudioClient } from '@h-ai/ai/client'
90
+ * import type { AudioTicketRequest } from '@h-ai/ai/client'
91
+ * function connect(issueTicket: (request: AudioTicketRequest) => Promise<string>) {
92
+ * return createAudioClient({ url: 'wss://example.com/api/v1/ai/audio', getTicket: issueTicket })
93
+ * }
227
94
  * ```
228
95
  */
229
- declare function collectStreamContent(stream: AsyncIterable<ChatCompletionChunk>): Promise<string>;
230
-
231
- /**
232
- * @h-ai/ai — 前端 A2A 客户端
233
- *
234
- * 浏览器端 A2A 操作客户端,通过 API 服务调用后端 A2A 能力。
235
- * @module ai-a2a-client
236
- */
237
-
238
- /**
239
- * A2A 客户端接口
240
- *
241
- * 提供浏览器端调用后端 A2A API 的能力。
242
- */
243
- interface A2AClientOperations {
244
- /** 获取当前 Agent Card 配置 */
245
- getAgentCard: () => Promise<A2AAgentCardConfig>;
246
- /** 查询 A2A 消息记录 */
247
- listMessages: (filter?: {
248
- contextId?: string;
249
- status?: string;
250
- limit?: number;
251
- offset?: number;
252
- }) => Promise<StorePage<A2AMessageRecord>>;
253
- /** 作为客户端调用远端 Agent */
254
- callRemoteAgent: (remoteUrl: string, message: string, options?: {
255
- timeout?: number;
256
- }) => Promise<A2ACallResult>;
257
- }
258
- /**
259
- * 创建 A2A 客户端
260
- *
261
- * @param api - API 适配器(来自 @h-ai/api-client)
262
- * @returns A2A 客户端操作实例
263
- */
264
- declare function createA2AClient(api: AIApiAdapter): A2AClientOperations;
96
+ declare function createAudioClient(config: AudioClientConfig): AudioClientOperations;
265
97
 
266
- export { type A2AClientOperations, type AIApiAdapter, type AIClient, type AIClientConfig, type StreamOptions, type StreamProgress, collectStreamContent, createA2AClient, createAIClient, parseSSE };
98
+ export { type AudioClientConfig, type AudioClientOperations, type AudioTicketRequest, createAudioClient };
@@ -1,3 +1,4 @@
1
- export { collectStreamContent, createA2AClient, createAIClient, parseSSE } from '../chunk-ABP7RKIP.js';
1
+ export { createAudioClient } from '../chunk-GMQFIWND.js';
2
+ import '../chunk-HYMP57AC.js';
2
3
  //# sourceMappingURL=index.js.map
3
4
  //# sourceMappingURL=index.js.map
package/dist/index.d.ts CHANGED
@@ -1,13 +1,20 @@
1
- export { O as A2AAgentCardConfig, P as A2AApiKeySecurity, Q as A2AAuthenticator, U as A2ACallOptions, V as A2ACallResult, W as A2ACallerIdentity, X as A2AClientCallRecord, A as A2AConfig, a as A2AConfigSchema, Y as A2AContextInfo, Z as A2AHandleResult, _ as A2AMessageRecord, $ as A2AOperations, a0 as A2ASecurityConfig, b as A2ASkillConfigSchema, a1 as A2ATaskFilter, c as AIConfig, d as AIConfigInput, e as AIConfigSchema, a2 as AILLMFunctionsDeps, a3 as AIRelStore, a4 as AIRelStoreOptions, a5 as AIStoreProvider, a6 as AIVectorStore, a7 as AskOptions, a8 as AssistantMessage, a9 as ChatCompletionChoice, aa as ChatCompletionChunk, ab as ChatCompletionDelta, ac as ChatCompletionRequest, ad as ChatCompletionResponse, ae as ChatHistoryOptions, af as ChatMessage, ag as ChatRecord, ah as Citation, C as CompressConfig, f as CompressConfigSchema, ai as DefineToolOptions, E as EmbeddingConfig, g as EmbeddingConfigSchema, aj as EntityDocumentRelation, ak as EntityDocumentResult, al as EntityListOptions, am as EntityQueryOptions, h as EntityType, i as EntityTypeSchema, F as FileConfig, j as FileConfigSchema, an as ImageContent, ao as InteractionScope, ap as KnowledgeAskOptions, aq as KnowledgeAskResult, K as KnowledgeConfig, k as KnowledgeConfigSchema, ar as KnowledgeDocumentInfo, as as KnowledgeDocumentListOptions, at as KnowledgeDocumentRemoveOptions, au as KnowledgeEntity, av as KnowledgeIngestBatchProgress, aw as KnowledgeIngestBatchResult, ax as KnowledgeIngestFileInput, ay as KnowledgeIngestInput, az as KnowledgeIngestResult, aA as KnowledgeOperations, aB as KnowledgeRetrieveItem, aC as KnowledgeRetrieveOptions, aD as KnowledgeRetrieveResult, aE as KnowledgeSetupOptions, aF as KnowledgeStore, L as LLMConfig, l as LLMConfigSchema, aG as LLMOperations, aH as LLMProvider, M as MCPConfig, m as MCPConfigSchema, n as MCPServerCapabilities, o as MCPServerCapabilitiesSchema, p as MCPServerConfig, q as MCPServerConfigSchema, aI as MemoryClearOptions, r as MemoryConfig, s as MemoryConfigSchema, aJ as MemoryEntry, aK as MemoryEntryInput, aL as MemoryExtractOptions, aM as MemoryInjectionOptions, aN as MemoryListOptions, aO as MemoryListPageOptions, aP as MemoryOperations, aQ as MemoryRecallOptions, t as MemoryType, u as MemoryTypeSchema, aR as MemoryUpdateInput, aS as MessageContent, aT as MessageRole, v as ModelEntry, w as ModelEntrySchema, x as ModelScenario, y as ModelScenarioSchema, aU as ObjectRef, aV as RagContextItem, aW as RagOperations, aX as RagOptions, aY as RagResult, aZ as RagStreamEvent, a_ as ReasoningOperations, a$ as ReasoningOptions, b0 as ReasoningResult, b1 as ReasoningStep, b2 as ReasoningStepType, b3 as ReasoningStrategy, b4 as ReasoningStreamEvent, R as ResolveRequiredModelEntryOptions, z as ResolvedModelConfig, B as RetrievalConfig, D as RetrievalConfigSchema, b5 as RetrievalOperations, b6 as RetrievalRequest, b7 as RetrievalResult, b8 as RetrievalResultItem, b9 as RetrievalSource, G as RetrievalSourceConfig, H as RetrievalSourceSchema, ba as SSEDecoder, bb as SSEEvent, bc as SessionInfo, bd as StoreFilter, be as StorePage, bf as StoreScope, bg as StreamOperations, bh as StreamProcessor, bi as StreamResult, S as SummaryConfig, I as SummaryConfigSchema, bj as SystemMessage, bk as TextContent, T as TokenConfig, J as TokenConfigSchema, bl as TokenUsage, bm as Tool, bn as ToolCall, bo as ToolDefinition, bp as ToolErrorType, bq as ToolMessage, br as ToolRegistryOperations, bs as ToolsOperations, bt as UserMessage, bu as WhereClause, bv as WhereOperator, bw as WhereValue, N as resolveModelEntry } from './ai-reasoning-types-CGUgkLF7.js';
2
- import { A as AIFunctions } from './ai-types-CRCjluXI.js';
3
- export { a as AIInitOptions, c as AIMCPFunctionsDeps, d as CompressOperations, e as CompressOptions, f as CompressResult, C as CompressionStrategy, b as CompressionStrategySchema, g as ContextChatOptions, h as ContextChatResult, i as ContextDeps, j as ContextManager, k as ContextManagerOptions, l as ContextOperations, m as ContextStreamEvent, E as EmbeddingItem, n as EmbeddingOperations, o as EmbeddingProvider, p as EmbeddingRequest, q as EmbeddingResponse, F as FileOperations, r as FileParseMethod, s as FileParseOptions, t as FileParseRequest, u as FileParseResult, H as HaiAIError, M as MCPContext, v as MCPOperations, w as MCPPrompt, x as MCPPromptArgument, y as MCPPromptContent, z as MCPPromptMessage, B as MCPProvider, D as MCPResource, G as MCPResourceContent, I as MCPToolDefinition, J as MCPToolHandler, K as McpServerOptions, O as OutputFormat, R as RerankDocument, L as RerankItem, N as RerankOperations, P as RerankRequest, Q as RerankResponse, S as SummaryOperations, T as SummaryOptions, U as SummaryResult, V as TokenOperations } from './ai-types-CRCjluXI.js';
4
- export { TaskStore as A2ATaskStore, AgentExecutor, ExecutionEventBus, RequestContext, ServerCallContext } from '@a2a-js/sdk/server';
1
+ import { r as AIFunctions, bK as McpServerOptions } from './ai-audio-ws-protocol-nfhO0tOo.js';
2
+ export { A as A2AAgentCardConfig, a as A2AApiKeySecurity, b as A2AAuthenticator, c as A2ACallOptions, d as A2ACallResult, e as A2ACallerIdentity, f as A2AConfig, g as A2AConfigSchema, h as A2AContextInfo, i as A2AHandleResult, j as A2AMessageRecord, k as A2AOperations, l as A2ASecurityConfig, m as A2ASkillConfigSchema, n as A2ATaskFilter, o as AIConfig, p as AIConfigInput, q as AIConfigSchema, s as AIInitOptions, t as AIRelStore, u as AIRelStoreCompareAndSwap, v as AIRelStoreOptions, w as AIStoreProvider, x as AIVectorBackend, y as AIVectorStore, z as AIVersionedRecord, B as AUDIO_WS_PATH, C as ApiType, D as ApiTypeSchema, E as AskOptions, F as AssistantMessage, G as AudioConfig, H as AudioConfigSchema, I as AudioFormatSchema, J as AudioModelEntry, K as AudioModelEntrySchema, L as AudioOperation, M as AudioOperationSchema, N as AudioOperationsSchema, O as AudioProviderName, P as AudioProviderSchema, Q as AudioWsClientMessage, R as AudioWsClientMessageSchema, S as AudioWsDoneMessage, T as AudioWsDoneMessageSchema, U as AudioWsEndMessage, V as AudioWsErrorMessage, W as AudioWsSegmentDoneMessage, X as AudioWsSegmentStartedMessage, Y as AudioWsServerMessage, Z as AudioWsSpeechMessage, _ as AudioWsStartMessage, $ as AudioWsStartMessageSchema, a0 as AudioWsTextMessage, a1 as AudioWsTextMessageSchema, a2 as AudioWsTranscriptMessage, a3 as ChatCompletionChoice, a4 as ChatCompletionChunk, a5 as ChatCompletionDelta, a6 as ChatCompletionRequest, a7 as ChatCompletionResponse, a8 as ChatHistoryOptions, a9 as ChatMessage, aa as ChatRecord, ab as Citation, ac as CommitTurnInput, ad as CompressConfig, ae as CompressConfigSchema, af as CompressOperations, ag as CompressOptions, ah as CompressResult, ai as CompressionStrategy, aj as CompressionStrategySchema, ak as ConsolidateOptions, al as ConsolidateResult, am as ContextChatOptions, an as ContextChatResult, ao as ContextManager, ap as ContextManagerOptions, aq as ContextOperations, ar as ContextResetOptions, as as ContextStreamEvent, at as ConversationTurn, au as ConversationTurnStatus, av as DefineToolOptions, aw as DeveloperMessage, ax as EmbeddingConfig, ay as EmbeddingConfigSchema, az as EmbeddingItem, aA as EmbeddingOperations, aB as EmbeddingRequest, aC as EmbeddingResponse, aD as EntityDocumentRelation, aE as EntityDocumentResult, aF as EntityListOptions, aG as EntityQueryOptions, aH as EntityType, aI as EntityTypeSchema, aJ as FileConfig, aK as FileConfigSchema, aL as FileOperations, aM as FileParseMethod, aN as FileParseOptions, aO as FileParseRequest, aP as FileParseResult, aQ as GenerateImageRequest, aR as GenerateImageResult, aS as GenerateObjectRequest, aT as GeneratedImage, aU as HaiAIError, aV as ImageConfig, aW as ImageConfigSchema, aX as ImageContent, aY as ImageModelEntry, aZ as ImageModelEntrySchema, a_ as ImageOperations, a$ as ImageProviderName, b0 as ImageProviderSchema, b1 as ImageSize, b2 as InteractionScope, b3 as KnowledgeAskOptions, b4 as KnowledgeAskResult, b5 as KnowledgeConfig, b6 as KnowledgeConfigSchema, b7 as KnowledgeDocumentInfo, b8 as KnowledgeDocumentListOptions, b9 as KnowledgeDocumentMetadata, ba as KnowledgeDocumentRemoveOptions, bb as KnowledgeDocumentRevision, bc as KnowledgeEntity, bd as KnowledgeIngestBatchProgress, be as KnowledgeIngestBatchResult, bf as KnowledgeIngestFileInput, bg as KnowledgeIngestInput, bh as KnowledgeIngestResult, bi as KnowledgeOperations, bj as KnowledgeRepairOptions, bk as KnowledgeRepairProgress, bl as KnowledgeRepairResult, bm as KnowledgeRetrieveItem, bn as KnowledgeRetrieveOptions, bo as KnowledgeRetrieveResult, bp as KnowledgeSetupOptions, bq as KnowledgeStore, br as LLMConfig, bs as LLMConfigSchema, bt as LLMOperations, bu as MCPConfig, bv as MCPConfigSchema, bw as MCPContext, bx as MCPOperations, by as MCPPrompt, bz as MCPPromptArgument, bA as MCPPromptContent, bB as MCPPromptMessage, bC as MCPResource, bD as MCPResourceContent, bE as MCPServerCapabilities, bF as MCPServerCapabilitiesSchema, bG as MCPServerConfig, bH as MCPServerConfigSchema, bI as MCPToolDefinition, bJ as MCPToolHandler, bL as MemoryAccessScope, bM as MemoryAdminOperations, bN as MemoryClearAllOptions, bO as MemoryClearOptions, bP as MemoryConfig, bQ as MemoryConfigSchema, bR as MemoryCoreOperations, bS as MemoryEntry, bT as MemoryEntryInput, bU as MemoryExtractOptions, bV as MemoryInjectionOptions, bW as MemoryListOptions, bX as MemoryListPageOptions, bY as MemoryOperations, bZ as MemoryRecallOptions, b_ as MemoryType, b$ as MemoryTypeSchema, c0 as MemoryUpdateInput, c1 as MessageContent, c2 as MessageRole, c3 as ModelEntry, c4 as ModelEntrySchema, c5 as ModelScenario, c6 as ModelScenarioSchema, c7 as ObjectRef, c8 as OptionalSecretSchema, c9 as OutputFormat, ca as PersonaOperations, cb as PersonaProfile, cc as PersonaProfileInput, cd as PersonaProfileUpdate, ce as PersonaScopeOptions, cf as RagContextItem, cg as RagOperations, ch as RagOptions, ci as RagResult, cj as RagStreamEvent, ck as ReasoningOperations, cl as ReasoningOptions, cm as ReasoningResult, cn as ReasoningStep, co as ReasoningStepType, cp as ReasoningStrategy, cq as ReasoningStreamEvent, cr as ReferenceImage, cs as RerankDocument, ct as RerankItem, cu as RerankOperations, cv as RerankRequest, cw as RerankResponse, cx as ResolveRequiredModelEntryOptions, cy as ResolvedAudioModel, cz as ResolvedImageModel, cA as ResolvedModelConfig, cB as RetrievalConfig, cC as RetrievalConfigSchema, cD as RetrievalOperations, cE as RetrievalRequest, cF as RetrievalResult, cG as RetrievalResultItem, cH as RetrievalSource, cI as RetrievalSourceConfig, cJ as RetrievalSourceSchema, cK as SSEDecoder, cL as SSEEvent, cM as ScopedMemoryBinding, cN as ScopedMemoryOperations, cO as SessionInfo, cP as StoreFilter, cQ as StorePage, cR as StoreScope, cS as StreamOperations, cT as StreamProcessor, cU as StreamResult, cV as SummaryConfig, cW as SummaryConfigSchema, cX as SummaryOperations, cY as SummaryOptions, cZ as SummaryResult, c_ as SystemMessage, c$ as TempModelConfig, d0 as TextContent, d1 as TokenConfig, d2 as TokenConfigSchema, d3 as TokenOperations, d4 as TokenUsage, d5 as Tool, d6 as ToolAuthorizationRequest, d7 as ToolAuthorizer, d8 as ToolCall, d9 as ToolDefinition, da as ToolErrorType, db as ToolExecutionContext, dc as ToolExecutionOptions, dd as ToolMessage, de as ToolRegistryOperations, df as ToolRegistryOptions, dg as ToolsOperations, dh as UserMessage, di as WhereClause, dj as WhereOperator, dk as WhereValue, dl as ensureAudioCredential, dm as resolveAudioModel, dn as resolveImageModel, dp as resolveModelApi, dq as resolveModelEntry, dr as serializePlayableAudio } from './ai-audio-ws-protocol-nfhO0tOo.js';
3
+ export { A as AudioCapabilitiesRequest, a as AudioContent, b as AudioFormat, c as AudioInputStream, d as AudioModelCapabilities, e as AudioOperations, f as AudioReference, P as PlayableAudio, S as SynthesisEvent, g as SynthesisOptions, h as SynthesisRequest, i as SynthesisResult, j as SynthesisStreamRequest, k as SynthesisTextSegment, T as TranscriptionEvent, l as TranscriptionOptions, m as TranscriptionRequest, n as TranscriptionResult, o as TranscriptionSegment, p as TranscriptionStreamRequest, q as TranscriptionTimestampGranularity, r as TranscriptionWord } from './ai-audio-types-4R5yUAVl.js';
4
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
+ export { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
6
  export { AgentCapabilities, AgentCard, AgentProvider, AgentSkill, Artifact, DataPart, FilePart, FileWithBytes, FileWithUri, Message, MessageSendParams, Part, PushNotificationConfig, Task, TaskArtifactUpdateEvent, TaskIdParams, TaskQueryParams, TaskState, TaskStatus, TaskStatusUpdateEvent, TextPart } from '@a2a-js/sdk';
7
+ export { AgentExecutor, ExecutionEventBus, RequestContext, ServerCallContext } from '@a2a-js/sdk/server';
8
+ export { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
9
+ export { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
10
+ export { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
6
11
  import '@h-ai/core';
7
- import '@h-ai/datapipe';
8
12
  import 'zod';
9
13
  import 'openai';
10
14
  import 'node:buffer';
15
+ import '@h-ai/datapipe';
16
+ import '@modelcontextprotocol/sdk/types.js';
17
+ import 'zod/v4/core';
11
18
 
12
19
  /**
13
20
  * @h-ai/ai — AI 服务主入口
@@ -22,19 +29,45 @@ import 'node:buffer';
22
29
  * @example
23
30
  * ```ts
24
31
  * import { ai } from '@h-ai/ai'
32
+ * import type { AIConfigInput, AIInitOptions } from '@h-ai/ai'
33
+ * async function run(config: AIConfigInput, options: AIInitOptions) {
34
+ * // 默认 Store 所需 reldb/vecdb 已由应用初始化;显式测试 Store 通过 options 注入。
35
+ * const initialized = await ai.init(config, options)
36
+ * if (!initialized.success) return initialized
37
+ * try {
38
+ * const result = await ai.llm.chat({ messages: [{ role: 'user', content: '你好' }] })
39
+ * if (!result.success) return result
40
+ * return result.data.choices[0]?.message.content
41
+ * }
42
+ * finally { await ai.close() }
43
+ * }
44
+ * ```
45
+ */
46
+ declare const ai: AIFunctions;
47
+
48
+ /**
49
+ * @h-ai/ai — MCP Server 创建与传输层
25
50
  *
26
- * // 初始化
27
- * await ai.init({ llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_API_KEY } })
51
+ * 基于 `@modelcontextprotocol/sdk` 封装,提供便捷的 MCP 服务器创建。
52
+ * @module ai-mcp-server
53
+ */
54
+
55
+ /**
56
+ * 创建 MCP 服务器
28
57
  *
29
- * // LLM 调用
30
- * const result = await ai.llm.chat({
31
- * messages: [{ role: 'user', content: '你好' }],
32
- * })
58
+ * @param options - 服务器选项(名称、版本)
59
+ * @returns McpServer 实例
33
60
  *
34
- * // 关闭
35
- * ai.close()
61
+ * @example
62
+ * ```ts
63
+ * import { createMcpServer, StdioServerTransport } from '@h-ai/ai'
64
+ *
65
+ * const server = createMcpServer({ name: 'my-server', version: '1.0.0' })
66
+ * // 注册工具 / 资源 ...
67
+ * const transport = new StdioServerTransport()
68
+ * await server.connect(transport)
36
69
  * ```
37
70
  */
38
- declare const ai: AIFunctions;
71
+ declare function createMcpServer(options: McpServerOptions): McpServer;
39
72
 
40
- export { AIFunctions, ai };
73
+ export { AIFunctions, McpServerOptions, ai, createMcpServer };