@h-ai/ai 1.0.0-beta.34 → 1.0.0-beta.35

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.
@@ -95,6 +95,66 @@ interface AudioClientOperations {
95
95
  */
96
96
  declare function createAudioClient(config: AudioClientConfig): AudioClientOperations;
97
97
 
98
+ /**
99
+ * 麦克风会话选项。应用通过回调决定何时转写和保存录音。
100
+ * @example
101
+ * ```ts
102
+ * import type { AudioRecorderOptions } from '@h-ai/ai/client'
103
+ * const options: AudioRecorderOptions = { maxDurationSeconds: 30, onStop: blob => void blob.size }
104
+ * ```
105
+ */
106
+ interface AudioRecorderOptions {
107
+ /** 请求麦克风时使用的音轨约束,默认 true。 */
108
+ audio?: MediaTrackConstraints | true;
109
+ /** MediaRecorder 的编码选项。 */
110
+ encoding?: MediaRecorderOptions;
111
+ /** 分段间隔,毫秒,默认 250。 */
112
+ timesliceMs?: number;
113
+ /** 达到录音时长上限后停止并发布最后一段数据。 */
114
+ maxDurationSeconds?: number;
115
+ /** 超过编码字节上限时中止并调用 onError。 */
116
+ maxInputBytes?: number;
117
+ /** 正常停止后的完整录音。 */
118
+ onStop: (recording: Blob) => void;
119
+ /** 录音开始后发生的编码或容量错误。 */
120
+ onError?: (error: Error) => void;
121
+ }
122
+ /**
123
+ * 浏览器麦克风会话。
124
+ * @example
125
+ * ```ts
126
+ * import { createAudioRecorder } from '@h-ai/ai/client'
127
+ * const recorder = createAudioRecorder({ onStop: blob => void blob.size })
128
+ * recorder.close()
129
+ * ```
130
+ */
131
+ interface AudioRecorder {
132
+ /** 请求麦克风并开始录音,权限、设备和配置失败时 reject。 */
133
+ start: () => Promise<void>;
134
+ /** 正常停止,最终数据随后由 onStop 发布。 */
135
+ stop: () => void;
136
+ /** 返回已经收到的录音分段,不改变录音状态。 */
137
+ snapshot: () => Blob;
138
+ /** 放弃本次录音及未完成的麦克风申请,释放已有轨道。 */
139
+ close: () => void;
140
+ }
141
+ /**
142
+ * 创建独立的浏览器麦克风会话,故读取权限及编码状态不依赖 AI 服务。
143
+ * @param options - 录音约束、会话上限和结果回调
144
+ * @returns 可开始、快照、停止或释放的会话实例
145
+ * @throws 上限或分段间隔无效时抛出 RangeError
146
+ * @example
147
+ * ```ts
148
+ * import { createAudioRecorder } from '@h-ai/ai/client'
149
+ * async function record() {
150
+ * const recorder = createAudioRecorder({ onStop: blob => void blob.size })
151
+ * await recorder.start()
152
+ * return recorder
153
+ * }
154
+ * ```
155
+ */
156
+ declare function createAudioRecorder(options: AudioRecorderOptions): AudioRecorder;
157
+
98
158
  /**
99
159
  * 浏览器端 WAV 编码工具
100
160
  *
@@ -103,11 +163,30 @@ declare function createAudioClient(config: AudioClientConfig): AudioClientOperat
103
163
  * 所有 API 均为浏览器专用(AudioContext / OfflineAudioContext),仅在客户端调用。
104
164
  * @module audio/wav
105
165
  */
166
+ /**
167
+ * WAV 转换的目标格式和处理上限。
168
+ * @example
169
+ * ```ts
170
+ * import type { AudioWavOptions } from '@h-ai/ai/client'
171
+ * const options: AudioWavOptions = { maxInputBytes: 1024 * 1024, maxDurationSeconds: 30, overflow: 'truncate' }
172
+ * ```
173
+ */
174
+ interface AudioWavOptions {
175
+ /** 输出采样率,单位 Hz,默认 16000。 */
176
+ sampleRate?: number;
177
+ /** 解码前允许的 Blob 最大字节数。 */
178
+ maxInputBytes?: number;
179
+ /** 输出 PCM 的最长秒数,在解码后、重采样前检查。 */
180
+ maxDurationSeconds?: number;
181
+ /** 超过最长秒数时默认拒绝,设为 truncate 时保留开头。 */
182
+ overflow?: 'reject' | 'truncate';
183
+ }
106
184
  /**
107
185
  * 将任意浏览器可解码的音频 Blob(如 MediaRecorder 的 webm)转换为单声道 16bit PCM WAV。
108
186
  *
109
187
  * @param blob - 录制得到的原始音频
110
- * @param sampleRate - 目标采样率(默认 16 kHz)
188
+ * @param options - 目标采样率(兼容旧调用)或含转换上限的配置
189
+ * @throws 配置无效、输入超限、解码失败或超时长且未指定截断时抛错
111
190
  * @returns `audio/wav` 类型的 Blob
112
191
  * @example
113
192
  * ```ts
@@ -118,7 +197,7 @@ declare function createAudioClient(config: AudioClientConfig): AudioClientOperat
118
197
  * }
119
198
  * ```
120
199
  */
121
- declare function blobToWav(blob: Blob, sampleRate?: number): Promise<Blob>;
200
+ declare function blobToWav(blob: Blob, options?: number | AudioWavOptions): Promise<Blob>;
122
201
 
123
- export { blobToWav, createAudioClient };
124
- export type { AudioClientConfig, AudioClientOperations, AudioTicketRequest };
202
+ export { blobToWav, createAudioClient, createAudioRecorder };
203
+ export type { AudioClientConfig, AudioClientOperations, AudioRecorder, AudioRecorderOptions, AudioTicketRequest, AudioWavOptions };
@@ -1,4 +1,4 @@
1
- export { blobToWav, createAudioClient } from '../chunk-UVBQCI7A.js';
2
- import '../chunk-C6T3ONVG.js';
1
+ export { blobToWav, createAudioClient, createAudioRecorder } from '../chunk-EUDI64QA.js';
2
+ import '../chunk-JD6YODU6.js';
3
3
  //# sourceMappingURL=index.js.map
4
4
  //# sourceMappingURL=index.js.map
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { J as AIFunctions, c2 as McpServerOptions } from './ai-acp-types-cue1ZWUk.js';
2
- export { A as A2AAgentCardConfig, a as A2AAgentCardDocument, b as A2AApiKeySecurity, c as A2AAuthenticator, d as A2ACallOptions, e as A2ACallResult, f as A2ACallerIdentity, g as A2AConfig, h as A2AConfigSchema, i as A2AContextInfo, j as A2AHandleResult, k as A2AMessageRecord, l as A2AOperations, m as A2ASecurityConfig, n as A2ASkillConfigSchema, o as A2ATaskFilter, p as ACPAgentAdapter, q as ACPAgentAdapterInput, r as ACPAgentLaunch, s as ACPAgentSchema, dF as ACPApprovalDecision, dG as ACPCitation, t as ACPClientOptions, u as ACPConfig, v as ACPConfigInput, w as ACPConfigSchema, x as ACPCreateSessionOptions, y as ACPGitReport, z as ACPOperations, dH as ACPPlatformPolicy, dI as ACPPlatformRequest, dJ as ACPProjectChanges, dK as ACPProjectSnapshot, B as ACPPublishSchema, dL as ACPPublishSnapshot, C as ACPRepositorySchema, dM as ACPRunObserver, dN as ACPRunRequest, D as ACPSessionInfo, dO as ACPSessionWorkspace, dP as ACPSubmitTurn, E as ACPTransport, dQ as ACPTurnOptions, F as ACPWorkspaceSchema, G as AIConfig, H as AIConfigInput, I as AIConfigSchema, K as AIInitOptions, L as AIRelStore, M as AIRelStoreCompareAndSwap, N as AIRelStoreOptions, O as AIResourceEntry, P as AIResourceRegistry, Q as AIStoreProvider, R as AIVectorBackend, S as AIVectorStore, T as AIVersionedRecord, U as AUDIO_WS_PATH, V as ApiType, W as ApiTypeSchema, X as AskOptions, Y as AssistantMessage, Z as AudioConfig, _ as AudioConfigSchema, $ as AudioFormatSchema, a0 as AudioModelEntry, a1 as AudioModelEntrySchema, a2 as AudioOperation, a3 as AudioOperationSchema, a4 as AudioOperationsSchema, a5 as AudioProviderName, a6 as AudioProviderSchema, a7 as AudioWsClientMessage, a8 as AudioWsClientMessageSchema, a9 as AudioWsDoneMessage, aa as AudioWsDoneMessageSchema, ab as AudioWsEndMessage, ac as AudioWsErrorMessage, ad as AudioWsSegmentDoneMessage, ae as AudioWsSegmentStartedMessage, af as AudioWsServerMessage, ag as AudioWsSpeechMessage, ah as AudioWsStartMessage, ai as AudioWsStartMessageSchema, aj as AudioWsTextMessage, ak as AudioWsTextMessageSchema, al as AudioWsTranscriptMessage, dR as BuiltinArtifact, dS as BuiltinArtifactAccess, dT as BuiltinArtifactReference, dU as BuiltinToolBinding, dV as BuiltinToolBroker, dW as BuiltinToolBrokerOptions, dX as BuiltinToolOptions, am as ChatCompletionChoice, an as ChatCompletionChunk, ao as ChatCompletionDelta, ap as ChatCompletionRequest, aq as ChatCompletionResponse, ar as ChatHistoryOptions, as as ChatMessage, at as ChatRecord, au as Citation, av as CommitTurnInput, aw as CompressConfig, ax as CompressConfigSchema, ay as CompressOperations, az as CompressOptions, aA as CompressResult, aB as CompressionStrategy, aC as CompressionStrategySchema, aD as ConsolidateOptions, aE as ConsolidateResult, aF as ContextChatOptions, aG as ContextChatResult, aH as ContextManager, aI as ContextManagerOptions, aJ as ContextOperations, aK as ContextResetOptions, aL as ContextStreamEvent, aM as ConversationTurn, aN as ConversationTurnStatus, dY as CreateBuiltinTools, aO as DeveloperMessage, aP as EmbeddingConfig, aQ as EmbeddingConfigSchema, aR as EmbeddingItem, aS as EmbeddingOperations, aT as EmbeddingRequest, aU as EmbeddingResponse, aV as EntityDocumentRelation, aW as EntityDocumentResult, aX as EntityListOptions, aY as EntityQueryOptions, aZ as EntityType, a_ as EntityTypeSchema, a$ as FileConfig, b0 as FileConfigSchema, b1 as GenerateImageRequest, b2 as GenerateImageResult, b3 as GenerateObjectRequest, b4 as GeneratedImage, b5 as HaiAIError, b6 as ImageConfig, b7 as ImageConfigSchema, b8 as ImageContent, b9 as ImageModelEntry, ba as ImageModelEntrySchema, bb as ImageOperations, bc as ImageProviderName, bd as ImageProviderSchema, be as ImageSize, bf as InteractionScope, bg as KnowledgeAskOptions, bh as KnowledgeAskResult, bi as KnowledgeConfig, bj as KnowledgeConfigSchema, bk as KnowledgeDocumentInfo, bl as KnowledgeDocumentListOptions, bm as KnowledgeDocumentMetadata, bn as KnowledgeDocumentRemoveOptions, bo as KnowledgeDocumentRevision, bp as KnowledgeEntity, bq as KnowledgeIngestBatchProgress, br as KnowledgeIngestBatchResult, bs as KnowledgeIngestFileInput, bt as KnowledgeIngestInput, bu as KnowledgeIngestResult, bv as KnowledgeOperations, bw as KnowledgeRepairOptions, bx as KnowledgeRepairProgress, by as KnowledgeRepairResult, bz as KnowledgeRetrieveItem, bA as KnowledgeRetrieveOptions, bB as KnowledgeRetrieveResult, bC as KnowledgeSetupOptions, bD as KnowledgeStore, bE as LLMConfig, bF as LLMConfigSchema, bG as LLMOperations, bH as MCPConfig, bI as MCPConfigSchema, bJ as MCPContext, bK as MCPExternalServer, bL as MCPExternalServerSchema, dZ as MCPJobFileContext, d_ as MCPJobFiles, bM as MCPOperations, bN as MCPPrompt, bO as MCPPromptArgument, bP as MCPPromptContent, bQ as MCPPromptMessage, bR as MCPResource, bS as MCPResourceContent, bT as MCPServerCapabilities, bU as MCPServerCapabilitiesSchema, bV as MCPServerConfig, bW as MCPServerConfigSchema, d$ as MCPServiceAuthorization, e0 as MCPServiceBinding, e1 as MCPServiceBindingRequest, e2 as MCPServiceBroker, e3 as MCPServiceBrokerOptions, e4 as MCPServiceOperations, e5 as MCPServiceRequest, bX as MCPToolDefinition, bY as MCPToolHandler, bZ as ManagedAudioOperations, b_ as ManagedImageOperations, b$ as ManagedLLMOperations, c0 as ManagedMCPOperations, c1 as ManagedRetrievalOperations, e6 as McpToolOptions, c3 as MemoryAccessScope, c4 as MemoryAdminOperations, c5 as MemoryClearAllOptions, c6 as MemoryClearOptions, c7 as MemoryConfig, c8 as MemoryConfigSchema, c9 as MemoryCoreOperations, ca as MemoryEntry, cb as MemoryEntryInput, cc as MemoryExtractOptions, cd as MemoryInjectionOptions, ce as MemoryListOptions, cf as MemoryListPageOptions, cg as MemoryOperations, ch as MemoryRecallOptions, ci as MemoryType, cj as MemoryTypeSchema, ck as MemoryUpdateInput, cl as MessageContent, cm as MessageRole, cn as ModelCapabilitiesSchema, co as ModelEntry, cp as ModelEntrySchema, cq as ModelScenario, cr as ModelScenarioSchema, cs as ObjectRef, ct as OptionalSecretSchema, cu as PersonaOperations, cv as PersonaProfile, cw as PersonaProfileInput, cx as PersonaProfileUpdate, cy as PersonaScopeOptions, cz as RagContextItem, cA as RagOperations, cB as RagOptions, cC as RagResult, cD as RagStreamEvent, cE as ReasoningOperations, cF as ReasoningOptions, cG as ReasoningResult, cH as ReasoningStep, cI as ReasoningStepType, cJ as ReasoningStrategy, cK as ReasoningStreamEvent, cL as ReferenceImage, cM as RerankDocument, cN as RerankItem, cO as RerankOperations, cP as RerankRequest, cQ as RerankResponse, cR as ResolveRequiredModelEntryOptions, cS as ResolvedAudioModel, cT as ResolvedImageModel, cU as ResolvedModelConfig, cV as RetrievalConfig, cW as RetrievalConfigSchema, cX as RetrievalOperations, cY as RetrievalRequest, cZ as RetrievalResult, c_ as RetrievalResultItem, c$ as RetrievalSource, d0 as RetrievalSourceConfig, d1 as RetrievalSourceSchema, d2 as SSEDecoder, d3 as SSEEvent, d4 as ScopedMemoryBinding, d5 as ScopedMemoryOperations, d6 as SessionInfo, d7 as StoreFilter, d8 as StorePage, d9 as StoreScope, da as StreamOperations, db as StreamProcessor, dc as StreamResult, dd as SummaryConfig, de as SummaryConfigSchema, df as SummaryOperations, dg as SummaryOptions, dh as SummaryResult, di as SystemMessage, dj as TempModelConfig, dk as TextContent, dl as TokenConfig, dm as TokenConfigSchema, dn as TokenOperations, dp as TokenUsage, dq as ToolCall, dr as ToolDefinition, ds as ToolMessage, dt as ToolRegistryOperations, du as ToolsOperations, dv as UserMessage, dw as WhereClause, dx as WhereOperator, dy as WhereValue, dz as ensureAudioCredential, dA as resolveAudioModel, dB as resolveImageModel, dC as resolveModelApi, dD as resolveModelEntry, dE as serializePlayableAudio } from './ai-acp-types-cue1ZWUk.js';
1
+ import { J as AIFunctions, c2 as McpServerOptions } from './ai-acp-types-CaVzhuVx.js';
2
+ export { A as A2AAgentCardConfig, a as A2AAgentCardDocument, b as A2AApiKeySecurity, c as A2AAuthenticator, d as A2ACallOptions, e as A2ACallResult, f as A2ACallerIdentity, g as A2AConfig, h as A2AConfigSchema, i as A2AContextInfo, j as A2AHandleResult, k as A2AMessageRecord, l as A2AOperations, m as A2ASecurityConfig, n as A2ASkillConfigSchema, o as A2ATaskFilter, p as ACPAgentAdapter, q as ACPAgentAdapterInput, r as ACPAgentLaunch, s as ACPAgentSchema, dF as ACPApprovalDecision, dG as ACPCitation, t as ACPClientOptions, u as ACPConfig, v as ACPConfigInput, w as ACPConfigSchema, x as ACPCreateSessionOptions, y as ACPGitReport, z as ACPOperations, dH as ACPPlatformPolicy, dI as ACPPlatformRequest, dJ as ACPProjectChanges, dK as ACPProjectSnapshot, B as ACPPublishSchema, dL as ACPPublishSnapshot, C as ACPRepositorySchema, dM as ACPRunObserver, dN as ACPRunRequest, D as ACPSessionInfo, dO as ACPSessionWorkspace, dP as ACPSubmitTurn, E as ACPTransport, dQ as ACPTurnOptions, F as ACPWorkspaceSchema, G as AIConfig, H as AIConfigInput, I as AIConfigSchema, K as AIInitOptions, L as AIRelStore, M as AIRelStoreCompareAndSwap, N as AIRelStoreOptions, O as AIResourceEntry, P as AIResourceRegistry, Q as AIStoreProvider, R as AIVectorBackend, S as AIVectorStore, T as AIVersionedRecord, U as AUDIO_WS_PATH, V as ApiType, W as ApiTypeSchema, X as AskOptions, Y as AssistantMessage, Z as AudioConfig, _ as AudioConfigSchema, $ as AudioFormatSchema, a0 as AudioModelEntry, a1 as AudioModelEntrySchema, a2 as AudioOperation, a3 as AudioOperationSchema, a4 as AudioOperationsSchema, a5 as AudioProviderName, a6 as AudioProviderSchema, a7 as AudioWsClientMessage, a8 as AudioWsClientMessageSchema, a9 as AudioWsDoneMessage, aa as AudioWsDoneMessageSchema, ab as AudioWsEndMessage, ac as AudioWsErrorMessage, ad as AudioWsSegmentDoneMessage, ae as AudioWsSegmentStartedMessage, af as AudioWsServerMessage, ag as AudioWsSpeechMessage, ah as AudioWsStartMessage, ai as AudioWsStartMessageSchema, aj as AudioWsTextMessage, ak as AudioWsTextMessageSchema, al as AudioWsTranscriptMessage, dR as BuiltinArtifact, dS as BuiltinArtifactAccess, dT as BuiltinArtifactReference, dU as BuiltinToolBinding, dV as BuiltinToolBroker, dW as BuiltinToolBrokerOptions, dX as BuiltinToolOptions, am as ChatCompletionChoice, an as ChatCompletionChunk, ao as ChatCompletionDelta, ap as ChatCompletionRequest, aq as ChatCompletionResponse, ar as ChatHistoryOptions, as as ChatMessage, at as ChatRecord, au as Citation, av as CommitTurnInput, aw as CompressConfig, ax as CompressConfigSchema, ay as CompressOperations, az as CompressOptions, aA as CompressResult, aB as CompressionStrategy, aC as CompressionStrategySchema, aD as ConsolidateOptions, aE as ConsolidateResult, aF as ContextChatOptions, aG as ContextChatResult, aH as ContextManager, aI as ContextManagerOptions, aJ as ContextOperations, aK as ContextResetOptions, aL as ContextStreamEvent, aM as ConversationTurn, aN as ConversationTurnStatus, dY as CreateBuiltinTools, aO as DeveloperMessage, aP as EmbeddingConfig, aQ as EmbeddingConfigSchema, aR as EmbeddingItem, aS as EmbeddingOperations, aT as EmbeddingRequest, aU as EmbeddingResponse, aV as EntityDocumentRelation, aW as EntityDocumentResult, aX as EntityListOptions, aY as EntityQueryOptions, aZ as EntityType, a_ as EntityTypeSchema, a$ as FileConfig, b0 as FileConfigSchema, b1 as GenerateImageRequest, b2 as GenerateImageResult, b3 as GenerateObjectRequest, b4 as GeneratedImage, b5 as HaiAIError, b6 as ImageConfig, b7 as ImageConfigSchema, b8 as ImageContent, b9 as ImageModelEntry, ba as ImageModelEntrySchema, bb as ImageOperations, bc as ImageProviderName, bd as ImageProviderSchema, be as ImageSize, bf as InteractionScope, dZ as JsonFieldPreview, d_ as JsonFieldPreviewOptions, bg as KnowledgeAskOptions, bh as KnowledgeAskResult, bi as KnowledgeConfig, bj as KnowledgeConfigSchema, bk as KnowledgeDocumentInfo, bl as KnowledgeDocumentListOptions, bm as KnowledgeDocumentMetadata, bn as KnowledgeDocumentRemoveOptions, bo as KnowledgeDocumentRevision, bp as KnowledgeEntity, bq as KnowledgeIngestBatchProgress, br as KnowledgeIngestBatchResult, bs as KnowledgeIngestFileInput, bt as KnowledgeIngestInput, bu as KnowledgeIngestResult, bv as KnowledgeOperations, bw as KnowledgeRepairOptions, bx as KnowledgeRepairProgress, by as KnowledgeRepairResult, bz as KnowledgeRetrieveItem, bA as KnowledgeRetrieveOptions, bB as KnowledgeRetrieveResult, bC as KnowledgeSetupOptions, bD as KnowledgeStore, bE as LLMConfig, bF as LLMConfigSchema, bG as LLMOperations, bH as MCPConfig, bI as MCPConfigSchema, bJ as MCPContext, bK as MCPExternalServer, bL as MCPExternalServerSchema, d$ as MCPJobFileContext, e0 as MCPJobFiles, bM as MCPOperations, bN as MCPPrompt, bO as MCPPromptArgument, bP as MCPPromptContent, bQ as MCPPromptMessage, bR as MCPResource, bS as MCPResourceContent, bT as MCPServerCapabilities, bU as MCPServerCapabilitiesSchema, bV as MCPServerConfig, bW as MCPServerConfigSchema, e1 as MCPServiceAuthorization, e2 as MCPServiceBinding, e3 as MCPServiceBindingRequest, e4 as MCPServiceBroker, e5 as MCPServiceBrokerOptions, e6 as MCPServiceOperations, e7 as MCPServiceRequest, bX as MCPToolDefinition, bY as MCPToolHandler, bZ as ManagedAudioOperations, b_ as ManagedImageOperations, b$ as ManagedLLMOperations, c0 as ManagedMCPOperations, c1 as ManagedRetrievalOperations, e8 as McpToolOptions, c3 as MemoryAccessScope, c4 as MemoryAdminOperations, c5 as MemoryClearAllOptions, c6 as MemoryClearOptions, c7 as MemoryConfig, c8 as MemoryConfigSchema, c9 as MemoryCoreOperations, ca as MemoryEntry, cb as MemoryEntryInput, cc as MemoryExtractOptions, cd as MemoryInjectionOptions, ce as MemoryListOptions, cf as MemoryListPageOptions, cg as MemoryOperations, ch as MemoryRecallOptions, ci as MemoryType, cj as MemoryTypeSchema, ck as MemoryUpdateInput, cl as MessageContent, cm as MessageRole, cn as ModelCapabilitiesSchema, co as ModelEntry, cp as ModelEntrySchema, cq as ModelScenario, cr as ModelScenarioSchema, cs as ObjectRef, ct as OptionalSecretSchema, cu as PersonaOperations, cv as PersonaProfile, cw as PersonaProfileInput, cx as PersonaProfileUpdate, cy as PersonaScopeOptions, cz as RagContextItem, cA as RagOperations, cB as RagOptions, cC as RagResult, cD as RagStreamEvent, cE as ReasoningOperations, cF as ReasoningOptions, cG as ReasoningResult, cH as ReasoningStep, cI as ReasoningStepType, cJ as ReasoningStrategy, cK as ReasoningStreamEvent, cL as ReferenceImage, cM as RerankDocument, cN as RerankItem, cO as RerankOperations, cP as RerankRequest, cQ as RerankResponse, cR as ResolveRequiredModelEntryOptions, cS as ResolvedAudioModel, cT as ResolvedImageModel, cU as ResolvedModelConfig, cV as RetrievalConfig, cW as RetrievalConfigSchema, cX as RetrievalOperations, cY as RetrievalRequest, cZ as RetrievalResult, c_ as RetrievalResultItem, c$ as RetrievalSource, d0 as RetrievalSourceConfig, d1 as RetrievalSourceSchema, d2 as SSEDecoder, d3 as SSEEvent, d4 as ScopedMemoryBinding, d5 as ScopedMemoryOperations, d6 as SessionInfo, d7 as StoreFilter, d8 as StorePage, d9 as StoreScope, da as StreamOperations, db as StreamProcessor, dc as StreamResult, dd as SummaryConfig, de as SummaryConfigSchema, df as SummaryOperations, dg as SummaryOptions, dh as SummaryResult, di as SystemMessage, dj as TempModelConfig, dk as TextContent, dl as TokenConfig, dm as TokenConfigSchema, dn as TokenOperations, dp as TokenUsage, dq as ToolCall, dr as ToolDefinition, ds as ToolMessage, dt as ToolRegistryOperations, du as ToolsOperations, dv as UserMessage, dw as WhereClause, dx as WhereOperator, dy as WhereValue, dz as ensureAudioCredential, dA as resolveAudioModel, dB as resolveImageModel, dC as resolveModelApi, dD as resolveModelEntry, dE as serializePlayableAudio } from './ai-acp-types-CaVzhuVx.js';
3
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
- export { F as FileOperations, a as FileParseMethod, b as FileParseOptions, c as FileParseRequest, d as FileParseResult, O as OutputFormat } from './ai-file-types-BN7l67hR.js';
4
+ export { F as FileOperations, a as FileParseMethod, b as FileParseOptions, c as FileParseRequest, d as FileParseResult, O as OutputFormat } from './ai-file-types-BMfnQU4W.js';
5
5
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6
6
  export { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
7
7
  export { AgentCapabilities, AgentCard, AgentInterface, AgentProvider, AgentSkill, Artifact, CancelTaskRequest, GetTaskRequest, Message, Part, Role, SendMessageRequest, StreamResponse, SubscribeToTaskRequest, Task, TaskArtifactUpdateEvent, TaskPushNotificationConfig, TaskState, TaskStatus, TaskStatusUpdateEvent } from '@a2a-js/sdk';
@@ -20,7 +20,6 @@ import 'openai';
20
20
  import '@h-ai/tools/server';
21
21
  import '@modelcontextprotocol/sdk/types.js';
22
22
  import 'node:http';
23
- import 'node:buffer';
24
23
 
25
24
  /**
26
25
  * AI 服务对象,统一的 AI 访问入口
package/dist/index.js CHANGED
@@ -1,16 +1,16 @@
1
- import { platformOptionsSchema, platformRunSchema, AIConfigSchema, MemoryConfigSchema, ModelEntrySchema, AudioModelEntrySchema, ImageModelEntrySchema, MCPExternalServerSchema, RetrievalSourceSchema, KnowledgeConfigSchema, TokenConfigSchema, SummaryConfigSchema, CompressConfigSchema, serializePlayableAudio, ACPConfigSchema, ACPAgentSchema, ACPWorkspaceSchema, AudioConfigSchema, resolveModelEntry, resolveAudioModel, ensureAudioCredential, platformScopeSchema, resolveModelApi, platformRequestSchema, sessionIdentitySchema, branchNameSchema, ImageConfigSchema, resolveImageModel, ACPPublishSchema } from './chunk-IVEOIRBO.js';
2
- export { A2AConfigSchema, A2ASkillConfigSchema, ACPAgentSchema, ACPConfigSchema, ACPPublishSchema, ACPRepositorySchema, ACPWorkspaceSchema, AIConfigSchema, AUDIO_WS_PATH, ApiTypeSchema, AudioConfigSchema, AudioFormatSchema, AudioModelEntrySchema, AudioOperationSchema, AudioOperationsSchema, AudioProviderSchema, AudioWsClientMessageSchema, AudioWsDoneMessageSchema, AudioWsStartMessageSchema, AudioWsTextMessageSchema, CompressConfigSchema, CompressionStrategySchema, EmbeddingConfigSchema, EntityTypeSchema, FileConfigSchema, ImageConfigSchema, ImageModelEntrySchema, ImageProviderSchema, KnowledgeConfigSchema, LLMConfigSchema, MCPConfigSchema, MCPExternalServerSchema, MCPServerCapabilitiesSchema, MCPServerConfigSchema, MemoryConfigSchema, MemoryTypeSchema, ModelCapabilitiesSchema, ModelEntrySchema, ModelScenarioSchema, OptionalSecretSchema, RetrievalConfigSchema, RetrievalSourceSchema, SummaryConfigSchema, TokenConfigSchema, ensureAudioCredential, resolveAudioModel, resolveImageModel, resolveModelApi, resolveModelEntry, serializePlayableAudio } from './chunk-IVEOIRBO.js';
1
+ import { platformOptionsSchema, platformRunSchema, AIConfigSchema, MemoryConfigSchema, ModelEntrySchema, AudioModelEntrySchema, ImageModelEntrySchema, MCPExternalServerSchema, RetrievalSourceSchema, KnowledgeConfigSchema, TokenConfigSchema, SummaryConfigSchema, CompressConfigSchema, serializePlayableAudio, ACPConfigSchema, ACPAgentSchema, ACPWorkspaceSchema, AudioConfigSchema, resolveModelEntry, resolveAudioModel, ensureAudioCredential, platformScopeSchema, resolveModelApi, platformRequestSchema, sessionIdentitySchema, branchNameSchema, ImageConfigSchema, resolveImageModel, ACPPublishSchema } from './chunk-PELGM4XN.js';
2
+ export { A2AConfigSchema, A2ASkillConfigSchema, ACPAgentSchema, ACPConfigSchema, ACPPublishSchema, ACPRepositorySchema, ACPWorkspaceSchema, AIConfigSchema, AUDIO_WS_PATH, ApiTypeSchema, AudioConfigSchema, AudioFormatSchema, AudioModelEntrySchema, AudioOperationSchema, AudioOperationsSchema, AudioProviderSchema, AudioWsClientMessageSchema, AudioWsDoneMessageSchema, AudioWsStartMessageSchema, AudioWsTextMessageSchema, CompressConfigSchema, CompressionStrategySchema, EmbeddingConfigSchema, EntityTypeSchema, FileConfigSchema, ImageConfigSchema, ImageModelEntrySchema, ImageProviderSchema, KnowledgeConfigSchema, LLMConfigSchema, MCPConfigSchema, MCPExternalServerSchema, MCPServerCapabilitiesSchema, MCPServerConfigSchema, MemoryConfigSchema, MemoryTypeSchema, ModelCapabilitiesSchema, ModelEntrySchema, ModelScenarioSchema, OptionalSecretSchema, RetrievalConfigSchema, RetrievalSourceSchema, SummaryConfigSchema, TokenConfigSchema, ensureAudioCredential, resolveAudioModel, resolveImageModel, resolveModelApi, resolveModelEntry, serializePlayableAudio } from './chunk-PELGM4XN.js';
3
3
  import { parseHtmlFile } from './chunk-OWR55FRO.js';
4
- import { aiM } from './chunk-HZDINADT.js';
5
- import { HaiAIError } from './chunk-C6T3ONVG.js';
6
- export { HaiAIError } from './chunk-C6T3ONVG.js';
4
+ import { aiM } from './chunk-CLCPQTW2.js';
5
+ import { HaiAIError } from './chunk-JD6YODU6.js';
6
+ export { HaiAIError } from './chunk-JD6YODU6.js';
7
7
  import { TaskState, SendMessageRequest, Message, Role, AgentCard, TaskStatus, Task } from '@a2a-js/sdk';
8
8
  export { Message, Part, Role, SendMessageRequest, Task, TaskArtifactUpdateEvent, TaskState, TaskStatus, TaskStatusUpdateEvent } from '@a2a-js/sdk';
9
9
  import { JsonRpcTransportHandler, ServerCallContext, AgentEvent, RequestContext, ResultManager, DefaultExecutionEventBus } from '@a2a-js/sdk/server';
10
10
  export { AgentEvent } from '@a2a-js/sdk/server';
11
11
  import process2 from 'process';
12
12
  import { core, err, ok } from '@h-ai/core';
13
- import { datapipe, HaiDatapipeError } from '@h-ai/datapipe';
13
+ import { datapipe } from '@h-ai/datapipe';
14
14
  import { JsonRpcTransportFactory, ClientFactory } from '@a2a-js/sdk/client';
15
15
  import { Buffer } from 'buffer';
16
16
  import { createHash, randomBytes, randomUUID } from 'crypto';
@@ -33,6 +33,7 @@ import { gunzipSync } from 'zlib';
33
33
  import { FormData as FormData$1, Agent, fetch as fetch$1 } from 'undici';
34
34
  import OpenAI3, { toFile } from 'openai';
35
35
  import { nanoid } from 'nanoid';
36
+ import { Worker } from 'worker_threads';
36
37
  import dns from 'dns';
37
38
  import { BlockList, isIP } from 'net';
38
39
  import { ToolSchema, PromptMessageSchema, TextResourceContentsSchema, BlobResourceContentsSchema, ListToolsRequestSchema, CallToolRequestSchema, CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
@@ -9495,10 +9496,12 @@ function createEmbeddingOperations(config, loadModels = () => config.llm) {
9495
9496
  }
9496
9497
  };
9497
9498
  }
9499
+ var parserWorkerUrl = new URL(import.meta.url.endsWith(".ts") ? "../../dist/ai-file-worker.js" : "./ai-file-worker.js", import.meta.url);
9498
9500
  var filePool = core.worker.createPool(
9499
- new URL(import.meta.url.endsWith(".ts") ? "../../dist/ai-file-worker.js" : "./ai-file-worker.js", import.meta.url),
9501
+ parserWorkerUrl,
9500
9502
  { maxWorkers: 2, maxQueuedJobs: 4, idleTimeoutMs: 15e3 }
9501
9503
  );
9504
+ var activeLocalParsers = 0;
9502
9505
  async function parseInWorker(job) {
9503
9506
  const result = await filePool.run(job);
9504
9507
  if (!result.success) {
@@ -9596,6 +9599,118 @@ function parseTextContent(content) {
9596
9599
  return content;
9597
9600
  return content.toString("utf-8");
9598
9601
  }
9602
+ function asBufferOrText(content) {
9603
+ return typeof content === "string" || Buffer.isBuffer(content) ? content : Buffer.from(content.buffer, content.byteOffset, content.byteLength);
9604
+ }
9605
+ async function parseBoundedLocalFile(request2) {
9606
+ const { filename, signal, options = {} } = request2;
9607
+ const {
9608
+ maxInputBytes: maxInputBytes2 = 4 * 1024 * 1024,
9609
+ maxPages = 100,
9610
+ maxTextLength = 12e3,
9611
+ maxZipEntries = 512,
9612
+ maxExpandedBytes = 24 * 1024 * 1024,
9613
+ timeoutMs = 2e4,
9614
+ outputFormat = "text"
9615
+ } = options;
9616
+ const content = asBufferOrText(request2.content);
9617
+ const inputBytes = typeof content === "string" ? Buffer.byteLength(content) : content.byteLength;
9618
+ if (options.useOcr || timeoutMs > 2147483647 || [
9619
+ maxInputBytes2,
9620
+ maxPages,
9621
+ maxTextLength,
9622
+ maxZipEntries,
9623
+ maxExpandedBytes,
9624
+ timeoutMs
9625
+ ].some((limit) => !Number.isSafeInteger(limit) || limit < 1) || !inputBytes || inputBytes > maxInputBytes2) {
9626
+ return err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileLocalInvalid"));
9627
+ }
9628
+ if (signal?.aborted)
9629
+ return err(HaiAIError.FILE_LOCAL_CANCELLED, aiM("ai_fileLocalCancelled"));
9630
+ const mimeType = detectMimeType(content, filename, options.mimeType);
9631
+ const parameters = {
9632
+ format: outputFormat,
9633
+ locale: core.i18n.getGlobalLocale(),
9634
+ limits: { maxTextLength, maxZipEntries, maxExpandedBytes }
9635
+ };
9636
+ const payload = typeof content === "string" ? content : Uint8Array.from(content);
9637
+ let job;
9638
+ if (TEXT_MIME_TYPES.has(mimeType)) {
9639
+ job = { ...parameters, type: "text", content: payload };
9640
+ } else if (mimeType === "text/html") {
9641
+ job = { ...parameters, type: "html", content: payload };
9642
+ } else if (typeof payload !== "string" && mimeType === "application/pdf") {
9643
+ job = {
9644
+ ...parameters,
9645
+ type: "pdf",
9646
+ content: payload,
9647
+ maxPages
9648
+ };
9649
+ } else if (typeof payload !== "string" && mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
9650
+ job = { ...parameters, type: "docx", content: payload };
9651
+ } else {
9652
+ return err(HaiAIError.FILE_UNSUPPORTED_FORMAT, aiM("ai_fileUnsupportedFormat", {
9653
+ params: { mimeType }
9654
+ }));
9655
+ }
9656
+ if (activeLocalParsers >= 3)
9657
+ return err(HaiAIError.FILE_LOCAL_BUSY, aiM("ai_fileLocalBusy"));
9658
+ activeLocalParsers++;
9659
+ let worker;
9660
+ const deadline = AbortSignal.timeout(timeoutMs);
9661
+ const operation = signal ? AbortSignal.any([signal, deadline]) : deadline;
9662
+ try {
9663
+ const thread = new Worker(parserWorkerUrl, {
9664
+ resourceLimits: { maxOldGenerationSizeMb: 160 }
9665
+ });
9666
+ worker = thread;
9667
+ const parsed = await new Promise((resolve3) => {
9668
+ const stop = () => finish(void 0);
9669
+ function finish(result) {
9670
+ operation.removeEventListener("abort", stop);
9671
+ resolve3(result);
9672
+ }
9673
+ operation.addEventListener("abort", stop, { once: true });
9674
+ thread.once("error", stop);
9675
+ thread.once("exit", stop);
9676
+ thread.once("message", (result) => finish(result));
9677
+ if (operation.aborted) {
9678
+ stop();
9679
+ } else {
9680
+ thread.postMessage(job, typeof payload === "string" ? [] : [payload.buffer]);
9681
+ }
9682
+ });
9683
+ if (signal?.aborted)
9684
+ return err(HaiAIError.FILE_LOCAL_CANCELLED, aiM("ai_fileLocalCancelled"));
9685
+ if (deadline.aborted)
9686
+ return err(HaiAIError.FILE_LOCAL_TIMEOUT, aiM("ai_fileLocalTimeout"));
9687
+ if (!parsed)
9688
+ return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileLocalFailed"));
9689
+ if (!parsed.success)
9690
+ return parsed;
9691
+ const { text, pageCount, truncated } = parsed.data;
9692
+ return ok({
9693
+ text,
9694
+ method: job.type,
9695
+ ...pageCount !== void 0 && { pageCount },
9696
+ metadata: {
9697
+ filename,
9698
+ mimeType,
9699
+ charCount: text.length,
9700
+ ...truncated && { truncated }
9701
+ }
9702
+ });
9703
+ } catch {
9704
+ return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileLocalFailed"));
9705
+ } finally {
9706
+ try {
9707
+ await worker?.terminate();
9708
+ } catch {
9709
+ logger15.warn("Local file parser worker termination failed");
9710
+ }
9711
+ activeLocalParsers--;
9712
+ }
9713
+ }
9599
9714
  async function parseImageWithOcr(content, mimeType, llmOps, model, outputFormat = "text", customPrompt) {
9600
9715
  const base64 = content.toString("base64");
9601
9716
  const dataUrl = `data:${mimeType};base64,${base64}`;
@@ -9653,7 +9768,10 @@ function createFileOperations(config, llmOps) {
9653
9768
  });
9654
9769
  }
9655
9770
  async function doParse(request2) {
9656
- const { content, filename, options = {} } = request2;
9771
+ if (request2.options?.mode === "local")
9772
+ return parseBoundedLocalFile(request2);
9773
+ const { filename, options = {} } = request2;
9774
+ const content = asBufferOrText(request2.content);
9657
9775
  const mimeType = detectMimeType(content, filename, options.mimeType);
9658
9776
  const outputFormat = options.outputFormat ?? "text";
9659
9777
  logger15.trace("Parsing file", {
@@ -10621,6 +10739,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10621
10739
  * 导入文档到知识库
10622
10740
  *
10623
10741
  * 流程:清洗 → 分块 → Embedding/完整实体准备 → 持久暂存 → vecdb → CAS 发布;
10742
+ * 清洗或分块失败时终止导入,避免对未按规则处理的正文生成向量。
10624
10743
  * 实体提取失败不发布新版本,已发布版本与待清理数据分别报告。
10625
10744
  *
10626
10745
  * @param input - 导入输入(documentId、content、可选 cleanOptions / chunkOptions / metadata 等)
@@ -10641,7 +10760,9 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10641
10760
  const enableEntityExtraction = input.enableEntityExtraction ?? config.enableEntityExtraction;
10642
10761
  const cleanOptions = {
10643
10762
  ...config.cleanOptions,
10644
- ...input.cleanOptions
10763
+ ...input.cleanOptions,
10764
+ normalizeWhitespace: input.cleanOptions?.normalizeWhitespace ?? config.cleanOptions.normalizeWhitespace,
10765
+ trim: input.cleanOptions?.trim ?? config.cleanOptions.trim
10645
10766
  };
10646
10767
  const chunkOptions = {
10647
10768
  ...config.chunkOptions,
@@ -10651,9 +10772,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10651
10772
  try {
10652
10773
  if (!await isCollectionReady(collection))
10653
10774
  return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10654
- let chunkResult = await datapipe2.pipeline().clean(cleanOptions).chunk(chunkOptions).run(input.content);
10655
- if (!chunkResult.success && (chunkResult.error.code === HaiDatapipeError.CLEAN_FAILED.code || chunkResult.error.code === HaiDatapipeError.CONFIG_ERROR.code))
10656
- chunkResult = await datapipe2.pipeline().chunk(chunkOptions).run(input.content);
10775
+ const chunkResult = await datapipe2.pipeline().clean(cleanOptions).chunk(chunkOptions).run(input.content);
10657
10776
  if (!chunkResult.success) {
10658
10777
  return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10659
10778
  params: { error: chunkResult.error.message }
@@ -11169,6 +11288,138 @@ ${contextText}
11169
11288
  };
11170
11289
  }
11171
11290
 
11291
+ // src/llm/ai-llm-json-preview.ts
11292
+ var escapedCharacters = {
11293
+ '"': '"',
11294
+ "\\": "\\",
11295
+ "/": "/",
11296
+ "b": "\b",
11297
+ "f": "\f",
11298
+ "n": "\n",
11299
+ "r": "\r",
11300
+ "t": " "
11301
+ };
11302
+ function createJsonFieldPreview(field, options = {}) {
11303
+ const { maxLength = 12e3, maxInputLength = 1e6 } = options;
11304
+ if (!field || !Number.isSafeInteger(maxLength) || maxLength < 1 || !Number.isSafeInteger(maxInputLength) || maxInputLength < 1) {
11305
+ throw new RangeError("Invalid JSON preview limits");
11306
+ }
11307
+ let received = 0;
11308
+ let depth = 0;
11309
+ let phase = "root";
11310
+ let inString = false;
11311
+ let capture;
11312
+ let escaping = false;
11313
+ let unicode;
11314
+ let token = "";
11315
+ let matches = false;
11316
+ let preview = "";
11317
+ let published = "";
11318
+ let finished = false;
11319
+ function append(character) {
11320
+ if (capture === "key" && token.length <= field.length)
11321
+ token += character;
11322
+ if (capture === "value" && preview.length < maxLength)
11323
+ preview += character;
11324
+ }
11325
+ function readString(character) {
11326
+ if (unicode !== void 0) {
11327
+ if (!/^[\da-f]$/i.test(character)) {
11328
+ finished = true;
11329
+ return;
11330
+ }
11331
+ unicode += character;
11332
+ if (unicode.length === 4) {
11333
+ append(String.fromCharCode(Number.parseInt(unicode, 16)));
11334
+ unicode = void 0;
11335
+ }
11336
+ return;
11337
+ }
11338
+ if (escaping) {
11339
+ escaping = false;
11340
+ if (character === "u") {
11341
+ unicode = "";
11342
+ } else if (Object.hasOwn(escapedCharacters, character)) {
11343
+ append(escapedCharacters[character]);
11344
+ } else {
11345
+ finished = true;
11346
+ }
11347
+ return;
11348
+ }
11349
+ if (character === "\\") {
11350
+ escaping = true;
11351
+ return;
11352
+ }
11353
+ if (character !== '"') {
11354
+ append(character);
11355
+ return;
11356
+ }
11357
+ inString = false;
11358
+ if (capture === "key") {
11359
+ matches = token === field;
11360
+ phase = "colon";
11361
+ } else if (capture === "value") {
11362
+ finished = true;
11363
+ }
11364
+ capture = void 0;
11365
+ }
11366
+ return {
11367
+ push(fragment) {
11368
+ received += fragment.length;
11369
+ if (received > maxInputLength)
11370
+ throw new RangeError("JSON stream exceeds its input length limit");
11371
+ for (const character of fragment) {
11372
+ if (finished)
11373
+ break;
11374
+ if (inString) {
11375
+ readString(character);
11376
+ continue;
11377
+ }
11378
+ if (/\s/u.test(character))
11379
+ continue;
11380
+ if (phase === "root") {
11381
+ if (character !== "{") {
11382
+ finished = true;
11383
+ break;
11384
+ }
11385
+ depth = 1;
11386
+ phase = "key";
11387
+ continue;
11388
+ }
11389
+ if (character === '"') {
11390
+ inString = true;
11391
+ if (depth === 1 && phase === "key") {
11392
+ capture = "key";
11393
+ token = "";
11394
+ } else if (depth === 1 && phase === "value") {
11395
+ capture = matches ? "value" : void 0;
11396
+ phase = "afterValue";
11397
+ }
11398
+ } else if (character === "{" || character === "[") {
11399
+ if (depth === 1 && phase === "value")
11400
+ phase = "afterValue";
11401
+ depth++;
11402
+ } else if (character === "}" || character === "]") {
11403
+ if (--depth === 0)
11404
+ finished = true;
11405
+ } else if (depth === 1) {
11406
+ if (character === ":" && phase === "colon")
11407
+ phase = "value";
11408
+ else if (character === "," && phase === "afterValue")
11409
+ phase = "key";
11410
+ else if (phase === "value")
11411
+ phase = "afterValue";
11412
+ }
11413
+ }
11414
+ const prefix = preview.slice(0, maxLength).replace(/[\uD800-\uDBFF]$/u, "");
11415
+ if (prefix === published)
11416
+ return void 0;
11417
+ published = prefix;
11418
+ return prefix;
11419
+ }
11420
+ };
11421
+ }
11422
+
11172
11423
  // src/tools/ai-tools-protocol-schema.ts
11173
11424
  var maps = /* @__PURE__ */ new Set([
11174
11425
  "properties",
@@ -12348,7 +12599,14 @@ function createAILLMFunctions(config, deps) {
12348
12599
  if (request2.systemPrompt)
12349
12600
  baseMessages.push({ role: "system", content: request2.systemPrompt });
12350
12601
  baseMessages.push(...request2.messages);
12351
- const jsonSchema = z.toJSONSchema(request2.schema);
12602
+ let jsonSchema;
12603
+ try {
12604
+ jsonSchema = z.toJSONSchema(request2.schema);
12605
+ } catch {
12606
+ return err(HaiAIError.INVALID_REQUEST, aiM("ai_generateObjectFailed", {
12607
+ params: { error: "schema cannot be represented as JSON Schema" }
12608
+ }));
12609
+ }
12352
12610
  const jsonObject = request2.responseFormat === "json_object";
12353
12611
  if (jsonObject) {
12354
12612
  baseMessages.unshift({
@@ -12373,32 +12631,80 @@ function createAILLMFunctions(config, deps) {
12373
12631
  })
12374
12632
  }
12375
12633
  ];
12376
- const result = await chatWithRecord({
12634
+ const chatRequest = {
12377
12635
  messages,
12378
12636
  model: request2.model,
12379
12637
  temperature: request2.temperature,
12380
12638
  tempModel: request2.tempModel,
12381
12639
  enablePersist: false,
12382
12640
  signal: request2.signal,
12641
+ max_tokens: request2.maxTokens,
12383
12642
  response_format: jsonObject ? { type: "json_object" } : {
12384
12643
  type: "json_schema",
12385
12644
  json_schema: { name: schemaName, schema: jsonSchema, strict: true }
12386
12645
  }
12387
- });
12388
- if (!result.success)
12389
- return result;
12390
- const content = result.data.choices[0]?.message?.content;
12391
- const text = typeof content === "string" ? content : "";
12646
+ };
12647
+ const preview = request2.preview;
12648
+ let text = "";
12649
+ let previewPublished = false;
12650
+ async function clearPreview() {
12651
+ if (!previewPublished)
12652
+ return;
12653
+ try {
12654
+ await preview?.onPrefix("");
12655
+ } catch {
12656
+ logger20.warn("Structured output preview cleanup failed");
12657
+ }
12658
+ }
12659
+ let finishReason = null;
12660
+ if (preview) {
12661
+ try {
12662
+ const parser = createJsonFieldPreview(preview.field, preview);
12663
+ for await (const chunk of chatStreamWithRecord(chatRequest)) {
12664
+ const choice = chunk.choices.find((item2) => item2.index === 0);
12665
+ if (!choice)
12666
+ continue;
12667
+ finishReason = choice.finish_reason ?? finishReason;
12668
+ const fragment = choice.delta.content;
12669
+ if (!fragment)
12670
+ continue;
12671
+ const prefix = parser.push(fragment);
12672
+ text += fragment;
12673
+ if (prefix !== void 0) {
12674
+ previewPublished = true;
12675
+ await preview.onPrefix(prefix);
12676
+ }
12677
+ }
12678
+ } catch {
12679
+ await clearPreview();
12680
+ return err(HaiAIError.RESOURCE_OPERATION_FAILED, aiM("ai_resourceOperationFailed"));
12681
+ }
12682
+ if (request2.signal?.aborted || finishReason !== "stop") {
12683
+ await clearPreview();
12684
+ lastError = "structured response did not finish";
12685
+ if (request2.signal?.aborted)
12686
+ break;
12687
+ continue;
12688
+ }
12689
+ } else {
12690
+ const result = await chatWithRecord(chatRequest);
12691
+ if (!result.success)
12692
+ return result;
12693
+ const content = result.data.choices[0]?.message?.content;
12694
+ text = typeof content === "string" ? content : "";
12695
+ }
12392
12696
  let parsed;
12393
12697
  try {
12394
12698
  parsed = JSON.parse(text);
12395
12699
  } catch {
12700
+ await clearPreview();
12396
12701
  lastError = "invalid JSON";
12397
12702
  continue;
12398
12703
  }
12399
12704
  const validated = request2.schema.safeParse(parsed);
12400
12705
  if (validated.success)
12401
12706
  return ok(validated.data);
12707
+ await clearPreview();
12402
12708
  lastError = validated.error.message;
12403
12709
  }
12404
12710
  return err(
@@ -12414,6 +12720,7 @@ function createAILLMFunctions(config, deps) {
12414
12720
  };
12415
12721
  const stream = {
12416
12722
  createProcessor: createStreamProcessor,
12723
+ createJsonFieldPreview,
12417
12724
  collect: collectStream,
12418
12725
  createSSEDecoder,
12419
12726
  encodeSSE
@@ -19198,7 +19505,10 @@ var notInitializedContext = {
19198
19505
  removeSession: () => Promise.resolve(notInitialized.result())
19199
19506
  };
19200
19507
  var notInitializedRerank = notInitialized.proxy();
19201
- var notInitializedFile = notInitialized.proxy();
19508
+ var notInitializedFile = {
19509
+ parse: (request2) => request2.options?.mode === "local" ? parseBoundedLocalFile(request2) : Promise.resolve(notInitialized.result()),
19510
+ parseText: () => Promise.resolve(notInitialized.result())
19511
+ };
19202
19512
  var notInitializedAudio = {
19203
19513
  models: notInitialized.proxy(),
19204
19514
  transcribe: () => Promise.resolve(notInitialized.result()),
@@ -19274,6 +19584,7 @@ var toolsOperations = {
19274
19584
  };
19275
19585
  var streamOperations = {
19276
19586
  createProcessor: createStreamProcessor,
19587
+ createJsonFieldPreview,
19277
19588
  collect: collectStream,
19278
19589
  createSSEDecoder,
19279
19590
  encodeSSE