@umituz/web-ai 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +98 -2
- package/dist/AIErrors-B2ogd1PB.d.ts +197 -0
- package/dist/AIErrors-C5EasV_c.d.cts +197 -0
- package/dist/ContentGeneration-B6iK2B33.d.cts +93 -0
- package/dist/ContentGeneration-B6iK2B33.d.ts +93 -0
- package/dist/ProviderConfig-DIFa9nmG.d.cts +108 -0
- package/dist/ProviderConfig-DIFa9nmG.d.ts +108 -0
- package/dist/cache-manager-Df9LLYGA.d.cts +31 -0
- package/dist/cache-manager-Df9LLYGA.d.ts +31 -0
- package/dist/chat/index.cjs +625 -0
- package/dist/chat/index.cjs.map +1 -0
- package/dist/chat/index.d.cts +25 -0
- package/dist/chat/index.d.ts +25 -0
- package/dist/chat/index.js +618 -0
- package/dist/chat/index.js.map +1 -0
- package/dist/chat.service-CL1qtYxe.d.cts +124 -0
- package/dist/chat.service-q05GnhEm.d.ts +124 -0
- package/dist/content/index.cjs +3976 -0
- package/dist/content/index.cjs.map +1 -0
- package/dist/content/index.d.cts +224 -0
- package/dist/content/index.d.ts +224 -0
- package/dist/content/index.js +3945 -0
- package/dist/content/index.js.map +1 -0
- package/dist/core/index.cjs +1137 -0
- package/dist/core/index.cjs.map +1 -0
- package/dist/core/index.d.cts +204 -0
- package/dist/core/index.d.ts +204 -0
- package/dist/core/index.js +1064 -0
- package/dist/core/index.js.map +1 -0
- package/dist/create-ai-DOI9jD3v.d.cts +251 -0
- package/dist/create-ai-DXEoke8-.d.ts +251 -0
- package/dist/hooks/index.cjs +5246 -0
- package/dist/hooks/index.cjs.map +1 -0
- package/dist/hooks/index.d.cts +210 -0
- package/dist/hooks/index.d.ts +210 -0
- package/dist/hooks/index.js +5235 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/index-DIHz8_OJ.d.ts +48 -0
- package/dist/index-DKHNcMbl.d.cts +48 -0
- package/dist/index-fXjxTR5W.d.cts +66 -0
- package/dist/index-fXjxTR5W.d.ts +66 -0
- package/dist/index.cjs +3309 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +11 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +3197 -0
- package/dist/index.js.map +1 -0
- package/dist/provider.factory-BxsfK4WW.d.cts +110 -0
- package/dist/provider.factory-DfDfk0dK.d.ts +110 -0
- package/dist/providers/index.cjs +2567 -0
- package/dist/providers/index.cjs.map +1 -0
- package/dist/providers/index.d.cts +332 -0
- package/dist/providers/index.d.ts +332 -0
- package/dist/providers/index.js +2533 -0
- package/dist/providers/index.js.map +1 -0
- package/dist/request-deduplicator.util-NDo0_n1y.d.cts +50 -0
- package/dist/request-deduplicator.util-NDo0_n1y.d.ts +50 -0
- package/dist/wizard/index.cjs +230 -0
- package/dist/wizard/index.cjs.map +1 -0
- package/dist/wizard/index.d.cts +86 -0
- package/dist/wizard/index.d.ts +86 -0
- package/dist/wizard/index.js +223 -0
- package/dist/wizard/index.js.map +1 -0
- package/package.json +114 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/core/tiers/index.ts","../../src/core/errors/ai-error-types.ts","../../src/core/errors/ai-error.ts","../../src/core/errors/error-classifier.ts","../../src/core/errors/http-status-classifier.ts","../../src/core/errors/user-friendly-error-resolver.ts","../../src/core/errors/error-resolver.ts","../../src/core/errors/response-error-message-extractor.ts","../../src/core/executor/retry-executor.strategy.ts","../../src/core/executor/queue-executor.strategy.ts","../../src/core/executor/dedupe-executor.strategy.ts","../../src/core/executor/composite-executor.strategy.ts","../../src/core/calculations/lru-key-selector.ts","../../src/core/calculations/cache-hit-rate.ts","../../src/core/utils/cache-key-builder.ts","../../src/core/utils/cache-manager.ts","../../src/core/calculations/exponential-backoff.ts","../../src/core/constants/identifier.constants.ts","../../src/core/utils/retry.ts","../../src/core/utils/request-queue.util.ts","../../src/core/utils/request-deduplicator.util.ts","../../src/core/calculations/timing-window.ts","../../src/core/utils/debounce.ts","../../src/core/utils/api-key-validator.ts","../../src/core/utils/coercion.util.ts","../../src/core/constants/protocol.constants.ts","../../src/core/parsers/sse-lines.ts","../../src/core/parsers/streaming-response.parser.ts","../../src/core/parsers/json-content-extractor.ts","../../src/core/parsers/json-response.parser.ts","../../src/core/parsers/structured-prompt.builder.ts","../../src/core/sse/sse-response.service.ts"],"names":["AIErrorType","retryManager"],"mappings":";AASO,IAAM,UAAA,GAAsC,CAAC,MAAA,EAAQ,UAAA,EAAY,UAAU;AAE3E,SAAS,WAAW,KAAA,EAAmC;AAC5D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAa,UAAA,CAAiC,SAAS,KAAK,CAAA;AACtF;AAEO,SAAS,YAAA,CACd,KAAA,EACA,IAAA,EACA,UAAA,EACQ;AACR,EAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,IAAI,CAAA,IAAK,KAAA,CAAM,QAAA;AACnC,EAAA,IAAI,CAAC,KAAA,EAAO;AACV,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,EAAG,UAAU,CAAA,mCAAA,EAAsC,IAAI,CAAA,yDAAA;AAAA,KACzD;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AAEO,SAAS,kBAAA,CACd,UACA,SAAA,EACc;AACd,EAAA,IAAI,CAAC,WAAW,OAAO,QAAA;AACvB,EAAA,OAAO,EAAE,GAAG,QAAA,EAAU,GAAG,SAAA,EAAU;AACrC;;;AClCO,IAAK,WAAA,qBAAAA,YAAAA,KAAL;AACL,EAAAA,aAAA,iBAAA,CAAA,GAAkB,iBAAA;AAClB,EAAAA,aAAA,gBAAA,CAAA,GAAiB,gBAAA;AACjB,EAAAA,aAAA,eAAA,CAAA,GAAgB,eAAA;AAChB,EAAAA,aAAA,aAAA,CAAA,GAAc,aAAA;AACd,EAAAA,aAAA,kBAAA,CAAA,GAAmB,kBAAA;AACnB,EAAAA,aAAA,cAAA,CAA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IAAA,CAAK,iBAAA,CAAkB,OAAO,EAAE,IAAA,EAAM,QAAQ,SAAA,CAAU,GAAG,GAAG,CAAA;AAC9D,QAAA,MAAA,EAAO;AAAA,MACT;AAAA,IACF;AAAA,GACD,CAAA;AACD,EAAA,OAAO,IAAI,SAAS,MAAA,EAAQ;AAAA,IAC1B,OAAA,EAAS;AAAA,MACP,cAAA,EAAgB,kCAAA;AAAA,MAChB,eAAA,EAAiB,wBAAA;AAAA,MACjB,mBAAA,EAAqB;AAAA;AACvB,GACD,CAAA;AACH","file":"index.js","sourcesContent":["import type { TextTier } from \"../types\";\n\n/**\n * Per-provider default model per tier. Config can override any slot; an\n * explicit `model` on a request overrides everything. This table is the knob\n * that turns \"switch from Claude to Groq\" into a config edit.\n */\nexport type TierModelMap = Readonly<Partial<Record<TextTier, string>>>;\n\nexport const TEXT_TIERS: ReadonlyArray<TextTier> = [\"fast\", \"balanced\", \"powerful\"];\n\nexport function isTextTier(value: unknown): value is TextTier {\n return typeof value === \"string\" && (TEXT_TIERS as readonly string[]).includes(value);\n}\n\nexport function resolveModel(\n tiers: TierModelMap,\n tier: TextTier,\n providerId: string,\n): string {\n const model = tiers[tier] ?? tiers.balanced;\n if (!model) {\n throw new Error(\n `${providerId} has no model configured for tier \"${tier}\" — pass an explicit model or configure the tier map`,\n );\n }\n return model;\n}\n\nexport function mergeTierOverrides(\n defaults: TierModelMap,\n overrides?: TierModelMap,\n): TierModelMap {\n if (!overrides) return defaults;\n return { ...defaults, ...overrides };\n}\n","\nexport enum AIErrorType {\n INVALID_API_KEY = \"INVALID_API_KEY\",\n MISSING_CONFIG = \"MISSING_CONFIG\",\n NETWORK_ERROR = \"NETWORK_ERROR\",\n ABORT_ERROR = \"ABORT_ERROR\",\n RATE_LIMIT_ERROR = \"RATE_LIMIT_ERROR\",\n SERVER_ERROR = \"SERVER_ERROR\",\n CLIENT_ERROR = \"CLIENT_ERROR\",\n UNKNOWN_ERROR = \"UNKNOWN_ERROR\",\n}\n\nexport const USER_FRIENDLY_ERROR_MESSAGES: Readonly<Record<AIErrorType, string>> = {\n [AIErrorType.INVALID_API_KEY]: \"Please check your API key and try again.\",\n [AIErrorType.MISSING_CONFIG]: \"The provider is not configured. Please create a provider with createAI first.\",\n [AIErrorType.NETWORK_ERROR]: \"Network error. Please check your connection and try again.\",\n [AIErrorType.ABORT_ERROR]: \"Request was cancelled.\",\n [AIErrorType.RATE_LIMIT_ERROR]: \"You've reached the rate limit. Please wait a moment and try again.\",\n [AIErrorType.SERVER_ERROR]: \"The AI service is temporarily unavailable. Please try again later.\",\n [AIErrorType.CLIENT_ERROR]: \"The request was invalid. Please check your input and try again.\",\n [AIErrorType.UNKNOWN_ERROR]: \"An unexpected error occurred. Please try again.\",\n};\n","\nimport { AIErrorType } from \"./ai-error-types\";\n\nexport interface AIErrorMetadata {\n readonly status?: number;\n readonly url?: string;\n readonly [key: string]: unknown;\n}\n\nconst KNOWN_ERROR_TYPES = new Set<string>(Object.values(AIErrorType));\n\nfunction mapCodeToType(code: string): AIErrorType {\n switch (code) {\n case \"VALIDATION_ERROR\":\n case \"CLIENT_ERROR\":\n return AIErrorType.CLIENT_ERROR;\n case \"INVALID_API_KEY\":\n return AIErrorType.INVALID_API_KEY;\n case \"MISSING_CONFIG\":\n case \"PROVIDER_UNAVAILABLE\":\n return AIErrorType.MISSING_CONFIG;\n case \"PROVIDER_QUOTA_EXHAUSTED\":\n case \"RATE_LIMIT_ERROR\":\n return AIErrorType.RATE_LIMIT_ERROR;\n case \"NETWORK_ERROR\":\n case \"TIMEOUT\":\n return AIErrorType.NETWORK_ERROR;\n case \"ABORT_ERROR\":\n case \"ABORTED\":\n return AIErrorType.ABORT_ERROR;\n case \"SERVER_ERROR\":\n case \"PROVIDER_ERROR\":\n case \"NO_RESULT\":\n return AIErrorType.SERVER_ERROR;\n default:\n return AIErrorType.UNKNOWN_ERROR;\n }\n}\n\nfunction mapMessageToCode(message: string, fallback: string = \"UNKNOWN\"): string {\n const lower = message.toLowerCase();\n if (lower.includes(\"validation\")) return \"VALIDATION_ERROR\";\n if (lower.includes(\"quota\")) return \"PROVIDER_QUOTA_EXHAUSTED\";\n if (lower.includes(\"unavailable\")) return \"PROVIDER_UNAVAILABLE\";\n if (lower.includes(\"timeout\") || lower.includes(\"aborted\")) {\n return lower.includes(\"aborted\") ? \"ABORTED\" : \"TIMEOUT\";\n }\n if (lower.includes(\"parse\") || lower.includes(\"json\")) return \"PARSE_ERROR\";\n if (lower.includes(\"no result\")) return \"NO_RESULT\";\n if (lower.includes(\"network\") || lower.includes(\"fetch\")) return \"NETWORK_ERROR\";\n return fallback;\n}\n\nexport class AIError extends Error {\n public readonly type: AIErrorType;\n public readonly code: string;\n public readonly cause?: unknown;\n public readonly metadata: AIErrorMetadata;\n\n constructor(\n typeOrMessage: AIErrorType | string,\n messageOrCode?: string,\n cause?: unknown,\n metadata: AIErrorMetadata = {},\n ) {\n let effectiveType: AIErrorType;\n let effectiveMessage: string;\n let effectiveCode: string;\n\n if (KNOWN_ERROR_TYPES.has(typeOrMessage)) {\n effectiveType = typeOrMessage as AIErrorType;\n effectiveMessage = messageOrCode ?? \"\";\n effectiveCode = effectiveType;\n } else {\n effectiveMessage = typeOrMessage;\n effectiveCode = messageOrCode ?? \"UNKNOWN\";\n effectiveType = mapCodeToType(effectiveCode);\n }\n\n super(effectiveMessage);\n this.name = \"AIError\";\n this.type = effectiveType;\n this.code = effectiveCode;\n this.cause = cause;\n this.metadata = metadata;\n }\n\n static from(error: unknown, fallbackCode: string = \"UNKNOWN\"): AIError {\n if (error instanceof AIError) return error;\n if (error instanceof Error) {\n const code = mapMessageToCode(error.message, fallbackCode);\n return new AIError(error.message, code, error);\n }\n return new AIError(String(error), fallbackCode, error);\n }\n\n override toString(): string {\n const statusPart =\n typeof this.metadata.status === \"number\" ? ` (HTTP ${this.metadata.status})` : \"\";\n return `${this.name} [${this.type}]: ${this.message}${statusPart}`;\n }\n\n toJSON(): {\n name: string;\n type: AIErrorType;\n code: string;\n message: string;\n metadata: AIErrorMetadata;\n } {\n return {\n name: this.name,\n type: this.type,\n code: this.code,\n message: this.message,\n metadata: this.metadata,\n };\n }\n}\n","\nimport { AIErrorType } from \"./ai-error-types\";\n\nconst DEFAULT_RETRYABLE_TYPES: ReadonlySet<AIErrorType> = new Set([\n AIErrorType.NETWORK_ERROR,\n AIErrorType.RATE_LIMIT_ERROR,\n AIErrorType.SERVER_ERROR,\n]);\n\nconst DEFAULT_AUTH_TYPES: ReadonlySet<AIErrorType> = new Set([\n AIErrorType.INVALID_API_KEY,\n]);\n\nexport interface ErrorClassificationRule {\n readonly retryable: ReadonlySet<AIErrorType>;\n readonly auth: ReadonlySet<AIErrorType>;\n}\n\nexport const DEFAULT_ERROR_CLASSIFICATION_RULE: ErrorClassificationRule = {\n retryable: DEFAULT_RETRYABLE_TYPES,\n auth: DEFAULT_AUTH_TYPES,\n};\n\nexport function isRetryableErrorType(\n type: AIErrorType,\n rule: ErrorClassificationRule = DEFAULT_ERROR_CLASSIFICATION_RULE,\n): boolean {\n return rule.retryable.has(type);\n}\n\nexport function isAuthErrorType(\n type: AIErrorType,\n rule: ErrorClassificationRule = DEFAULT_ERROR_CLASSIFICATION_RULE,\n): boolean {\n return rule.auth.has(type);\n}\n","\nimport { AIErrorType } from \"./ai-error-types\";\n\nexport interface HttpStatusClassificationRule {\n readonly unauthorizedStatuses: ReadonlySet<number>;\n readonly rateLimitedStatus: number;\n readonly serverErrorThreshold: number;\n readonly clientErrorThreshold: number;\n}\n\nexport const DEFAULT_HTTP_STATUS_RULE: HttpStatusClassificationRule = {\n unauthorizedStatuses: new Set([401, 403]),\n rateLimitedStatus: 429,\n serverErrorThreshold: 500,\n clientErrorThreshold: 400,\n};\n\nexport function classifyHttpStatus(\n status: number,\n rule: HttpStatusClassificationRule = DEFAULT_HTTP_STATUS_RULE,\n): AIErrorType {\n if (rule.unauthorizedStatuses.has(status)) return AIErrorType.INVALID_API_KEY;\n if (status === rule.rateLimitedStatus) return AIErrorType.RATE_LIMIT_ERROR;\n if (status >= rule.serverErrorThreshold) return AIErrorType.SERVER_ERROR;\n if (status >= rule.clientErrorThreshold) return AIErrorType.CLIENT_ERROR;\n return AIErrorType.UNKNOWN_ERROR;\n}\n","\nimport { AIError } from \"./ai-error\";\nimport { AIErrorType, USER_FRIENDLY_ERROR_MESSAGES } from \"./ai-error-types\";\n\nconst KEYWORD_FALLBACK_RULES: ReadonlyArray<{ keywords: ReadonlyArray<string>; type: AIErrorType }> = [\n { keywords: [\"api key\", \"unauthorized\"], type: AIErrorType.INVALID_API_KEY },\n { keywords: [\"rate limit\"], type: AIErrorType.RATE_LIMIT_ERROR },\n { keywords: [\"network\", \"fetch\"], type: AIErrorType.NETWORK_ERROR },\n { keywords: [\"abort\"], type: AIErrorType.ABORT_ERROR },\n];\n\nexport function resolveUserFriendlyErrorMessage(error: unknown): string {\n if (error instanceof AIError) {\n return USER_FRIENDLY_ERROR_MESSAGES[error.type];\n }\n\n if (error instanceof Error) {\n const lower = error.message.toLowerCase();\n for (const rule of KEYWORD_FALLBACK_RULES) {\n if (rule.keywords.some((kw) => lower.includes(kw))) {\n return USER_FRIENDLY_ERROR_MESSAGES[rule.type];\n }\n }\n if (error.message.length > 0) return error.message;\n }\n\n return USER_FRIENDLY_ERROR_MESSAGES[AIErrorType.UNKNOWN_ERROR];\n}\n","\nimport { resolveUserFriendlyErrorMessage } from \"./user-friendly-error-resolver\";\nimport { AIError } from \"./ai-error\";\nimport { AIErrorType, USER_FRIENDLY_ERROR_MESSAGES } from \"./ai-error-types\";\nimport type { AIErrorMetadata } from \"./ai-error\";\n\nexport const resolveUserFriendlyMessage = resolveUserFriendlyErrorMessage;\n\nexport interface LoggedError {\n readonly message: string;\n readonly type: string;\n readonly stack?: string;\n readonly metadata?: AIErrorMetadata;\n}\n\nexport function formatErrorForLogging(error: unknown): LoggedError {\n if (error instanceof AIError) {\n return {\n message: error.message,\n type: error.type,\n stack: error.stack,\n metadata: error.metadata,\n };\n }\n if (error instanceof Error) {\n return { message: error.message, type: error.name, stack: error.stack };\n }\n return { message: String(error), type: typeof error };\n}\n\nexport { AIErrorType, USER_FRIENDLY_ERROR_MESSAGES };\n","\nimport { AIErrorType } from \"./ai-error-types\";\n\nexport interface AIErrorBody {\n readonly error?: { readonly message?: string };\n readonly message?: string;\n}\n\nexport function extractErrorMessageFromJsonBody(body: unknown): string | null {\n if (!body || typeof body !== \"object\") return null;\n const candidate = body as AIErrorBody;\n const message = candidate.error?.message ?? candidate.message;\n if (typeof message === \"string\" && message.length > 0) return message;\n return null;\n}\n\nexport function buildHttpStatusFallback(status: number, statusText: string): string {\n const trimmedStatusText = statusText.trim();\n if (trimmedStatusText.length > 0) {\n return `HTTP ${status}: ${trimmedStatusText}`;\n }\n return `HTTP ${status}`;\n}\n\nexport async function extractErrorMessageFromResponse(response: Response): Promise<string> {\n const body: unknown = await response.json().catch(() => null);\n const fromBody = extractErrorMessageFromJsonBody(body);\n if (fromBody) return fromBody;\n return buildHttpStatusFallback(response.status, response.statusText);\n}\n\nexport function describeAIErrorType(type: AIErrorType): string {\n return `AIError[${type}]`;\n}\n","\nimport type { IRequestExecutor } from \"./request-executor.strategy\";\nimport { RetryManager, RetryOptions } from \"../utils/retry\";\n\nexport class RetryExecutor<TArgs extends unknown[], TResult>\n implements IRequestExecutor<TArgs, TResult>\n{\n constructor(\n private readonly retryManager: RetryManager,\n private readonly options?: RetryOptions,\n ) {}\n\n execute(fn: (...args: TArgs) => Promise<TResult>, ...args: TArgs): Promise<TResult> {\n return this.retryManager.execute(() => fn(...args), this.options);\n }\n}\n","\nimport type { IRequestExecutor } from \"./request-executor.strategy\";\nimport { RequestQueue } from \"../utils/request-queue.util\";\n\nexport class QueueExecutor<TArgs extends unknown[], TResult>\n implements IRequestExecutor<TArgs, TResult>\n{\n constructor(\n private readonly queue: RequestQueue,\n private readonly priority: number,\n ) {}\n\n execute(fn: (...args: TArgs) => Promise<TResult>, ...args: TArgs): Promise<TResult> {\n return this.queue.add(() => fn(...args), this.priority);\n }\n}\n","\nimport type { IRequestExecutor } from \"./request-executor.strategy\";\nimport type { RequestDeduplicator } from \"../utils/request-deduplicator.util\";\n\nexport type KeyGenerator<TArgs extends unknown[]> = (...args: TArgs) => string;\n\nexport interface DedupeExecutorOptions<TArgs extends unknown[]> {\n readonly generateKey: KeyGenerator<TArgs>;\n}\n\nexport class DedupeExecutor<TArgs extends unknown[], TResult>\n implements IRequestExecutor<TArgs, TResult>\n{\n constructor(\n private readonly deduplicator: RequestDeduplicator,\n private readonly options: DedupeExecutorOptions<TArgs>,\n ) {}\n\n execute(fn: (...args: TArgs) => Promise<TResult>, ...args: TArgs): Promise<TResult> {\n const key = this.options.generateKey(...args);\n return this.deduplicator.execute(key, () => fn(...args));\n }\n}\n","\nimport type { IRequestExecutor } from \"./request-executor.strategy\";\n\ntype AnyExecutor = IRequestExecutor<unknown[], unknown>;\n\nexport class CompositeExecutor<TArgs extends unknown[], TResult>\n implements IRequestExecutor<TArgs, TResult>\n{\n private readonly executors: ReadonlyArray<AnyExecutor>;\n\n constructor(executors: ReadonlyArray<IRequestExecutor<TArgs, TResult>>) {\n this.executors = executors as unknown as ReadonlyArray<AnyExecutor>;\n }\n\n execute(fn: (...args: TArgs) => Promise<TResult>, ...args: TArgs): Promise<TResult> {\n const composed = this.compress(fn as unknown as (...a: unknown[]) => Promise<unknown>);\n return composed(...args) as Promise<TResult>;\n }\n\n private compress(fn: (...args: unknown[]) => Promise<unknown>): (...args: unknown[]) => Promise<unknown> {\n return this.executors.reduceRight(\n (innerFn, executor) => (...a: unknown[]) => executor.execute(innerFn, ...a),\n fn,\n );\n }\n}\n","\nexport interface AccessTimestamped {\n readonly lastAccess: number;\n}\n\nexport function selectLeastRecentlyUsedKey<K, V extends AccessTimestamped>(\n entries: ReadonlyMap<K, V>,\n): K | null {\n let oldestKey: K | null = null;\n let oldestAccess = Number.POSITIVE_INFINITY;\n\n for (const [key, entry] of entries.entries()) {\n if (entry.lastAccess < oldestAccess) {\n oldestAccess = entry.lastAccess;\n oldestKey = key;\n }\n }\n\n return oldestKey;\n}\n","\nexport interface AccessCounted {\n readonly accessCount: number;\n}\n\nexport function calculateCacheHitRate(\n entries: ReadonlyArray<AccessCounted>,\n): number {\n if (entries.length === 0) return 0;\n const totalAccess = entries.reduce((sum, e) => sum + e.accessCount, 0);\n return totalAccess / entries.length;\n}\n","\nexport function buildCacheKey(params: Readonly<Record<string, unknown>>): string {\n const sortedKeys = Object.keys(params).sort();\n const sortedParams: Record<string, unknown> = {};\n for (const key of sortedKeys) {\n sortedParams[key] = params[key];\n }\n return JSON.stringify(sortedParams);\n}\n","\nimport { selectLeastRecentlyUsedKey } from \"../calculations/lru-key-selector\";\nimport { calculateCacheHitRate } from \"../calculations/cache-hit-rate\";\nimport { buildCacheKey } from \"./cache-key-builder\";\n\ninterface CacheEntry<T> {\n readonly value: T;\n readonly timestamp: number;\n accessCount: number;\n lastAccess: number;\n}\n\nexport interface CacheOptions {\n readonly maxSize?: number;\n readonly ttl?: number;\n}\n\nconst DEFAULT_CACHE_MAX_SIZE = 100;\nconst DEFAULT_CACHE_TTL_MS = 300_000;\n\nexport class CacheManager {\n private readonly cache = new Map<string, CacheEntry<unknown>>();\n private readonly maxSize: number;\n private readonly ttl: number;\n\n constructor(options: CacheOptions = {}) {\n this.maxSize = options.maxSize ?? DEFAULT_CACHE_MAX_SIZE;\n this.ttl = options.ttl ?? DEFAULT_CACHE_TTL_MS;\n }\n\n get<T>(key: string): T | null {\n const entry = this.cache.get(key);\n if (!entry) return null;\n if (this.isExpired(entry)) {\n this.cache.delete(key);\n return null;\n }\n entry.accessCount += 1;\n entry.lastAccess = Date.now();\n return entry.value as T;\n }\n\n set<T>(key: string, value: T): void {\n if (this.cache.size >= this.maxSize && !this.cache.has(key)) {\n const lruKey = selectLeastRecentlyUsedKey(this.cache);\n if (lruKey !== null) this.cache.delete(lruKey);\n }\n this.cache.set(key, {\n value,\n timestamp: Date.now(),\n accessCount: 1,\n lastAccess: Date.now(),\n });\n }\n\n has(key: string): boolean {\n const entry = this.cache.get(key);\n return entry !== undefined && !this.isExpired(entry);\n }\n\n delete(key: string): boolean {\n return this.cache.delete(key);\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n generateKey(params: Readonly<Record<string, unknown>>): string {\n return buildCacheKey(params);\n }\n\n getStats(): CacheStats {\n const now = Date.now();\n const entries = Array.from(this.cache.entries()).map(([key, entry]) => ({\n key,\n accessCount: entry.accessCount,\n ageMs: now - entry.timestamp,\n }));\n const hitRate = calculateCacheHitRate(\n Array.from(this.cache.values()).map((e) => ({ accessCount: e.accessCount })),\n );\n return {\n size: this.cache.size,\n maxSize: this.maxSize,\n hitRate,\n entries,\n };\n }\n\n private isExpired(entry: CacheEntry<unknown>): boolean {\n return Date.now() - entry.timestamp > this.ttl;\n }\n}\n\nexport interface CacheStats {\n readonly size: number;\n readonly maxSize: number;\n readonly hitRate: number;\n readonly entries: ReadonlyArray<{\n readonly key: string;\n readonly accessCount: number;\n readonly ageMs: number;\n }>;\n}\n\nexport const cacheManager = new CacheManager();\n","\nexport interface ExponentialBackoffParams {\n readonly attempt: number;\n readonly initialDelay: number;\n readonly maxDelay: number;\n readonly backoffMultiplier: number;\n readonly jitterFactor: number;\n readonly random?: () => number;\n}\n\nexport function calculateExponentialBackoff(params: ExponentialBackoffParams): number {\n const {\n attempt,\n initialDelay,\n maxDelay,\n backoffMultiplier,\n jitterFactor,\n random = Math.random,\n } = params;\n\n const base = initialDelay * Math.pow(backoffMultiplier, Math.max(0, attempt - 1));\n const capped = Math.min(base, maxDelay);\n const jitterMultiplier = random() * 2 - 1;\n const jitter = capped * jitterFactor * jitterMultiplier;\n\n return Math.max(0, capped + jitter);\n}\n","\nexport const MESSAGE_ID_PREFIX = \"msg-\" as const;\nexport const CHAT_MESSAGE_ID_SUFFIX_LENGTH = 9;\nexport const CACHE_KEY_TYPE_COMPLETION = \"completion\" as const;\nexport const CACHE_KEY_TYPE_CHAT = \"chat\" as const;\nexport const CACHE_KEY_TYPE_RESPONSE = \"response\" as const;\nexport const SYSTEM_PROMPT_CACHE_PREFIX = \"system-prompt\" as const;\n\nexport const USER_ROLE = \"user\" as const;\nexport const ASSISTANT_ROLE = \"assistant\" as const;\nexport const SYSTEM_ROLE = \"system\" as const;\n\nexport const QUEUE_PRIORITY_USER_REQUEST = 10;\nexport const DEFAULT_RETRY_MAX_ATTEMPTS = 3;\nexport const DEFAULT_RETRY_INITIAL_DELAY_MS = 1000;\nexport const DEFAULT_RETRY_MAX_DELAY_MS = 10000;\nexport const DEFAULT_RETRY_BACKOFF_MULTIPLIER = 2;\nexport const DEFAULT_RETRY_JITTER_FACTOR = 0.1;\n","\nimport { AIError } from \"../errors/ai-error\";\nimport { calculateExponentialBackoff } from \"../calculations/exponential-backoff\";\nimport {\n isRetryableErrorType,\n DEFAULT_ERROR_CLASSIFICATION_RULE,\n} from \"../errors/error-classifier\";\nimport {\n DEFAULT_RETRY_MAX_ATTEMPTS,\n DEFAULT_RETRY_INITIAL_DELAY_MS,\n DEFAULT_RETRY_MAX_DELAY_MS,\n DEFAULT_RETRY_BACKOFF_MULTIPLIER,\n DEFAULT_RETRY_JITTER_FACTOR,\n} from \"../constants/identifier.constants\";\n\nexport interface RetryOptions {\n readonly maxAttempts?: number;\n readonly initialDelay?: number;\n readonly maxDelay?: number;\n readonly backoffMultiplier?: number;\n readonly jitterFactor?: number;\n readonly shouldRetry?: (error: Error) => boolean;\n}\n\nconst RETRYABLE_MESSAGE_KEYWORDS: ReadonlyArray<string> = [\n \"network\",\n \"timeout\",\n \"econnrefused\",\n \"enotfound\",\n \"etimedout\",\n];\n\nexport class RetryManager {\n private readonly defaults: Required<\n Pick<RetryOptions, \"maxAttempts\" | \"initialDelay\" | \"maxDelay\" | \"backoffMultiplier\" | \"jitterFactor\">\n >;\n\n constructor() {\n this.defaults = {\n maxAttempts: DEFAULT_RETRY_MAX_ATTEMPTS,\n initialDelay: DEFAULT_RETRY_INITIAL_DELAY_MS,\n maxDelay: DEFAULT_RETRY_MAX_DELAY_MS,\n backoffMultiplier: DEFAULT_RETRY_BACKOFF_MULTIPLIER,\n jitterFactor: DEFAULT_RETRY_JITTER_FACTOR,\n };\n }\n\n async execute<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {\n const maxAttempts = options.maxAttempts ?? this.defaults.maxAttempts;\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n if (attempt >= maxAttempts || !this.shouldRetry(lastError, options)) {\n throw lastError;\n }\n\n const delay = calculateExponentialBackoff({\n attempt,\n initialDelay: options.initialDelay ?? this.defaults.initialDelay,\n maxDelay: options.maxDelay ?? this.defaults.maxDelay,\n backoffMultiplier: options.backoffMultiplier ?? this.defaults.backoffMultiplier,\n jitterFactor: options.jitterFactor ?? this.defaults.jitterFactor,\n });\n await this.delay(delay);\n }\n }\n\n throw lastError ?? new Error(\"Retry loop exited without result\");\n }\n\n private shouldRetry(error: Error, options: RetryOptions): boolean {\n if (options.shouldRetry) return options.shouldRetry(error);\n\n if (error instanceof AIError) {\n return isRetryableErrorType(error.type, DEFAULT_ERROR_CLASSIFICATION_RULE);\n }\n\n const lower = error.message.toLowerCase();\n return RETRYABLE_MESSAGE_KEYWORDS.some((kw) => lower.includes(kw));\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\nexport const retryManager = new RetryManager();\n\nexport async function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n return retryManager.execute(fn, options);\n}\n","\ninterface QueuedRequest<T> {\n readonly id: string;\n readonly priority: number;\n readonly requestFn: () => Promise<T>;\n readonly resolve: (value: T) => void;\n readonly reject: (reason: unknown) => void;\n readonly timestamp: number;\n}\n\nexport interface QueueOptions {\n readonly maxConcurrent?: number;\n readonly defaultPriority?: number;\n readonly requestTimeout?: number;\n}\n\nconst DEFAULT_MAX_CONCURRENT = 3;\nconst DEFAULT_PRIORITY = 0;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\nexport class RequestQueue {\n private queue: QueuedRequest<unknown>[] = [];\n private readonly activeRequests = new Set<string>();\n private readonly maxConcurrent: number;\n private readonly defaultPriority: number;\n private readonly requestTimeout: number;\n private requestIdCounter = 0;\n\n constructor(options: QueueOptions = {}) {\n this.maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT;\n this.defaultPriority = options.defaultPriority ?? DEFAULT_PRIORITY;\n this.requestTimeout = options.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT_MS;\n }\n\n add<T>(requestFn: () => Promise<T>, priority?: number): Promise<T> {\n return new Promise((resolve, reject) => {\n const id = `req-${++this.requestIdCounter}`;\n const queuedRequest: QueuedRequest<T> = {\n id,\n priority: priority ?? this.defaultPriority,\n requestFn,\n resolve: resolve as (value: unknown) => void,\n reject,\n timestamp: Date.now(),\n };\n\n this.queue.push(queuedRequest as QueuedRequest<unknown>);\n this.sortQueue();\n this.process();\n });\n }\n\n cancelAll(): void {\n for (const request of this.queue) {\n request.reject(new Error(\"Request was cancelled\"));\n }\n this.queue = [];\n }\n\n private sortQueue(): void {\n this.queue.sort((a, b) => {\n if (a.priority !== b.priority) {\n return b.priority - a.priority;\n }\n return a.timestamp - b.timestamp;\n });\n }\n\n private process(): void {\n while (this.queue.length > 0 && this.activeRequests.size < this.maxConcurrent) {\n const request = this.queue.shift();\n if (!request) break;\n this.executeRequest(request);\n }\n }\n\n private executeRequest<T>(request: QueuedRequest<T>): void {\n this.activeRequests.add(request.id);\n\n const timeoutId = setTimeout(() => {\n this.activeRequests.delete(request.id);\n request.reject(new Error(`Request ${request.id} timed out`));\n this.process();\n }, this.requestTimeout);\n\n request.requestFn()\n .then((result) => {\n clearTimeout(timeoutId);\n request.resolve(result);\n })\n .catch((error: unknown) => {\n clearTimeout(timeoutId);\n request.reject(error);\n })\n .finally(() => {\n this.activeRequests.delete(request.id);\n this.process();\n });\n }\n}\n\nexport const requestQueue = new RequestQueue();\n","\ninterface PendingRequest<T> {\n readonly promise: Promise<T>;\n readonly timestamp: number;\n}\n\nconst DEFAULT_DEDUPE_TTL_MS = 30_000;\n\nexport class RequestDeduplicator {\n private readonly pendingRequests = new Map<string, PendingRequest<unknown>>();\n private readonly ttl: number;\n\n constructor(ttl: number = DEFAULT_DEDUPE_TTL_MS) {\n this.ttl = ttl;\n }\n\n execute<T>(key: string, requestFn: () => Promise<T>): Promise<T> {\n this.cleanup();\n\n const existing = this.pendingRequests.get(key);\n if (existing) {\n return existing.promise as Promise<T>;\n }\n\n const promise = requestFn();\n this.pendingRequests.set(key, {\n promise,\n timestamp: Date.now(),\n });\n\n // The cleanup chain must swallow its own rejection: callers handle the\n // original `promise`, and an unhandled `.finally` derivative would crash\n // hosts that treat unhandled rejections as fatal (Workers, vitest).\n promise\n .catch(() => undefined)\n .then(() => {\n this.pendingRequests.delete(key);\n });\n\n return promise;\n }\n\n cancelAll(): void {\n this.pendingRequests.clear();\n }\n\n private cleanup(): void {\n const now = Date.now();\n for (const [key, request] of this.pendingRequests.entries()) {\n if (now - request.timestamp > this.ttl) {\n this.pendingRequests.delete(key);\n }\n }\n }\n}\n\nexport const requestDeduplicator = new RequestDeduplicator();\n","\nexport interface LeadingEdgeParams {\n readonly now: number;\n readonly lastCallTime: number;\n readonly interval: number;\n readonly leadingEnabled: boolean;\n readonly isThrottled: boolean;\n}\n\nexport function shouldCallOnLeadingEdge(params: LeadingEdgeParams): boolean {\n const { now, lastCallTime, interval, leadingEnabled, isThrottled } = params;\n if (!leadingEnabled) return false;\n if (isThrottled) return false;\n return now - lastCallTime >= interval;\n}\n\nexport interface TrailingDelayParams {\n readonly interval: number;\n readonly timeSinceLastCall: number;\n}\n\nexport function calculateTrailingDelay(params: TrailingDelayParams): number {\n return Math.max(0, params.interval - params.timeSinceLastCall);\n}\n\nexport function isWithinWindow(now: number, lastCallTime: number, interval: number): boolean {\n return now - lastCallTime < interval;\n}\n","\nimport {\n shouldCallOnLeadingEdge,\n calculateTrailingDelay,\n} from \"../calculations/timing-window\";\n\ntype TimerHandle = ReturnType<typeof setTimeout>;\n\nexport interface DebounceOptions {\n readonly delay?: number;\n readonly leading?: boolean;\n readonly trailing?: boolean;\n}\n\nexport interface ThrottleOptions {\n readonly interval?: number;\n readonly leading?: boolean;\n readonly trailing?: boolean;\n}\n\nconst DEFAULT_DEBOUNCE_DELAY_MS = 300;\nconst DEFAULT_THROTTLE_INTERVAL_MS = 1000;\n\nexport class DebounceManager {\n private readonly timers = new Map<string, TimerHandle>();\n private readonly lastArgs = new Map<string, readonly unknown[]>();\n\n debounce<T extends (...args: never[]) => unknown>(\n fn: T,\n options: DebounceOptions = {},\n ): T {\n const delay = options.delay ?? DEFAULT_DEBOUNCE_DELAY_MS;\n const leading = options.leading ?? false;\n const trailing = options.trailing ?? true;\n\n let timer: TimerHandle | null = null;\n let lastCallTime = 0;\n let lastResult: unknown;\n\n return ((...args: never[]) => {\n const now = Date.now();\n const shouldCallLeading = shouldCallOnLeadingEdge({\n now,\n lastCallTime,\n interval: delay,\n leadingEnabled: leading,\n isThrottled: timer !== null,\n });\n\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n\n if (shouldCallLeading) {\n lastCallTime = now;\n lastResult = fn(...args);\n return lastResult;\n }\n\n if (trailing) {\n timer = setTimeout(() => {\n timer = null;\n lastCallTime = Date.now();\n lastResult = fn(...args);\n }, delay);\n }\n\n return lastResult;\n }) as T;\n }\n\n debounceByKey<T extends (...args: never[]) => unknown>(\n key: string,\n fn: T,\n delay: number = DEFAULT_DEBOUNCE_DELAY_MS,\n ): T {\n return ((...args: never[]) => {\n this.lastArgs.set(key, args);\n const existingTimer = this.timers.get(key);\n if (existingTimer) clearTimeout(existingTimer);\n\n const timer = setTimeout(() => {\n this.timers.delete(key);\n const pendingArgs = this.lastArgs.get(key);\n this.lastArgs.delete(key);\n if (pendingArgs) fn(...(pendingArgs as never[]));\n }, delay);\n\n this.timers.set(key, timer);\n }) as T;\n }\n\n cancelDebounce(key: string): void {\n const timer = this.timers.get(key);\n if (timer) {\n clearTimeout(timer);\n this.timers.delete(key);\n }\n this.lastArgs.delete(key);\n }\n\n flushDebounce<T extends (...args: never[]) => unknown>(\n key: string,\n fn: T,\n ): void {\n this.cancelDebounce(key);\n const args = this.lastArgs.get(key);\n if (args) {\n fn(...(args as never[]));\n this.lastArgs.delete(key);\n }\n }\n}\n\nexport class ThrottleManager {\n private readonly timers = new Map<string, TimerHandle>();\n private readonly lastArgs = new Map<string, readonly unknown[]>();\n\n throttle<T extends (...args: never[]) => unknown>(\n fn: T,\n options: ThrottleOptions = {},\n ): T {\n const interval = options.interval ?? DEFAULT_THROTTLE_INTERVAL_MS;\n const leading = options.leading ?? true;\n const trailing = options.trailing ?? false;\n\n let timer: TimerHandle | null = null;\n let lastCallTime = 0;\n let lastResult: unknown;\n let pendingArgs: readonly unknown[] | null = null;\n\n return ((...args: never[]) => {\n const now = Date.now();\n const timeSinceLastCall = now - lastCallTime;\n const shouldCall = shouldCallOnLeadingEdge({\n now,\n lastCallTime,\n interval,\n leadingEnabled: leading,\n isThrottled: timer !== null,\n });\n pendingArgs = args;\n\n if (shouldCall) {\n lastCallTime = now;\n lastResult = fn(...args);\n return lastResult;\n }\n\n if (trailing && !timer) {\n const delay = calculateTrailingDelay({ interval, timeSinceLastCall });\n timer = setTimeout(() => {\n timer = null;\n lastCallTime = Date.now();\n if (pendingArgs) {\n lastResult = fn(...(pendingArgs as never[]));\n pendingArgs = null;\n }\n }, delay);\n }\n\n return lastResult;\n }) as T;\n }\n\n throttleByKey<T extends (...args: never[]) => unknown>(\n key: string,\n fn: T,\n interval: number = DEFAULT_THROTTLE_INTERVAL_MS,\n ): T {\n return ((...args: never[]) => {\n const existingTimer = this.timers.get(key);\n if (existingTimer) {\n this.lastArgs.set(key, args);\n return;\n }\n\n fn(...args);\n\n const timer = setTimeout(() => {\n this.timers.delete(key);\n const pendingArgs = this.lastArgs.get(key);\n if (pendingArgs) {\n this.lastArgs.delete(key);\n fn(...(pendingArgs as never[]));\n const nextTimer = setTimeout(() => {\n this.timers.delete(key);\n }, interval);\n this.timers.set(key, nextTimer);\n }\n }, interval);\n\n this.timers.set(key, timer);\n }) as T;\n }\n\n cancelThrottle(key: string): void {\n const timer = this.timers.get(key);\n if (timer) {\n clearTimeout(timer);\n this.timers.delete(key);\n }\n this.lastArgs.delete(key);\n }\n\n isThrottled(key: string): boolean {\n return this.timers.has(key);\n }\n}\n\nexport const debounceManager = new DebounceManager();\nexport const throttleManager = new ThrottleManager();\n\nexport function debounce<T extends (...args: never[]) => unknown>(\n fn: T,\n delay?: number,\n): T {\n return debounceManager.debounce(fn, { delay });\n}\n\nexport function throttle<T extends (...args: never[]) => unknown>(\n fn: T,\n interval?: number,\n): T {\n return throttleManager.throttle(fn, { interval });\n}\n","\nexport interface ApiKeyValidationRule {\n readonly minLength: number;\n}\n\nexport const DEFAULT_API_KEY_RULE: ApiKeyValidationRule = {\n minLength: 10,\n};\n\nexport function isValidApiKey(\n apiKey: string | undefined | null,\n rule: ApiKeyValidationRule = DEFAULT_API_KEY_RULE,\n): apiKey is string {\n if (!apiKey) return false;\n return apiKey.trim().length >= rule.minLength;\n}\n\nexport function validateApiKey(\n apiKey: string | undefined | null,\n rule: ApiKeyValidationRule = DEFAULT_API_KEY_RULE,\n): { valid: boolean; reason?: string } {\n if (!apiKey) {\n return { valid: false, reason: \"API key is required\" };\n }\n const trimmed = apiKey.trim();\n if (trimmed.length === 0) {\n return { valid: false, reason: \"API key cannot be empty\" };\n }\n if (trimmed.length < rule.minLength) {\n return {\n valid: false,\n reason: `API key must be at least ${rule.minLength} characters`,\n };\n }\n return { valid: true };\n}\n","export function asRecord(value: unknown): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return {};\n return value as Record<string, unknown>;\n}\n\nexport function asStringArray(value: unknown, max: number): string[] {\n if (!Array.isArray(value)) return [];\n return value\n .filter((entry): entry is string => typeof entry === \"string\" && entry.trim().length > 0)\n .slice(0, max);\n}\n\nexport function asObjectArray(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) return [];\n return value.filter(\n (entry): entry is Record<string, unknown> =>\n typeof entry === \"object\" && entry !== null && !Array.isArray(entry),\n );\n}\n\nexport function asTrimmedOptionalString(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function clampScore(value: unknown, min: number, max: number): number | null {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return null;\n return Math.max(min, Math.min(max, Math.round(value)));\n}\n\nexport function oneOfCatalog<T extends readonly string[]>(\n catalog: T,\n value: unknown,\n): T[number] | null {\n return catalog.includes(value as T[number]) ? (value as T[number]) : null;\n}\n","export const SSE_PREFIX = \"data: \" as const;\nexport const SSE_DONE_MARKER = \"[DONE]\" as const;\n\nexport const JSON_CODE_BLOCK_PATTERN = /```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/;\nexport const JSON_OBJECT_PATTERN = /\\{[\\s\\S]*\\}/;\nexport const JSON_ARRAY_PATTERN = /\\[[\\s\\S]*\\]/;\n","import { SSE_DONE_MARKER, SSE_PREFIX } from \"../constants/protocol.constants\";\n\nexport function isSseDataLine(line: string): boolean {\n return line.startsWith(SSE_PREFIX) || line.startsWith(\"data:\");\n}\n\nexport function extractSseDataPayload(line: string): string {\n if (line.startsWith(SSE_PREFIX)) {\n return line.slice(SSE_PREFIX.length);\n }\n if (line.startsWith(\"data:\")) {\n return line.slice(5);\n }\n return line;\n}\n\nexport function isSseDoneMarker(payload: string): boolean {\n return payload === SSE_DONE_MARKER;\n}\n\nexport function splitSseLines(rawChunk: string): ReadonlyArray<string> {\n return rawChunk.split(\"\\n\").map((l) => l.trim()).filter((l) => l.length > 0);\n}\n\nexport interface NormalizedSseChunk {\n readonly payload: string;\n readonly isDone: boolean;\n}\n\nexport function normalizeSseChunk(rawChunk: string): ReadonlyArray<NormalizedSseChunk> {\n const lines = splitSseLines(rawChunk);\n const result: NormalizedSseChunk[] = [];\n for (const line of lines) {\n if (!isSseDataLine(line)) continue;\n const payload = extractSseDataPayload(line);\n result.push({ payload, isDone: isSseDoneMarker(payload) });\n }\n return result;\n}\n","import { AIError } from \"../errors/ai-error\";\nimport { AIErrorType } from \"../errors/ai-error-types\";\nimport {\n isSseDataLine,\n extractSseDataPayload,\n isSseDoneMarker,\n} from \"./sse-lines\";\n\n/**\n * Extracts the text delta from a single SSE `data:` payload, or null when the\n * payload carries no displayable text. Provider-specific: each provider passes\n * its own extractor so the line-buffering machinery below stays generic.\n */\nexport type SseDeltaExtractor = (payload: string) => string | null;\n\nexport interface StreamingParserCallbacks {\n readonly onChunk: (content: string) => void;\n}\n\nexport class StreamingResponseParser {\n private readonly decoder = new TextDecoder();\n\n constructor(\n private readonly callbacks: StreamingParserCallbacks,\n private readonly extractDelta: SseDeltaExtractor,\n ) {}\n\n async parse(stream: ReadableStream<Uint8Array>): Promise<string> {\n const reader = stream.getReader();\n const contentChunks: string[] = [];\n let buffer = \"\";\n\n const consumeLine = (rawLine: string): void => {\n const line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n const trimmed = line.trim();\n if (trimmed.length === 0 || !isSseDataLine(trimmed)) return;\n const payload = extractSseDataPayload(trimmed);\n if (isSseDoneMarker(payload)) return;\n const content = this.extractDelta(payload);\n if (content !== null) {\n contentChunks.push(content);\n this.callbacks.onChunk(content);\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += this.decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n for (const line of lines) consumeLine(line);\n }\n\n buffer += this.decoder.decode();\n if (buffer.length > 0) consumeLine(buffer);\n } catch (error) {\n if (error instanceof AIError) throw error;\n throw new AIError(\n AIErrorType.NETWORK_ERROR,\n \"Stream was interrupted\",\n error instanceof Error ? error : undefined,\n );\n } finally {\n reader.releaseLock();\n }\n\n return contentChunks.join(\"\");\n }\n}\n","\nimport {\n JSON_ARRAY_PATTERN,\n JSON_CODE_BLOCK_PATTERN,\n JSON_OBJECT_PATTERN,\n} from \"../constants/protocol.constants\";\n\nexport function extractJsonFromCodeFence(content: string): string | null {\n const match = content.match(JSON_CODE_BLOCK_PATTERN);\n if (match && match[1]) return match[1].trim();\n return null;\n}\n\nexport function extractJsonObject(content: string): string | null {\n const match = content.match(JSON_OBJECT_PATTERN);\n if (match && match[0]) return match[0];\n return null;\n}\n\nexport function extractJsonArray(content: string): string | null {\n const match = content.match(JSON_ARRAY_PATTERN);\n if (match && match[0]) return match[0];\n return null;\n}\n\nexport function repairCommonJsonDefects(text: string): string {\n return text\n .replace(/(:\\s*-?\\d+(?:\\.\\d+)?)\\s*\"/g, \"$1\")\n .replace(/(:\\s*\"[^\"]*\")\"/g, \"$1\");\n}\n\nexport function extractJsonCandidate(content: string): string {\n const fromFence = extractJsonFromCodeFence(content);\n if (fromFence) return fromFence;\n\n const objectIndex = content.indexOf(\"{\");\n const arrayIndex = content.indexOf(\"[\");\n\n if (objectIndex !== -1 && (arrayIndex === -1 || objectIndex < arrayIndex)) {\n const obj = extractJsonObject(content);\n if (obj) return obj;\n } else if (arrayIndex !== -1) {\n const arr = extractJsonArray(content);\n if (arr) return arr;\n }\n\n return content.trim();\n}\n","\nimport { AIError } from \"../errors/ai-error\";\nimport { AIErrorType } from \"../errors/ai-error-types\";\nimport { extractJsonCandidate, repairCommonJsonDefects } from \"./json-content-extractor\";\n\nexport class JsonResponseParser {\n parse<T>(rawContent: string): T {\n const candidate = extractJsonCandidate(rawContent);\n try {\n return JSON.parse(candidate) as T;\n } catch {\n try {\n return JSON.parse(repairCommonJsonDefects(candidate)) as T;\n } catch (error) {\n throw new AIError(\n AIErrorType.UNKNOWN_ERROR,\n \"Failed to parse structured response as JSON\",\n error instanceof Error ? error : undefined,\n { rawContent },\n );\n }\n }\n }\n}\n","\nexport class StructuredPromptBuilder {\n private schema: Record<string, unknown> | undefined;\n private request: string;\n\n constructor(request: string) {\n this.request = request;\n }\n\n static for(request: string): StructuredPromptBuilder {\n return new StructuredPromptBuilder(request);\n }\n\n withSchema(schema: Record<string, unknown> | undefined): this {\n this.schema = schema;\n return this;\n }\n\n build(): string {\n const schemaSection = this.schema\n ? `Expected JSON schema:\\n${JSON.stringify(this.schema, null, 2)}\\n\\n`\n : \"\";\n\n return (\n \"Please generate a JSON response for the following request.\\n\\n\" +\n schemaSection +\n `Request:\\n${this.request}\\n\\n` +\n \"Respond only with valid JSON, formatted as:\\n```json\\n{...}\\n```\"\n );\n }\n}\n","import {\n extractSseDataPayload,\n isSseDataLine,\n isSseDoneMarker,\n} from \"../parsers/sse-lines\";\nimport type { SseDeltaExtractor } from \"../parsers/streaming-response.parser\";\n\nexport const SSE_BRIDGE_EVENTS = {\n delta: \"delta\",\n done: \"done\",\n error: \"error\",\n} as const;\n\nexport interface SseResponseOptions {\n readonly donePayload: unknown;\n readonly errorCode: (error: unknown) => string;\n readonly onStreamFailure?: (error: unknown) => Promise<void> | void;\n /** Provider-specific: pulls the displayable text delta out of an SSE payload. */\n readonly extractDelta: SseDeltaExtractor;\n}\n\nexport function createSseResponse(\n openUpstream: () => Promise<ReadableStream<Uint8Array>>,\n options: SseResponseOptions,\n): Response {\n const encoder = new TextEncoder();\n const decoder = new TextDecoder();\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n let closed = false;\n const emit = (event: string, data: unknown) => {\n if (closed) return;\n try {\n controller.enqueue(\n encoder.encode(`event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`),\n );\n } catch {\n closed = true;\n }\n };\n const finish = () => {\n if (closed) return;\n closed = true;\n try {\n controller.close();\n } catch {\n closed = true;\n }\n };\n let delivered = false;\n const consumeLine = (line: string): boolean => {\n const trimmed = line.trim();\n if (!isSseDataLine(trimmed)) return false;\n const payload = extractSseDataPayload(trimmed);\n if (isSseDoneMarker(payload)) return true;\n const text = options.extractDelta(payload);\n if (text) {\n delivered = true;\n emit(SSE_BRIDGE_EVENTS.delta, { text });\n }\n return false;\n };\n try {\n const upstream = await openUpstream();\n const reader = upstream.getReader();\n let buffer = \"\";\n let finished = false;\n while (!finished) {\n const { value, done: readerDone } = await reader.read();\n if (readerDone) break;\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n for (const line of lines) {\n finished = consumeLine(line);\n if (finished) break;\n }\n }\n if (!finished && buffer.length > 0) consumeLine(buffer);\n emit(SSE_BRIDGE_EVENTS.done, options.donePayload);\n finish();\n } catch (err) {\n if (!delivered && options.onStreamFailure) {\n await options.onStreamFailure(err);\n }\n emit(SSE_BRIDGE_EVENTS.error, { code: options.errorCode(err) });\n finish();\n }\n },\n });\n return new Response(stream, {\n headers: {\n \"content-type\": \"text/event-stream; charset=utf-8\",\n \"cache-control\": \"no-cache, no-transform\",\n \"x-accel-buffering\": \"no\",\n },\n });\n}\n"]}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { c as TextTier } from './index-fXjxTR5W.cjs';
|
|
2
|
+
import { c as ProviderFactory } from './provider.factory-BxsfK4WW.cjs';
|
|
3
|
+
import { c as TierModelMap } from './index-DKHNcMbl.cjs';
|
|
4
|
+
import { c as GeminiConfig, F as FalConfig, P as PrunaConfig } from './ProviderConfig-DIFa9nmG.cjs';
|
|
5
|
+
|
|
6
|
+
declare const ANTHROPIC_MODELS: {
|
|
7
|
+
readonly OPUS_5_5: "claude-opus-5-5";
|
|
8
|
+
readonly SONNET_5_5: "claude-sonnet-5-5";
|
|
9
|
+
readonly HAIKU_5_5: "claude-haiku-5-5";
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Neutral tier → Claude model. fast = Haiku for cheap high-volume turns,
|
|
13
|
+
* balanced = Sonnet for everyday quality, powerful = Opus for the heavy
|
|
14
|
+
* lifting. Override per instance via `models` in provider config.
|
|
15
|
+
*/
|
|
16
|
+
declare const ANTHROPIC_TIERS: TierModelMap;
|
|
17
|
+
/**
|
|
18
|
+
* Single bump point for the wire protocol version. Every request sends this
|
|
19
|
+
* as the `anthropic-version` header; the shapes in anthropic.entities.ts are
|
|
20
|
+
* pinned to it.
|
|
21
|
+
*/
|
|
22
|
+
declare const ANTHROPIC_API_VERSION: "2026-10-21";
|
|
23
|
+
/** The Messages API requires max_tokens on every request. */
|
|
24
|
+
declare const ANTHROPIC_DEFAULT_MAX_TOKENS = 16000;
|
|
25
|
+
type AnthropicEffort = "low" | "medium" | "high";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Anthropic Messages API wire types, pinned to anthropic-version 2026-10-21.
|
|
29
|
+
* Two hard rules live here as types so the builder cannot violate them:
|
|
30
|
+
* - `max_tokens` is required on every request.
|
|
31
|
+
* - sampling parameters (temperature/top_p) are NOT part of this request
|
|
32
|
+
* shape — this API version rejects them with a 400.
|
|
33
|
+
*/
|
|
34
|
+
interface AnthropicProviderConfig {
|
|
35
|
+
readonly apiKey: string;
|
|
36
|
+
readonly baseUrl?: string;
|
|
37
|
+
readonly timeoutMs?: number;
|
|
38
|
+
/** Per-tier model overrides; merged over ANTHROPIC_TIERS. */
|
|
39
|
+
readonly models?: TierModelMap;
|
|
40
|
+
/** Reasoning effort hint; defaults come from ANTHROPIC_DEFAULT_EFFORT per model. */
|
|
41
|
+
readonly effort?: AnthropicEffort;
|
|
42
|
+
}
|
|
43
|
+
type AnthropicMessageRole = "user" | "assistant";
|
|
44
|
+
interface AnthropicMessage {
|
|
45
|
+
readonly role: AnthropicMessageRole;
|
|
46
|
+
readonly content: string;
|
|
47
|
+
}
|
|
48
|
+
interface AnthropicOutputConfig {
|
|
49
|
+
/** Reasoning effort: low | medium | high. Omitted when not specified. */
|
|
50
|
+
readonly effort?: AnthropicEffort;
|
|
51
|
+
}
|
|
52
|
+
interface AnthropicMessagesRequest {
|
|
53
|
+
readonly model: string;
|
|
54
|
+
readonly messages: AnthropicMessage[];
|
|
55
|
+
/** Required — the API rejects requests without it. */
|
|
56
|
+
readonly max_tokens: number;
|
|
57
|
+
/** Top-level system prompt slot; preferred over in-band system messages. */
|
|
58
|
+
readonly system?: string;
|
|
59
|
+
readonly output_config?: AnthropicOutputConfig;
|
|
60
|
+
readonly stop_sequences?: string[];
|
|
61
|
+
readonly stream?: boolean;
|
|
62
|
+
}
|
|
63
|
+
interface AnthropicTextBlock {
|
|
64
|
+
readonly type: "text";
|
|
65
|
+
readonly text: string;
|
|
66
|
+
}
|
|
67
|
+
type AnthropicContentBlock = AnthropicTextBlock;
|
|
68
|
+
type AnthropicStopReason = "end_turn" | "max_tokens" | "stop_sequence" | "refusal";
|
|
69
|
+
interface AnthropicUsage {
|
|
70
|
+
readonly input_tokens: number;
|
|
71
|
+
readonly output_tokens: number;
|
|
72
|
+
}
|
|
73
|
+
interface AnthropicMessagesResponse {
|
|
74
|
+
readonly id: string;
|
|
75
|
+
readonly type: "message";
|
|
76
|
+
readonly role: "assistant";
|
|
77
|
+
readonly model: string;
|
|
78
|
+
readonly content: AnthropicContentBlock[];
|
|
79
|
+
readonly stop_reason: AnthropicStopReason | null;
|
|
80
|
+
readonly stop_sequence: string | null;
|
|
81
|
+
readonly usage: AnthropicUsage;
|
|
82
|
+
}
|
|
83
|
+
interface AnthropicMessageStartEvent {
|
|
84
|
+
readonly type: "message_start";
|
|
85
|
+
readonly message: {
|
|
86
|
+
readonly id: string;
|
|
87
|
+
readonly model: string;
|
|
88
|
+
readonly usage?: AnthropicUsage;
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
interface AnthropicContentBlockDeltaEvent {
|
|
92
|
+
readonly type: "content_block_delta";
|
|
93
|
+
readonly index: number;
|
|
94
|
+
/** text_delta events carry text; other delta kinds (thinking etc.) don't. */
|
|
95
|
+
readonly delta: {
|
|
96
|
+
readonly type: string;
|
|
97
|
+
readonly text?: string;
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
interface AnthropicMessageDeltaEvent {
|
|
101
|
+
readonly type: "message_delta";
|
|
102
|
+
readonly delta: {
|
|
103
|
+
readonly stop_reason?: AnthropicStopReason | null;
|
|
104
|
+
};
|
|
105
|
+
readonly usage?: AnthropicUsage;
|
|
106
|
+
}
|
|
107
|
+
interface AnthropicMessageStopEvent {
|
|
108
|
+
readonly type: "message_stop";
|
|
109
|
+
}
|
|
110
|
+
interface AnthropicErrorEvent {
|
|
111
|
+
readonly type: "error";
|
|
112
|
+
readonly error: {
|
|
113
|
+
readonly type: string;
|
|
114
|
+
readonly message: string;
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
type AnthropicStreamEvent = AnthropicMessageStartEvent | AnthropicContentBlockDeltaEvent | AnthropicMessageDeltaEvent | AnthropicMessageStopEvent | AnthropicErrorEvent;
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Groq wire types. The `Groq` prefix is deliberate: these describe Groq's
|
|
121
|
+
* OpenAI-compatible chat/completions wire format and nothing else. Providers
|
|
122
|
+
* translate core `TextRequest`s into these; the rest of the package never
|
|
123
|
+
* sees them.
|
|
124
|
+
*/
|
|
125
|
+
interface GroqProviderConfig {
|
|
126
|
+
readonly apiKey: string;
|
|
127
|
+
readonly baseUrl?: string;
|
|
128
|
+
readonly timeoutMs?: number;
|
|
129
|
+
/** Per-tier model overrides; merged over GROQ_TIERS. */
|
|
130
|
+
readonly models?: TierModelMap;
|
|
131
|
+
}
|
|
132
|
+
type GroqReasoningEffort = "low" | "medium" | "high";
|
|
133
|
+
interface GroqGenerationConfig {
|
|
134
|
+
readonly temperature?: number;
|
|
135
|
+
readonly maxTokens?: number;
|
|
136
|
+
readonly topP?: number;
|
|
137
|
+
readonly n?: number;
|
|
138
|
+
readonly stop?: string[];
|
|
139
|
+
readonly frequencyPenalty?: number;
|
|
140
|
+
readonly presencePenalty?: number;
|
|
141
|
+
readonly reasoningEffort?: GroqReasoningEffort;
|
|
142
|
+
}
|
|
143
|
+
type GroqMessageRole = "system" | "user" | "assistant";
|
|
144
|
+
interface GroqMessage {
|
|
145
|
+
readonly role: GroqMessageRole;
|
|
146
|
+
readonly content: string;
|
|
147
|
+
}
|
|
148
|
+
interface GroqChatRequest {
|
|
149
|
+
readonly model: string;
|
|
150
|
+
readonly messages: GroqMessage[];
|
|
151
|
+
readonly temperature?: number;
|
|
152
|
+
readonly max_tokens?: number;
|
|
153
|
+
readonly top_p?: number;
|
|
154
|
+
readonly n?: number;
|
|
155
|
+
readonly stop?: string[];
|
|
156
|
+
readonly frequency_penalty?: number;
|
|
157
|
+
readonly presence_penalty?: number;
|
|
158
|
+
readonly reasoning_effort?: GroqReasoningEffort;
|
|
159
|
+
readonly response_format?: {
|
|
160
|
+
readonly type: "json_object";
|
|
161
|
+
};
|
|
162
|
+
readonly stream?: boolean;
|
|
163
|
+
}
|
|
164
|
+
type GroqFinishReason = "stop" | "length" | "content_filter";
|
|
165
|
+
interface GroqChoice {
|
|
166
|
+
readonly index: number;
|
|
167
|
+
readonly message: {
|
|
168
|
+
readonly role: "assistant";
|
|
169
|
+
readonly content: string;
|
|
170
|
+
};
|
|
171
|
+
readonly finish_reason: GroqFinishReason;
|
|
172
|
+
readonly logprobs: null | object;
|
|
173
|
+
}
|
|
174
|
+
interface GroqUsage {
|
|
175
|
+
readonly prompt_tokens: number;
|
|
176
|
+
readonly completion_tokens: number;
|
|
177
|
+
readonly total_tokens: number;
|
|
178
|
+
readonly prompt_time?: number;
|
|
179
|
+
readonly completion_time?: number;
|
|
180
|
+
readonly total_time?: number;
|
|
181
|
+
}
|
|
182
|
+
interface GroqChatResponse {
|
|
183
|
+
readonly id: string;
|
|
184
|
+
readonly object: string;
|
|
185
|
+
readonly created: number;
|
|
186
|
+
readonly model: string;
|
|
187
|
+
readonly choices: GroqChoice[];
|
|
188
|
+
readonly usage: GroqUsage;
|
|
189
|
+
readonly system_fingerprint?: string;
|
|
190
|
+
readonly x_groq?: {
|
|
191
|
+
readonly id?: string;
|
|
192
|
+
/** Present on the final chunk of a stream when usage accounting is enabled. */
|
|
193
|
+
readonly usage?: GroqUsage;
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
interface GroqChunkChoice {
|
|
197
|
+
readonly index: number;
|
|
198
|
+
readonly delta: {
|
|
199
|
+
readonly role?: "assistant";
|
|
200
|
+
readonly content?: string;
|
|
201
|
+
};
|
|
202
|
+
readonly finish_reason: GroqFinishReason | null;
|
|
203
|
+
readonly logprobs: null | object;
|
|
204
|
+
}
|
|
205
|
+
interface GroqChatChunk {
|
|
206
|
+
readonly id: string;
|
|
207
|
+
readonly object: string;
|
|
208
|
+
readonly created: number;
|
|
209
|
+
readonly model: string;
|
|
210
|
+
readonly choices: GroqChunkChoice[];
|
|
211
|
+
readonly system_fingerprint?: string;
|
|
212
|
+
readonly x_groq?: {
|
|
213
|
+
readonly id?: string;
|
|
214
|
+
readonly usage?: GroqUsage;
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
interface StreamRequestOptions {
|
|
218
|
+
readonly signal?: AbortSignal;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Composition root for the whole package — replaces the old
|
|
223
|
+
* `configureProvider()` singleton. A provider block's presence means the
|
|
224
|
+
* provider is enabled; presence of its apiKey is what actually registers it.
|
|
225
|
+
* `priority` decides who serves first; the fallback walk handles the rest.
|
|
226
|
+
*
|
|
227
|
+
* ```ts
|
|
228
|
+
* const ai = createAI({
|
|
229
|
+
* priority: ['anthropic', 'groq'],
|
|
230
|
+
* defaultTier: 'balanced',
|
|
231
|
+
* anthropic: { apiKey: env.ANTHROPIC_API_KEY },
|
|
232
|
+
* groq: { apiKey: env.GROQ_API_KEY },
|
|
233
|
+
* });
|
|
234
|
+
* const { text, usage } = await ai.chat({ messages, systemPrompt });
|
|
235
|
+
* ```
|
|
236
|
+
*/
|
|
237
|
+
interface AIProviderConfig {
|
|
238
|
+
/** Provider ids in preference order for every capability. */
|
|
239
|
+
priority?: ReadonlyArray<string>;
|
|
240
|
+
fallbackEnabled?: boolean;
|
|
241
|
+
/** Tier used when a request names neither model nor tier. Default 'balanced'. */
|
|
242
|
+
defaultTier?: TextTier;
|
|
243
|
+
anthropic?: AnthropicProviderConfig;
|
|
244
|
+
groq?: GroqProviderConfig;
|
|
245
|
+
gemini?: Omit<GeminiConfig, "enabled">;
|
|
246
|
+
fal?: Omit<FalConfig, "enabled">;
|
|
247
|
+
pruna?: Omit<PrunaConfig, "enabled">;
|
|
248
|
+
}
|
|
249
|
+
declare function createAI(config?: AIProviderConfig): ProviderFactory;
|
|
250
|
+
|
|
251
|
+
export { type AIProviderConfig as A, type GroqChatChunk as G, type StreamRequestOptions as S, ANTHROPIC_API_VERSION as a, ANTHROPIC_DEFAULT_MAX_TOKENS as b, ANTHROPIC_MODELS as c, ANTHROPIC_TIERS as d, type AnthropicEffort as e, type AnthropicMessagesRequest as f, type AnthropicMessagesResponse as g, type AnthropicProviderConfig as h, type AnthropicStopReason as i, type AnthropicStreamEvent as j, type GroqChatRequest as k, type GroqChatResponse as l, type GroqMessage as m, type GroqProviderConfig as n, createAI as o, type AnthropicMessage as p, type GroqGenerationConfig as q };
|