@umituz/web-ai 1.0.11 → 1.2.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.
Files changed (48) hide show
  1. package/README.md +29 -3
  2. package/dist/{cancellation-error-_39nYWwz.d.cts → cancellation-error-BWb59Wkj.d.cts} +1 -1
  3. package/dist/{cancellation-error-hYcE9AS9.d.ts → cancellation-error-D9LETLCD.d.ts} +1 -1
  4. package/dist/chat/index.cjs +1 -0
  5. package/dist/chat/index.cjs.map +1 -1
  6. package/dist/chat/index.js +1 -0
  7. package/dist/chat/index.js.map +1 -1
  8. package/dist/content/index.cjs +622 -8
  9. package/dist/content/index.cjs.map +1 -1
  10. package/dist/content/index.d.cts +2 -2
  11. package/dist/content/index.d.ts +2 -2
  12. package/dist/content/index.js +622 -8
  13. package/dist/content/index.js.map +1 -1
  14. package/dist/context-manager-CuZz0vnC.d.cts +104 -0
  15. package/dist/context-manager-CuZz0vnC.d.ts +104 -0
  16. package/dist/core/index.cjs +147 -10
  17. package/dist/core/index.cjs.map +1 -1
  18. package/dist/core/index.d.cts +91 -73
  19. package/dist/core/index.d.ts +91 -73
  20. package/dist/core/index.js +141 -11
  21. package/dist/core/index.js.map +1 -1
  22. package/dist/{create-ai-D-oEWzf9.d.ts → create-ai-Cq3HkJxd.d.ts} +61 -1
  23. package/dist/{create-ai-DRysRImc.d.cts → create-ai-DDyTVzef.d.cts} +61 -1
  24. package/dist/hooks/index.cjs +747 -15
  25. package/dist/hooks/index.cjs.map +1 -1
  26. package/dist/hooks/index.d.cts +57 -4
  27. package/dist/hooks/index.d.ts +57 -4
  28. package/dist/hooks/index.js +746 -16
  29. package/dist/hooks/index.js.map +1 -1
  30. package/dist/index.cjs +1180 -242
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.cts +7 -6
  33. package/dist/index.d.ts +7 -6
  34. package/dist/index.js +1140 -243
  35. package/dist/index.js.map +1 -1
  36. package/dist/providers/index.cjs +1212 -362
  37. package/dist/providers/index.cjs.map +1 -1
  38. package/dist/providers/index.d.cts +422 -10
  39. package/dist/providers/index.d.ts +422 -10
  40. package/dist/providers/index.js +1179 -363
  41. package/dist/providers/index.js.map +1 -1
  42. package/dist/remote-chat-client-LrNlew4n.d.cts +70 -0
  43. package/dist/remote-chat-client-LrNlew4n.d.ts +70 -0
  44. package/dist/{requestQueue-D89wx91Q.d.cts → requestQueue--h2uZ-Q3.d.cts} +1 -1
  45. package/dist/{requestQueue-AP6n_bRH.d.ts → requestQueue-BGeCy4Fd.d.ts} +1 -1
  46. package/package.json +1 -1
  47. package/dist/tool-call-accumulator-C7KhaXZA.d.cts +0 -69
  48. package/dist/tool-call-accumulator-C7KhaXZA.d.ts +0 -69
@@ -2,9 +2,10 @@ import { c as TokenUsage, C as ChatMessage } from '../index-OhvYUTXf.cjs';
2
2
  export { F as FinishReason, G as GenerationResult, P as ProviderHealth, S as StructuredGeneration, a as StructuredTextRequest, T as TextRequest, b as TextTier } from '../index-OhvYUTXf.cjs';
3
3
  import { A as AIError, b as AIErrorType, a as AIErrorMetadata } from '../index-Dv8gRzAu.cjs';
