@umituz/web-ai 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/core/index.cjs +110 -13
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +51 -2
- package/dist/core/index.d.ts +51 -2
- package/dist/core/index.js +103 -14
- package/dist/core/index.js.map +1 -1
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +1 -1
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.js.map +1 -1
- package/dist/index.cjs +119 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +111 -14
- package/dist/index.js.map +1 -1
- package/dist/providers/index.cjs +13 -0
- package/dist/providers/index.cjs.map +1 -1
- package/dist/providers/index.d.cts +6 -1
- package/dist/providers/index.d.ts +6 -1
- package/dist/providers/index.js +13 -1
- package/dist/providers/index.js.map +1 -1
- package/dist/{remote-chat-client-LrNlew4n.d.cts → remote-chat-client-DnmLTBUA.d.cts} +11 -1
- package/dist/{remote-chat-client-LrNlew4n.d.ts → remote-chat-client-DnmLTBUA.d.ts} +11 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
export { C as ChatMessage, F as FinishReason, G as GenerationResult, P as ProviderHealth, S as StructuredGeneration, a as StructuredTextRequest, T as TextRequest, b as TextTier, c as TokenUsage } from './index-OhvYUTXf.cjs';
|
|
2
2
|
export { A as AIError, a as AIErrorMetadata, b as AIErrorType, b as GroqErrorType, T as TEXT_TIERS, c as TierModelMap, U as USER_FRIENDLY_ERROR_MESSAGES, i as isTextTier, m as mergeTierOverrides, r as resolveModel } from './index-Dv8gRzAu.cjs';
|
|
3
|
-
export { AIErrorBody, AI_ERROR_STATUS, AccessCounted, AccessTimestamped, AgentContext, ApiKeyValidationRule, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, ChunkOptions, CompositeExecutor, DEFAULT_AI_IDENTITY, DEFAULT_API_KEY_RULE, DEFAULT_EMBED_BATCH_SIZE, DEFAULT_ERROR_CLASSIFICATION_RULE, DEFAULT_GENERATION, DEFAULT_HTTP_STATUS_RULE, DEFAULT_RETRY_BACKOFF_MULTIPLIER, DEFAULT_RETRY_INITIAL_DELAY_MS, DEFAULT_RETRY_JITTER_FACTOR, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, DEFAULT_TASK_POLICIES, DebounceManager, DebounceOptions, DedupeExecutor, DedupeExecutorOptions, DiffChangeCount, DiffLine, EmbeddingsBatchAdapter, ErrorClassificationRule, ExponentialBackoffParams, FailoverErrorLike, FetchLike, GENERATION_BOUNDS, GenerationSettings, GroqError, GroqErrorMetadata, HttpStatusClassificationRule, IRequestExecutor, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, LeadingEdgeParams, LoggedError, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, MarkdownSegment, MemoryLike, ModelPricing, ModelWithProvider, NormalizedSseChunk, ProjectContext, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, ResearchSource, ResearchStreamEvent, RetryExecutor, SEARCH_MAX_RESULTS, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, SYSTEM_PROMPT_VERSION, SearchTopic, SseDeltaExtractor, SseResponseOptions, StreamEvent, StreamingParserCallbacks, StreamingResponseParser, StructuredPromptBuilder, SystemPromptInput, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TRANSIENT_ERROR_CODES, TaskPlan, TaskPolicy, TaskState, ThrottleManager, ThrottleOptions, ToolSchema, ToolValidationResult, ToolValidatorFunction, TrailingDelayParams, UsageRecordData, UsageRecordInput, UsageSeriesDayRow, UsageSeriesMessageRow, UsageSeriesPoint, UsageTrendPoint, UsageWindowTotals, VectorCandidate, VectorMatch, WebSearchInput, WebSearchResponse, WebSearchResult, ZodLikeIssue, ZodLikeSchema, accumulateReport, aiErrorStatus, asObjectArray, asRecord, asStringArray, asTrimmedOptionalString, batchEmbed, buildCacheKey, buildHttpStatusFallback, buildResearchMessages, buildSystemPrompt, buildUsageDailySeries, buildUsageData, calculateCacheHitRate, calculateExponentialBackoff, calculateTrailingDelay, canFailover, canStartTask, capText, chunkText, clampScore, classifyHttpStatus, computeCostMicros, cosineSimilarity, countChanges, createSseResponse, debounce, debounceManager, defaultSseDeltaExtractor, deriveSnippetTitle, describeAIErrorType, diffLines, dotProduct, errorRatePct, extractErrorMessageFromJsonBody, extractErrorMessageFromResponse, extractJsonArray, extractJsonCandidate, extractJsonFromCodeFence, extractJsonObject, extractSseDataPayload, extractText, failoverCandidate, findTopKSimilar, formatCost, formatErrorForLogging, formatSseEvent, generateRandomBase36Suffix, isAuthErrorType, isRetryableErrorType, isSseDataLine, isSseDoneMarker, isTextLike, isTransientError, isValidApiKey, isWithinWindow, magnitude, nextAttemptDelayMs, normalizeGenerationSettings, normalizeSources, normalizeSseChunk, oneOfCatalog, planTaskFailure, repairCommonJsonDefects, replayFirst, resolveUserFriendlyErrorMessage, resolveUserFriendlyMessage, searchWeb, selectLeastRecentlyUsedKey, selectMemories, shouldCallOnLeadingEdge, splitMarkdown, splitSseLines, sseStreamResponse, throttle, throttleManager, usageTrendOf, usageWindowTotals, validateApiKey, validateToolArgs } from './core/index.cjs';
|
|
3
|
+
export { AIErrorBody, AI_ERROR_STATUS, AccessCounted, AccessTimestamped, AgentContext, AiFailure, AllowanceWindow, AllowanceWindowOptions, ApiKeyValidationRule, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, ChunkOptions, CompositeExecutor, DEFAULT_AI_IDENTITY, DEFAULT_ALLOWANCE_WINDOW_MS, DEFAULT_API_KEY_RULE, DEFAULT_EMBED_BATCH_SIZE, DEFAULT_ERROR_CLASSIFICATION_RULE, DEFAULT_GENERATION, DEFAULT_HTTP_STATUS_RULE, DEFAULT_RETRY_BACKOFF_MULTIPLIER, DEFAULT_RETRY_INITIAL_DELAY_MS, DEFAULT_RETRY_JITTER_FACTOR, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, DEFAULT_TASK_POLICIES, DebounceManager, DebounceOptions, DedupeExecutor, DedupeExecutorOptions, DeriveTitleOptions, DiffChangeCount, DiffLine, EmbeddingsBatchAdapter, ErrorClassificationRule, ExponentialBackoffParams, FailoverErrorLike, FetchLike, GENERATION_BOUNDS, GenerationSettings, GroqError, GroqErrorMetadata, HttpStatusClassificationRule, IRequestExecutor, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, LeadingEdgeParams, LoggedError, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, MarkdownSegment, MemoryLike, ModelPricing, ModelWithProvider, NormalizedSseChunk, ProjectContext, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, ResearchSource, ResearchStreamEvent, RetryExecutor, SEARCH_MAX_RESULTS, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, STUCK_TASK_THRESHOLD_MS, SYSTEM_PROMPT_VERSION, SearchTopic, SseDeltaExtractor, SseResponseOptions, StreamEvent, StreamingParserCallbacks, StreamingResponseParser, StructuredPromptBuilder, StuckTaskPlan, StuckTaskState, SystemPromptInput, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TRANSIENT_ERROR_CODES, TaskPlan, TaskPolicy, TaskState, ThrottleManager, ThrottleOptions, ToolSchema, ToolValidationResult, ToolValidatorFunction, TrailingDelayParams, UsageRecordData, UsageRecordInput, UsageSeriesDayRow, UsageSeriesMessageRow, UsageSeriesPoint, UsageTrendPoint, UsageWindowTotals, VectorCandidate, VectorMatch, WebSearchInput, WebSearchResponse, WebSearchResult, ZodLikeIssue, ZodLikeSchema, accumulateReport, aiErrorStatus, aiFailureOf, asObjectArray, asRecord, asStringArray, asTrimmedOptionalString, batchEmbed, buildCacheKey, buildHttpStatusFallback, buildResearchMessages, buildSystemPrompt, buildUsageDailySeries, buildUsageData, calculateCacheHitRate, calculateExponentialBackoff, calculateTrailingDelay, canFailover, canStartTask, capText, chunkText, clampScore, classifyHttpStatus, computeCostMicros, cosineSimilarity, countChanges, createAllowanceWindow, createSseResponse, debounce, debounceManager, defaultSseDeltaExtractor, deriveConversationTitle, deriveSnippetTitle, describeAIErrorType, diffLines, dotProduct, errorRatePct, extractErrorMessageFromJsonBody, extractErrorMessageFromResponse, extractJsonArray, extractJsonCandidate, extractJsonFromCodeFence, extractJsonObject, extractSseDataPayload, extractText, failoverCandidate, findTopKSimilar, formatCost, formatErrorForLogging, formatSseEvent, generateRandomBase36Suffix, isAuthErrorType, isRetryableErrorType, isSseDataLine, isSseDoneMarker, isTextLike, isTransientError, isValidApiKey, isWithinWindow, magnitude, nextAttemptDelayMs, normalizeGenerationSettings, normalizeSources, normalizeSseChunk, oneOfCatalog, planStuckRecovery, planTaskFailure, repairCommonJsonDefects, replayFirst, resolveUserFriendlyErrorMessage, resolveUserFriendlyMessage, searchWeb, selectLeastRecentlyUsedKey, selectMemories, shouldCallOnLeadingEdge, splitMarkdown, splitSseLines, sseStreamResponse, throttle, throttleManager, usageTrendOf, usageWindowTotals, validateApiKey, validateToolArgs } from './core/index.cjs';
|
|
4
4
|
export { A as AiError, a as AiErrorCode, b as AssistantToolCall, C as CODE_MESSAGES, c as ContextBudget, d as ContextMessage, e as ContextRole, P as ProviderErrorShape, Q as QueueOptions, R as RequestDeduplicator, f as RequestQueue, g as RetryManager, h as RetryOptions, S as STATUS_TO_CODE, T as ToolCallAccumulator, W as WireToolCallDelta, i as aiErrorMessage, j as buildContext, k as errorFromStatus, l as errorFromUnknown, m as estimateMessageTokens, n as estimateTokens, r as requestDeduplicator, o as requestQueue, p as retryManager, w as withRetry } from './context-manager-CuZz0vnC.cjs';
|
|
5
5
|
export { C as CacheManager, a as CacheOptions, b as CacheStats, c as cacheManager } from './cache-manager-Df9LLYGA.cjs';
|
|
6
|
-
export { P as ParsedSseEvent, R as RemoteChatClient, a as RemoteChatClientOptions, b as RemoteChatStreamBody, c as RemoteChatUrls, d as RemoteStreamHandle, S as StreamCallbacks, e as createRemoteChatClient, p as parseSseEvent, r as readSseResponse } from './remote-chat-client-
|
|
6
|
+
export { P as ParsedSseEvent, R as RemoteChatClient, a as RemoteChatClientOptions, b as RemoteChatStreamBody, c as RemoteChatUrls, d as RemoteStreamHandle, S as StreamCallbacks, e as createRemoteChatClient, i as iterateSseData, f as iterateSseJson, p as parseSseEvent, r as readSseResponse } from './remote-chat-client-DnmLTBUA.cjs';
|
|
7
7
|
export { A as AnyProvider, C as CostEstimateRequest, I as IAIProvider, a as IMediaProvider, b as IProviderBase, c as ITextGenerator, d as ITextProvider, P as ProviderCapability, e as ProviderFactory, f as ProviderFactoryConfig, T as TextGenerationOptions, g as createProviderFactory, i as isMediaProvider, h as isTextProvider } from './provider.factory-Ce6Een1G.cjs';
|
|
8
|
-
export { ADAPTER_MEDIA_TIMEOUT_MS, ADAPTER_TIMEOUT_MS, API_ENDPOINTS, AdapterChatMessage, AdapterChatRole, AdapterConfig, AdapterEnvBinding, AdapterProviderBinding, AdapterRequest, AdapterResolver, AdapterResolverTiming, AnthropicHttpTransport, AnthropicProvider, AnthropicRequestBuilder, AppContainer, AudioTranscriptionAdapter, AudioTranscriptionRequest, AudioTranscriptionResult, AuthenticationError, BaseAIProvider, BaseAIProvider as BaseProvider, BaseProviderConfig, ChatAdapter, ConversationAttempt, ConversationAttemptModel, ConversationAttemptSettings, ConversationEvent, ConversationTurnResult, DEFAULT_BASE_URL, DEFAULT_GENERATION_CONFIG, DEFAULT_MODELS, EmbeddingsAdapter, EmbeddingsRequest, EmbeddingsResult, FAL_ASPECT_IMAGE_SIZES, FalAudioModelSpec, FalJobInput, FalJobOutput, FalJobStatus, FalProvider, FalQueueClient, FalQueueEnv, FalQueueError, FalStatusResponse, FalStatusSnapshot, FalSubmitResponse, FalSubmittedJob, FalVideoModelSpec, GEMINI_TIERS, GROQ_MODELS, GROQ_TIERS, GeminiProvider, GenerationFailedError, GroqChatRequestBuilder, GroqConfigStore, GroqHttpClient, GroqHttpClientDeps, GroqHttpTransport, GroqProvider, IMAGE_B64_LIMIT, IMAGE_QUALITIES, IMAGE_SIZES, ImageAdapter, ImageRequest, ImageResult, ImageSize, OpenAiCompatibleConfig, OpenAiCompatibleProvider, ProviderError, ProviderEvent, PrunaProgressStage, PrunaProvider, PrunaRequest, RequestImage, RunConversationInput, SPEECH_INPUT_MAX, SPEECH_VOICES, SpeechAdapter, SpeechRequest, SpeechResult, SpeechVoice, StructuredJsonRequest, TIMEOUTS, TimeoutError, ToolDefinition, ValidationError, WORKERS_AI_LLM_MODEL, WORKERS_AI_TIERS, WorkersAIProvider, WorkersAISpeechEngine, WorkersAISpeechResult, WorkersAITextOptions, apiKeyAvailable, audioTranscriptionAdapterFor, buildFalAudioInput, buildFalAudioLyrics, buildFalImageInput, buildFalTagPrompt, buildFalVideoInput, chatAdapterFor, configureProvider, consumeAnthropicStream, consumeGroqStream, createAdapterResolver, createAnthropicAdapter, createAssistantMessage, createFalProvider, createFalQueue, createGeminiProvider, createGroqProvider, createMessage, createOpenAiAudioTranscriptionAdapter, createOpenAiCompatibleAdapter, createOpenAiCompatibleProvider, createOpenAiEmbeddingsAdapter, createOpenAiImageAdapter, createOpenAiSpeechAdapter, createPrunaProvider, createSystemMessage, createUserMessage, createWorkersAIProvider, defaultEffortForModel, embeddingsAdapterFor, extractContentFromSsePayload, extractTextFromMessages, falQueueConfigured, formatMessagesForDisplay, generateImageThenVideo, generatePruna, generateWithPruna, getProvider, imageAdapterFor, mapAnthropicStopReason, parseFalAudioOutput, parseFalImageOutput, parseFalVideoOutput, pollForResult, promptToMessages, requestStructuredJson, resetProvider, resolveApiKey, runConversation, runWorkersAIText, speakWithWorkersAI, speechAdapterFor, streamWorkersAIText, submitPrediction, toGroqMessages, uploadImage, workersAIConfigured } from './providers/index.cjs';
|
|
8
|
+
export { ADAPTER_MEDIA_TIMEOUT_MS, ADAPTER_TIMEOUT_MS, API_ENDPOINTS, AdapterChatMessage, AdapterChatRole, AdapterConfig, AdapterEnvBinding, AdapterProviderBinding, AdapterRequest, AdapterResolver, AdapterResolverTiming, AnthropicHttpTransport, AnthropicProvider, AnthropicRequestBuilder, AppContainer, AudioTranscriptionAdapter, AudioTranscriptionRequest, AudioTranscriptionResult, AuthenticationError, BaseAIProvider, BaseAIProvider as BaseProvider, BaseProviderConfig, BootProviderOptions, ChatAdapter, ConversationAttempt, ConversationAttemptModel, ConversationAttemptSettings, ConversationEvent, ConversationTurnResult, DEFAULT_BASE_URL, DEFAULT_GENERATION_CONFIG, DEFAULT_MODELS, EmbeddingsAdapter, EmbeddingsRequest, EmbeddingsResult, FAL_ASPECT_IMAGE_SIZES, FalAudioModelSpec, FalJobInput, FalJobOutput, FalJobStatus, FalProvider, FalQueueClient, FalQueueEnv, FalQueueError, FalStatusResponse, FalStatusSnapshot, FalSubmitResponse, FalSubmittedJob, FalVideoModelSpec, GEMINI_TIERS, GROQ_MODELS, GROQ_TIERS, GeminiProvider, GenerationFailedError, GroqChatRequestBuilder, GroqConfigStore, GroqHttpClient, GroqHttpClientDeps, GroqHttpTransport, GroqProvider, IMAGE_B64_LIMIT, IMAGE_QUALITIES, IMAGE_SIZES, ImageAdapter, ImageRequest, ImageResult, ImageSize, OpenAiCompatibleConfig, OpenAiCompatibleProvider, ProviderError, ProviderEvent, PrunaProgressStage, PrunaProvider, PrunaRequest, RequestImage, RunConversationInput, SPEECH_INPUT_MAX, SPEECH_VOICES, SpeechAdapter, SpeechRequest, SpeechResult, SpeechVoice, StructuredJsonRequest, TIMEOUTS, TimeoutError, ToolDefinition, ValidationError, WORKERS_AI_LLM_MODEL, WORKERS_AI_TIERS, WorkersAIProvider, WorkersAISpeechEngine, WorkersAISpeechResult, WorkersAITextOptions, apiKeyAvailable, audioTranscriptionAdapterFor, bootProvider, buildFalAudioInput, buildFalAudioLyrics, buildFalImageInput, buildFalTagPrompt, buildFalVideoInput, chatAdapterFor, configureProvider, consumeAnthropicStream, consumeGroqStream, createAdapterResolver, createAnthropicAdapter, createAssistantMessage, createFalProvider, createFalQueue, createGeminiProvider, createGroqProvider, createMessage, createOpenAiAudioTranscriptionAdapter, createOpenAiCompatibleAdapter, createOpenAiCompatibleProvider, createOpenAiEmbeddingsAdapter, createOpenAiImageAdapter, createOpenAiSpeechAdapter, createPrunaProvider, createSystemMessage, createUserMessage, createWorkersAIProvider, defaultEffortForModel, embeddingsAdapterFor, extractContentFromSsePayload, extractTextFromMessages, falQueueConfigured, formatMessagesForDisplay, generateImageThenVideo, generatePruna, generateWithPruna, getProvider, imageAdapterFor, mapAnthropicStopReason, parseFalAudioOutput, parseFalImageOutput, parseFalVideoOutput, pollForResult, promptToMessages, requestStructuredJson, resetProvider, resolveApiKey, runConversation, runWorkersAIText, speakWithWorkersAI, speechAdapterFor, streamWorkersAIText, submitPrediction, toGroqMessages, uploadImage, workersAIConfigured } from './providers/index.cjs';
|
|
9
9
|
export { A as AIProviderConfig, a as ANTHROPIC_API_VERSION, b as ANTHROPIC_DEFAULT_MAX_TOKENS, c as ANTHROPIC_MODELS, d as ANTHROPIC_TIERS, e as AnthropicEffort, f as AnthropicMessagesRequest, g as AnthropicMessagesResponse, h as AnthropicProviderConfig, i as AnthropicStopReason, j as AnthropicStreamEvent, G as GroqChatChunk, k as GroqChatRequest, l as GroqChatResponse, m as GroqChoice, n as GroqChunkChoice, o as GroqConfig, p as GroqErrorResponse, q as GroqGenerationConfig, r as GroqMessage, s as GroqMessageRole, t as GroqProviderConfig, u as GroqReasoningEffort, v as GroqUsage, O as OpenAiCompatibleProviderConfig, S as StreamRequestOptions, W as WorkersAIBinding, w as WorkersAIEnv, x as WorkersAIError, y as WorkersAIMessage, z as WorkersAIProviderConfig, B as createAI } from './create-ai-DDyTVzef.cjs';
|
|
10
10
|
export { C as CancellationError, G as GenerateOptions, a as GenerationStage, I as IGroqChatService, b as IGroqHttpClient, c as ImageToImageInput, d as ImageToVideoInput, P as PrunaAspectRatio, e as PrunaInput, f as PrunaModelId, g as PrunaOutput, h as PrunaPredictionResponse, i as PrunaResolution, j as PrunaResult, S as StreamingCallbacks, k as StructuredGenerationOptions, T as TextGenerationService, l as TextToImageInput, m as TextToVideoInput } from './cancellation-error-BWb59Wkj.cjs';
|
|
11
11
|
export { C as ChatConfig, a as ChatConversation, b as ChatMessageSender, c as ChatMessageType, d as ChatService, e as ChatTokenUsage, f as ConversationMessage, D as DEFAULT_PROMPT_STRATEGY, I as IChatService, g as IChatStorage, h as IMessageFormatter, S as SendMessageInput, i as SendMessageResult, j as SystemPromptStrategy, U as UseChatOptions, k as UseChatReturn, l as extractTokenUsage } from './chat.service-8MaW9pum.cjs';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
export { C as ChatMessage, F as FinishReason, G as GenerationResult, P as ProviderHealth, S as StructuredGeneration, a as StructuredTextRequest, T as TextRequest, b as TextTier, c as TokenUsage } from './index-OhvYUTXf.js';
|
|
2
2
|
export { A as AIError, a as AIErrorMetadata, b as AIErrorType, b as GroqErrorType, T as TEXT_TIERS, c as TierModelMap, U as USER_FRIENDLY_ERROR_MESSAGES, i as isTextTier, m as mergeTierOverrides, r as resolveModel } from './index-1e91KRYU.js';
|
|
3
|
-
export { AIErrorBody, AI_ERROR_STATUS, AccessCounted, AccessTimestamped, AgentContext, ApiKeyValidationRule, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, ChunkOptions, CompositeExecutor, DEFAULT_AI_IDENTITY, DEFAULT_API_KEY_RULE, DEFAULT_EMBED_BATCH_SIZE, DEFAULT_ERROR_CLASSIFICATION_RULE, DEFAULT_GENERATION, DEFAULT_HTTP_STATUS_RULE, DEFAULT_RETRY_BACKOFF_MULTIPLIER, DEFAULT_RETRY_INITIAL_DELAY_MS, DEFAULT_RETRY_JITTER_FACTOR, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, DEFAULT_TASK_POLICIES, DebounceManager, DebounceOptions, DedupeExecutor, DedupeExecutorOptions, DiffChangeCount, DiffLine, EmbeddingsBatchAdapter, ErrorClassificationRule, ExponentialBackoffParams, FailoverErrorLike, FetchLike, GENERATION_BOUNDS, GenerationSettings, GroqError, GroqErrorMetadata, HttpStatusClassificationRule, IRequestExecutor, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, LeadingEdgeParams, LoggedError, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, MarkdownSegment, MemoryLike, ModelPricing, ModelWithProvider, NormalizedSseChunk, ProjectContext, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, ResearchSource, ResearchStreamEvent, RetryExecutor, SEARCH_MAX_RESULTS, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, SYSTEM_PROMPT_VERSION, SearchTopic, SseDeltaExtractor, SseResponseOptions, StreamEvent, StreamingParserCallbacks, StreamingResponseParser, StructuredPromptBuilder, SystemPromptInput, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TRANSIENT_ERROR_CODES, TaskPlan, TaskPolicy, TaskState, ThrottleManager, ThrottleOptions, ToolSchema, ToolValidationResult, ToolValidatorFunction, TrailingDelayParams, UsageRecordData, UsageRecordInput, UsageSeriesDayRow, UsageSeriesMessageRow, UsageSeriesPoint, UsageTrendPoint, UsageWindowTotals, VectorCandidate, VectorMatch, WebSearchInput, WebSearchResponse, WebSearchResult, ZodLikeIssue, ZodLikeSchema, accumulateReport, aiErrorStatus, asObjectArray, asRecord, asStringArray, asTrimmedOptionalString, batchEmbed, buildCacheKey, buildHttpStatusFallback, buildResearchMessages, buildSystemPrompt, buildUsageDailySeries, buildUsageData, calculateCacheHitRate, calculateExponentialBackoff, calculateTrailingDelay, canFailover, canStartTask, capText, chunkText, clampScore, classifyHttpStatus, computeCostMicros, cosineSimilarity, countChanges, createSseResponse, debounce, debounceManager, defaultSseDeltaExtractor, deriveSnippetTitle, describeAIErrorType, diffLines, dotProduct, errorRatePct, extractErrorMessageFromJsonBody, extractErrorMessageFromResponse, extractJsonArray, extractJsonCandidate, extractJsonFromCodeFence, extractJsonObject, extractSseDataPayload, extractText, failoverCandidate, findTopKSimilar, formatCost, formatErrorForLogging, formatSseEvent, generateRandomBase36Suffix, isAuthErrorType, isRetryableErrorType, isSseDataLine, isSseDoneMarker, isTextLike, isTransientError, isValidApiKey, isWithinWindow, magnitude, nextAttemptDelayMs, normalizeGenerationSettings, normalizeSources, normalizeSseChunk, oneOfCatalog, planTaskFailure, repairCommonJsonDefects, replayFirst, resolveUserFriendlyErrorMessage, resolveUserFriendlyMessage, searchWeb, selectLeastRecentlyUsedKey, selectMemories, shouldCallOnLeadingEdge, splitMarkdown, splitSseLines, sseStreamResponse, throttle, throttleManager, usageTrendOf, usageWindowTotals, validateApiKey, validateToolArgs } from './core/index.js';
|
|
3
|
+
export { AIErrorBody, AI_ERROR_STATUS, AccessCounted, AccessTimestamped, AgentContext, AiFailure, AllowanceWindow, AllowanceWindowOptions, ApiKeyValidationRule, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, ChunkOptions, CompositeExecutor, DEFAULT_AI_IDENTITY, DEFAULT_ALLOWANCE_WINDOW_MS, DEFAULT_API_KEY_RULE, DEFAULT_EMBED_BATCH_SIZE, DEFAULT_ERROR_CLASSIFICATION_RULE, DEFAULT_GENERATION, DEFAULT_HTTP_STATUS_RULE, DEFAULT_RETRY_BACKOFF_MULTIPLIER, DEFAULT_RETRY_INITIAL_DELAY_MS, DEFAULT_RETRY_JITTER_FACTOR, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, DEFAULT_TASK_POLICIES, DebounceManager, DebounceOptions, DedupeExecutor, DedupeExecutorOptions, DeriveTitleOptions, DiffChangeCount, DiffLine, EmbeddingsBatchAdapter, ErrorClassificationRule, ExponentialBackoffParams, FailoverErrorLike, FetchLike, GENERATION_BOUNDS, GenerationSettings, GroqError, GroqErrorMetadata, HttpStatusClassificationRule, IRequestExecutor, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, LeadingEdgeParams, LoggedError, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, MarkdownSegment, MemoryLike, ModelPricing, ModelWithProvider, NormalizedSseChunk, ProjectContext, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, ResearchSource, ResearchStreamEvent, RetryExecutor, SEARCH_MAX_RESULTS, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, STUCK_TASK_THRESHOLD_MS, SYSTEM_PROMPT_VERSION, SearchTopic, SseDeltaExtractor, SseResponseOptions, StreamEvent, StreamingParserCallbacks, StreamingResponseParser, StructuredPromptBuilder, StuckTaskPlan, StuckTaskState, SystemPromptInput, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TRANSIENT_ERROR_CODES, TaskPlan, TaskPolicy, TaskState, ThrottleManager, ThrottleOptions, ToolSchema, ToolValidationResult, ToolValidatorFunction, TrailingDelayParams, UsageRecordData, UsageRecordInput, UsageSeriesDayRow, UsageSeriesMessageRow, UsageSeriesPoint, UsageTrendPoint, UsageWindowTotals, VectorCandidate, VectorMatch, WebSearchInput, WebSearchResponse, WebSearchResult, ZodLikeIssue, ZodLikeSchema, accumulateReport, aiErrorStatus, aiFailureOf, asObjectArray, asRecord, asStringArray, asTrimmedOptionalString, batchEmbed, buildCacheKey, buildHttpStatusFallback, buildResearchMessages, buildSystemPrompt, buildUsageDailySeries, buildUsageData, calculateCacheHitRate, calculateExponentialBackoff, calculateTrailingDelay, canFailover, canStartTask, capText, chunkText, clampScore, classifyHttpStatus, computeCostMicros, cosineSimilarity, countChanges, createAllowanceWindow, createSseResponse, debounce, debounceManager, defaultSseDeltaExtractor, deriveConversationTitle, deriveSnippetTitle, describeAIErrorType, diffLines, dotProduct, errorRatePct, extractErrorMessageFromJsonBody, extractErrorMessageFromResponse, extractJsonArray, extractJsonCandidate, extractJsonFromCodeFence, extractJsonObject, extractSseDataPayload, extractText, failoverCandidate, findTopKSimilar, formatCost, formatErrorForLogging, formatSseEvent, generateRandomBase36Suffix, isAuthErrorType, isRetryableErrorType, isSseDataLine, isSseDoneMarker, isTextLike, isTransientError, isValidApiKey, isWithinWindow, magnitude, nextAttemptDelayMs, normalizeGenerationSettings, normalizeSources, normalizeSseChunk, oneOfCatalog, planStuckRecovery, planTaskFailure, repairCommonJsonDefects, replayFirst, resolveUserFriendlyErrorMessage, resolveUserFriendlyMessage, searchWeb, selectLeastRecentlyUsedKey, selectMemories, shouldCallOnLeadingEdge, splitMarkdown, splitSseLines, sseStreamResponse, throttle, throttleManager, usageTrendOf, usageWindowTotals, validateApiKey, validateToolArgs } from './core/index.js';
|
|
4
4
|
export { A as AiError, a as AiErrorCode, b as AssistantToolCall, C as CODE_MESSAGES, c as ContextBudget, d as ContextMessage, e as ContextRole, P as ProviderErrorShape, Q as QueueOptions, R as RequestDeduplicator, f as RequestQueue, g as RetryManager, h as RetryOptions, S as STATUS_TO_CODE, T as ToolCallAccumulator, W as WireToolCallDelta, i as aiErrorMessage, j as buildContext, k as errorFromStatus, l as errorFromUnknown, m as estimateMessageTokens, n as estimateTokens, r as requestDeduplicator, o as requestQueue, p as retryManager, w as withRetry } from './context-manager-CuZz0vnC.js';
|
|
5
5
|
export { C as CacheManager, a as CacheOptions, b as CacheStats, c as cacheManager } from './cache-manager-Df9LLYGA.js';
|
|
6
|
-
export { P as ParsedSseEvent, R as RemoteChatClient, a as RemoteChatClientOptions, b as RemoteChatStreamBody, c as RemoteChatUrls, d as RemoteStreamHandle, S as StreamCallbacks, e as createRemoteChatClient, p as parseSseEvent, r as readSseResponse } from './remote-chat-client-
|
|
6
|
+
export { P as ParsedSseEvent, R as RemoteChatClient, a as RemoteChatClientOptions, b as RemoteChatStreamBody, c as RemoteChatUrls, d as RemoteStreamHandle, S as StreamCallbacks, e as createRemoteChatClient, i as iterateSseData, f as iterateSseJson, p as parseSseEvent, r as readSseResponse } from './remote-chat-client-DnmLTBUA.js';
|
|
7
7
|
export { A as AnyProvider, C as CostEstimateRequest, I as IAIProvider, a as IMediaProvider, b as IProviderBase, c as ITextGenerator, d as ITextProvider, P as ProviderCapability, e as ProviderFactory, f as ProviderFactoryConfig, T as TextGenerationOptions, g as createProviderFactory, i as isMediaProvider, h as isTextProvider } from './provider.factory-B9RNUTYj.js';
|
|
8
|
-
export { ADAPTER_MEDIA_TIMEOUT_MS, ADAPTER_TIMEOUT_MS, API_ENDPOINTS, AdapterChatMessage, AdapterChatRole, AdapterConfig, AdapterEnvBinding, AdapterProviderBinding, AdapterRequest, AdapterResolver, AdapterResolverTiming, AnthropicHttpTransport, AnthropicProvider, AnthropicRequestBuilder, AppContainer, AudioTranscriptionAdapter, AudioTranscriptionRequest, AudioTranscriptionResult, AuthenticationError, BaseAIProvider, BaseAIProvider as BaseProvider, BaseProviderConfig, ChatAdapter, ConversationAttempt, ConversationAttemptModel, ConversationAttemptSettings, ConversationEvent, ConversationTurnResult, DEFAULT_BASE_URL, DEFAULT_GENERATION_CONFIG, DEFAULT_MODELS, EmbeddingsAdapter, EmbeddingsRequest, EmbeddingsResult, FAL_ASPECT_IMAGE_SIZES, FalAudioModelSpec, FalJobInput, FalJobOutput, FalJobStatus, FalProvider, FalQueueClient, FalQueueEnv, FalQueueError, FalStatusResponse, FalStatusSnapshot, FalSubmitResponse, FalSubmittedJob, FalVideoModelSpec, GEMINI_TIERS, GROQ_MODELS, GROQ_TIERS, GeminiProvider, GenerationFailedError, GroqChatRequestBuilder, GroqConfigStore, GroqHttpClient, GroqHttpClientDeps, GroqHttpTransport, GroqProvider, IMAGE_B64_LIMIT, IMAGE_QUALITIES, IMAGE_SIZES, ImageAdapter, ImageRequest, ImageResult, ImageSize, OpenAiCompatibleConfig, OpenAiCompatibleProvider, ProviderError, ProviderEvent, PrunaProgressStage, PrunaProvider, PrunaRequest, RequestImage, RunConversationInput, SPEECH_INPUT_MAX, SPEECH_VOICES, SpeechAdapter, SpeechRequest, SpeechResult, SpeechVoice, StructuredJsonRequest, TIMEOUTS, TimeoutError, ToolDefinition, ValidationError, WORKERS_AI_LLM_MODEL, WORKERS_AI_TIERS, WorkersAIProvider, WorkersAISpeechEngine, WorkersAISpeechResult, WorkersAITextOptions, apiKeyAvailable, audioTranscriptionAdapterFor, buildFalAudioInput, buildFalAudioLyrics, buildFalImageInput, buildFalTagPrompt, buildFalVideoInput, chatAdapterFor, configureProvider, consumeAnthropicStream, consumeGroqStream, createAdapterResolver, createAnthropicAdapter, createAssistantMessage, createFalProvider, createFalQueue, createGeminiProvider, createGroqProvider, createMessage, createOpenAiAudioTranscriptionAdapter, createOpenAiCompatibleAdapter, createOpenAiCompatibleProvider, createOpenAiEmbeddingsAdapter, createOpenAiImageAdapter, createOpenAiSpeechAdapter, createPrunaProvider, createSystemMessage, createUserMessage, createWorkersAIProvider, defaultEffortForModel, embeddingsAdapterFor, extractContentFromSsePayload, extractTextFromMessages, falQueueConfigured, formatMessagesForDisplay, generateImageThenVideo, generatePruna, generateWithPruna, getProvider, imageAdapterFor, mapAnthropicStopReason, parseFalAudioOutput, parseFalImageOutput, parseFalVideoOutput, pollForResult, promptToMessages, requestStructuredJson, resetProvider, resolveApiKey, runConversation, runWorkersAIText, speakWithWorkersAI, speechAdapterFor, streamWorkersAIText, submitPrediction, toGroqMessages, uploadImage, workersAIConfigured } from './providers/index.js';
|
|
8
|
+
export { ADAPTER_MEDIA_TIMEOUT_MS, ADAPTER_TIMEOUT_MS, API_ENDPOINTS, AdapterChatMessage, AdapterChatRole, AdapterConfig, AdapterEnvBinding, AdapterProviderBinding, AdapterRequest, AdapterResolver, AdapterResolverTiming, AnthropicHttpTransport, AnthropicProvider, AnthropicRequestBuilder, AppContainer, AudioTranscriptionAdapter, AudioTranscriptionRequest, AudioTranscriptionResult, AuthenticationError, BaseAIProvider, BaseAIProvider as BaseProvider, BaseProviderConfig, BootProviderOptions, ChatAdapter, ConversationAttempt, ConversationAttemptModel, ConversationAttemptSettings, ConversationEvent, ConversationTurnResult, DEFAULT_BASE_URL, DEFAULT_GENERATION_CONFIG, DEFAULT_MODELS, EmbeddingsAdapter, EmbeddingsRequest, EmbeddingsResult, FAL_ASPECT_IMAGE_SIZES, FalAudioModelSpec, FalJobInput, FalJobOutput, FalJobStatus, FalProvider, FalQueueClient, FalQueueEnv, FalQueueError, FalStatusResponse, FalStatusSnapshot, FalSubmitResponse, FalSubmittedJob, FalVideoModelSpec, GEMINI_TIERS, GROQ_MODELS, GROQ_TIERS, GeminiProvider, GenerationFailedError, GroqChatRequestBuilder, GroqConfigStore, GroqHttpClient, GroqHttpClientDeps, GroqHttpTransport, GroqProvider, IMAGE_B64_LIMIT, IMAGE_QUALITIES, IMAGE_SIZES, ImageAdapter, ImageRequest, ImageResult, ImageSize, OpenAiCompatibleConfig, OpenAiCompatibleProvider, ProviderError, ProviderEvent, PrunaProgressStage, PrunaProvider, PrunaRequest, RequestImage, RunConversationInput, SPEECH_INPUT_MAX, SPEECH_VOICES, SpeechAdapter, SpeechRequest, SpeechResult, SpeechVoice, StructuredJsonRequest, TIMEOUTS, TimeoutError, ToolDefinition, ValidationError, WORKERS_AI_LLM_MODEL, WORKERS_AI_TIERS, WorkersAIProvider, WorkersAISpeechEngine, WorkersAISpeechResult, WorkersAITextOptions, apiKeyAvailable, audioTranscriptionAdapterFor, bootProvider, buildFalAudioInput, buildFalAudioLyrics, buildFalImageInput, buildFalTagPrompt, buildFalVideoInput, chatAdapterFor, configureProvider, consumeAnthropicStream, consumeGroqStream, createAdapterResolver, createAnthropicAdapter, createAssistantMessage, createFalProvider, createFalQueue, createGeminiProvider, createGroqProvider, createMessage, createOpenAiAudioTranscriptionAdapter, createOpenAiCompatibleAdapter, createOpenAiCompatibleProvider, createOpenAiEmbeddingsAdapter, createOpenAiImageAdapter, createOpenAiSpeechAdapter, createPrunaProvider, createSystemMessage, createUserMessage, createWorkersAIProvider, defaultEffortForModel, embeddingsAdapterFor, extractContentFromSsePayload, extractTextFromMessages, falQueueConfigured, formatMessagesForDisplay, generateImageThenVideo, generatePruna, generateWithPruna, getProvider, imageAdapterFor, mapAnthropicStopReason, parseFalAudioOutput, parseFalImageOutput, parseFalVideoOutput, pollForResult, promptToMessages, requestStructuredJson, resetProvider, resolveApiKey, runConversation, runWorkersAIText, speakWithWorkersAI, speechAdapterFor, streamWorkersAIText, submitPrediction, toGroqMessages, uploadImage, workersAIConfigured } from './providers/index.js';
|
|
9
9
|
export { A as AIProviderConfig, a as ANTHROPIC_API_VERSION, b as ANTHROPIC_DEFAULT_MAX_TOKENS, c as ANTHROPIC_MODELS, d as ANTHROPIC_TIERS, e as AnthropicEffort, f as AnthropicMessagesRequest, g as AnthropicMessagesResponse, h as AnthropicProviderConfig, i as AnthropicStopReason, j as AnthropicStreamEvent, G as GroqChatChunk, k as GroqChatRequest, l as GroqChatResponse, m as GroqChoice, n as GroqChunkChoice, o as GroqConfig, p as GroqErrorResponse, q as GroqGenerationConfig, r as GroqMessage, s as GroqMessageRole, t as GroqProviderConfig, u as GroqReasoningEffort, v as GroqUsage, O as OpenAiCompatibleProviderConfig, S as StreamRequestOptions, W as WorkersAIBinding, w as WorkersAIEnv, x as WorkersAIError, y as WorkersAIMessage, z as WorkersAIProviderConfig, B as createAI } from './create-ai-Cq3HkJxd.js';
|
|
10
10
|
export { C as CancellationError, G as GenerateOptions, a as GenerationStage, I as IGroqChatService, b as IGroqHttpClient, c as ImageToImageInput, d as ImageToVideoInput, P as PrunaAspectRatio, e as PrunaInput, f as PrunaModelId, g as PrunaOutput, h as PrunaPredictionResponse, i as PrunaResolution, j as PrunaResult, S as StreamingCallbacks, k as StructuredGenerationOptions, T as TextGenerationService, l as TextToImageInput, m as TextToVideoInput } from './cancellation-error-D9LETLCD.js';
|
|
11
11
|
export { C as ChatConfig, a as ChatConversation, b as ChatMessageSender, c as ChatMessageType, d as ChatService, e as ChatTokenUsage, f as ConversationMessage, D as DEFAULT_PROMPT_STRATEGY, I as IChatService, g as IChatStorage, h as IMessageFormatter, S as SendMessageInput, i as SendMessageResult, j as SystemPromptStrategy, U as UseChatOptions, k as UseChatReturn, l as extractTokenUsage } from './chat.service-B4Isrckn.js';
|
package/dist/index.js
CHANGED
|
@@ -320,6 +320,31 @@ function aiErrorStatus(code) {
|
|
|
320
320
|
return AI_ERROR_STATUS[code];
|
|
321
321
|
}
|
|
322
322
|
|
|
323
|
+
// src/core/errors/ai-failure.ts
|
|
324
|
+
var TYPE_TO_CODE = {
|
|
325
|
+
["INVALID_API_KEY" /* INVALID_API_KEY */]: "invalid_key",
|
|
326
|
+
["MISSING_CONFIG" /* MISSING_CONFIG */]: "missing_key",
|
|
327
|
+
["NETWORK_ERROR" /* NETWORK_ERROR */]: "network",
|
|
328
|
+
["ABORT_ERROR" /* ABORT_ERROR */]: "timeout",
|
|
329
|
+
["RATE_LIMIT_ERROR" /* RATE_LIMIT_ERROR */]: "rate_limited",
|
|
330
|
+
["SERVER_ERROR" /* SERVER_ERROR */]: "upstream_error",
|
|
331
|
+
["CLIENT_ERROR" /* CLIENT_ERROR */]: "invalid_request",
|
|
332
|
+
["UNKNOWN_ERROR" /* UNKNOWN_ERROR */]: "upstream_error"
|
|
333
|
+
};
|
|
334
|
+
function aiFailureOf(error) {
|
|
335
|
+
if (error instanceof AiError) {
|
|
336
|
+
return { code: error.code, status: AI_ERROR_STATUS[error.code], message: error.userMessage };
|
|
337
|
+
}
|
|
338
|
+
if (error instanceof AIError) {
|
|
339
|
+
const code = TYPE_TO_CODE[error.type];
|
|
340
|
+
return { code, status: AI_ERROR_STATUS[code], message: CODE_MESSAGES[code] };
|
|
341
|
+
}
|
|
342
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
343
|
+
return { code: "timeout", status: AI_ERROR_STATUS.timeout, message: CODE_MESSAGES.timeout };
|
|
344
|
+
}
|
|
345
|
+
return { code: "upstream_error", status: AI_ERROR_STATUS.upstream_error, message: CODE_MESSAGES.upstream_error };
|
|
346
|
+
}
|
|
347
|
+
|
|
323
348
|
// src/core/executor/retry-executor.strategy.ts
|
|
324
349
|
var RetryExecutor = class {
|
|
325
350
|
constructor(retryManager2, options) {
|
|
@@ -930,6 +955,34 @@ function failoverCandidate(primary, fallback) {
|
|
|
930
955
|
return fallback;
|
|
931
956
|
}
|
|
932
957
|
|
|
958
|
+
// src/core/utils/title.ts
|
|
959
|
+
function deriveConversationTitle(content, options = {}) {
|
|
960
|
+
const fallback = options.fallback ?? "";
|
|
961
|
+
const maxChars = options.maxChars ?? 60;
|
|
962
|
+
const firstLine = content.split("\n").map((line) => line.trim()).find((line) => line.length > 0);
|
|
963
|
+
const cleaned = (firstLine ?? fallback).replace(/^#{1,6}\s+/, "").replace(/^[>*-]\s+/, "").replace(/\s+/g, " ");
|
|
964
|
+
if (cleaned.length === 0) return fallback;
|
|
965
|
+
return cleaned.length > maxChars ? `${cleaned.slice(0, maxChars).trimEnd()}\u2026` : cleaned;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// src/core/utils/allowance-window.ts
|
|
969
|
+
var DEFAULT_ALLOWANCE_WINDOW_MS = 36e5;
|
|
970
|
+
function createAllowanceWindow(options) {
|
|
971
|
+
const windowMs = options.windowMs ?? DEFAULT_ALLOWANCE_WINDOW_MS;
|
|
972
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
973
|
+
return {
|
|
974
|
+
allow(key, now = Date.now()) {
|
|
975
|
+
const bucket = buckets.get(key);
|
|
976
|
+
if (bucket === void 0 || now - bucket.windowStart >= windowMs) {
|
|
977
|
+
buckets.set(key, { windowStart: now, count: 1 });
|
|
978
|
+
return true;
|
|
979
|
+
}
|
|
980
|
+
bucket.count += 1;
|
|
981
|
+
return bucket.count <= options.limit;
|
|
982
|
+
}
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
|
|
933
986
|
// src/core/constants/protocol.constants.ts
|
|
934
987
|
var SSE_PREFIX = "data: ";
|
|
935
988
|
var SSE_DONE_MARKER = "[DONE]";
|
|
@@ -1309,6 +1362,11 @@ function planTaskFailure(task, errorDetail, backoffBaseMs, now = /* @__PURE__ */
|
|
|
1309
1362
|
}
|
|
1310
1363
|
};
|
|
1311
1364
|
}
|
|
1365
|
+
var STUCK_TASK_THRESHOLD_MS = 15 * 60 * 1e3;
|
|
1366
|
+
function planStuckRecovery(task, now = /* @__PURE__ */ new Date(), thresholdMs = STUCK_TASK_THRESHOLD_MS) {
|
|
1367
|
+
if (now.getTime() - task.updatedAt.getTime() < thresholdMs) return null;
|
|
1368
|
+
return task.attempts >= task.maxAttempts ? { action: "fail" } : { action: "requeue" };
|
|
1369
|
+
}
|
|
1312
1370
|
|
|
1313
1371
|
// src/core/sse/sse-response.service.ts
|
|
1314
1372
|
var SSE_BRIDGE_EVENTS = {
|
|
@@ -1908,21 +1966,52 @@ async function readSseResponse(response, callbacks) {
|
|
|
1908
1966
|
callbacks.onError?.("request_failed", "The server returned an empty stream.");
|
|
1909
1967
|
return;
|
|
1910
1968
|
}
|
|
1911
|
-
const
|
|
1969
|
+
for await (const event of iterateSseJson(response)) {
|
|
1970
|
+
if (event) dispatchSseEvent(event, callbacks);
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
function dataPayloadOf(frame) {
|
|
1974
|
+
let data = null;
|
|
1975
|
+
for (const line of frame.split("\n")) {
|
|
1976
|
+
if (line.startsWith("data:")) {
|
|
1977
|
+
const payload = line.slice(5).trim();
|
|
1978
|
+
data = data === null ? payload : `${data}
|
|
1979
|
+
${payload}`;
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
return data !== null && data.length > 0 ? data : null;
|
|
1983
|
+
}
|
|
1984
|
+
async function* iterateSseData(source) {
|
|
1985
|
+
const body = source instanceof Response ? source.body : source;
|
|
1986
|
+
if (!body) {
|
|
1987
|
+
throw new Error("iterateSseData: the response has no body to read");
|
|
1988
|
+
}
|
|
1989
|
+
const reader = body.getReader();
|
|
1912
1990
|
const decoder = new TextDecoder();
|
|
1913
1991
|
let buffer = "";
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1992
|
+
try {
|
|
1993
|
+
while (true) {
|
|
1994
|
+
const { done, value } = await reader.read();
|
|
1995
|
+
if (done) break;
|
|
1996
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1997
|
+
let boundary = buffer.indexOf("\n\n");
|
|
1998
|
+
while (boundary !== -1) {
|
|
1999
|
+
const frame = buffer.slice(0, boundary);
|
|
2000
|
+
buffer = buffer.slice(boundary + 2);
|
|
2001
|
+
boundary = buffer.indexOf("\n\n");
|
|
2002
|
+
const data = dataPayloadOf(frame);
|
|
2003
|
+
if (data) yield data;
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
} finally {
|
|
2007
|
+
await reader.cancel().catch(() => void 0);
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
async function* iterateSseJson(source) {
|
|
2011
|
+
for await (const data of iterateSseData(source)) {
|
|
2012
|
+
try {
|
|
2013
|
+
yield JSON.parse(data);
|
|
2014
|
+
} catch {
|
|
1926
2015
|
}
|
|
1927
2016
|
}
|
|
1928
2017
|
}
|
|
@@ -6012,6 +6101,14 @@ function resetProvider() {
|
|
|
6012
6101
|
container?.groqHttpClient.reset();
|
|
6013
6102
|
container = null;
|
|
6014
6103
|
}
|
|
6104
|
+
function bootProvider(apiKey, options = {}) {
|
|
6105
|
+
if (!isValidApiKey(apiKey)) return null;
|
|
6106
|
+
return getProvider() ?? configureProvider({
|
|
6107
|
+
apiKey: apiKey.trim(),
|
|
6108
|
+
timeoutMs: options.timeoutMs ?? 3e4,
|
|
6109
|
+
textModel: options.textModel ?? GROQ_MODELS.GPT_OSS_120B
|
|
6110
|
+
});
|
|
6111
|
+
}
|
|
6015
6112
|
|
|
6016
6113
|
// src/providers/workers-ai/workers-ai.speech.ts
|
|
6017
6114
|
var WORKERS_AI_SPEECH_TIMEOUT_MS = 45e3;
|
|
@@ -8316,6 +8413,6 @@ function buildVideoRequest(data) {
|
|
|
8316
8413
|
}
|
|
8317
8414
|
}
|
|
8318
8415
|
|
|
8319
|
-
export { ABTestService, ADAPTER_MEDIA_TIMEOUT_MS, ADAPTER_TIMEOUT_MS, AIContentService, AIError, AIErrorType, AI_ERROR_STATUS, ANTHROPIC_API_VERSION, ANTHROPIC_DEFAULT_MAX_TOKENS, ANTHROPIC_MODELS, ANTHROPIC_TIERS, API_ENDPOINTS, ASPECT_RATIO_OPTIONS, ASPECT_RATIO_VALUES, AiError, AnalysisService, AnthropicHttpTransport, AnthropicProvider, AnthropicRequestBuilder, AuthenticationError, BaseProvider as BaseAIProvider, BaseProvider, BlogService, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, CODE_MESSAGES, CONTENT_WIZARD_STEPS, CacheManager, CancellationError, ChatIdGenerator, ChatService, CompositeExecutor, ContentCalendarService, DEFAULT_AI_IDENTITY, DEFAULT_API_KEY_RULE, DEFAULT_BASE_URL, DEFAULT_EMBED_BATCH_SIZE, DEFAULT_ERROR_CLASSIFICATION_RULE, DEFAULT_GENERATION, DEFAULT_GENERATION_CONFIG, DEFAULT_HTTP_STATUS_RULE, DEFAULT_MODELS, DEFAULT_PROMPT_STRATEGY, DEFAULT_RETRY_BACKOFF_MULTIPLIER, DEFAULT_RETRY_INITIAL_DELAY_MS, DEFAULT_RETRY_JITTER_FACTOR, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, DEFAULT_TASK_POLICIES, DebounceManager, DedupeExecutor, FAL_ASPECT_IMAGE_SIZES, FalProvider, FalQueueError, GEMINI_TIERS, GENERATION_BOUNDS, CREDIT_COSTS as GENERATION_COSTS, GROQ_MODELS, GROQ_TIERS, GeminiProvider, GenerationExecutor, GenerationFailedError, GroqChatRequestBuilder, GroqConfigStore, GroqError, AIErrorType as GroqErrorType, GroqHttpClient, GroqHttpTransport, GroqProvider, IMAGE_B64_LIMIT, IMAGE_QUALITIES, IMAGE_QUALITY_OPTIONS, IMAGE_QUALITY_VALUES, IMAGE_SIZES, IMAGE_WIZARD_STEPS, ImagePromptService, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, MOTION_OPTIONS, MediaGenerationService, OpenAiCompatibleProvider, PromptBuilder, ProviderError, ProviderFactory, ProviderQuotaExhaustedError, ProviderUnavailableError, PrunaProvider, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, RequestDeduplicator, RequestPriority, RequestQueue, RetryExecutor, RetryManager, SEARCH_MAX_RESULTS, SPEECH_INPUT_MAX, SPEECH_VOICES, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, STATUS_TO_CODE, STYLE_PRESETS, SYSTEM_PROMPT_VERSION, SeoService, SocialService, StreamingResponseParser, StructuredPromptBuilder, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TEXT_TIERS, TIMEOUTS, TRANSIENT_ERROR_CODES, TextGenerationService, ThrottleManager, TimeoutError, ToolCallAccumulator, USER_FRIENDLY_ERROR_MESSAGES, VIDEO_DURATION_OPTIONS, VIDEO_DURATION_OPTIONS_SECONDS, VIDEO_QUALITY_OPTIONS, VIDEO_QUALITY_VALUES, VIDEO_WIZARD_STEPS, ValidationError2 as ValidationError, VideoScriptService, WORKERS_AI_LLM_MODEL, WORKERS_AI_TIERS, WorkersAIError, WorkersAIProvider, accumulateReport, aiErrorMessage, aiErrorStatus, apiKeyAvailable, asObjectArray, asRecord, asStringArray, asTrimmedOptionalString, audioTranscriptionAdapterFor, batchEmbed, batchRequest, buildCacheKey, buildContentRequest, buildContext, buildFalAudioInput, buildFalAudioLyrics, buildFalImageInput, buildFalTagPrompt, buildFalVideoInput, buildHttpStatusFallback, buildImageRequest, buildResearchMessages, buildSystemPrompt, buildUsageDailySeries, buildUsageData, buildVideoRequest, cacheManager, calculateCacheHitRate, calculateContentCreditCost as calculateCreditCost, calculateExponentialBackoff, calculateTrailingDelay, canFailover, canStartTask, capText, chatAdapterFor, chatIdGenerator, chunkText, clampScore, classifyHttpStatus, computeCostMicros, configureProvider, consumeAnthropicStream, consumeGroqStream, cosineSimilarity, countChanges, createAI, createAdapterResolver, createAnthropicAdapter, createAssistantMessage, createFalProvider, createFalQueue, createGeminiProvider, createGroqProvider, createMessage, createOpenAiAudioTranscriptionAdapter, createOpenAiCompatibleAdapter, createOpenAiCompatibleProvider, createOpenAiEmbeddingsAdapter, createOpenAiImageAdapter, createOpenAiSpeechAdapter, createProviderFactory, createPrunaProvider, createRemoteChatClient, createSseResponse, createSystemMessage, createUserMessage, createWorkersAIProvider, debounce, debounceManager, defaultEffortForModel, defaultSseDeltaExtractor, deriveSnippetTitle, describeAIErrorType, diffLines, dotProduct, embeddingsAdapterFor, errorFromStatus, errorFromUnknown, errorRatePct, estimateMessageTokens, estimateTokens, extractContentFromSsePayload, extractErrorMessageFromJsonBody, extractErrorMessageFromResponse, extractJSON, extractJsonArray, extractJsonCandidate, extractJsonFromCodeFence, extractJsonObject, extractSseDataPayload, extractText, extractTextFromMessages, extractTokenUsage, failoverCandidate, falQueueConfigured, findTopKSimilar, formatCost, formatErrorForLogging, formatMessagesForDisplay, formatSseEvent, generateImageThenVideo, generate as generatePruna, generateRandomBase36Suffix, generateWithPruna, getDimensionsForAspectRatio, getProvider, getRecommendedQuality, imageAdapterFor, isAuthErrorType, isMediaProvider, isRetryableErrorType, isSseDataLine, isSseDoneMarker, isTextLike, isTextProvider, isTextTier, isTransientError, isValidApiKey, isValidJSON, isWithinWindow, magnitude, mapAnthropicStopReason, mergeTierOverrides, messageFormatter, nextAttemptDelayMs, normalizeGenerationSettings, normalizeSources, normalizeSseChunk, oneOfCatalog, parseAIResponse, parseFalAudioOutput, parseFalImageOutput, parseFalVideoOutput, parseSseEvent, planTaskFailure, pollForResult, promptToMessages, readSseResponse, repairCommonJsonDefects, replayFirst, requestDeduplicator, requestQueue, requestStructuredJson, resetProvider, resolveApiKey, resolveModel, resolveUserFriendlyErrorMessage, resolveUserFriendlyMessage, retryManager, runConversation, runWorkersAIText, safeJSONParse, searchWeb, selectLeastRecentlyUsedKey, selectMemories, shouldCallOnLeadingEdge, speakWithWorkersAI, speechAdapterFor, splitMarkdown, splitSseLines, sseStreamResponse, streamWorkersAIText, submitPrediction, throttle, throttleManager, toGroqMessages, uploadImage, usageTrendOf, usageWindowTotals, validateApiKey, validateToolArgs, withRetry, workersAIConfigured };
|
|
8416
|
+
export { ABTestService, ADAPTER_MEDIA_TIMEOUT_MS, ADAPTER_TIMEOUT_MS, AIContentService, AIError, AIErrorType, AI_ERROR_STATUS, ANTHROPIC_API_VERSION, ANTHROPIC_DEFAULT_MAX_TOKENS, ANTHROPIC_MODELS, ANTHROPIC_TIERS, API_ENDPOINTS, ASPECT_RATIO_OPTIONS, ASPECT_RATIO_VALUES, AiError, AnalysisService, AnthropicHttpTransport, AnthropicProvider, AnthropicRequestBuilder, AuthenticationError, BaseProvider as BaseAIProvider, BaseProvider, BlogService, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, CODE_MESSAGES, CONTENT_WIZARD_STEPS, CacheManager, CancellationError, ChatIdGenerator, ChatService, CompositeExecutor, ContentCalendarService, DEFAULT_AI_IDENTITY, DEFAULT_ALLOWANCE_WINDOW_MS, DEFAULT_API_KEY_RULE, DEFAULT_BASE_URL, DEFAULT_EMBED_BATCH_SIZE, DEFAULT_ERROR_CLASSIFICATION_RULE, DEFAULT_GENERATION, DEFAULT_GENERATION_CONFIG, DEFAULT_HTTP_STATUS_RULE, DEFAULT_MODELS, DEFAULT_PROMPT_STRATEGY, DEFAULT_RETRY_BACKOFF_MULTIPLIER, DEFAULT_RETRY_INITIAL_DELAY_MS, DEFAULT_RETRY_JITTER_FACTOR, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, DEFAULT_TASK_POLICIES, DebounceManager, DedupeExecutor, FAL_ASPECT_IMAGE_SIZES, FalProvider, FalQueueError, GEMINI_TIERS, GENERATION_BOUNDS, CREDIT_COSTS as GENERATION_COSTS, GROQ_MODELS, GROQ_TIERS, GeminiProvider, GenerationExecutor, GenerationFailedError, GroqChatRequestBuilder, GroqConfigStore, GroqError, AIErrorType as GroqErrorType, GroqHttpClient, GroqHttpTransport, GroqProvider, IMAGE_B64_LIMIT, IMAGE_QUALITIES, IMAGE_QUALITY_OPTIONS, IMAGE_QUALITY_VALUES, IMAGE_SIZES, IMAGE_WIZARD_STEPS, ImagePromptService, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, MOTION_OPTIONS, MediaGenerationService, OpenAiCompatibleProvider, PromptBuilder, ProviderError, ProviderFactory, ProviderQuotaExhaustedError, ProviderUnavailableError, PrunaProvider, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, RequestDeduplicator, RequestPriority, RequestQueue, RetryExecutor, RetryManager, SEARCH_MAX_RESULTS, SPEECH_INPUT_MAX, SPEECH_VOICES, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, STATUS_TO_CODE, STUCK_TASK_THRESHOLD_MS, STYLE_PRESETS, SYSTEM_PROMPT_VERSION, SeoService, SocialService, StreamingResponseParser, StructuredPromptBuilder, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TEXT_TIERS, TIMEOUTS, TRANSIENT_ERROR_CODES, TextGenerationService, ThrottleManager, TimeoutError, ToolCallAccumulator, USER_FRIENDLY_ERROR_MESSAGES, VIDEO_DURATION_OPTIONS, VIDEO_DURATION_OPTIONS_SECONDS, VIDEO_QUALITY_OPTIONS, VIDEO_QUALITY_VALUES, VIDEO_WIZARD_STEPS, ValidationError2 as ValidationError, VideoScriptService, WORKERS_AI_LLM_MODEL, WORKERS_AI_TIERS, WorkersAIError, WorkersAIProvider, accumulateReport, aiErrorMessage, aiErrorStatus, aiFailureOf, apiKeyAvailable, asObjectArray, asRecord, asStringArray, asTrimmedOptionalString, audioTranscriptionAdapterFor, batchEmbed, batchRequest, bootProvider, buildCacheKey, buildContentRequest, buildContext, buildFalAudioInput, buildFalAudioLyrics, buildFalImageInput, buildFalTagPrompt, buildFalVideoInput, buildHttpStatusFallback, buildImageRequest, buildResearchMessages, buildSystemPrompt, buildUsageDailySeries, buildUsageData, buildVideoRequest, cacheManager, calculateCacheHitRate, calculateContentCreditCost as calculateCreditCost, calculateExponentialBackoff, calculateTrailingDelay, canFailover, canStartTask, capText, chatAdapterFor, chatIdGenerator, chunkText, clampScore, classifyHttpStatus, computeCostMicros, configureProvider, consumeAnthropicStream, consumeGroqStream, cosineSimilarity, countChanges, createAI, createAdapterResolver, createAllowanceWindow, createAnthropicAdapter, createAssistantMessage, createFalProvider, createFalQueue, createGeminiProvider, createGroqProvider, createMessage, createOpenAiAudioTranscriptionAdapter, createOpenAiCompatibleAdapter, createOpenAiCompatibleProvider, createOpenAiEmbeddingsAdapter, createOpenAiImageAdapter, createOpenAiSpeechAdapter, createProviderFactory, createPrunaProvider, createRemoteChatClient, createSseResponse, createSystemMessage, createUserMessage, createWorkersAIProvider, debounce, debounceManager, defaultEffortForModel, defaultSseDeltaExtractor, deriveConversationTitle, deriveSnippetTitle, describeAIErrorType, diffLines, dotProduct, embeddingsAdapterFor, errorFromStatus, errorFromUnknown, errorRatePct, estimateMessageTokens, estimateTokens, extractContentFromSsePayload, extractErrorMessageFromJsonBody, extractErrorMessageFromResponse, extractJSON, extractJsonArray, extractJsonCandidate, extractJsonFromCodeFence, extractJsonObject, extractSseDataPayload, extractText, extractTextFromMessages, extractTokenUsage, failoverCandidate, falQueueConfigured, findTopKSimilar, formatCost, formatErrorForLogging, formatMessagesForDisplay, formatSseEvent, generateImageThenVideo, generate as generatePruna, generateRandomBase36Suffix, generateWithPruna, getDimensionsForAspectRatio, getProvider, getRecommendedQuality, imageAdapterFor, isAuthErrorType, isMediaProvider, isRetryableErrorType, isSseDataLine, isSseDoneMarker, isTextLike, isTextProvider, isTextTier, isTransientError, isValidApiKey, isValidJSON, isWithinWindow, iterateSseData, iterateSseJson, magnitude, mapAnthropicStopReason, mergeTierOverrides, messageFormatter, nextAttemptDelayMs, normalizeGenerationSettings, normalizeSources, normalizeSseChunk, oneOfCatalog, parseAIResponse, parseFalAudioOutput, parseFalImageOutput, parseFalVideoOutput, parseSseEvent, planStuckRecovery, planTaskFailure, pollForResult, promptToMessages, readSseResponse, repairCommonJsonDefects, replayFirst, requestDeduplicator, requestQueue, requestStructuredJson, resetProvider, resolveApiKey, resolveModel, resolveUserFriendlyErrorMessage, resolveUserFriendlyMessage, retryManager, runConversation, runWorkersAIText, safeJSONParse, searchWeb, selectLeastRecentlyUsedKey, selectMemories, shouldCallOnLeadingEdge, speakWithWorkersAI, speechAdapterFor, splitMarkdown, splitSseLines, sseStreamResponse, streamWorkersAIText, submitPrediction, throttle, throttleManager, toGroqMessages, uploadImage, usageTrendOf, usageWindowTotals, validateApiKey, validateToolArgs, withRetry, workersAIConfigured };
|
|
8320
8417
|
//# sourceMappingURL=index.js.map
|
|
8321
8418
|
//# sourceMappingURL=index.js.map
|