4
4
  export { 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';
5
- import { b as RetryManager, c as RetryOptions, a as RequestQueue, R as RequestDeduplicator } from '../tool-call-accumulator-C7KhaXZA.cjs';
6
- export { A as AssistantToolCall, Q as QueueOptions, T as ToolCallAccumulator, W as WireToolCallDelta, r as requestDeduplicator, d as requestQueue, e as retryManager, w as withRetry } from '../tool-call-accumulator-C7KhaXZA.cjs';
5
+ import { a as AiErrorCode, g as RetryManager, h as RetryOptions, f as RequestQueue, R as RequestDeduplicator } from '../context-manager-CuZz0vnC.cjs';
6
+ export { A as AiError, b as AssistantToolCall, C as CODE_MESSAGES, c as ContextBudget, d as ContextMessage, e as ContextRole, P as ProviderErrorShape, Q as QueueOptions, 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';
7
7
  export { C as CacheManager, a as CacheOptions, b as CacheStats, c as cacheManager } from '../cache-manager-Df9LLYGA.cjs';
8
+ 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-LrNlew4n.cjs';
8
9
 
9
10
  type GroqErrorMetadata = AIErrorMetadata;
10
11
 
@@ -55,21 +56,30 @@ declare function buildHttpStatusFallback(status: number, statusText: string): st
55
56
  declare function extractErrorMessageFromResponse(response: Response): Promise<string>;
56
57
  declare function describeAIErrorType(type: AIErrorType): string;
57
58
 
58
- type AiErrorCode = 'invalid_key' | 'missing_key' | 'rate_limited' | 'capacity' | 'timeout' | 'invalid_request' | 'model_unavailable' | 'upstream_error' | 'network' | 'cancelled';
59
- declare const STATUS_TO_CODE: Readonly<Record<number, AiErrorCode>>;
60
- declare const CODE_MESSAGES: Readonly<Record<AiErrorCode, string>>;
61
- declare class AiError extends Error {
62
- readonly code: AiErrorCode;
63
- constructor(code: AiErrorCode, message?: string);
64
- get userMessage(): string;
65
- }
66
- declare function aiErrorMessage(code: AiErrorCode): string;
67
- interface ProviderErrorShape {
68
- readonly type?: string;
69
- readonly code?: string;
70
- }
71
- declare function errorFromStatus(status: number, detail?: string, provider?: ProviderErrorShape): AiError;
72
- declare function errorFromUnknown(err: unknown): AiError;
59
+ /**
60
+ * HTTP status each AiErrorCode maps to when an AI failure is surfaced
61
+ * through a server route (hono/express-style `c.json(body, status)`).
62
+ *
63
+ * The map is intentionally `as const` so indexed access keeps the literal
64
+ * types — frameworks like hono type their status argument as a union of
65
+ * known literals, and a plain `Record<AiErrorCode, number>` would widen
66
+ * past it.
67
+ */
68
+ declare const AI_ERROR_STATUS: {
69
+ readonly invalid_key: 502;
70
+ readonly missing_key: 503;
71
+ readonly rate_limited: 429;
72
+ readonly capacity: 503;
73
+ readonly timeout: 504;
74
+ readonly invalid_request: 400;
75
+ readonly model_unavailable: 503;
76
+ readonly upstream_error: 502;
77
+ readonly network: 502;
78
+ readonly cancelled: 400;
79
+ };
80
+ /** Status for a single code; kept as a function for call sites that only
81
+ * have the code, not an AiError instance. */
82
+ declare function aiErrorStatus(code: AiErrorCode): number;
73
83
 
74
84
  interface IRequestExecutor<TArgs extends unknown[], TResult> {
75
85
  execute(fn: (...args: TArgs) => Promise<TResult>, ...args: TArgs): Promise<TResult>;
@@ -340,25 +350,6 @@ interface SseResponseOptions {
340
350
  declare function defaultSseDeltaExtractor(payload: string): string | null;
341
351
  declare function createSseResponse(openUpstream: () => Promise<ReadableStream<Uint8Array>>, options: SseResponseOptions): Response;
342
352
 
343
- type ContextRole = 'system' | 'user' | 'assistant' | 'tool';
344
- interface ContextMessage {
345
- readonly role: ContextRole;
346
- readonly content: string;
347
- readonly toolCalls?: ReadonlyArray<{
348
- id: string;
349
- name: string;
350
- arguments: string;
351
- }>;
352
- readonly toolCallId?: string;
353
- }
354
- interface ContextBudget {
355
- readonly contextWindow: number;
356
- readonly maxOutputTokens: number;
357
- }
358
- declare function estimateTokens(text: string): number;
359
- declare function estimateMessageTokens(message: ContextMessage): number;
360
- declare function buildContext<T extends ContextMessage = ContextMessage>(history: ReadonlyArray<T>, systemPrompt: string, budget: ContextBudget): T[];
361
-
362
353
  declare const SYSTEM_PROMPT_VERSION = 2;
363
354
  declare const DEFAULT_AI_IDENTITY: string;
364
355
  interface ProjectContext {
@@ -536,42 +527,6 @@ declare const GENERATION_BOUNDS: {
536
527
  declare const DEFAULT_GENERATION: Required<GenerationSettings>;
537
528
  declare function normalizeGenerationSettings(requested: GenerationSettings | undefined, maxModelTokens?: number): Required<GenerationSettings>;
538
529
 
539
- interface StreamCallbacks<TToolCall = unknown> {
540
- onDelta(channel: 'answer' | 'reasoning', text: string): void;
541
- onUsage?(usage: {
542
- inputTokens: number;
543
- outputTokens: number;
544
- reasoningTokens?: number;
545
- }): void;
546
- onToolCall?(toolCall: TToolCall): void;
547
- onDone?(messageId: string): void;
548
- onError?(code: string, message: string): void;
549
- }
550
- type ParsedSseEvent<TToolCall = unknown> = {
551
- readonly type: 'delta';
552
- readonly channel: 'answer' | 'reasoning';
553
- readonly text: string;
554
- } | {
555
- readonly type: 'usage';
556
- readonly usage: {
557
- readonly inputTokens: number;
558
- readonly outputTokens: number;
559
- readonly reasoningTokens?: number;
560
- };
561
- } | {
562
- readonly type: 'tool_call';
563
- readonly toolCall: TToolCall;
564
- } | {
565
- readonly type: 'done';
566
- readonly messageId: string;
567
- } | {
568
- readonly type: 'error';
569
- readonly code: string;
570
- readonly message: string;
571
- };
572
- declare function parseSseEvent<TToolCall = unknown>(rawEvent: string): ParsedSseEvent<TToolCall> | null;
573
- declare function readSseResponse<TToolCall = unknown>(response: Response, callbacks: StreamCallbacks<TToolCall>): Promise<void>;
574
-
575
530
  type ToolValidationResult = {
576
531
  readonly ok: true;
577
532
  } | {
@@ -602,6 +557,69 @@ interface ZodLikeSchema {
602
557
  type ToolSchema = ToolValidatorFunction | ZodLikeSchema;
603
558
  declare function validateToolArgs(toolKey: string, args: Record<string, unknown>, schemas: Record<string, ToolSchema>): ToolValidationResult;
604
559
 
560
+ /**
561
+ * Usage analytics over sparse day aggregates.
562
+ *
563
+ * Servers typically bucket usage rows per UTC day in SQL and hand back only
564
+ * the days that have data. These helpers turn those sparse rows into a
565
+ * zero-filled daily series and derive the window totals / trends / error
566
+ * rates a usage dashboard needs — pure functions, no persistence coupling.
567
+ */
568
+ /** One point of a zero-filled daily series (UTC `YYYY-MM-DD` date keys). */
569
+ interface UsageSeriesPoint {
570
+ readonly date: string;
571
+ readonly requests: number;
572
+ readonly attempts: number;
573
+ readonly errors: number;
574
+ readonly inputTokens: number;
575
+ readonly outputTokens: number;
576
+ readonly reasoningTokens: number;
577
+ readonly costMicros: number;
578
+ }
579
+ /** Sparse usage aggregate for a day, straight from SQL. Numbers may arrive
580
+ * as strings depending on the driver (pg/bigint columns). */
581
+ interface UsageSeriesDayRow {
582
+ readonly date: string;
583
+ readonly requests?: number | string | null;
584
+ readonly inputTokens?: number | string | null;
585
+ readonly outputTokens?: number | string | null;
586
+ readonly reasoningTokens?: number | string | null;
587
+ readonly costMicros?: number | string | null;
588
+ }
589
+ /** Sparse message-attempt aggregate for a day (attempts vs errors). */
590
+ interface UsageSeriesMessageRow {
591
+ readonly date: string;
592
+ readonly attempts?: number | string | null;
593
+ readonly errors?: number | string | null;
594
+ }
595
+ interface UsageWindowTotals {
596
+ readonly requests: number;
597
+ readonly attempts: number;
598
+ readonly errors: number;
599
+ readonly inputTokens: number;
600
+ readonly outputTokens: number;
601
+ readonly costMicros: number;
602
+ }
603
+ interface UsageTrendPoint {
604
+ readonly current: number;
605
+ readonly previous: number;
606
+ /** Percentage change; null when the previous window was empty (avoid ±∞). */
607
+ readonly deltaPct: number | null;
608
+ }
609
+ /**
610
+ * Merge sparse SQL day aggregates into a zero-filled series covering the
611
+ * last `days` UTC days ending today. Both trend windows (current +
612
+ * previous) fit in the result when called with the doubled length.
613
+ */
614
+ declare function buildUsageDailySeries(days: number, usageRows: readonly UsageSeriesDayRow[], messageRows: readonly UsageSeriesMessageRow[], today?: Date): UsageSeriesPoint[];
615
+ /** Sum a contiguous slice of the daily series. `to` is exclusive; both may
616
+ * be negative (Python-style windowing over the tail of the series). */
617
+ declare function usageWindowTotals(series: readonly UsageSeriesPoint[], from: number, to: number): UsageWindowTotals;
618
+ /** Percentage change between two windows; null when the previous window is empty. */
619
+ declare function usageTrendOf(current: number, previous: number): UsageTrendPoint;
620
+ /** Errors / attempts as a percentage (0–100); 0 when there were no attempts. */
621
+ declare function errorRatePct(errors: number, attempts: number): number;
622
+
605
623
  declare const SSE_PREFIX: "data: ";
606
624
  declare const SSE_DONE_MARKER: "[DONE]";
607
625
  declare const JSON_CODE_BLOCK_PATTERN: RegExp;
@@ -613,4 +631,4 @@ declare const DEFAULT_RETRY_MAX_DELAY_MS = 10000;
613
631
  declare const DEFAULT_RETRY_BACKOFF_MULTIPLIER = 2;
614
632
  declare const DEFAULT_RETRY_JITTER_FACTOR = 0.1;
615
633
 
616
- export { AIError, type AIErrorBody, AIErrorMetadata, AIErrorType, type AccessCounted, type AccessTimestamped, type AgentContext, AiError, type AiErrorCode, type ApiKeyValidationRule, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, CODE_MESSAGES, ChatMessage, type ChunkOptions, CompositeExecutor, type ContextBudget, type ContextMessage, type ContextRole, 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, type DebounceOptions, DedupeExecutor, type DedupeExecutorOptions, type DiffChangeCount, type DiffLine, type EmbeddingsBatchAdapter, type ErrorClassificationRule, type ExponentialBackoffParams, type FailoverErrorLike, type FetchLike, GENERATION_BOUNDS, type GenerationSettings, GroqError, type GroqErrorMetadata, AIErrorType as GroqErrorType, type HttpStatusClassificationRule, type IRequestExecutor, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, type LeadingEdgeParams, type LoggedError, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, type MarkdownSegment, type MemoryLike, type ModelPricing, type ModelWithProvider, type NormalizedSseChunk, type ParsedSseEvent, type ProjectContext, type ProviderErrorShape, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, RequestDeduplicator, RequestQueue, type ResearchSource, type ResearchStreamEvent, RetryExecutor, RetryManager, RetryOptions, SEARCH_MAX_RESULTS, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, STATUS_TO_CODE, SYSTEM_PROMPT_VERSION, type SearchTopic, type SseDeltaExtractor, type SseResponseOptions, type StreamCallbacks, type StreamEvent, type StreamingParserCallbacks, StreamingResponseParser, StructuredPromptBuilder, type SystemPromptInput, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TRANSIENT_ERROR_CODES, type TaskPlan, type TaskPolicy, type TaskState, ThrottleManager, type ThrottleOptions, TokenUsage, type ToolSchema, type ToolValidationResult, type ToolValidatorFunction, type TrailingDelayParams, type UsageRecordData, type UsageRecordInput, type VectorCandidate, type VectorMatch, type WebSearchInput, type WebSearchResponse, type WebSearchResult, type ZodLikeIssue, type ZodLikeSchema, accumulateReport, aiErrorMessage, asObjectArray, asRecord, asStringArray, asTrimmedOptionalString, batchEmbed, buildCacheKey, buildContext, buildHttpStatusFallback, buildResearchMessages, buildSystemPrompt, buildUsageData, calculateCacheHitRate, calculateExponentialBackoff, calculateTrailingDelay, canFailover, canStartTask, capText, chunkText, clampScore, classifyHttpStatus, computeCostMicros, cosineSimilarity, countChanges, createSseResponse, debounce, debounceManager, defaultSseDeltaExtractor, deriveSnippetTitle, describeAIErrorType, diffLines, dotProduct, errorFromStatus, errorFromUnknown, estimateMessageTokens, estimateTokens, 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, parseSseEvent, planTaskFailure, readSseResponse, repairCommonJsonDefects, replayFirst, resolveUserFriendlyErrorMessage, resolveUserFriendlyMessage, searchWeb, selectLeastRecentlyUsedKey, selectMemories, shouldCallOnLeadingEdge, splitMarkdown, splitSseLines, sseStreamResponse, throttle, throttleManager, validateApiKey, validateToolArgs };
634
+ export { AIError, type AIErrorBody, AIErrorMetadata, AIErrorType, AI_ERROR_STATUS, type AccessCounted, type AccessTimestamped, type AgentContext, AiErrorCode, type ApiKeyValidationRule, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, ChatMessage, type 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, type DebounceOptions, DedupeExecutor, type DedupeExecutorOptions, type DiffChangeCount, type DiffLine, type EmbeddingsBatchAdapter, type ErrorClassificationRule, type ExponentialBackoffParams, type FailoverErrorLike, type FetchLike, GENERATION_BOUNDS, type GenerationSettings, GroqError, type GroqErrorMetadata, AIErrorType as GroqErrorType, type HttpStatusClassificationRule, type IRequestExecutor, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, type LeadingEdgeParams, type LoggedError, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, type MarkdownSegment, type MemoryLike, type ModelPricing, type ModelWithProvider, type NormalizedSseChunk, type ProjectContext, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, RequestDeduplicator, RequestQueue, type ResearchSource, type ResearchStreamEvent, RetryExecutor, RetryManager, RetryOptions, SEARCH_MAX_RESULTS, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, SYSTEM_PROMPT_VERSION, type SearchTopic, type SseDeltaExtractor, type SseResponseOptions, type StreamEvent, type StreamingParserCallbacks, StreamingResponseParser, StructuredPromptBuilder, type SystemPromptInput, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TRANSIENT_ERROR_CODES, type TaskPlan, type TaskPolicy, type TaskState, ThrottleManager, type ThrottleOptions, TokenUsage, type ToolSchema, type ToolValidationResult, type ToolValidatorFunction, type TrailingDelayParams, type UsageRecordData, type UsageRecordInput, type UsageSeriesDayRow, type UsageSeriesMessageRow, type UsageSeriesPoint, type UsageTrendPoint, type UsageWindowTotals, type VectorCandidate, type VectorMatch, type WebSearchInput, type WebSearchResponse, type WebSearchResult, type ZodLikeIssue, type 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 };
@@ -2,9 +2,10 @@ import { c as TokenUsage, C as ChatMessage } from '../index-OhvYUTXf.js';
2
2
  export { F as FinishReason, G as GenerationResult, P as ProviderHealth, S as StructuredGeneration, a as StructuredTextRequest, T as TextRequest, b as TextTier } from '../index-OhvYUTXf.js';
3
3
  import { A as AIError, b as AIErrorType, a as AIErrorMetadata } from '../index-1e91KRYU.js';
4
4
  export { 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';
5
- import { b as RetryManager, c as RetryOptions, a as RequestQueue, R as RequestDeduplicator } from '../tool-call-accumulator-C7KhaXZA.js';
6
- export { A as AssistantToolCall, Q as QueueOptions, T as ToolCallAccumulator, W as WireToolCallDelta, r as requestDeduplicator, d as requestQueue, e as retryManager, w as withRetry } from '../tool-call-accumulator-C7KhaXZA.js';
5
+ import { a as AiErrorCode, g as RetryManager, h as RetryOptions, f as RequestQueue, R as RequestDeduplicator } from '../context-manager-CuZz0vnC.js';
6
+ export { A as AiError, b as AssistantToolCall, C as CODE_MESSAGES, c as ContextBudget, d as ContextMessage, e as ContextRole, P as ProviderErrorShape, Q as QueueOptions, 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';
7
7
  export { C as CacheManager, a as CacheOptions, b as CacheStats, c as cacheManager } from '../cache-manager-Df9LLYGA.js';
8
+ 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-LrNlew4n.js';
8
9
 
9
10
  type GroqErrorMetadata = AIErrorMetadata;
10
11
 
@@ -55,21 +56,30 @@ declare function buildHttpStatusFallback(status: number, statusText: string): st
55
56
  declare function extractErrorMessageFromResponse(response: Response): Promise<string>;
56
57
  declare function describeAIErrorType(type: AIErrorType): string;
57
58
 
58
- type AiErrorCode = 'invalid_key' | 'missing_key' | 'rate_limited' | 'capacity' | 'timeout' | 'invalid_request' | 'model_unavailable' | 'upstream_error' | 'network' | 'cancelled';
59
- declare const STATUS_TO_CODE: Readonly<Record<number, AiErrorCode>>;
60
- declare const CODE_MESSAGES: Readonly<Record<AiErrorCode, string>>;
61
- declare class AiError extends Error {
62
- readonly code: AiErrorCode;
63
- constructor(code: AiErrorCode, message?: string);
64
- get userMessage(): string;
65
- }
66
- declare function aiErrorMessage(code: AiErrorCode): string;
67
- interface ProviderErrorShape {
68
- readonly type?: string;
69
- readonly code?: string;
70
- }
71
- declare function errorFromStatus(status: number, detail?: string, provider?: ProviderErrorShape): AiError;
72
- declare function errorFromUnknown(err: unknown): AiError;
59
+ /**
60
+ * HTTP status each AiErrorCode maps to when an AI failure is surfaced
61
+ * through a server route (hono/express-style `c.json(body, status)`).
62
+ *
63
+ * The map is intentionally `as const` so indexed access keeps the literal
64
+ * types — frameworks like hono type their status argument as a union of
65
+ * known literals, and a plain `Record<AiErrorCode, number>` would widen
66
+ * past it.
67
+ */
68
+ declare const AI_ERROR_STATUS: {
69
+ readonly invalid_key: 502;
70
+ readonly missing_key: 503;
71
+ readonly rate_limited: 429;
72
+ readonly capacity: 503;
73
+ readonly timeout: 504;
74
+ readonly invalid_request: 400;
75
+ readonly model_unavailable: 503;
76
+ readonly upstream_error: 502;
77
+ readonly network: 502;
78
+ readonly cancelled: 400;
79
+ };
80
+ /** Status for a single code; kept as a function for call sites that only
81
+ * have the code, not an AiError instance. */
82
+ declare function aiErrorStatus(code: AiErrorCode): number;
73
83
 
74
84
  interface IRequestExecutor<TArgs extends unknown[], TResult> {
75
85
  execute(fn: (...args: TArgs) => Promise<TResult>, ...args: TArgs): Promise<TResult>;
@@ -340,25 +350,6 @@ interface SseResponseOptions {
340
350
  declare function defaultSseDeltaExtractor(payload: string): string | null;
341
351
  declare function createSseResponse(openUpstream: () => Promise<ReadableStream<Uint8Array>>, options: SseResponseOptions): Response;
342
352
 
343
- type ContextRole = 'system' | 'user' | 'assistant' | 'tool';
344
- interface ContextMessage {
345
- readonly role: ContextRole;
346
- readonly content: string;
347
- readonly toolCalls?: ReadonlyArray<{
348
- id: string;
349
- name: string;
350
- arguments: string;
351
- }>;
352
- readonly toolCallId?: string;
353
- }
354
- interface ContextBudget {
355
- readonly contextWindow: number;
356
- readonly maxOutputTokens: number;
357
- }
358
- declare function estimateTokens(text: string): number;
359
- declare function estimateMessageTokens(message: ContextMessage): number;
360
- declare function buildContext<T extends ContextMessage = ContextMessage>(history: ReadonlyArray<T>, systemPrompt: string, budget: ContextBudget): T[];
361
-
362
353
  declare const SYSTEM_PROMPT_VERSION = 2;
363
354
  declare const DEFAULT_AI_IDENTITY: string;
364
355
  interface ProjectContext {
@@ -536,42 +527,6 @@ declare const GENERATION_BOUNDS: {
536
527
  declare const DEFAULT_GENERATION: Required<GenerationSettings>;
537
528
  declare function normalizeGenerationSettings(requested: GenerationSettings | undefined, maxModelTokens?: number): Required<GenerationSettings>;
538
529
 
539
- interface StreamCallbacks<TToolCall = unknown> {
540
- onDelta(channel: 'answer' | 'reasoning', text: string): void;
541
- onUsage?(usage: {
542
- inputTokens: number;
543
- outputTokens: number;
544
- reasoningTokens?: number;
545
- }): void;
546
- onToolCall?(toolCall: TToolCall): void;
547
- onDone?(messageId: string): void;
548
- onError?(code: string, message: string): void;
549
- }
550
- type ParsedSseEvent<TToolCall = unknown> = {
551
- readonly type: 'delta';
552
- readonly channel: 'answer' | 'reasoning';
553
- readonly text: string;
554
- } | {
555
- readonly type: 'usage';
556
- readonly usage: {
557
- readonly inputTokens: number;
558
- readonly outputTokens: number;
559
- readonly reasoningTokens?: number;
560
- };
561
- } | {
562
- readonly type: 'tool_call';
563
- readonly toolCall: TToolCall;
564
- } | {
565
- readonly type: 'done';
566
- readonly messageId: string;
567
- } | {
568
- readonly type: 'error';
569
- readonly code: string;
570
- readonly message: string;
571
- };
572
- declare function parseSseEvent<TToolCall = unknown>(rawEvent: string): ParsedSseEvent<TToolCall> | null;
573
- declare function readSseResponse<TToolCall = unknown>(response: Response, callbacks: StreamCallbacks<TToolCall>): Promise<void>;
574
-
575
530
  type ToolValidationResult = {
576
531
  readonly ok: true;
577
532
  } | {
@@ -602,6 +557,69 @@ interface ZodLikeSchema {
602
557
  type ToolSchema = ToolValidatorFunction | ZodLikeSchema;
603
558
  declare function validateToolArgs(toolKey: string, args: Record<string, unknown>, schemas: Record<string, ToolSchema>): ToolValidationResult;
604
559
 
560
+ /**
561
+ * Usage analytics over sparse day aggregates.
562
+ *
563
+ * Servers typically bucket usage rows per UTC day in SQL and hand back only
564
+ * the days that have data. These helpers turn those sparse rows into a
565
+ * zero-filled daily series and derive the window totals / trends / error
566
+ * rates a usage dashboard needs — pure functions, no persistence coupling.
567
+ */
568
+ /** One point of a zero-filled daily series (UTC `YYYY-MM-DD` date keys). */
569
+ interface UsageSeriesPoint {
570
+ readonly date: string;
571
+ readonly requests: number;
572
+ readonly attempts: number;
573
+ readonly errors: number;
574
+ readonly inputTokens: number;
575
+ readonly outputTokens: number;
576
+ readonly reasoningTokens: number;
577
+ readonly costMicros: number;
578
+ }
579
+ /** Sparse usage aggregate for a day, straight from SQL. Numbers may arrive
580
+ * as strings depending on the driver (pg/bigint columns). */
581
+ interface UsageSeriesDayRow {
582
+ readonly date: string;
583
+ readonly requests?: number | string | null;
584
+ readonly inputTokens?: number | string | null;
585
+ readonly outputTokens?: number | string | null;
586
+ readonly reasoningTokens?: number | string | null;
587
+ readonly costMicros?: number | string | null;
588
+ }
589
+ /** Sparse message-attempt aggregate for a day (attempts vs errors). */
590
+ interface UsageSeriesMessageRow {
591
+ readonly date: string;
592
+ readonly attempts?: number | string | null;
593
+ readonly errors?: number | string | null;
594
+ }
595
+ interface UsageWindowTotals {
596
+ readonly requests: number;
597
+ readonly attempts: number;
598
+ readonly errors: number;
599
+ readonly inputTokens: number;
600
+ readonly outputTokens: number;
601
+ readonly costMicros: number;
602
+ }
603
+ interface UsageTrendPoint {
604
+ readonly current: number;
605
+ readonly previous: number;
606
+ /** Percentage change; null when the previous window was empty (avoid ±∞). */
607
+ readonly deltaPct: number | null;
608
+ }
609
+ /**
610
+ * Merge sparse SQL day aggregates into a zero-filled series covering the
611
+ * last `days` UTC days ending today. Both trend windows (current +
612
+ * previous) fit in the result when called with the doubled length.
613
+ */
614
+ declare function buildUsageDailySeries(days: number, usageRows: readonly UsageSeriesDayRow[], messageRows: readonly UsageSeriesMessageRow[], today?: Date): UsageSeriesPoint[];
615
+ /** Sum a contiguous slice of the daily series. `to` is exclusive; both may
616
+ * be negative (Python-style windowing over the tail of the series). */
617
+ declare function usageWindowTotals(series: readonly UsageSeriesPoint[], from: number, to: number): UsageWindowTotals;
618
+ /** Percentage change between two windows; null when the previous window is empty. */
619
+ declare function usageTrendOf(current: number, previous: number): UsageTrendPoint;
620
+ /** Errors / attempts as a percentage (0–100); 0 when there were no attempts. */
621
+ declare function errorRatePct(errors: number, attempts: number): number;
622
+
605
623
  declare const SSE_PREFIX: "data: ";
606
624
  declare const SSE_DONE_MARKER: "[DONE]";
607
625
  declare const JSON_CODE_BLOCK_PATTERN: RegExp;
@@ -613,4 +631,4 @@ declare const DEFAULT_RETRY_MAX_DELAY_MS = 10000;
613
631
  declare const DEFAULT_RETRY_BACKOFF_MULTIPLIER = 2;
614
632
  declare const DEFAULT_RETRY_JITTER_FACTOR = 0.1;
615
633
 
616
- export { AIError, type AIErrorBody, AIErrorMetadata, AIErrorType, type AccessCounted, type AccessTimestamped, type AgentContext, AiError, type AiErrorCode, type ApiKeyValidationRule, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, CODE_MESSAGES, ChatMessage, type ChunkOptions, CompositeExecutor, type ContextBudget, type ContextMessage, type ContextRole, 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, type DebounceOptions, DedupeExecutor, type DedupeExecutorOptions, type DiffChangeCount, type DiffLine, type EmbeddingsBatchAdapter, type ErrorClassificationRule, type ExponentialBackoffParams, type FailoverErrorLike, type FetchLike, GENERATION_BOUNDS, type GenerationSettings, GroqError, type GroqErrorMetadata, AIErrorType as GroqErrorType, type HttpStatusClassificationRule, type IRequestExecutor, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, type LeadingEdgeParams, type LoggedError, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, type MarkdownSegment, type MemoryLike, type ModelPricing, type ModelWithProvider, type NormalizedSseChunk, type ParsedSseEvent, type ProjectContext, type ProviderErrorShape, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, RequestDeduplicator, RequestQueue, type ResearchSource, type ResearchStreamEvent, RetryExecutor, RetryManager, RetryOptions, SEARCH_MAX_RESULTS, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, STATUS_TO_CODE, SYSTEM_PROMPT_VERSION, type SearchTopic, type SseDeltaExtractor, type SseResponseOptions, type StreamCallbacks, type StreamEvent, type StreamingParserCallbacks, StreamingResponseParser, StructuredPromptBuilder, type SystemPromptInput, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TRANSIENT_ERROR_CODES, type TaskPlan, type TaskPolicy, type TaskState, ThrottleManager, type ThrottleOptions, TokenUsage, type ToolSchema, type ToolValidationResult, type ToolValidatorFunction, type TrailingDelayParams, type UsageRecordData, type UsageRecordInput, type VectorCandidate, type VectorMatch, type WebSearchInput, type WebSearchResponse, type WebSearchResult, type ZodLikeIssue, type ZodLikeSchema, accumulateReport, aiErrorMessage, asObjectArray, asRecord, asStringArray, asTrimmedOptionalString, batchEmbed, buildCacheKey, buildContext, buildHttpStatusFallback, buildResearchMessages, buildSystemPrompt, buildUsageData, calculateCacheHitRate, calculateExponentialBackoff, calculateTrailingDelay, canFailover, canStartTask, capText, chunkText, clampScore, classifyHttpStatus, computeCostMicros, cosineSimilarity, countChanges, createSseResponse, debounce, debounceManager, defaultSseDeltaExtractor, deriveSnippetTitle, describeAIErrorType, diffLines, dotProduct, errorFromStatus, errorFromUnknown, estimateMessageTokens, estimateTokens, 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, parseSseEvent, planTaskFailure, readSseResponse, repairCommonJsonDefects, replayFirst, resolveUserFriendlyErrorMessage, resolveUserFriendlyMessage, searchWeb, selectLeastRecentlyUsedKey, selectMemories, shouldCallOnLeadingEdge, splitMarkdown, splitSseLines, sseStreamResponse, throttle, throttleManager, validateApiKey, validateToolArgs };
634
+ export { AIError, type AIErrorBody, AIErrorMetadata, AIErrorType, AI_ERROR_STATUS, type AccessCounted, type AccessTimestamped, type AgentContext, AiErrorCode, type ApiKeyValidationRule, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, ChatMessage, type 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, type DebounceOptions, DedupeExecutor, type DedupeExecutorOptions, type DiffChangeCount, type DiffLine, type EmbeddingsBatchAdapter, type ErrorClassificationRule, type ExponentialBackoffParams, type FailoverErrorLike, type FetchLike, GENERATION_BOUNDS, type GenerationSettings, GroqError, type GroqErrorMetadata, AIErrorType as GroqErrorType, type HttpStatusClassificationRule, type IRequestExecutor, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, type LeadingEdgeParams, type LoggedError, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, type MarkdownSegment, type MemoryLike, type ModelPricing, type ModelWithProvider, type NormalizedSseChunk, type ProjectContext, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, RequestDeduplicator, RequestQueue, type ResearchSource, type ResearchStreamEvent, RetryExecutor, RetryManager, RetryOptions, SEARCH_MAX_RESULTS, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, SYSTEM_PROMPT_VERSION, type SearchTopic, type SseDeltaExtractor, type SseResponseOptions, type StreamEvent, type StreamingParserCallbacks, StreamingResponseParser, StructuredPromptBuilder, type SystemPromptInput, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TRANSIENT_ERROR_CODES, type TaskPlan, type TaskPolicy, type TaskState, ThrottleManager, type ThrottleOptions, TokenUsage, type ToolSchema, type ToolValidationResult, type ToolValidatorFunction, type TrailingDelayParams, type UsageRecordData, type UsageRecordInput, type UsageSeriesDayRow, type UsageSeriesMessageRow, type UsageSeriesPoint, type UsageTrendPoint, type UsageWindowTotals, type VectorCandidate, type VectorMatch, type WebSearchInput, type WebSearchResponse, type WebSearchResult, type ZodLikeIssue, type 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 };
@@ -303,6 +303,23 @@ function errorFromUnknown(err) {
303
303
  return new AiError("upstream_error");
304
304
  }
305
305
 
306
+ // src/core/errors/error-status.ts
307
+ var AI_ERROR_STATUS = {
308
+ invalid_key: 502,
309
+ missing_key: 503,
310
+ rate_limited: 429,
311
+ capacity: 503,
312
+ timeout: 504,
313
+ invalid_request: 400,
314
+ model_unavailable: 503,
315
+ upstream_error: 502,
316
+ network: 502,
317
+ cancelled: 400
318
+ };
319
+ function aiErrorStatus(code) {
320
+ return AI_ERROR_STATUS[code];
321
+ }
322
+
306
323
  // src/core/executor/retry-executor.strategy.ts
307
324
  var RetryExecutor = class {
308
325
  constructor(retryManager2, options) {
@@ -1419,13 +1436,14 @@ function buildContext(history, systemPrompt, budget) {
1419
1436
  const selected = [];
1420
1437
  for (let i = history.length - 1; i >= 0; i -= 1) {
1421
1438
  const message = history[i];
1439
+ if (!message) continue;
1422
1440
  const cost = estimateMessageTokens(message);
1423
1441
  if (used + cost > available && selected.length > 0) break;
1424
1442
  used += cost;
1425
1443
  selected.push(message);
1426
1444
  }
1427
1445
  selected.reverse();
1428
- while (selected.length > 1 && (selected[0].role === "assistant" || selected[0].role === "tool")) {
1446
+ while (selected.length > 1 && (selected[0]?.role === "assistant" || selected[0]?.role === "tool")) {
1429
1447
  selected.shift();
1430
1448
  }
1431
1449
  return [{ role: "system", content: systemPrompt }, ...selected];
@@ -1628,7 +1646,10 @@ function diffLines(before, after) {
1628
1646
  const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
1629
1647
  for (let i2 = m - 1; i2 >= 0; i2 -= 1) {
1630
1648
  for (let j2 = n - 1; j2 >= 0; j2 -= 1) {
1631
- dp[i2][j2] = a[i2] === b[j2] ? dp[i2 + 1][j2 + 1] + 1 : Math.max(dp[i2 + 1][j2], dp[i2][j2 + 1]);
1649
+ const row = dp[i2];
1650
+ if (row) {
1651
+ row[j2] = a[i2] === b[j2] ? (dp[i2 + 1]?.[j2 + 1] ?? 0) + 1 : Math.max(dp[i2 + 1]?.[j2] ?? 0, row[j2 + 1] ?? 0);
1652
+ }
1632
1653
  }
1633
1654
  }
1634
1655
  const out = [];
@@ -1636,23 +1657,23 @@ function diffLines(before, after) {
1636
1657
  let j = 0;
1637
1658
  while (i < m && j < n) {
1638
1659
  if (a[i] === b[j]) {
1639
- out.push({ type: "same", text: a[i] });
1660
+ out.push({ type: "same", text: a[i] ?? "" });
1640
1661
  i += 1;
1641
1662
  j += 1;
1642
- } else if (dp[i + 1][j] >= dp[i][j + 1]) {
1643
- out.push({ type: "remove", text: a[i] });
1663
+ } else if ((dp[i + 1]?.[j] ?? 0) >= (dp[i]?.[j + 1] ?? 0)) {
1664
+ out.push({ type: "remove", text: a[i] ?? "" });
1644
1665
  i += 1;
1645
1666
  } else {
1646
- out.push({ type: "add", text: b[j] });
1667
+ out.push({ type: "add", text: b[j] ?? "" });
1647
1668
  j += 1;
1648
1669
  }
1649
1670
  }
1650
1671
  while (i < m) {
1651
- out.push({ type: "remove", text: a[i] });
1672
+ out.push({ type: "remove", text: a[i] ?? "" });
1652
1673
  i += 1;
1653
1674
  }
1654
1675
  while (j < n) {
1655
- out.push({ type: "add", text: b[j] });
1676
+ out.push({ type: "add", text: b[j] ?? "" });
1656
1677
  j += 1;
1657
1678
  }
1658
1679
  return out;
@@ -1767,14 +1788,14 @@ function dotProduct(a, b) {
1767
1788
  const length = Math.min(a.length, b.length);
1768
1789
  let sum = 0;
1769
1790
  for (let i = 0; i < length; i += 1) {
1770
- sum += a[i] * b[i];
1791
+ sum += (a[i] ?? 0) * (b[i] ?? 0);
1771
1792
  }
1772
1793
  return sum;
1773
1794
  }
1774
1795
  function magnitude(v) {
1775
1796
  let sum = 0;
1776
1797
  for (let i = 0; i < v.length; i += 1) {
1777
- sum += v[i] * v[i];
1798
+ sum += (v[i] ?? 0) * (v[i] ?? 0);
1778
1799
  }
1779
1800
  return Math.sqrt(sum);
1780
1801
  }
@@ -1919,6 +1940,115 @@ function validateToolArgs(toolKey, args, schemas) {
1919
1940
  return { ok: false, error: `Invalid schema definition for tool: ${toolKey}` };
1920
1941
  }
1921
1942
 
1922
- export { AIError, AIErrorType, AiError, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, CODE_MESSAGES, CacheManager, 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, DedupeExecutor, GENERATION_BOUNDS, GroqError, AIErrorType as GroqErrorType, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, RequestDeduplicator, RequestQueue, RetryExecutor, RetryManager, SEARCH_MAX_RESULTS, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, STATUS_TO_CODE, SYSTEM_PROMPT_VERSION, StreamingResponseParser, StructuredPromptBuilder, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TEXT_TIERS, TRANSIENT_ERROR_CODES, ThrottleManager, ToolCallAccumulator, USER_FRIENDLY_ERROR_MESSAGES, accumulateReport, aiErrorMessage, asObjectArray, asRecord, asStringArray, asTrimmedOptionalString, batchEmbed, buildCacheKey, buildContext, buildHttpStatusFallback, buildResearchMessages, buildSystemPrompt, buildUsageData, cacheManager, calculateCacheHitRate, calculateExponentialBackoff, calculateTrailingDelay, canFailover, canStartTask, capText, chunkText, clampScore, classifyHttpStatus, computeCostMicros, cosineSimilarity, countChanges, createSseResponse, debounce, debounceManager, defaultSseDeltaExtractor, deriveSnippetTitle, describeAIErrorType, diffLines, dotProduct, errorFromStatus, errorFromUnknown, estimateMessageTokens, estimateTokens, extractErrorMessageFromJsonBody, extractErrorMessageFromResponse, extractJsonArray, extractJsonCandidate, extractJsonFromCodeFence, extractJsonObject, extractSseDataPayload, extractText, failoverCandidate, findTopKSimilar, formatCost, formatErrorForLogging, formatSseEvent, generateRandomBase36Suffix, isAuthErrorType, isRetryableErrorType, isSseDataLine, isSseDoneMarker, isTextLike, isTextTier, isTransientError, isValidApiKey, isWithinWindow, magnitude, mergeTierOverrides, nextAttemptDelayMs, normalizeGenerationSettings, normalizeSources, normalizeSseChunk, oneOfCatalog, parseSseEvent, planTaskFailure, readSseResponse, repairCommonJsonDefects, replayFirst, requestDeduplicator, requestQueue, resolveModel, resolveUserFriendlyErrorMessage, resolveUserFriendlyMessage, retryManager, searchWeb, selectLeastRecentlyUsedKey, selectMemories, shouldCallOnLeadingEdge, splitMarkdown, splitSseLines, sseStreamResponse, throttle, throttleManager, validateApiKey, validateToolArgs, withRetry };
1943
+ // src/core/analytics/usage-series.ts
1944
+ function num(value) {
1945
+ const parsed = typeof value === "number" ? value : Number(value ?? 0);
1946
+ return Number.isFinite(parsed) ? parsed : 0;
1947
+ }
1948
+ function utcDateKey(base, offsetDays) {
1949
+ const shifted = new Date(base.getTime() - offsetDays * 864e5);
1950
+ return shifted.toISOString().slice(0, 10);
1951
+ }
1952
+ function buildUsageDailySeries(days, usageRows, messageRows, today = /* @__PURE__ */ new Date()) {
1953
+ const usageByDate = new Map(usageRows.map((row) => [row.date, row]));
1954
+ const messageByDate = new Map(messageRows.map((row) => [row.date, row]));
1955
+ const series = [];
1956
+ for (let offset = days - 1; offset >= 0; offset -= 1) {
1957
+ const date = utcDateKey(today, offset);
1958
+ const usage = usageByDate.get(date);
1959
+ const message = messageByDate.get(date);
1960
+ series.push({
1961
+ date,
1962
+ requests: num(usage?.requests),
1963
+ attempts: num(message?.attempts),
1964
+ errors: num(message?.errors),
1965
+ inputTokens: num(usage?.inputTokens),
1966
+ outputTokens: num(usage?.outputTokens),
1967
+ reasoningTokens: num(usage?.reasoningTokens),
1968
+ costMicros: num(usage?.costMicros)
1969
+ });
1970
+ }
1971
+ return series;
1972
+ }
1973
+ function usageWindowTotals(series, from, to) {
1974
+ const slice = series.slice(from, to);
1975
+ return slice.reduce(
1976
+ (acc, day) => ({
1977
+ requests: acc.requests + day.requests,
1978
+ attempts: acc.attempts + day.attempts,
1979
+ errors: acc.errors + day.errors,
1980
+ inputTokens: acc.inputTokens + day.inputTokens,
1981
+ outputTokens: acc.outputTokens + day.outputTokens,
1982
+ costMicros: acc.costMicros + day.costMicros
1983
+ }),
1984
+ { requests: 0, attempts: 0, errors: 0, inputTokens: 0, outputTokens: 0, costMicros: 0 }
1985
+ );
1986
+ }
1987
+ function usageTrendOf(current, previous) {
1988
+ return {
1989
+ current,
1990
+ previous,
1991
+ deltaPct: previous > 0 ? (current - previous) / previous * 100 : null
1992
+ };
1993
+ }
1994
+ function errorRatePct(errors, attempts) {
1995
+ if (attempts <= 0) return 0;
1996
+ return errors / attempts * 100;
1997
+ }
1998
+
1999
+ // src/core/remote/remote-chat-client.ts
2000
+ async function surfaceHttpError(response, callbacks) {
2001
+ const payload = await response.json().catch(() => null);
2002
+ callbacks.onError?.(payload?.code ?? "request_failed", payload?.error ?? "Request failed");
2003
+ }
2004
+ function createRemoteChatClient(options) {
2005
+ const doFetch = options.fetchImpl ?? fetch;
2006
+ const { urls } = options;
2007
+ return {
2008
+ streamChat(conversationId, body, callbacks) {
2009
+ const controller = new AbortController();
2010
+ const promise = (async () => {
2011
+ const response = await doFetch(urls.stream(conversationId), {
2012
+ method: "POST",
2013
+ headers: { "content-type": "application/json" },
2014
+ body: JSON.stringify(body),
2015
+ signal: controller.signal
2016
+ });
2017
+ if (!response.ok) {
2018
+ await surfaceHttpError(response, callbacks);
2019
+ return;
2020
+ }
2021
+ if (!response.body) {
2022
+ callbacks.onError?.("request_failed", "The server returned an empty stream.");
2023
+ return;
2024
+ }
2025
+ await readSseResponse(response, callbacks);
2026
+ })();
2027
+ return {
2028
+ promise,
2029
+ abort: () => controller.abort()
2030
+ };
2031
+ },
2032
+ async resolveToolCall(conversationId, toolCallId, approved, callbacks) {
2033
+ const response = await doFetch(urls.resolveToolCall(conversationId, toolCallId), {
2034
+ method: "POST",
2035
+ headers: { "content-type": "application/json" },
2036
+ body: JSON.stringify({ approved })
2037
+ });
2038
+ if (!response.ok) {
2039
+ await surfaceHttpError(response, callbacks);
2040
+ return false;
2041
+ }
2042
+ const contentType = response.headers.get("content-type") ?? "";
2043
+ if (!contentType.includes("text/event-stream") || !response.body) {
2044
+ return false;
2045
+ }
2046
+ await readSseResponse(response, callbacks);
2047
+ return true;
2048
+ }
2049
+ };
2050
+ }
2051
+
2052
+ export { AIError, AIErrorType, AI_ERROR_STATUS, AiError, CHUNK_MAX_CHARS, CHUNK_OVERLAP_CHARS, CHUNK_TEXT_LIMIT, CODE_MESSAGES, CacheManager, 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, DedupeExecutor, GENERATION_BOUNDS, GroqError, AIErrorType as GroqErrorType, JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN, JsonResponseParser, MEMORY_MAX_ITEMS, MEMORY_TOTAL_LIMIT, MICROS_PER_UNIT, QueueExecutor, RESEARCH_MAX_OUTPUT_TOKENS, RESEARCH_QUERY_MAX, RESEARCH_QUERY_MIN, RESEARCH_REPORT_MIN_CHARS, RESEARCH_SNIPPET_MAX_CHARS, RESEARCH_TEMPERATURE, RequestDeduplicator, RequestQueue, RetryExecutor, RetryManager, SEARCH_MAX_RESULTS, SSE_BRIDGE_EVENTS, SSE_DONE_MARKER, SSE_PREFIX, STATUS_TO_CODE, SYSTEM_PROMPT_VERSION, StreamingResponseParser, StructuredPromptBuilder, TEXT_EXTRACT_PER_FILE_LIMIT, TEXT_EXTRACT_TOTAL_LIMIT, TEXT_TIERS, TRANSIENT_ERROR_CODES, ThrottleManager, ToolCallAccumulator, USER_FRIENDLY_ERROR_MESSAGES, accumulateReport, aiErrorMessage, aiErrorStatus, asObjectArray, asRecord, asStringArray, asTrimmedOptionalString, batchEmbed, buildCacheKey, buildContext, buildHttpStatusFallback, buildResearchMessages, buildSystemPrompt, buildUsageDailySeries, buildUsageData, cacheManager, calculateCacheHitRate, calculateExponentialBackoff, calculateTrailingDelay, canFailover, canStartTask, capText, chunkText, clampScore, classifyHttpStatus, computeCostMicros, cosineSimilarity, countChanges, createRemoteChatClient, createSseResponse, debounce, debounceManager, defaultSseDeltaExtractor, deriveSnippetTitle, describeAIErrorType, diffLines, dotProduct, errorFromStatus, errorFromUnknown, errorRatePct, estimateMessageTokens, estimateTokens, extractErrorMessageFromJsonBody, extractErrorMessageFromResponse, extractJsonArray, extractJsonCandidate, extractJsonFromCodeFence, extractJsonObject, extractSseDataPayload, extractText, failoverCandidate, findTopKSimilar, formatCost, formatErrorForLogging, formatSseEvent, generateRandomBase36Suffix, isAuthErrorType, isRetryableErrorType, isSseDataLine, isSseDoneMarker, isTextLike, isTextTier, isTransientError, isValidApiKey, isWithinWindow, magnitude, mergeTierOverrides, nextAttemptDelayMs, normalizeGenerationSettings, normalizeSources, normalizeSseChunk, oneOfCatalog, parseSseEvent, planTaskFailure, readSseResponse, repairCommonJsonDefects, replayFirst, requestDeduplicator, requestQueue, resolveModel, resolveUserFriendlyErrorMessage, resolveUserFriendlyMessage, retryManager, searchWeb, selectLeastRecentlyUsedKey, selectMemories, shouldCallOnLeadingEdge, splitMarkdown, splitSseLines, sseStreamResponse, throttle, throttleManager, usageTrendOf, usageWindowTotals, validateApiKey, validateToolArgs, withRetry };
1923
2053
  //# sourceMappingURL=index.js.map
1924
2054
  //# sourceMappingURL=index.js.map