@jecruz/merc-ai 0.1.4 → 0.1.6

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 (111) hide show
  1. package/README.md +34 -7
  2. package/dist/env-api-keys.d.ts.map +1 -1
  3. package/dist/env-api-keys.js +1 -1
  4. package/dist/env-api-keys.js.map +1 -1
  5. package/dist/image-models.generated.d.ts +345 -0
  6. package/dist/image-models.generated.d.ts.map +1 -1
  7. package/dist/image-models.generated.js +348 -3
  8. package/dist/image-models.generated.js.map +1 -1
  9. package/dist/index.d.ts +3 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +3 -0
  12. package/dist/index.js.map +1 -1
  13. package/dist/models.d.ts.map +1 -1
  14. package/dist/models.generated.d.ts +15282 -3882
  15. package/dist/models.generated.d.ts.map +1 -1
  16. package/dist/models.generated.js +18368 -10964
  17. package/dist/models.generated.js.map +1 -1
  18. package/dist/models.js +4 -1
  19. package/dist/models.js.map +1 -1
  20. package/dist/providers/amazon-bedrock.d.ts.map +1 -1
  21. package/dist/providers/amazon-bedrock.js +188 -19
  22. package/dist/providers/amazon-bedrock.js.map +1 -1
  23. package/dist/providers/anthropic.d.ts.map +1 -1
  24. package/dist/providers/anthropic.js +101 -34
  25. package/dist/providers/anthropic.js.map +1 -1
  26. package/dist/providers/azure-openai-responses.d.ts +2 -0
  27. package/dist/providers/azure-openai-responses.d.ts.map +1 -1
  28. package/dist/providers/azure-openai-responses.js +8 -3
  29. package/dist/providers/azure-openai-responses.js.map +1 -1
  30. package/dist/providers/google-shared.d.ts +15 -4
  31. package/dist/providers/google-shared.d.ts.map +1 -1
  32. package/dist/providers/google-shared.js +80 -15
  33. package/dist/providers/google-shared.js.map +1 -1
  34. package/dist/providers/google-vertex.d.ts.map +1 -1
  35. package/dist/providers/google-vertex.js +23 -60
  36. package/dist/providers/google-vertex.js.map +1 -1
  37. package/dist/providers/google.d.ts.map +1 -1
  38. package/dist/providers/google.js +19 -68
  39. package/dist/providers/google.js.map +1 -1
  40. package/dist/providers/mistral.d.ts +1 -1
  41. package/dist/providers/mistral.d.ts.map +1 -1
  42. package/dist/providers/mistral.js +44 -60
  43. package/dist/providers/mistral.js.map +1 -1
  44. package/dist/providers/openai-codex-responses.d.ts.map +1 -1
  45. package/dist/providers/openai-codex-responses.js +250 -124
  46. package/dist/providers/openai-codex-responses.js.map +1 -1
  47. package/dist/providers/openai-completions.d.ts.map +1 -1
  48. package/dist/providers/openai-completions.js +88 -38
  49. package/dist/providers/openai-completions.js.map +1 -1
  50. package/dist/providers/openai-prompt-cache.d.ts +3 -0
  51. package/dist/providers/openai-prompt-cache.d.ts.map +1 -0
  52. package/dist/providers/openai-prompt-cache.js +10 -0
  53. package/dist/providers/openai-prompt-cache.js.map +1 -0
  54. package/dist/providers/openai-responses-shared.d.ts.map +1 -1
  55. package/dist/providers/openai-responses-shared.js +154 -211
  56. package/dist/providers/openai-responses-shared.js.map +1 -1
  57. package/dist/providers/openai-responses.d.ts.map +1 -1
  58. package/dist/providers/openai-responses.js +15 -9
  59. package/dist/providers/openai-responses.js.map +1 -1
  60. package/dist/providers/openrouter-images.d.ts.map +1 -1
  61. package/dist/providers/openrouter-images.js +5 -2
  62. package/dist/providers/openrouter-images.js.map +1 -1
  63. package/dist/providers/simple-options.d.ts +15 -3
  64. package/dist/providers/simple-options.d.ts.map +1 -1
  65. package/dist/providers/simple-options.js +34 -4
  66. package/dist/providers/simple-options.js.map +1 -1
  67. package/dist/types.d.ts +35 -2
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/types.js.map +1 -1
  70. package/dist/utils/error-body.d.ts +5 -0
  71. package/dist/utils/error-body.d.ts.map +1 -1
  72. package/dist/utils/error-body.js +53 -5
  73. package/dist/utils/error-body.js.map +1 -1
  74. package/dist/utils/estimate.d.ts +22 -0
  75. package/dist/utils/estimate.d.ts.map +1 -0
  76. package/dist/utils/estimate.js +104 -0
  77. package/dist/utils/estimate.js.map +1 -0
  78. package/dist/utils/event-stream.d.ts.map +1 -1
  79. package/dist/utils/event-stream.js +25 -7
  80. package/dist/utils/event-stream.js.map +1 -1
  81. package/dist/utils/json-parse.d.ts +3 -0
  82. package/dist/utils/json-parse.d.ts.map +1 -1
  83. package/dist/utils/json-parse.js +15 -0
  84. package/dist/utils/json-parse.js.map +1 -1
  85. package/dist/utils/oauth/anthropic.d.ts.map +1 -1
  86. package/dist/utils/oauth/anthropic.js +16 -10
  87. package/dist/utils/oauth/anthropic.js.map +1 -1
  88. package/dist/utils/oauth/github-copilot.d.ts.map +1 -1
  89. package/dist/utils/oauth/github-copilot.js +57 -21
  90. package/dist/utils/oauth/github-copilot.js.map +1 -1
  91. package/dist/utils/oauth/openai-codex.d.ts.map +1 -1
  92. package/dist/utils/oauth/openai-codex.js +73 -16
  93. package/dist/utils/oauth/openai-codex.js.map +1 -1
  94. package/dist/utils/oauth/types.d.ts +2 -0
  95. package/dist/utils/oauth/types.d.ts.map +1 -1
  96. package/dist/utils/oauth/types.js.map +1 -1
  97. package/dist/utils/overflow.d.ts +9 -1
  98. package/dist/utils/overflow.d.ts.map +1 -1
  99. package/dist/utils/overflow.js +23 -6
  100. package/dist/utils/overflow.js.map +1 -1
  101. package/dist/utils/provider-env.d.ts.map +1 -1
  102. package/dist/utils/provider-env.js +45 -10
  103. package/dist/utils/provider-env.js.map +1 -1
  104. package/dist/utils/tool-call-id.d.ts +11 -0
  105. package/dist/utils/tool-call-id.d.ts.map +1 -0
  106. package/dist/utils/tool-call-id.js +96 -0
  107. package/dist/utils/tool-call-id.js.map +1 -0
  108. package/dist/utils/validation.d.ts.map +1 -1
  109. package/dist/utils/validation.js +9 -0
  110. package/dist/utils/validation.js.map +1 -1
  111. package/package.json +4 -1
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { AssistantMessageDiagnostic } from \"./utils/diagnostics.js\";\nimport type { AssistantImagesEventStream, AssistantMessageEventStream } from \"./utils/event-stream.js\";\n\nexport type {\n\tAssistantImagesEventStream,\n\tAssistantMessageEventStream,\n} from \"./utils/event-stream.js\";\n\nexport type KnownApi =\n\t| \"openai-completions\"\n\t| \"mistral-conversations\"\n\t| \"openai-responses\"\n\t| \"azure-openai-responses\"\n\t| \"openai-codex-responses\"\n\t| \"anthropic-messages\"\n\t| \"bedrock-converse-stream\"\n\t| \"google-generative-ai\"\n\t| \"google-vertex\"\n\t| \"claude-cli\";\n\nexport type Api = KnownApi | (string & {});\n\nexport type KnownImagesApi = \"openrouter-images\";\n\nexport type ImagesApi = KnownImagesApi | (string & {});\n\nexport type KnownProvider =\n\t| \"amazon-bedrock\"\n\t| \"anthropic\"\n\t| \"google\"\n\t| \"google-vertex\"\n\t| \"openai\"\n\t| \"azure-openai-responses\"\n\t| \"openai-codex\"\n\t| \"deepseek\"\n\t| \"github-copilot\"\n\t| \"xai\"\n\t| \"groq\"\n\t| \"cerebras\"\n\t| \"openrouter\"\n\t| \"vercel-ai-gateway\"\n\t| \"zai\"\n\t| \"zai-coding-cn\"\n\t| \"mistral\"\n\t| \"minimax\"\n\t| \"minimax-cn\"\n\t| \"moonshotai\"\n\t| \"moonshotai-cn\"\n\t| \"huggingface\"\n\t| \"fireworks\"\n\t| \"together\"\n\t| \"ant-ling\"\n\t| \"opencode\"\n\t| \"opencode-go\"\n\t| \"kimi-coding\"\n\t| \"cloudflare-workers-ai\"\n\t| \"cloudflare-ai-gateway\"\n\t| \"xiaomi\"\n\t| \"xiaomi-token-plan-cn\"\n\t| \"xiaomi-token-plan-ams\"\n\t| \"xiaomi-token-plan-sgp\";\nexport type Provider = KnownProvider | string;\n\nexport type KnownImagesProvider = \"openrouter\";\n\nexport type ImagesProvider = KnownImagesProvider | string;\n\nexport type ThinkingLevel = \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\nexport type ModelThinkingLevel = \"off\" | ThinkingLevel;\n/** Provider-specific reasoning map from Pi thinking levels to provider values. */\nexport type ThinkingLevelMap = Partial<Record<ModelThinkingLevel, string | null>>;\n\n/** Token budgets for each thinking level (token-based providers only) */\nexport interface ThinkingBudgets {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\n// Base options all providers share\nexport type CacheRetention = \"none\" | \"short\" | \"long\";\n\nexport type Transport = \"sse\" | \"websocket\" | \"websocket-cached\" | \"auto\";\n\n/** Provider-scoped environment overrides. Explicit values take precedence over process.env. */\nexport type ProviderEnv = Readonly<Record<string, string | undefined>>;\n\nexport interface ProviderResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\nexport interface StreamOptions {\n\ttemperature?: number;\n\tmaxTokens?: number;\n\tsignal?: AbortSignal;\n\tapiKey?: string;\n\t/**\n\t * Preferred transport for providers that support multiple transports.\n\t * Providers that do not support this option ignore it.\n\t */\n\ttransport?: Transport;\n\t/**\n\t * Prompt cache retention preference. Providers map this to their supported values.\n\t * Default: \"short\".\n\t */\n\tcacheRetention?: CacheRetention;\n\t/**\n\t * Optional session identifier for providers that support session-based caching.\n\t * Providers can use this to enable prompt caching, request routing, or other\n\t * session-aware features. Ignored by providers that don't support it.\n\t */\n\tsessionId?: string;\n\t/**\n\t * Optional callback for inspecting or replacing provider payloads before sending.\n\t * Return undefined to keep the payload unchanged.\n\t */\n\tonPayload?: (payload: unknown, model: Model<Api>) => unknown | undefined | Promise<unknown | undefined>;\n\t/**\n\t * Optional callback invoked after an HTTP response is received and before\n\t * its body stream is consumed.\n\t */\n\tonResponse?: (response: ProviderResponse, model: Model<Api>) => void | Promise<void>;\n\t/**\n\t * Optional custom HTTP headers to include in API requests.\n\t * Merged with provider defaults; can override default headers.\n\t * Not supported by all providers (e.g., AWS Bedrock uses SDK auth).\n\t */\n\theaders?: Record<string, string>;\n\t/**\n\t * HTTP request timeout in milliseconds for providers/SDKs that support it.\n\t * For example, OpenAI and Anthropic SDK clients default to 10 minutes.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * Maximum retry attempts for providers/SDKs that support client-side retries.\n\t * For example, OpenAI and Anthropic SDK clients default to 2.\n\t */\n\tmaxRetries?: number;\n\t/**\n\t * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.\n\t * If the server's requested delay exceeds this value, the request fails immediately\n\t * with an error containing the requested delay, allowing higher-level retry logic\n\t * to handle it with user visibility.\n\t * Default: 60000 (60 seconds). Set to 0 to disable the cap.\n\t */\n\tmaxRetryDelayMs?: number;\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t * For example, Anthropic uses `user_id` for abuse tracking and rate limiting.\n\t */\n\tmetadata?: Record<string, unknown>;\n\t/**\n\t * Provider-scoped environment values. These take precedence over process.env\n\t * for provider configuration and credential discovery.\n\t */\n\tenv?: ProviderEnv;\n}\n\nexport type ProviderStreamOptions = StreamOptions & Record<string, unknown>;\n\nexport interface ImagesOptions {\n\tsignal?: AbortSignal;\n\tapiKey?: string;\n\t/** Provider-scoped environment values used for image-provider configuration. */\n\tenv?: ProviderEnv;\n\t/**\n\t * Optional callback for inspecting or replacing provider payloads before sending.\n\t * Return undefined to keep the payload unchanged.\n\t */\n\tonPayload?: (payload: unknown, model: ImagesModel<ImagesApi>) => unknown | undefined | Promise<unknown | undefined>;\n\t/**\n\t * Optional callback invoked after an HTTP response is received.\n\t */\n\tonResponse?: (response: ProviderResponse, model: ImagesModel<ImagesApi>) => void | Promise<void>;\n\t/**\n\t * Optional custom HTTP headers to include in API requests.\n\t * Merged with provider defaults; can override default headers.\n\t */\n\theaders?: Record<string, string>;\n\t/**\n\t * HTTP request timeout in milliseconds for providers/SDKs that support it.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * Maximum retry attempts for providers/SDKs that support client-side retries.\n\t */\n\tmaxRetries?: number;\n\t/**\n\t * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.\n\t * If the server's requested delay exceeds this value, the request fails immediately\n\t * with an error containing the requested delay, allowing higher-level retry logic\n\t * to handle it with user visibility.\n\t * Default: 60000 (60 seconds). Set to 0 to disable the cap.\n\t */\n\tmaxRetryDelayMs?: number;\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t */\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type ProviderImagesOptions = ImagesOptions & Record<string, unknown>;\n\n// Unified options with reasoning passed to streamSimple() and completeSimple()\nexport interface SimpleStreamOptions extends StreamOptions {\n\treasoning?: ThinkingLevel;\n\t/** Custom token budgets for thinking levels (token-based providers only) */\n\tthinkingBudgets?: ThinkingBudgets;\n}\n\n// Generic StreamFunction with typed options.\n//\n// Contract:\n// - Must return an AssistantMessageEventStream.\n// - Once invoked, request/model/runtime failures should be encoded in the\n// returned stream, not thrown.\n// - Error termination must produce an AssistantMessage with stopReason\n// \"error\" or \"aborted\" and errorMessage, emitted via the stream protocol.\nexport type StreamFunction<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> = (\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: TOptions,\n) => AssistantMessageEventStream;\n\nexport type ImagesFunction<TApi extends ImagesApi = ImagesApi, TOptions extends ImagesOptions = ImagesOptions> = (\n\tmodel: ImagesModel<TApi>,\n\tcontext: ImagesContext,\n\toptions?: TOptions,\n) => AssistantImagesEventStream;\n\nexport interface TextSignatureV1 {\n\tv: 1;\n\tid: string;\n\tphase?: \"commentary\" | \"final_answer\";\n}\n\nexport interface TextContent {\n\ttype: \"text\";\n\ttext: string;\n\ttextSignature?: string; // e.g., for OpenAI responses, message metadata (legacy id string or TextSignatureV1 JSON)\n}\n\nexport interface ThinkingContent {\n\ttype: \"thinking\";\n\tthinking: string;\n\tthinkingSignature?: string; // e.g., for OpenAI responses, the reasoning item ID\n\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t * to the API for multi-turn continuity. */\n\tredacted?: boolean;\n}\n\nexport interface ImageContent {\n\ttype: \"image\";\n\tdata: string; // base64 encoded image data\n\tmimeType: string; // e.g., \"image/jpeg\", \"image/png\"\n}\n\nexport interface ToolCall {\n\ttype: \"toolCall\";\n\tid: string;\n\tname: string;\n\targuments: Record<string, any>;\n\tthoughtSignature?: string; // Google-specific: opaque signature for reusing thought context\n}\n\n/** Alternate per-million-token pricing for a higher input-token band. */\nexport interface CostTier {\n\tinputTokensAbove: number;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n}\n\nexport interface Usage {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\ttotalTokens: number;\n\tcost: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n}\n\nexport type StopReason = \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\";\n\nexport interface UserMessage {\n\trole: \"user\";\n\tcontent: string | (TextContent | ImageContent)[];\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface AssistantMessage {\n\trole: \"assistant\";\n\tcontent: (TextContent | ThinkingContent | ImageContent | ToolCall)[];\n\tapi: Api;\n\tprovider: Provider;\n\tmodel: string;\n\tresponseModel?: string; // Concrete `chunk.model` when different from the requested `model` (e.g. OpenRouter `auto` -> `anthropic/...`)\n\tresponseId?: string; // Provider-specific response/message identifier when the upstream API exposes one\n\tdiagnostics?: AssistantMessageDiagnostic[]; // Redacted provider/runtime diagnostics for failures and recoveries.\n\tusage: Usage;\n\tstopReason: StopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface ToolResultMessage<TDetails = any> {\n\trole: \"toolResult\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tcontent: (TextContent | ImageContent)[]; // Supports text and images\n\tdetails?: TDetails;\n\t/**\n\t * Tool names that were activated by this tool result and should be loaded\n\t * lazily at this transcript position when supported by the provider.\n\t */\n\taddedToolNames?: string[];\n\tisError: boolean;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport type Message = UserMessage | AssistantMessage | ToolResultMessage;\n\nexport type ImagesInputContent = TextContent | ImageContent;\nexport type ImagesOutputContent = TextContent | ImageContent;\n\nexport interface ImagesContext {\n\tinput: ImagesInputContent[];\n}\n\nexport type ImagesStopReason = \"stop\" | \"error\" | \"aborted\";\n\nexport interface AssistantImages {\n\tapi: ImagesApi;\n\tprovider: ImagesProvider;\n\tmodel: string;\n\toutput: ImagesOutputContent[];\n\tresponseId?: string;\n\tusage?: Usage;\n\tstopReason: ImagesStopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nimport type { TSchema } from \"typebox\";\n\nexport interface Tool<TParameters extends TSchema = TSchema> {\n\tname: string;\n\tdescription: string;\n\tparameters: TParameters;\n}\n\nexport interface Context {\n\tsystemPrompt?: string;\n\tmessages: Message[];\n\ttools?: Tool[];\n}\n\n/**\n * Event protocol for AssistantMessageEventStream.\n *\n * Streams should emit `start` before partial updates, then terminate with either:\n * - `done` carrying the final successful AssistantMessage, or\n * - `error` carrying the final AssistantMessage with stopReason \"error\" or \"aborted\"\n * and errorMessage.\n */\nexport type AssistantMessageEvent =\n\t| { type: \"start\"; partial: AssistantMessage }\n\t| { type: \"text_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"text_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"thinking_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"thinking_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"image_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"image_end\"; contentIndex: number; image: ImageContent; partial: AssistantMessage }\n\t| { type: \"toolcall_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"toolcall_end\"; contentIndex: number; toolCall: ToolCall; partial: AssistantMessage }\n\t| { type: \"done\"; reason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\">; message: AssistantMessage }\n\t| { type: \"error\"; reason: Extract<StopReason, \"aborted\" | \"error\">; error: AssistantMessage };\n\nexport type AssistantImagesEvent =\n\t| { type: \"start\"; partial: AssistantImages }\n\t| { type: \"image_start\"; contentIndex: number; partial: AssistantImages }\n\t| { type: \"image_end\"; contentIndex: number; image: ImageContent; partial: AssistantImages }\n\t| { type: \"done\"; reason: Extract<ImagesStopReason, \"stop\">; images: AssistantImages }\n\t| { type: \"error\"; reason: Extract<ImagesStopReason, \"aborted\" | \"error\">; error: AssistantImages };\n\n/**\n * Compatibility settings for OpenAI-compatible completions APIs.\n * Use this to override URL-based auto-detection for custom providers.\n */\nexport interface OpenAICompletionsCompat {\n\t/** Whether the provider supports the `store` field. Default: auto-detected from URL. */\n\tsupportsStore?: boolean;\n\t/** Whether the provider supports the `developer` role (vs `system`). Default: auto-detected from URL. */\n\tsupportsDeveloperRole?: boolean;\n\t/** Whether the provider supports `reasoning_effort`. Default: auto-detected from URL. */\n\tsupportsReasoningEffort?: boolean;\n\t/** Whether the provider supports `stream_options: { include_usage: true }` for token usage in streaming responses. Default: true. */\n\tsupportsUsageInStreaming?: boolean;\n\t/** Which field to use for max tokens. Default: auto-detected from URL. */\n\tmaxTokensField?: \"max_completion_tokens\" | \"max_tokens\";\n\t/** Whether tool results require the `name` field. Default: auto-detected from URL. */\n\trequiresToolResultName?: boolean;\n\t/** Whether a user message after tool results requires an assistant message in between. Default: auto-detected from URL. */\n\trequiresAssistantAfterToolResult?: boolean;\n\t/** Whether thinking blocks must be converted to text blocks with <thinking> delimiters. Default: auto-detected from URL. */\n\trequiresThinkingAsText?: boolean;\n\t/** Whether all replayed assistant messages must include an empty reasoning_content field when reasoning is enabled. */\n\trequiresReasoningContentOnAssistantMessages?: boolean;\n\t/** Format for reasoning/thinking parameter. \"openai\" uses reasoning_effort, \"openrouter\" uses reasoning: { effort }, \"deepseek\" uses thinking: { type } plus reasoning_effort when supported, \"together\" uses reasoning: { enabled } plus reasoning_effort when supported, \"ant-ling\" uses reasoning: { effort }, \"zai\" uses thinking: { type }, \"qwen\" uses top-level enable_thinking: boolean, \"qwen-chat-template\" uses chat_template_kwargs.enable_thinking, \"minimax\" uses thinking: { type } plus reasoning_split, and \"string-thinking\" uses top-level thinking: string. Default: \"openai\". */\n\tthinkingFormat?:\n\t\t| \"openai\"\n\t\t| \"openrouter\"\n\t\t| \"deepseek\"\n\t\t| \"together\"\n\t\t| \"ant-ling\"\n\t\t| \"zai\"\n\t\t| \"qwen\"\n\t\t| \"qwen-chat-template\"\n\t\t| \"minimax\";\n\t/** OpenRouter-specific routing preferences. Only used when baseUrl points to OpenRouter. */\n\topenRouterRouting?: OpenRouterRouting;\n\t/** Whether the model uses OpenRouter's image-generation response shape with assistant `message.images`. */\n\topenRouterImageGeneration?: boolean;\n\t/** Vercel AI Gateway routing preferences. Only used when baseUrl points to Vercel AI Gateway. */\n\tvercelGatewayRouting?: VercelGatewayRouting;\n\t/** Whether z.ai supports top-level `tool_stream: true` for streaming tool call deltas. Default: false. */\n\tzaiToolStream?: boolean;\n\t/** Whether the provider supports the `strict` field in tool definitions. Default: true. */\n\tsupportsStrictMode?: boolean;\n\t/** Cache control convention for prompt caching. \"anthropic\" applies Anthropic-style `cache_control` markers to the system prompt, last tool definition, and last user/assistant text content. */\n\tcacheControlFormat?: \"anthropic\";\n\t/** Whether to send session-affinity data from `options.sessionId`. Default: false. */\n\tsendSessionAffinityHeaders?: boolean;\n\t/** Session-affinity header format. Default: auto-detected. */\n\tsessionAffinityFormat?: \"openai\" | \"openai-nosession\" | \"openrouter\";\n\t/** Whether the provider supports long prompt cache retention (`prompt_cache_retention: \"24h\"` or Anthropic-style `cache_control.ttl: \"1h\"`, depending on format). Default: true. */\n\tsupportsLongCacheRetention?: boolean;\n}\n\n/** Compatibility settings for OpenAI Responses APIs. */\nexport interface OpenAIResponsesCompat {\n\t/** Whether the provider supports the `developer` role (vs `system`). Default: true. */\n\tsupportsDeveloperRole?: boolean;\n\t/** Session-affinity header format. Default: auto-detected. */\n\tsessionAffinityFormat?: \"openai\" | \"openai-nosession\" | \"openrouter\";\n\t/** Whether the provider supports `prompt_cache_retention: \"24h\"`. Default: true. */\n\tsupportsLongCacheRetention?: boolean;\n\t/** Whether the provider supports client-side tool search / deferred tool loading. Default: false. */\n\tsupportsToolSearch?: boolean;\n}\n\n/** Compatibility settings for Anthropic Messages-compatible APIs. */\nexport interface AnthropicMessagesCompat {\n\t/** Whether the provider supports adaptive thinking payloads. */\n\tforceAdaptiveThinking?: boolean;\n\t/**\n\t * Whether the provider accepts per-tool `eager_input_streaming`.\n\t * When false, the Anthropic provider omits `tools[].eager_input_streaming`\n\t * and sends the legacy `fine-grained-tool-streaming-2025-05-14` beta header\n\t * for tool-enabled requests.\n\t * Default: true.\n\t */\n\tsupportsEagerToolInputStreaming?: boolean;\n\t/** Whether the provider supports Anthropic long cache retention (`cache_control.ttl: \"1h\"`). Default: true. */\n\tsupportsLongCacheRetention?: boolean;\n\t/**\n\t * Whether to send the `x-session-affinity` header from `options.sessionId`\n\t * when caching is enabled. Required for providers like Fireworks that use\n\t * session affinity for prompt cache routing (requests to the same replica\n\t * maximize cache hits).\n\t * Default: false.\n\t */\n\tsendSessionAffinityHeaders?: boolean;\n\t/**\n\t * Whether the provider supports Anthropic-style `cache_control` markers on\n\t * tool definitions. When false, `cache_control` is omitted from tool params.\n\t * Some Anthropic-compatible providers (e.g., Fireworks) do not support this\n\t * field on tools and may reject or ignore it.\n\t * Default: true.\n\t */\n\tsupportsCacheControlOnTools?: boolean;\n\t/** Whether the provider supports client-side `tool_reference` blocks. Default: false for unsupported models. */\n\tsupportsToolReferences?: boolean;\n}\n\n/**\n * OpenRouter provider routing preferences.\n * Controls which upstream providers OpenRouter routes requests to.\n * Sent as the `provider` field in the OpenRouter API request body.\n * @see https://openrouter.ai/docs/guides/routing/provider-selection\n */\nexport interface OpenRouterRouting {\n\t/** Whether to allow backup providers to serve requests. Default: true. */\n\tallow_fallbacks?: boolean;\n\t/** Whether to filter providers to only those that support all parameters in the request. Default: false. */\n\trequire_parameters?: boolean;\n\t/** Data collection setting. \"allow\" (default): allow providers that may store/train on data. \"deny\": only use providers that don't collect user data. */\n\tdata_collection?: \"deny\" | \"allow\";\n\t/** Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. */\n\tzdr?: boolean;\n\t/** Whether to restrict routing to only models that allow text distillation. */\n\tenforce_distillable_text?: boolean;\n\t/** An ordered list of provider names/slugs to try in sequence, falling back to the next if unavailable. */\n\torder?: string[];\n\t/** List of provider names/slugs to exclusively allow for this request. */\n\tonly?: string[];\n\t/** List of provider names/slugs to skip for this request. */\n\tignore?: string[];\n\t/** A list of quantization levels to filter providers by (e.g., [\"fp16\", \"bf16\", \"fp8\", \"fp6\", \"int8\", \"int4\", \"fp4\", \"fp32\"]). */\n\tquantizations?: string[];\n\t/** Sorting strategy. Can be a string (e.g., \"price\", \"throughput\", \"latency\") or an object with `by` and `partition`. */\n\tsort?:\n\t\t| string\n\t\t| {\n\t\t\t\t/** The sorting metric: \"price\", \"throughput\", \"latency\". */\n\t\t\t\tby?: string;\n\t\t\t\t/** Partitioning strategy: \"model\" (default) or \"none\". */\n\t\t\t\tpartition?: string | null;\n\t\t };\n\t/** Maximum price per million tokens (USD). */\n\tmax_price?: {\n\t\t/** Price per million prompt tokens. */\n\t\tprompt?: number | string;\n\t\t/** Price per million completion tokens. */\n\t\tcompletion?: number | string;\n\t\t/** Price per image. */\n\t\timage?: number | string;\n\t\t/** Price per audio unit. */\n\t\taudio?: number | string;\n\t\t/** Price per request. */\n\t\trequest?: number | string;\n\t};\n\t/** Preferred minimum throughput (tokens/second). Can be a number (applies to p50) or an object with percentile-specific cutoffs. */\n\tpreferred_min_throughput?:\n\t\t| number\n\t\t| {\n\t\t\t\t/** Minimum tokens/second at the 50th percentile. */\n\t\t\t\tp50?: number;\n\t\t\t\t/** Minimum tokens/second at the 75th percentile. */\n\t\t\t\tp75?: number;\n\t\t\t\t/** Minimum tokens/second at the 90th percentile. */\n\t\t\t\tp90?: number;\n\t\t\t\t/** Minimum tokens/second at the 99th percentile. */\n\t\t\t\tp99?: number;\n\t\t };\n\t/** Preferred maximum latency (seconds). Can be a number (applies to p50) or an object with percentile-specific cutoffs. */\n\tpreferred_max_latency?:\n\t\t| number\n\t\t| {\n\t\t\t\t/** Maximum latency in seconds at the 50th percentile. */\n\t\t\t\tp50?: number;\n\t\t\t\t/** Maximum latency in seconds at the 75th percentile. */\n\t\t\t\tp75?: number;\n\t\t\t\t/** Maximum latency in seconds at the 90th percentile. */\n\t\t\t\tp90?: number;\n\t\t\t\t/** Maximum latency in seconds at the 99th percentile. */\n\t\t\t\tp99?: number;\n\t\t };\n}\n\n/**\n * Vercel AI Gateway routing preferences.\n * Controls which upstream providers the gateway routes requests to.\n * @see https://vercel.com/docs/ai-gateway/models-and-providers/provider-options\n */\nexport interface VercelGatewayRouting {\n\t/** List of provider slugs to exclusively use for this request (e.g., [\"bedrock\", \"anthropic\"]). */\n\tonly?: string[];\n\t/** List of provider slugs to try in order (e.g., [\"anthropic\", \"openai\"]). */\n\torder?: string[];\n}\n\n// Model interface for the unified model system\nexport interface Model<TApi extends Api> {\n\tid: string;\n\tname: string;\n\tapi: TApi;\n\tprovider: Provider;\n\tbaseUrl: string;\n\treasoning: boolean;\n\t/**\n\t * Maps pi thinking levels to provider/model-specific values.\n\t * Missing keys use provider defaults. null marks a level as unsupported.\n\t */\n\tthinkingLevelMap?: ThinkingLevelMap;\n\tinput: (\"text\" | \"image\")[];\n\tcost: {\n\t\tinput: number; // $/million tokens\n\t\toutput: number; // $/million tokens\n\t\tcacheRead: number; // $/million tokens\n\t\tcacheWrite: number; // $/million tokens\n\t\ttiers?: CostTier[];\n\t};\n\tcontextWindow: number;\n\tmaxTokens: number;\n\theaders?: Record<string, string>;\n\t/** Disable provider authentication headers for trusted local-compatible endpoints. */\n\tauthHeader?: boolean;\n\t/** Compatibility overrides for OpenAI-compatible APIs. If not set, auto-detected from baseUrl. */\n\tcompat?: TApi extends \"openai-completions\"\n\t\t? OpenAICompletionsCompat\n\t\t: TApi extends \"openai-responses\" | \"openai-codex-responses\"\n\t\t\t? OpenAIResponsesCompat\n\t\t\t: TApi extends \"anthropic-messages\"\n\t\t\t\t? AnthropicMessagesCompat\n\t\t\t\t: never;\n}\n\nexport interface ImagesModel<TApi extends ImagesApi>\n\textends Omit<Model<Api>, \"api\" | \"provider\" | \"reasoning\" | \"contextWindow\" | \"maxTokens\" | \"compat\"> {\n\tapi: TApi;\n\tprovider: ImagesProvider;\n\toutput: (\"text\" | \"image\")[];\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { AssistantMessageDiagnostic } from \"./utils/diagnostics.js\";\nimport type { AssistantImagesEventStream, AssistantMessageEventStream } from \"./utils/event-stream.js\";\n\nexport type {\n\tAssistantImagesEventStream,\n\tAssistantMessageEventStream,\n} from \"./utils/event-stream.js\";\n\nexport type KnownApi =\n\t| \"openai-completions\"\n\t| \"mistral-conversations\"\n\t| \"openai-responses\"\n\t| \"azure-openai-responses\"\n\t| \"openai-codex-responses\"\n\t| \"anthropic-messages\"\n\t| \"bedrock-converse-stream\"\n\t| \"google-generative-ai\"\n\t| \"google-vertex\"\n\t| \"claude-cli\";\n\nexport type Api = KnownApi | (string & {});\n\nexport type KnownImagesApi = \"openrouter-images\";\n\nexport type ImagesApi = KnownImagesApi | (string & {});\n\nexport type KnownProvider =\n\t| \"amazon-bedrock\"\n\t| \"anthropic\"\n\t| \"google\"\n\t| \"google-vertex\"\n\t| \"openai\"\n\t| \"azure-openai-responses\"\n\t| \"openai-codex\"\n\t| \"deepseek\"\n\t| \"github-copilot\"\n\t| \"xai\"\n\t| \"groq\"\n\t| \"cerebras\"\n\t| \"openrouter\"\n\t| \"vercel-ai-gateway\"\n\t| \"zai\"\n\t| \"zai-coding-cn\"\n\t| \"mistral\"\n\t| \"minimax\"\n\t| \"minimax-cn\"\n\t| \"moonshotai\"\n\t| \"moonshotai-cn\"\n\t| \"huggingface\"\n\t| \"fireworks\"\n\t| \"together\"\n\t| \"ant-ling\"\n\t| \"opencode\"\n\t| \"opencode-go\"\n\t| \"kimi-coding\"\n\t| \"cloudflare-workers-ai\"\n\t| \"cloudflare-ai-gateway\"\n\t| \"xiaomi\"\n\t| \"xiaomi-token-plan-cn\"\n\t| \"xiaomi-token-plan-ams\"\n\t| \"xiaomi-token-plan-sgp\";\nexport type Provider = KnownProvider | string;\n\nexport type KnownImagesProvider = \"openrouter\";\n\nexport type ImagesProvider = KnownImagesProvider | string;\n\nexport type ThinkingLevel = \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\nexport type ModelThinkingLevel = \"off\" | ThinkingLevel;\n/** Provider-specific reasoning map from Pi thinking levels to provider values. */\nexport type ThinkingLevelMap = Partial<Record<ModelThinkingLevel, string | null>>;\n\n/** Token budgets for each thinking level (token-based providers only) */\nexport interface ThinkingBudgets {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\n// Base options all providers share\nexport type CacheRetention = \"none\" | \"short\" | \"long\";\n\nexport type Transport = \"sse\" | \"websocket\" | \"websocket-cached\" | \"auto\";\n\n/** Provider-scoped environment overrides. Explicit values take precedence over process.env. */\nexport type ProviderEnv = Readonly<Record<string, string | undefined>>;\n\nexport interface ProviderResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\nexport interface StreamOptions {\n\ttemperature?: number;\n\tmaxTokens?: number;\n\tsignal?: AbortSignal;\n\tapiKey?: string;\n\t/**\n\t * Preferred transport for providers that support multiple transports.\n\t * Providers that do not support this option ignore it.\n\t */\n\ttransport?: Transport;\n\t/**\n\t * Prompt cache retention preference. Providers map this to their supported values.\n\t * Default: \"short\".\n\t */\n\tcacheRetention?: CacheRetention;\n\t/**\n\t * Optional session identifier for providers that support session-based caching.\n\t * Providers can use this to enable prompt caching, request routing, or other\n\t * session-aware features. Ignored by providers that don't support it.\n\t */\n\tsessionId?: string;\n\t/**\n\t * Optional callback for inspecting or replacing provider payloads before sending.\n\t * Return undefined to keep the payload unchanged.\n\t */\n\tonPayload?: (payload: unknown, model: Model<Api>) => unknown | undefined | Promise<unknown | undefined>;\n\t/**\n\t * Optional callback invoked after an HTTP response is received and before\n\t * its body stream is consumed.\n\t */\n\tonResponse?: (response: ProviderResponse, model: Model<Api>) => void | Promise<void>;\n\t/**\n\t * Optional custom HTTP headers to include in API requests.\n\t * Merged with provider defaults; can override default headers.\n\t * Not supported by all providers (e.g., AWS Bedrock uses SDK auth).\n\t */\n\theaders?: Record<string, string>;\n\t/**\n\t * HTTP request timeout in milliseconds for providers/SDKs that support it.\n\t * For example, OpenAI and Anthropic SDK clients default to 10 minutes.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * WebSocket connect timeout in milliseconds for providers that support\n\t * WebSocket transports. This covers the connection/open handshake only;\n\t * stream idleness after connection uses timeoutMs.\n\t */\n\twebsocketConnectTimeoutMs?: number;\n\t/**\n\t * Maximum retry attempts for providers/SDKs that support client-side retries.\n\t * For example, OpenAI and Anthropic SDK clients default to 2.\n\t */\n\tmaxRetries?: number;\n\t/**\n\t * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.\n\t * If the server's requested delay exceeds this value, the request fails immediately\n\t * with an error containing the requested delay, allowing higher-level retry logic\n\t * to handle it with user visibility.\n\t * Default: 60000 (60 seconds). Set to 0 to disable the cap.\n\t */\n\tmaxRetryDelayMs?: number;\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t * For example, Anthropic uses `user_id` for abuse tracking and rate limiting.\n\t */\n\tmetadata?: Record<string, unknown>;\n\t/**\n\t * Provider-scoped environment values. These take precedence over process.env\n\t * for provider configuration and credential discovery.\n\t */\n\tenv?: ProviderEnv;\n}\n\nexport type ProviderStreamOptions = StreamOptions & Record<string, unknown>;\n\nexport interface ImagesOptions {\n\tsignal?: AbortSignal;\n\tapiKey?: string;\n\t/** Provider-scoped environment values used for image-provider configuration. */\n\tenv?: ProviderEnv;\n\t/**\n\t * Optional callback for inspecting or replacing provider payloads before sending.\n\t * Return undefined to keep the payload unchanged.\n\t */\n\tonPayload?: (payload: unknown, model: ImagesModel<ImagesApi>) => unknown | undefined | Promise<unknown | undefined>;\n\t/**\n\t * Optional callback invoked after an HTTP response is received.\n\t */\n\tonResponse?: (response: ProviderResponse, model: ImagesModel<ImagesApi>) => void | Promise<void>;\n\t/**\n\t * Optional custom HTTP headers to include in API requests.\n\t * Merged with provider defaults; can override default headers.\n\t */\n\theaders?: Record<string, string>;\n\t/**\n\t * HTTP request timeout in milliseconds for providers/SDKs that support it.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * Maximum retry attempts for providers/SDKs that support client-side retries.\n\t */\n\tmaxRetries?: number;\n\t/**\n\t * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.\n\t * If the server's requested delay exceeds this value, the request fails immediately\n\t * with an error containing the requested delay, allowing higher-level retry logic\n\t * to handle it with user visibility.\n\t * Default: 60000 (60 seconds). Set to 0 to disable the cap.\n\t */\n\tmaxRetryDelayMs?: number;\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t */\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type ProviderImagesOptions = ImagesOptions & Record<string, unknown>;\n\n// Unified options with reasoning passed to streamSimple() and completeSimple()\nexport interface SimpleStreamOptions extends StreamOptions {\n\treasoning?: ThinkingLevel;\n\t/** Custom token budgets for thinking levels (token-based providers only) */\n\tthinkingBudgets?: ThinkingBudgets;\n}\n\n// Generic StreamFunction with typed options.\n//\n// Contract:\n// - Must return an AssistantMessageEventStream.\n// - Once invoked, request/model/runtime failures should be encoded in the\n// returned stream, not thrown.\n// - Error termination must produce an AssistantMessage with stopReason\n// \"error\" or \"aborted\" and errorMessage, emitted via the stream protocol.\nexport type StreamFunction<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> = (\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: TOptions,\n) => AssistantMessageEventStream;\n\nexport type ImagesFunction<TApi extends ImagesApi = ImagesApi, TOptions extends ImagesOptions = ImagesOptions> = (\n\tmodel: ImagesModel<TApi>,\n\tcontext: ImagesContext,\n\toptions?: TOptions,\n) => AssistantImagesEventStream;\n\nexport interface TextSignatureV1 {\n\tv: 1;\n\tid: string;\n\tphase?: \"commentary\" | \"final_answer\";\n}\n\nexport interface TextContent {\n\ttype: \"text\";\n\ttext: string;\n\ttextSignature?: string; // e.g., for OpenAI responses, message metadata (legacy id string or TextSignatureV1 JSON)\n}\n\nexport interface ThinkingContent {\n\ttype: \"thinking\";\n\tthinking: string;\n\tthinkingSignature?: string; // e.g., for OpenAI responses, the reasoning item ID\n\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t * to the API for multi-turn continuity. */\n\tredacted?: boolean;\n}\n\nexport interface ImageContent {\n\ttype: \"image\";\n\tdata: string; // base64 encoded image data\n\tmimeType: string; // e.g., \"image/jpeg\", \"image/png\"\n}\n\nexport interface ToolCall {\n\ttype: \"toolCall\";\n\tid: string;\n\tname: string;\n\targuments: Record<string, any>;\n\t/** Completed raw arguments were invalid; execution must return this error instead. */\n\targumentsError?: string;\n\tthoughtSignature?: string; // Google-specific: opaque signature for reusing thought context\n\t/** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */\n\tnamespace?: string;\n}\n\n/** Alternate per-million-token pricing for a higher input-token band. */\nexport interface CostTier {\n\tinputTokensAbove: number;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n}\n\nexport interface Usage {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\t/** Subset of `cacheWrite` written with 1h retention. Only Anthropic reports this split. */\n\tcacheWrite1h?: number;\n\ttotalTokens: number;\n\tcost: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n}\n\nexport type StopReason = \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\";\n\nexport interface UserMessage {\n\trole: \"user\";\n\tcontent: string | (TextContent | ImageContent)[];\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\n/** Bounded provider error identifiers for policy decisions; never raw error payloads. */\nexport interface ProviderErrorMetadata {\n\tcode?: string;\n\ttype?: string;\n}\n\nexport interface AssistantMessage {\n\trole: \"assistant\";\n\tcontent: (TextContent | ThinkingContent | ImageContent | ToolCall)[];\n\tapi: Api;\n\tprovider: Provider;\n\tmodel: string;\n\tresponseModel?: string; // Concrete `chunk.model` when different from the requested `model` (e.g. OpenRouter `auto` -> `anthropic/...`)\n\tresponseId?: string; // Provider-specific response/message identifier when the upstream API exposes one\n\tdiagnostics?: AssistantMessageDiagnostic[]; // Redacted provider/runtime diagnostics for failures and recoveries.\n\tusage: Usage;\n\tstopReason: StopReason;\n\terrorMessage?: string;\n\terrorMetadata?: ProviderErrorMetadata;\n\trawStopReason?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface ToolResultMessage<TDetails = any> {\n\trole: \"toolResult\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tcontent: (TextContent | ImageContent)[]; // Supports text and images\n\tdetails?: TDetails;\n\t/**\n\t * Tool names that were activated by this tool result and should be loaded\n\t * lazily at this transcript position when supported by the provider.\n\t */\n\taddedToolNames?: string[];\n\tisError: boolean;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport type Message = UserMessage | AssistantMessage | ToolResultMessage;\n\nexport type ImagesInputContent = TextContent | ImageContent;\nexport type ImagesOutputContent = TextContent | ImageContent;\n\nexport interface ImagesContext {\n\tinput: ImagesInputContent[];\n}\n\nexport type ImagesStopReason = \"stop\" | \"error\" | \"aborted\";\n\nexport interface AssistantImages {\n\tapi: ImagesApi;\n\tprovider: ImagesProvider;\n\tmodel: string;\n\toutput: ImagesOutputContent[];\n\tresponseId?: string;\n\tusage?: Usage;\n\tstopReason: ImagesStopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nimport type { TSchema } from \"typebox\";\n\nexport interface Tool<TParameters extends TSchema = TSchema> {\n\tname: string;\n\tdescription: string;\n\tparameters: TParameters;\n}\n\nexport interface Context {\n\tsystemPrompt?: string;\n\tmessages: Message[];\n\ttools?: Tool[];\n}\n\n/**\n * Event protocol for AssistantMessageEventStream.\n *\n * Streams should emit `start` before partial updates, then terminate with either:\n * - `done` carrying the final successful AssistantMessage, or\n * - `error` carrying the final AssistantMessage with stopReason \"error\" or \"aborted\"\n * and errorMessage.\n */\nexport type AssistantMessageEvent =\n\t| { type: \"start\"; partial: AssistantMessage }\n\t| { type: \"text_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"text_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"thinking_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"thinking_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"image_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"image_end\"; contentIndex: number; image: ImageContent; partial: AssistantMessage }\n\t| { type: \"toolcall_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"toolcall_end\"; contentIndex: number; toolCall: ToolCall; partial: AssistantMessage }\n\t| { type: \"done\"; reason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\">; message: AssistantMessage }\n\t| { type: \"error\"; reason: Extract<StopReason, \"aborted\" | \"error\">; error: AssistantMessage };\n\nexport type AssistantImagesEvent =\n\t| { type: \"start\"; partial: AssistantImages }\n\t| { type: \"image_start\"; contentIndex: number; partial: AssistantImages }\n\t| { type: \"image_end\"; contentIndex: number; image: ImageContent; partial: AssistantImages }\n\t| { type: \"done\"; reason: Extract<ImagesStopReason, \"stop\">; images: AssistantImages }\n\t| { type: \"error\"; reason: Extract<ImagesStopReason, \"aborted\" | \"error\">; error: AssistantImages };\n\n/**\n * Compatibility settings for OpenAI-compatible completions APIs.\n * Use this to override URL-based auto-detection for custom providers.\n */\nexport interface OpenAICompletionsCompat {\n\t/** Whether the provider supports the `store` field. Default: auto-detected from URL. */\n\tsupportsStore?: boolean;\n\t/** Whether the provider supports the `developer` role (vs `system`). Default: auto-detected from URL. */\n\tsupportsDeveloperRole?: boolean;\n\t/** Whether the provider supports `reasoning_effort`. Default: auto-detected from URL. */\n\tsupportsReasoningEffort?: boolean;\n\t/** Whether the provider supports `stream_options: { include_usage: true }` for token usage in streaming responses. Default: true. */\n\tsupportsUsageInStreaming?: boolean;\n\t/** Whether streamed responses include `finish_reason`. When false, Merc infers `stop` or `toolUse` when the stream ends. Default: true. */\n\tsupportsFinishReason?: boolean;\n\t/** Which field to use for max tokens. Default: auto-detected from URL. */\n\tmaxTokensField?: \"max_completion_tokens\" | \"max_tokens\";\n\t/** Whether tool results require the `name` field. Default: auto-detected from URL. */\n\trequiresToolResultName?: boolean;\n\t/** Whether a user message after tool results requires an assistant message in between. Default: auto-detected from URL. */\n\trequiresAssistantAfterToolResult?: boolean;\n\t/** Whether thinking blocks must be converted to text blocks with <thinking> delimiters. Default: auto-detected from URL. */\n\trequiresThinkingAsText?: boolean;\n\t/** Whether all replayed assistant messages must include an empty reasoning_content field when reasoning is enabled. */\n\trequiresReasoningContentOnAssistantMessages?: boolean;\n\t/** Format for reasoning/thinking parameter. \"openai\" uses reasoning_effort, \"openrouter\" uses reasoning: { effort }, \"deepseek\" uses thinking: { type } plus reasoning_effort when supported, \"together\" uses reasoning: { enabled } plus reasoning_effort when supported, \"ant-ling\" uses reasoning: { effort }, \"zai\" uses thinking: { type }, \"qwen\" uses top-level enable_thinking: boolean, \"qwen-chat-template\" uses chat_template_kwargs.enable_thinking, \"minimax\" uses thinking: { type } plus reasoning_split, and \"string-thinking\" uses top-level thinking: string. Default: \"openai\". */\n\tthinkingFormat?:\n\t\t| \"openai\"\n\t\t| \"openrouter\"\n\t\t| \"deepseek\"\n\t\t| \"together\"\n\t\t| \"ant-ling\"\n\t\t| \"zai\"\n\t\t| \"qwen\"\n\t\t| \"qwen-chat-template\"\n\t\t| \"minimax\";\n\t/** OpenRouter-specific routing preferences. Only used when baseUrl points to OpenRouter. */\n\topenRouterRouting?: OpenRouterRouting;\n\t/** Whether the model uses OpenRouter's image-generation response shape with assistant `message.images`. */\n\topenRouterImageGeneration?: boolean;\n\t/** Vercel AI Gateway routing preferences. Only used when baseUrl points to Vercel AI Gateway. */\n\tvercelGatewayRouting?: VercelGatewayRouting;\n\t/** Whether z.ai supports top-level `tool_stream: true` for streaming tool call deltas. Default: false. */\n\tzaiToolStream?: boolean;\n\t/** Whether the provider supports the `strict` field in tool definitions. Default: true. */\n\tsupportsStrictMode?: boolean;\n\t/** Cache control convention for prompt caching. \"anthropic\" applies Anthropic-style `cache_control` markers to the system prompt, last tool definition, and last user/assistant text content. */\n\tcacheControlFormat?: \"anthropic\";\n\t/** Whether to send session-affinity data from `options.sessionId`. Default: true for OpenRouter endpoints, false otherwise. */\n\tsendSessionAffinityHeaders?: boolean;\n\t/** Session-affinity header format. Default: auto-detected. */\n\tsessionAffinityFormat?: \"openai\" | \"openai-nosession\" | \"openrouter\";\n\t/** Whether the provider supports long prompt cache retention (`prompt_cache_retention: \"24h\"` or Anthropic-style `cache_control.ttl: \"1h\"`, depending on format). Default: true. */\n\tsupportsLongCacheRetention?: boolean;\n}\n\n/** Compatibility settings for OpenAI Responses APIs. */\nexport interface OpenAIResponsesCompat {\n\t/** Whether the provider supports the `developer` role (vs `system`). Default: true. */\n\tsupportsDeveloperRole?: boolean;\n\t/** Session-affinity header format. Default: auto-detected. */\n\tsessionAffinityFormat?: \"openai\" | \"openai-nosession\" | \"openrouter\";\n\t/** Whether the provider supports `prompt_cache_retention: \"24h\"`. Default: true. */\n\tsupportsLongCacheRetention?: boolean;\n\t/** Whether the provider supports client-side tool search / deferred tool loading. Default: false. */\n\tsupportsToolSearch?: boolean;\n\t/** Whether the provider accepts the `max_output_tokens` parameter. Some Codex-protocol gateways reject it. Default: true. */\n\tsupportsMaxOutputTokens?: boolean;\n\t/** Whether the model accepts `prompt_cache_options` (OpenAI models that bill prompt-cache writes, GPT-5.6 onward). Older OpenAI models reject the parameter. Default: true for OpenAI models with a cache-write price, false otherwise. */\n\tsupportsExplicitPromptCacheMode?: boolean;\n}\n\n/** Compatibility settings for Anthropic Messages-compatible APIs. */\nexport interface AnthropicMessagesCompat {\n\t/** Whether the provider supports adaptive thinking payloads. */\n\tforceAdaptiveThinking?: boolean;\n\t/**\n\t * Whether the provider accepts per-tool `eager_input_streaming`.\n\t * When false, the Anthropic provider omits `tools[].eager_input_streaming`\n\t * and sends the legacy `fine-grained-tool-streaming-2025-05-14` beta header\n\t * for tool-enabled requests.\n\t * Default: true.\n\t */\n\tsupportsEagerToolInputStreaming?: boolean;\n\t/** Whether the provider supports Anthropic long cache retention (`cache_control.ttl: \"1h\"`). Default: true. */\n\tsupportsLongCacheRetention?: boolean;\n\t/**\n\t * Whether to send the `x-session-affinity` header from `options.sessionId`\n\t * when caching is enabled. Required for providers like Fireworks that use\n\t * session affinity for prompt cache routing (requests to the same replica\n\t * maximize cache hits).\n\t * Default: true for OpenRouter endpoints, false otherwise.\n\t */\n\tsendSessionAffinityHeaders?: boolean;\n\t/** Session-affinity format. `\"openrouter\"` sends `x-session-id`; when unset, sends `x-session-affinity`. */\n\tsessionAffinityFormat?: \"openrouter\";\n\t/**\n\t * Whether the provider supports Anthropic-style `cache_control` markers on\n\t * tool definitions. When false, `cache_control` is omitted from tool params.\n\t * Some Anthropic-compatible providers (e.g., Fireworks) do not support this\n\t * field on tools and may reject or ignore it.\n\t * Default: true.\n\t */\n\tsupportsCacheControlOnTools?: boolean;\n\t/** Whether the provider supports client-side `tool_reference` blocks. Default: false for unsupported models. */\n\tsupportsToolReferences?: boolean;\n\t/**\n\t * Whether the model accepts the Anthropic `temperature` request field.\n\t * Claude Opus 4.7+ rejects non-default temperature values.\n\t * Default: true.\n\t */\n\tsupportsTemperature?: boolean;\n}\n\n/**\n * OpenRouter provider routing preferences.\n * Controls which upstream providers OpenRouter routes requests to.\n * Sent as the `provider` field in the OpenRouter API request body.\n * @see https://openrouter.ai/docs/guides/routing/provider-selection\n */\nexport interface OpenRouterRouting {\n\t/** Whether to allow backup providers to serve requests. Default: true. */\n\tallow_fallbacks?: boolean;\n\t/** Whether to filter providers to only those that support all parameters in the request. Default: false. */\n\trequire_parameters?: boolean;\n\t/** Data collection setting. \"allow\" (default): allow providers that may store/train on data. \"deny\": only use providers that don't collect user data. */\n\tdata_collection?: \"deny\" | \"allow\";\n\t/** Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. */\n\tzdr?: boolean;\n\t/** Whether to restrict routing to only models that allow text distillation. */\n\tenforce_distillable_text?: boolean;\n\t/** An ordered list of provider names/slugs to try in sequence, falling back to the next if unavailable. */\n\torder?: string[];\n\t/** List of provider names/slugs to exclusively allow for this request. */\n\tonly?: string[];\n\t/** List of provider names/slugs to skip for this request. */\n\tignore?: string[];\n\t/** A list of quantization levels to filter providers by (e.g., [\"fp16\", \"bf16\", \"fp8\", \"fp6\", \"int8\", \"int4\", \"fp4\", \"fp32\"]). */\n\tquantizations?: string[];\n\t/** Sorting strategy. Can be a string (e.g., \"price\", \"throughput\", \"latency\") or an object with `by` and `partition`. */\n\tsort?:\n\t\t| string\n\t\t| {\n\t\t\t\t/** The sorting metric: \"price\", \"throughput\", \"latency\". */\n\t\t\t\tby?: string;\n\t\t\t\t/** Partitioning strategy: \"model\" (default) or \"none\". */\n\t\t\t\tpartition?: string | null;\n\t\t };\n\t/** Maximum price per million tokens (USD). */\n\tmax_price?: {\n\t\t/** Price per million prompt tokens. */\n\t\tprompt?: number | string;\n\t\t/** Price per million completion tokens. */\n\t\tcompletion?: number | string;\n\t\t/** Price per image. */\n\t\timage?: number | string;\n\t\t/** Price per audio unit. */\n\t\taudio?: number | string;\n\t\t/** Price per request. */\n\t\trequest?: number | string;\n\t};\n\t/** Preferred minimum throughput (tokens/second). Can be a number (applies to p50) or an object with percentile-specific cutoffs. */\n\tpreferred_min_throughput?:\n\t\t| number\n\t\t| {\n\t\t\t\t/** Minimum tokens/second at the 50th percentile. */\n\t\t\t\tp50?: number;\n\t\t\t\t/** Minimum tokens/second at the 75th percentile. */\n\t\t\t\tp75?: number;\n\t\t\t\t/** Minimum tokens/second at the 90th percentile. */\n\t\t\t\tp90?: number;\n\t\t\t\t/** Minimum tokens/second at the 99th percentile. */\n\t\t\t\tp99?: number;\n\t\t };\n\t/** Preferred maximum latency (seconds). Can be a number (applies to p50) or an object with percentile-specific cutoffs. */\n\tpreferred_max_latency?:\n\t\t| number\n\t\t| {\n\t\t\t\t/** Maximum latency in seconds at the 50th percentile. */\n\t\t\t\tp50?: number;\n\t\t\t\t/** Maximum latency in seconds at the 75th percentile. */\n\t\t\t\tp75?: number;\n\t\t\t\t/** Maximum latency in seconds at the 90th percentile. */\n\t\t\t\tp90?: number;\n\t\t\t\t/** Maximum latency in seconds at the 99th percentile. */\n\t\t\t\tp99?: number;\n\t\t };\n}\n\n/**\n * Vercel AI Gateway routing preferences.\n * Controls which upstream providers the gateway routes requests to.\n * @see https://vercel.com/docs/ai-gateway/models-and-providers/provider-options\n */\nexport interface VercelGatewayRouting {\n\t/** List of provider slugs to exclusively use for this request (e.g., [\"bedrock\", \"anthropic\"]). */\n\tonly?: string[];\n\t/** List of provider slugs to try in order (e.g., [\"anthropic\", \"openai\"]). */\n\torder?: string[];\n}\n\n// Model interface for the unified model system\nexport interface Model<TApi extends Api> {\n\tid: string;\n\tname: string;\n\tapi: TApi;\n\tprovider: Provider;\n\tbaseUrl: string;\n\treasoning: boolean;\n\t/**\n\t * Maps pi thinking levels to provider/model-specific values.\n\t * Missing keys use provider defaults. null marks a level as unsupported.\n\t */\n\tthinkingLevelMap?: ThinkingLevelMap;\n\tinput: (\"text\" | \"image\")[];\n\tcost: {\n\t\tinput: number; // $/million tokens\n\t\toutput: number; // $/million tokens\n\t\tcacheRead: number; // $/million tokens\n\t\tcacheWrite: number; // $/million tokens\n\t\ttiers?: CostTier[];\n\t};\n\tcontextWindow: number;\n\tmaxTokens: number;\n\theaders?: Record<string, string>;\n\t/** Disable provider authentication headers for trusted local-compatible endpoints. */\n\tauthHeader?: boolean;\n\t/** Compatibility overrides for OpenAI-compatible APIs. If not set, auto-detected from baseUrl. */\n\tcompat?: TApi extends \"openai-completions\"\n\t\t? OpenAICompletionsCompat\n\t\t: TApi extends \"openai-responses\" | \"openai-codex-responses\"\n\t\t\t? OpenAIResponsesCompat\n\t\t\t: TApi extends \"anthropic-messages\"\n\t\t\t\t? AnthropicMessagesCompat\n\t\t\t\t: never;\n}\n\nexport interface ImagesModel<TApi extends ImagesApi>\n\textends Omit<Model<Api>, \"api\" | \"provider\" | \"reasoning\" | \"contextWindow\" | \"maxTokens\" | \"compat\"> {\n\tapi: TApi;\n\tprovider: ImagesProvider;\n\toutput: (\"text\" | \"image\")[];\n}\n"]}
@@ -1,5 +1,10 @@
1
+ import type { ProviderErrorMetadata } from "../types.js";
1
2
  export declare const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;
3
+ /** Identify known deterministic request failures from safe provider identifiers. */
4
+ export declare function isDeterministicProviderError(metadata?: ProviderErrorMetadata): boolean;
2
5
  export interface NormalizedProviderError {
6
+ /** Safe code/type identifiers for retry policy, separate from display text. */
7
+ errorMetadata?: ProviderErrorMetadata;
3
8
  /** HTTP status code, when one could be extracted from the SDK error object. */
4
9
  status?: number;
5
10
  /** Raw HTTP body reason, bounded to avoid untrusted error amplification. */
@@ -1 +1 @@
1
- {"version":3,"file":"error-body.d.ts","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,MAAM,WAAW,uBAAuB;IACvC,+EAA+E;IAC/E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4EAA4E;IAC5E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,kEAAkE;IAClE,OAAO,EAAE,MAAM,CAAC;IAChB,+DAA+D;IAC/D,kBAAkB,EAAE,OAAO,CAAC;CAC5B;AAWD,2EAA2E;AAC3E,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CAY9E;AAED,+EAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,uBAAuB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAO1F;AAED,iFAAiF;AACjF,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGxE;AAED,qFAAqF;AACrF,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOxD","sourcesContent":["// Shared normalization for provider HTTP error objects.\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\nexport interface NormalizedProviderError {\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, bounded to avoid untrusted error amplification. */\n\tbody?: string;\n\t/** Error message or a safe serialization of a non-Error throw. */\n\tmessage: string;\n\t/** Whether the message already contains the extracted body. */\n\tmessageCarriesBody: boolean;\n}\n\ntype SdkErrorShape = Error & {\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\n/** Normalize SDK-specific status, body, and message fields for display. */\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tif (!(error instanceof Error)) return { message: safeJsonStringify(error), messageCarriesBody: false };\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\treturn {\n\t\tstatus,\n\t\tbody,\n\t\tmessage: error.message,\n\t\tmessageCarriesBody: body === undefined || error.message.includes(body),\n\t};\n}\n\n/** Format a normalized provider error while preserving the provider prefix. */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\n/** Bound provider-controlled error text before exposing it in the transcript. */\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\n/** Serialize unknown thrown values without allowing serialization to throw again. */\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst responseBody = error.$response?.body;\n\tconst body =\n\t\ttypeof error.body === \"string\"\n\t\t\t? error.body\n\t\t\t: isNonEmptyObject(error.error)\n\t\t\t\t? safeJsonStringify(error.error)\n\t\t\t\t: typeof responseBody === \"string\"\n\t\t\t\t\t? responseBody\n\t\t\t\t\t: isNonEmptyObject(responseBody)\n\t\t\t\t\t\t? safeJsonStringify(responseBody)\n\t\t\t\t\t\t: undefined;\n\tif (body === undefined || body.trim().length === 0) return undefined;\n\treturn truncateErrorText(body.trim(), MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\nfunction isNonEmptyObject(value: unknown): boolean {\n\treturn typeof value === \"object\" && value !== null && Object.keys(value).length > 0;\n}\n"]}
1
+ {"version":3,"file":"error-body.d.ts","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEzD,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,oFAAoF;AACpF,wBAAgB,4BAA4B,CAAC,QAAQ,CAAC,EAAE,qBAAqB,GAAG,OAAO,CAItF;AAED,MAAM,WAAW,uBAAuB;IACvC,+EAA+E;IAC/E,aAAa,CAAC,EAAE,qBAAqB,CAAC;IACtC,+EAA+E;IAC/E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4EAA4E;IAC5E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,kEAAkE;IAClE,OAAO,EAAE,MAAM,CAAC;IAChB,+DAA+D;IAC/D,kBAAkB,EAAE,OAAO,CAAC;CAC5B;AAWD,2EAA2E;AAC3E,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CAe9E;AAkCD,+EAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,uBAAuB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAO1F;AAED,iFAAiF;AACjF,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGxE;AAED,qFAAqF;AACrF,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOxD","sourcesContent":["// Shared normalization for provider HTTP error objects.\n\nimport type { ProviderErrorMetadata } from \"../types.js\";\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\n/** Identify known deterministic request failures from safe provider identifiers. */\nexport function isDeterministicProviderError(metadata?: ProviderErrorMetadata): boolean {\n\treturn [metadata?.code, metadata?.type].some(\n\t\t(identifier) => identifier === \"tool_use_failed\" || identifier === \"invalid_request_error\",\n\t);\n}\n\nexport interface NormalizedProviderError {\n\t/** Safe code/type identifiers for retry policy, separate from display text. */\n\terrorMetadata?: ProviderErrorMetadata;\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, bounded to avoid untrusted error amplification. */\n\tbody?: string;\n\t/** Error message or a safe serialization of a non-Error throw. */\n\tmessage: string;\n\t/** Whether the message already contains the extracted body. */\n\tmessageCarriesBody: boolean;\n}\n\ntype SdkErrorShape = Error & {\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\n/** Normalize SDK-specific status, body, and message fields for display. */\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tconst errorMetadata = extractErrorMetadata(error);\n\tconst metadata = errorMetadata ? { errorMetadata } : {};\n\tif (!(error instanceof Error)) return { ...metadata, message: safeJsonStringify(error), messageCarriesBody: false };\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\treturn {\n\t\t...metadata,\n\t\tstatus,\n\t\tbody,\n\t\tmessage: error.message,\n\t\tmessageCarriesBody: body === undefined || error.message.includes(body),\n\t};\n}\n\nfunction extractErrorMetadata(error: unknown): ProviderErrorMetadata | undefined {\n\tlet code: string | undefined;\n\tlet type: string | undefined;\n\t// SDKs expose identifiers directly, in error.error, or in a nested error envelope.\n\tfor (let depth = 0; depth < 3 && error !== null && typeof error === \"object\"; depth++) {\n\t\tconst fields = error as { code?: unknown; type?: unknown; error?: unknown; body?: unknown; message?: unknown };\n\t\t// The provider envelope is more specific than an SDK wrapper's identifiers.\n\t\tcode = identifier(fields.code) ?? code;\n\t\t// SSE's outer type=\"error\" is a transport discriminator, not a provider type.\n\t\ttype = identifier(fields.type === \"error\" && fields.error ? undefined : fields.type) ?? type;\n\t\terror = fields.error;\n\t\tconst serialized =\n\t\t\ttypeof fields.body === \"string\"\n\t\t\t\t? fields.body\n\t\t\t\t: typeof fields.message === \"string\" && fields.message.trim().startsWith(\"{\")\n\t\t\t\t\t? fields.message\n\t\t\t\t\t: undefined;\n\t\tif (!error && serialized && serialized.length <= MAX_PROVIDER_ERROR_BODY_CHARS) {\n\t\t\ttry {\n\t\t\t\terror = JSON.parse(serialized);\n\t\t\t} catch {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn code || type ? { ...(code ? { code } : {}), ...(type ? { type } : {}) } : undefined;\n}\n\nfunction identifier(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && /^[a-zA-Z0-9_-]{1,128}$/.test(value) ? value : undefined;\n}\n\n/** Format a normalized provider error while preserving the provider prefix. */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\n/** Bound provider-controlled error text before exposing it in the transcript. */\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\n/** Serialize unknown thrown values without allowing serialization to throw again. */\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst responseBody = error.$response?.body;\n\tconst body =\n\t\ttypeof error.body === \"string\"\n\t\t\t? error.body\n\t\t\t: isPlainNonEmptyObject(error.error)\n\t\t\t\t? safeJsonStringify(error.error)\n\t\t\t\t: typeof responseBody === \"string\"\n\t\t\t\t\t? responseBody\n\t\t\t\t\t: isPlainNonEmptyObject(responseBody)\n\t\t\t\t\t\t? safeJsonStringify(responseBody)\n\t\t\t\t\t\t: undefined;\n\tif (body === undefined || body.trim().length === 0) return undefined;\n\treturn truncateErrorText(body.trim(), MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\n/**\n * Only a plain object counts as an HTTP body. SDK error fields can hold class\n * instances (for example AWS SDK v3's `$response.body` stream wrapper); serializing\n * one yields internals noise that would replace the real `error.message`. Parsed\n * JSON bodies are plain objects by construction, so real bodies still surface.\n */\nfunction isPlainNonEmptyObject(value: unknown): boolean {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== Object.prototype && proto !== null) return false;\n\treturn Object.keys(value).length > 0;\n}\n"]}
@@ -1,19 +1,56 @@
1
1
  // Shared normalization for provider HTTP error objects.
2
2
  export const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;
3
+ /** Identify known deterministic request failures from safe provider identifiers. */
4
+ export function isDeterministicProviderError(metadata) {
5
+ return [metadata?.code, metadata?.type].some((identifier) => identifier === "tool_use_failed" || identifier === "invalid_request_error");
6
+ }
3
7
  /** Normalize SDK-specific status, body, and message fields for display. */
4
8
  export function normalizeProviderError(error) {
9
+ const errorMetadata = extractErrorMetadata(error);
10
+ const metadata = errorMetadata ? { errorMetadata } : {};
5
11
  if (!(error instanceof Error))
6
- return { message: safeJsonStringify(error), messageCarriesBody: false };
12
+ return { ...metadata, message: safeJsonStringify(error), messageCarriesBody: false };
7
13
  const sdkError = error;
8
14
  const status = extractStatus(sdkError);
9
15
  const body = extractBody(sdkError);
10
16
  return {
17
+ ...metadata,
11
18
  status,
12
19
  body,
13
20
  message: error.message,
14
21
  messageCarriesBody: body === undefined || error.message.includes(body),
15
22
  };
16
23
  }
24
+ function extractErrorMetadata(error) {
25
+ let code;
26
+ let type;
27
+ // SDKs expose identifiers directly, in error.error, or in a nested error envelope.
28
+ for (let depth = 0; depth < 3 && error !== null && typeof error === "object"; depth++) {
29
+ const fields = error;
30
+ // The provider envelope is more specific than an SDK wrapper's identifiers.
31
+ code = identifier(fields.code) ?? code;
32
+ // SSE's outer type="error" is a transport discriminator, not a provider type.
33
+ type = identifier(fields.type === "error" && fields.error ? undefined : fields.type) ?? type;
34
+ error = fields.error;
35
+ const serialized = typeof fields.body === "string"
36
+ ? fields.body
37
+ : typeof fields.message === "string" && fields.message.trim().startsWith("{")
38
+ ? fields.message
39
+ : undefined;
40
+ if (!error && serialized && serialized.length <= MAX_PROVIDER_ERROR_BODY_CHARS) {
41
+ try {
42
+ error = JSON.parse(serialized);
43
+ }
44
+ catch {
45
+ break;
46
+ }
47
+ }
48
+ }
49
+ return code || type ? { ...(code ? { code } : {}), ...(type ? { type } : {}) } : undefined;
50
+ }
51
+ function identifier(value) {
52
+ return typeof value === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(value) ? value : undefined;
53
+ }
17
54
  /** Format a normalized provider error while preserving the provider prefix. */
18
55
  export function formatProviderError(norm, prefix) {
19
56
  if (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {
@@ -54,18 +91,29 @@ function extractBody(error) {
54
91
  const responseBody = error.$response?.body;
55
92
  const body = typeof error.body === "string"
56
93
  ? error.body
57
- : isNonEmptyObject(error.error)
94
+ : isPlainNonEmptyObject(error.error)
58
95
  ? safeJsonStringify(error.error)
59
96
  : typeof responseBody === "string"
60
97
  ? responseBody
61
- : isNonEmptyObject(responseBody)
98
+ : isPlainNonEmptyObject(responseBody)
62
99
  ? safeJsonStringify(responseBody)
63
100
  : undefined;
64
101
  if (body === undefined || body.trim().length === 0)
65
102
  return undefined;
66
103
  return truncateErrorText(body.trim(), MAX_PROVIDER_ERROR_BODY_CHARS);
67
104
  }
68
- function isNonEmptyObject(value) {
69
- return typeof value === "object" && value !== null && Object.keys(value).length > 0;
105
+ /**
106
+ * Only a plain object counts as an HTTP body. SDK error fields can hold class
107
+ * instances (for example AWS SDK v3's `$response.body` stream wrapper); serializing
108
+ * one yields internals noise that would replace the real `error.message`. Parsed
109
+ * JSON bodies are plain objects by construction, so real bodies still surface.
110
+ */
111
+ function isPlainNonEmptyObject(value) {
112
+ if (typeof value !== "object" || value === null)
113
+ return false;
114
+ const proto = Object.getPrototypeOf(value);
115
+ if (proto !== Object.prototype && proto !== null)
116
+ return false;
117
+ return Object.keys(value).length > 0;
70
118
  }
71
119
  //# sourceMappingURL=error-body.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-body.js","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAAA,wDAAwD;AAExD,MAAM,CAAC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAsBlD,2EAA2E;AAC3E,MAAM,UAAU,sBAAsB,CAAC,KAAc,EAA2B;IAC/E,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,iBAAiB,CAAC,KAAK,CAAC,EAAE,kBAAkB,EAAE,KAAK,EAAE,CAAC;IAEvG,MAAM,QAAQ,GAAG,KAAsB,CAAC;IACxC,MA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C;IACjB,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IACrE,OAAO,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,6BAA6B,CAAC,CAAC;AAAA,CACrE;AAED,SAAS,gBAAgB,CAAC,KAAc,EAAW;IAClD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;AAAA,CACpF","sourcesContent":["// Shared normalization for provider HTTP error objects.\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\nexport interface NormalizedProviderError {\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, bounded to avoid untrusted error amplification. */\n\tbody?: string;\n\t/** Error message or a safe serialization of a non-Error throw. */\n\tmessage: string;\n\t/** Whether the message already contains the extracted body. */\n\tmessageCarriesBody: boolean;\n}\n\ntype SdkErrorShape = Error & {\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\n/** Normalize SDK-specific status, body, and message fields for display. */\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tif (!(error instanceof Error)) return { message: safeJsonStringify(error), messageCarriesBody: false };\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\treturn {\n\t\tstatus,\n\t\tbody,\n\t\tmessage: error.message,\n\t\tmessageCarriesBody: body === undefined || error.message.includes(body),\n\t};\n}\n\n/** Format a normalized provider error while preserving the provider prefix. */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\n/** Bound provider-controlled error text before exposing it in the transcript. */\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\n/** Serialize unknown thrown values without allowing serialization to throw again. */\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst responseBody = error.$response?.body;\n\tconst body =\n\t\ttypeof error.body === \"string\"\n\t\t\t? error.body\n\t\t\t: isNonEmptyObject(error.error)\n\t\t\t\t? safeJsonStringify(error.error)\n\t\t\t\t: typeof responseBody === \"string\"\n\t\t\t\t\t? responseBody\n\t\t\t\t\t: isNonEmptyObject(responseBody)\n\t\t\t\t\t\t? safeJsonStringify(responseBody)\n\t\t\t\t\t\t: undefined;\n\tif (body === undefined || body.trim().length === 0) return undefined;\n\treturn truncateErrorText(body.trim(), MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\nfunction isNonEmptyObject(value: unknown): boolean {\n\treturn typeof value === \"object\" && value !== null && Object.keys(value).length > 0;\n}\n"]}
1
+ {"version":3,"file":"error-body.js","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAAA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;IACrE,OAAO,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,6BAA6B,CAAC,CAAC;AAAA,CACrE;AAED;;;;;GAKG;AACH,SAAS,qBAAqB,CAAC,KAAc,EAAW;IACvD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,KAAK,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC3C,IAAI,KAAK,KAAK,MAAM,CAAC,SAAS,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC/D,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;AAAA,CACrC","sourcesContent":["// Shared normalization for provider HTTP error objects.\n\nimport type { ProviderErrorMetadata } from \"../types.js\";\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\n/** Identify known deterministic request failures from safe provider identifiers. */\nexport function isDeterministicProviderError(metadata?: ProviderErrorMetadata): boolean {\n\treturn [metadata?.code, metadata?.type].some(\n\t\t(identifier) => identifier === \"tool_use_failed\" || identifier === \"invalid_request_error\",\n\t);\n}\n\nexport interface NormalizedProviderError {\n\t/** Safe code/type identifiers for retry policy, separate from display text. */\n\terrorMetadata?: ProviderErrorMetadata;\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, bounded to avoid untrusted error amplification. */\n\tbody?: string;\n\t/** Error message or a safe serialization of a non-Error throw. */\n\tmessage: string;\n\t/** Whether the message already contains the extracted body. */\n\tmessageCarriesBody: boolean;\n}\n\ntype SdkErrorShape = Error & {\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\n/** Normalize SDK-specific status, body, and message fields for display. */\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tconst errorMetadata = extractErrorMetadata(error);\n\tconst metadata = errorMetadata ? { errorMetadata } : {};\n\tif (!(error instanceof Error)) return { ...metadata, message: safeJsonStringify(error), messageCarriesBody: false };\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\treturn {\n\t\t...metadata,\n\t\tstatus,\n\t\tbody,\n\t\tmessage: error.message,\n\t\tmessageCarriesBody: body === undefined || error.message.includes(body),\n\t};\n}\n\nfunction extractErrorMetadata(error: unknown): ProviderErrorMetadata | undefined {\n\tlet code: string | undefined;\n\tlet type: string | undefined;\n\t// SDKs expose identifiers directly, in error.error, or in a nested error envelope.\n\tfor (let depth = 0; depth < 3 && error !== null && typeof error === \"object\"; depth++) {\n\t\tconst fields = error as { code?: unknown; type?: unknown; error?: unknown; body?: unknown; message?: unknown };\n\t\t// The provider envelope is more specific than an SDK wrapper's identifiers.\n\t\tcode = identifier(fields.code) ?? code;\n\t\t// SSE's outer type=\"error\" is a transport discriminator, not a provider type.\n\t\ttype = identifier(fields.type === \"error\" && fields.error ? undefined : fields.type) ?? type;\n\t\terror = fields.error;\n\t\tconst serialized =\n\t\t\ttypeof fields.body === \"string\"\n\t\t\t\t? fields.body\n\t\t\t\t: typeof fields.message === \"string\" && fields.message.trim().startsWith(\"{\")\n\t\t\t\t\t? fields.message\n\t\t\t\t\t: undefined;\n\t\tif (!error && serialized && serialized.length <= MAX_PROVIDER_ERROR_BODY_CHARS) {\n\t\t\ttry {\n\t\t\t\terror = JSON.parse(serialized);\n\t\t\t} catch {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn code || type ? { ...(code ? { code } : {}), ...(type ? { type } : {}) } : undefined;\n}\n\nfunction identifier(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && /^[a-zA-Z0-9_-]{1,128}$/.test(value) ? value : undefined;\n}\n\n/** Format a normalized provider error while preserving the provider prefix. */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\n/** Bound provider-controlled error text before exposing it in the transcript. */\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\n/** Serialize unknown thrown values without allowing serialization to throw again. */\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst responseBody = error.$response?.body;\n\tconst body =\n\t\ttypeof error.body === \"string\"\n\t\t\t? error.body\n\t\t\t: isPlainNonEmptyObject(error.error)\n\t\t\t\t? safeJsonStringify(error.error)\n\t\t\t\t: typeof responseBody === \"string\"\n\t\t\t\t\t? responseBody\n\t\t\t\t\t: isPlainNonEmptyObject(responseBody)\n\t\t\t\t\t\t? safeJsonStringify(responseBody)\n\t\t\t\t\t\t: undefined;\n\tif (body === undefined || body.trim().length === 0) return undefined;\n\treturn truncateErrorText(body.trim(), MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\n/**\n * Only a plain object counts as an HTTP body. SDK error fields can hold class\n * instances (for example AWS SDK v3's `$response.body` stream wrapper); serializing\n * one yields internals noise that would replace the real `error.message`. Parsed\n * JSON bodies are plain objects by construction, so real bodies still surface.\n */\nfunction isPlainNonEmptyObject(value: unknown): boolean {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== Object.prototype && proto !== null) return false;\n\treturn Object.keys(value).length > 0;\n}\n"]}
@@ -0,0 +1,22 @@
1
+ import type { Context, Message, Usage } from "../types.js";
2
+ export interface ContextUsageEstimate {
3
+ /** Larger of usage-backed and fresh full-context estimates. */
4
+ tokens: number;
5
+ /** Tokens reported by the most recent assistant usage block. */
6
+ usageTokens: number;
7
+ /** Estimated tokens after the most recent assistant usage block. */
8
+ trailingTokens: number;
9
+ /** Index of the message that provided usage, or null when none exists. */
10
+ lastUsageIndex: number | null;
11
+ }
12
+ export declare function calculateContextTokens(usage: Usage): number;
13
+ export declare function estimateTextTokens(text: string): number;
14
+ export declare function estimateMessageTokens(message: Message): number;
15
+ /**
16
+ * Compare the latest assistant usage plus estimated trailing messages with a fresh
17
+ * estimate of all current messages, system prompt and tools. Use the larger total
18
+ * so a changed prefix cannot hide behind older usage. Usage-source metadata remains
19
+ * unchanged even when the fresh estimate raises the total.
20
+ */
21
+ export declare function estimateContextTokens(context: Context): ContextUsageEstimate;
22
+ //# sourceMappingURL=estimate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"estimate.d.ts","sourceRoot":"","sources":["../../src/utils/estimate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAoB,OAAO,EAAgB,OAAO,EAAe,KAAK,EAAE,MAAM,aAAa,CAAC;AAExG,MAAM,WAAW,oBAAoB;IACpC,+DAA+D;IAC/D,MAAM,EAAE,MAAM,CAAC;IACf,gEAAgE;IAChE,WAAW,EAAE,MAAM,CAAC;IACpB,oEAAoE;IACpE,cAAc,EAAE,MAAM,CAAC;IACvB,0EAA0E;IAC1E,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B;AAKD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,CAE3D;AAkBD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEvD;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAkB9D;AAuCD;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,oBAAoB,CAkB5E","sourcesContent":["import type { AssistantMessage, Context, ImageContent, Message, TextContent, Usage } from \"../types.js\";\n\nexport interface ContextUsageEstimate {\n\t/** Larger of usage-backed and fresh full-context estimates. */\n\ttokens: number;\n\t/** Tokens reported by the most recent assistant usage block. */\n\tusageTokens: number;\n\t/** Estimated tokens after the most recent assistant usage block. */\n\ttrailingTokens: number;\n\t/** Index of the message that provided usage, or null when none exists. */\n\tlastUsageIndex: number | null;\n}\n\nconst CHARS_PER_TOKEN = 3.5;\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\nfunction safeJsonStringify(value: unknown): string {\n\ttry {\n\t\treturn JSON.stringify(value) ?? \"undefined\";\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\nfunction estimateTextAndImageContentChars(content: string | Array<TextContent | ImageContent>): number {\n\tif (typeof content === \"string\") return content.length;\n\n\tlet chars = 0;\n\tfor (const block of content) chars += block.type === \"text\" ? block.text.length : ESTIMATED_IMAGE_CHARS;\n\treturn chars;\n}\n\nexport function estimateTextTokens(text: string): number {\n\treturn Math.ceil(text.length / CHARS_PER_TOKEN);\n}\n\nexport function estimateMessageTokens(message: Message): number {\n\tif (message.role === \"user\" || message.role === \"toolResult\") {\n\t\treturn Math.ceil(estimateTextAndImageContentChars(message.content) / CHARS_PER_TOKEN);\n\t}\n\n\tlet chars = 0;\n\tfor (const block of message.content) {\n\t\tif (block.type === \"text\") {\n\t\t\tchars += block.text.length;\n\t\t} else if (block.type === \"thinking\") {\n\t\t\tchars += block.thinking.length;\n\t\t} else if (block.type === \"image\") {\n\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t} else {\n\t\t\tchars += block.name.length + safeJsonStringify(block.arguments).length;\n\t\t}\n\t}\n\treturn Math.ceil(chars / CHARS_PER_TOKEN);\n}\n\nfunction getLastAssistantUsageInfo(messages: readonly Message[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role !== \"assistant\") continue;\n\t\tconst assistant = message as AssistantMessage;\n\t\tif (assistant.stopReason === \"aborted\" || assistant.stopReason === \"error\") continue;\n\t\tif (calculateContextTokens(assistant.usage) > 0) return { usage: assistant.usage, index: i };\n\t}\n\treturn undefined;\n}\n\nfunction estimateMessages(messages: readonly Message[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\tif (usageInfo) {\n\t\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\t\tlet trailingTokens = 0;\n\t\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\t\ttrailingTokens += estimateMessageTokens(messages[i]);\n\t\t}\n\t\treturn {\n\t\t\ttokens: usageTokens + trailingTokens,\n\t\t\tusageTokens,\n\t\t\ttrailingTokens,\n\t\t\tlastUsageIndex: usageInfo.index,\n\t\t};\n\t}\n\n\tlet tokens = 0;\n\tfor (const message of messages) tokens += estimateMessageTokens(message);\n\treturn {\n\t\ttokens,\n\t\tusageTokens: 0,\n\t\ttrailingTokens: tokens,\n\t\tlastUsageIndex: null,\n\t};\n}\n\n/**\n * Compare the latest assistant usage plus estimated trailing messages with a fresh\n * estimate of all current messages, system prompt and tools. Use the larger total\n * so a changed prefix cannot hide behind older usage. Usage-source metadata remains\n * unchanged even when the fresh estimate raises the total.\n */\nexport function estimateContextTokens(context: Context): ContextUsageEstimate {\n\tconst estimate = estimateMessages(context.messages);\n\n\tlet prefixTokens = context.systemPrompt ? estimateTextTokens(context.systemPrompt) : 0;\n\tif (context.tools && context.tools.length > 0) {\n\t\tprefixTokens += estimateTextTokens(safeJsonStringify(context.tools));\n\t}\n\tconst freshTokens = context.messages.reduce(\n\t\t(tokens, message) => tokens + estimateMessageTokens(message),\n\t\tprefixTokens,\n\t);\n\n\treturn {\n\t\ttokens: Math.max(estimate.tokens, freshTokens),\n\t\tusageTokens: estimate.usageTokens,\n\t\ttrailingTokens: estimate.lastUsageIndex === null ? freshTokens : estimate.trailingTokens,\n\t\tlastUsageIndex: estimate.lastUsageIndex,\n\t};\n}\n"]}
@@ -0,0 +1,104 @@
1
+ const CHARS_PER_TOKEN = 3.5;
2
+ const ESTIMATED_IMAGE_CHARS = 4800;
3
+ export function calculateContextTokens(usage) {
4
+ return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
5
+ }
6
+ function safeJsonStringify(value) {
7
+ try {
8
+ return JSON.stringify(value) ?? "undefined";
9
+ }
10
+ catch {
11
+ return "[unserializable]";
12
+ }
13
+ }
14
+ function estimateTextAndImageContentChars(content) {
15
+ if (typeof content === "string")
16
+ return content.length;
17
+ let chars = 0;
18
+ for (const block of content)
19
+ chars += block.type === "text" ? block.text.length : ESTIMATED_IMAGE_CHARS;
20
+ return chars;
21
+ }
22
+ export function estimateTextTokens(text) {
23
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
24
+ }
25
+ export function estimateMessageTokens(message) {
26
+ if (message.role === "user" || message.role === "toolResult") {
27
+ return Math.ceil(estimateTextAndImageContentChars(message.content) / CHARS_PER_TOKEN);
28
+ }
29
+ let chars = 0;
30
+ for (const block of message.content) {
31
+ if (block.type === "text") {
32
+ chars += block.text.length;
33
+ }
34
+ else if (block.type === "thinking") {
35
+ chars += block.thinking.length;
36
+ }
37
+ else if (block.type === "image") {
38
+ chars += ESTIMATED_IMAGE_CHARS;
39
+ }
40
+ else {
41
+ chars += block.name.length + safeJsonStringify(block.arguments).length;
42
+ }
43
+ }
44
+ return Math.ceil(chars / CHARS_PER_TOKEN);
45
+ }
46
+ function getLastAssistantUsageInfo(messages) {
47
+ for (let i = messages.length - 1; i >= 0; i--) {
48
+ const message = messages[i];
49
+ if (message.role !== "assistant")
50
+ continue;
51
+ const assistant = message;
52
+ if (assistant.stopReason === "aborted" || assistant.stopReason === "error")
53
+ continue;
54
+ if (calculateContextTokens(assistant.usage) > 0)
55
+ return { usage: assistant.usage, index: i };
56
+ }
57
+ return undefined;
58
+ }
59
+ function estimateMessages(messages) {
60
+ const usageInfo = getLastAssistantUsageInfo(messages);
61
+ if (usageInfo) {
62
+ const usageTokens = calculateContextTokens(usageInfo.usage);
63
+ let trailingTokens = 0;
64
+ for (let i = usageInfo.index + 1; i < messages.length; i++) {
65
+ trailingTokens += estimateMessageTokens(messages[i]);
66
+ }
67
+ return {
68
+ tokens: usageTokens + trailingTokens,
69
+ usageTokens,
70
+ trailingTokens,
71
+ lastUsageIndex: usageInfo.index,
72
+ };
73
+ }
74
+ let tokens = 0;
75
+ for (const message of messages)
76
+ tokens += estimateMessageTokens(message);
77
+ return {
78
+ tokens,
79
+ usageTokens: 0,
80
+ trailingTokens: tokens,
81
+ lastUsageIndex: null,
82
+ };
83
+ }
84
+ /**
85
+ * Compare the latest assistant usage plus estimated trailing messages with a fresh
86
+ * estimate of all current messages, system prompt and tools. Use the larger total
87
+ * so a changed prefix cannot hide behind older usage. Usage-source metadata remains
88
+ * unchanged even when the fresh estimate raises the total.
89
+ */
90
+ export function estimateContextTokens(context) {
91
+ const estimate = estimateMessages(context.messages);
92
+ let prefixTokens = context.systemPrompt ? estimateTextTokens(context.systemPrompt) : 0;
93
+ if (context.tools && context.tools.length > 0) {
94
+ prefixTokens += estimateTextTokens(safeJsonStringify(context.tools));
95
+ }
96
+ const freshTokens = context.messages.reduce((tokens, message) => tokens + estimateMessageTokens(message), prefixTokens);
97
+ return {
98
+ tokens: Math.max(estimate.tokens, freshTokens),
99
+ usageTokens: estimate.usageTokens,
100
+ trailingTokens: estimate.lastUsageIndex === null ? freshTokens : estimate.trailingTokens,
101
+ lastUsageIndex: estimate.lastUsageIndex,
102
+ };
103
+ }
104
+ //# sourceMappingURL=estimate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"estimate.js","sourceRoot":"","sources":["../../src/utils/estimate.ts"],"names":[],"mappings":"AAaA,MAAM,eAAe,GAAG,GAAG,CAAC;AAC5B,MAAM,qBAAqB,GAAG,IAAI,CAAC;AAEnC,MAAM,UAAU,sBAAsB,CAAC,KAAY,EAAU;IAC5D,OAAO,KAAK,CAAC,WAAW,IAAI,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,UAAU,CAAC;AAAA,CAC5F;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAU;IAClD,IAAI,CAAC;QACJ,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,WAAW,CAAC;IAC7C,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,kBAAkB,CAAC;IAC3B,CAAC;AAAA,CACD;AAED,SAAS,gCAAgC,CAAC,OAAmD,EAAU;IACtG,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,OAAO,CAAC,MAAM,CAAC;IAEvD,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,KAAK,IAAI,OAAO;QAAE,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,qBAAqB,CAAC;IACxG,OAAO,KAAK,CAAC;AAAA,CACb;AAED,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAU;IACxD,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,eAAe,CAAC,CAAC;AAAA,CAChD;AAED,MAAM,UAAU,qBAAqB,CAAC,OAAgB,EAAU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AkB,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvF,IAAI,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC/C,YAAY,IAAI,kBAAkB,CAAC,iBAAiB,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IACtE,CAAC;IACD,MAAM,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,MAAM,CAC1C,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,MAAM,GAAG,qBAAqB,CAAC,OAAO,CAAC,EAC5D,YAAY,CACZ,CAAC;IAEF,OAAO;QACN,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;QAC9C,WAAW,EAAE,QAAQ,CAAC,WAAW;QACjC,cAAc,EAAE,QAAQ,CAAC,cAAc,KAAK,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,cAAc;QACxF,cAAc,EAAE,QAAQ,CAAC,cAAc;KACvC,CAAC;AAAA,CACF","sourcesContent":["import type { AssistantMessage, Context, ImageContent, Message, TextContent, Usage } from \"../types.js\";\n\nexport interface ContextUsageEstimate {\n\t/** Larger of usage-backed and fresh full-context estimates. */\n\ttokens: number;\n\t/** Tokens reported by the most recent assistant usage block. */\n\tusageTokens: number;\n\t/** Estimated tokens after the most recent assistant usage block. */\n\ttrailingTokens: number;\n\t/** Index of the message that provided usage, or null when none exists. */\n\tlastUsageIndex: number | null;\n}\n\nconst CHARS_PER_TOKEN = 3.5;\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\nfunction safeJsonStringify(value: unknown): string {\n\ttry {\n\t\treturn JSON.stringify(value) ?? \"undefined\";\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\nfunction estimateTextAndImageContentChars(content: string | Array<TextContent | ImageContent>): number {\n\tif (typeof content === \"string\") return content.length;\n\n\tlet chars = 0;\n\tfor (const block of content) chars += block.type === \"text\" ? block.text.length : ESTIMATED_IMAGE_CHARS;\n\treturn chars;\n}\n\nexport function estimateTextTokens(text: string): number {\n\treturn Math.ceil(text.length / CHARS_PER_TOKEN);\n}\n\nexport function estimateMessageTokens(message: Message): number {\n\tif (message.role === \"user\" || message.role === \"toolResult\") {\n\t\treturn Math.ceil(estimateTextAndImageContentChars(message.content) / CHARS_PER_TOKEN);\n\t}\n\n\tlet chars = 0;\n\tfor (const block of message.content) {\n\t\tif (block.type === \"text\") {\n\t\t\tchars += block.text.length;\n\t\t} else if (block.type === \"thinking\") {\n\t\t\tchars += block.thinking.length;\n\t\t} else if (block.type === \"image\") {\n\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t} else {\n\t\t\tchars += block.name.length + safeJsonStringify(block.arguments).length;\n\t\t}\n\t}\n\treturn Math.ceil(chars / CHARS_PER_TOKEN);\n}\n\nfunction getLastAssistantUsageInfo(messages: readonly Message[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role !== \"assistant\") continue;\n\t\tconst assistant = message as AssistantMessage;\n\t\tif (assistant.stopReason === \"aborted\" || assistant.stopReason === \"error\") continue;\n\t\tif (calculateContextTokens(assistant.usage) > 0) return { usage: assistant.usage, index: i };\n\t}\n\treturn undefined;\n}\n\nfunction estimateMessages(messages: readonly Message[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\tif (usageInfo) {\n\t\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\t\tlet trailingTokens = 0;\n\t\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\t\ttrailingTokens += estimateMessageTokens(messages[i]);\n\t\t}\n\t\treturn {\n\t\t\ttokens: usageTokens + trailingTokens,\n\t\t\tusageTokens,\n\t\t\ttrailingTokens,\n\t\t\tlastUsageIndex: usageInfo.index,\n\t\t};\n\t}\n\n\tlet tokens = 0;\n\tfor (const message of messages) tokens += estimateMessageTokens(message);\n\treturn {\n\t\ttokens,\n\t\tusageTokens: 0,\n\t\ttrailingTokens: tokens,\n\t\tlastUsageIndex: null,\n\t};\n}\n\n/**\n * Compare the latest assistant usage plus estimated trailing messages with a fresh\n * estimate of all current messages, system prompt and tools. Use the larger total\n * so a changed prefix cannot hide behind older usage. Usage-source metadata remains\n * unchanged even when the fresh estimate raises the total.\n */\nexport function estimateContextTokens(context: Context): ContextUsageEstimate {\n\tconst estimate = estimateMessages(context.messages);\n\n\tlet prefixTokens = context.systemPrompt ? estimateTextTokens(context.systemPrompt) : 0;\n\tif (context.tools && context.tools.length > 0) {\n\t\tprefixTokens += estimateTextTokens(safeJsonStringify(context.tools));\n\t}\n\tconst freshTokens = context.messages.reduce(\n\t\t(tokens, message) => tokens + estimateMessageTokens(message),\n\t\tprefixTokens,\n\t);\n\n\treturn {\n\t\ttokens: Math.max(estimate.tokens, freshTokens),\n\t\tusageTokens: estimate.usageTokens,\n\t\ttrailingTokens: estimate.lastUsageIndex === null ? freshTokens : estimate.trailingTokens,\n\t\tlastUsageIndex: estimate.lastUsageIndex,\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"event-stream.d.ts","sourceRoot":"","sources":["../../src/utils/event-stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAGlH,qBAAa,WAAW,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAE,YAAW,aAAa,CAAC,CAAC,CAAC;IAQ5D,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,aAAa;IARtB,OAAO,CAAC,KAAK,CAAW;IACxB,OAAO,CAAC,OAAO,CAA8C;IAC7D,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,kBAAkB,CAAa;IACvC,OAAO,CAAC,kBAAkB,CAAuB;IAEjD,YACS,UAAU,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,OAAO,EACjC,aAAa,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,EAKtC;IAED,IAAI,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAenB;IAED,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,IAAI,CAUpB;IAEM,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC,CAYhD;IAED,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,CAEnB;CACD;AAED,qBAAa,2BAA4B,SAAQ,WAAW,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;IACpG,cAYC;CACD;AAED,qBAAa,0BAA2B,SAAQ,WAAW,CAAC,oBAAoB,EAAE,eAAe,CAAC;IACjG,cAYC;CACD;AAED,+EAA+E;AAC/E,wBAAgB,iCAAiC,IAAI,2BAA2B,CAE/E;AAED,8EAA8E;AAC9E,wBAAgB,gCAAgC,IAAI,0BAA0B,CAE7E","sourcesContent":["import type { AssistantImages, AssistantImagesEvent, AssistantMessage, AssistantMessageEvent } from \"../types.js\";\n\n// Generic event stream class for async iteration\nexport class EventStream<T, R = T> implements AsyncIterable<T> {\n\tprivate queue: T[] = [];\n\tprivate waiting: ((value: IteratorResult<T>) => void)[] = [];\n\tprivate done = false;\n\tprivate finalResultPromise: Promise<R>;\n\tprivate resolveFinalResult!: (result: R) => void;\n\n\tconstructor(\n\t\tprivate isComplete: (event: T) => boolean,\n\t\tprivate extractResult: (event: T) => R,\n\t) {\n\t\tthis.finalResultPromise = new Promise((resolve) => {\n\t\t\tthis.resolveFinalResult = resolve;\n\t\t});\n\t}\n\n\tpush(event: T): void {\n\t\tif (this.done) return;\n\n\t\tif (this.isComplete(event)) {\n\t\t\tthis.done = true;\n\t\t\tthis.resolveFinalResult(this.extractResult(event));\n\t\t}\n\n\t\t// Deliver to waiting consumer or queue it\n\t\tconst waiter = this.waiting.shift();\n\t\tif (waiter) {\n\t\t\twaiter({ value: event, done: false });\n\t\t} else {\n\t\t\tthis.queue.push(event);\n\t\t}\n\t}\n\n\tend(result?: R): void {\n\t\tthis.done = true;\n\t\tif (result !== undefined) {\n\t\t\tthis.resolveFinalResult(result);\n\t\t}\n\t\t// Notify all waiting consumers that we're done\n\t\twhile (this.waiting.length > 0) {\n\t\t\tconst waiter = this.waiting.shift()!;\n\t\t\twaiter({ value: undefined as any, done: true });\n\t\t}\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\twhile (true) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tyield this.queue.shift()!;\n\t\t\t} else if (this.done) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tconst result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.push(resolve));\n\t\t\t\tif (result.done) return;\n\t\t\t\tyield result.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tresult(): Promise<R> {\n\t\treturn this.finalResultPromise;\n\t}\n}\n\nexport class AssistantMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.message;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\nexport class AssistantImagesEventStream extends EventStream<AssistantImagesEvent, AssistantImages> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.images;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream(): AssistantMessageEventStream {\n\treturn new AssistantMessageEventStream();\n}\n\n/** Factory function for AssistantImagesEventStream (for use in extensions) */\nexport function createAssistantImagesEventStream(): AssistantImagesEventStream {\n\treturn new AssistantImagesEventStream();\n}\n"]}
1
+ {"version":3,"file":"event-stream.d.ts","sourceRoot":"","sources":["../../src/utils/event-stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAwBlH,qBAAa,WAAW,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAE,YAAW,aAAa,CAAC,CAAC,CAAC;IAQ5D,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,aAAa;IARtB,OAAO,CAAC,KAAK,CAAsB;IACnC,OAAO,CAAC,OAAO,CAAuD;IACtE,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,kBAAkB,CAAa;IACvC,OAAO,CAAC,kBAAkB,CAAuB;IAEjD,YACS,UAAU,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,OAAO,EACjC,aAAa,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,EAKtC;IAED,IAAI,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAenB;IAED,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,IAAI,CAUpB;IAEM,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC,CAYhD;IAED,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,CAEnB;CACD;AAED,qBAAa,2BAA4B,SAAQ,WAAW,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;IACpG,cAYC;CACD;AAED,qBAAa,0BAA2B,SAAQ,WAAW,CAAC,oBAAoB,EAAE,eAAe,CAAC;IACjG,cAYC;CACD;AAED,+EAA+E;AAC/E,wBAAgB,iCAAiC,IAAI,2BAA2B,CAE/E;AAED,8EAA8E;AAC9E,wBAAgB,gCAAgC,IAAI,0BAA0B,CAE7E","sourcesContent":["import type { AssistantImages, AssistantImagesEvent, AssistantMessage, AssistantMessageEvent } from \"../types.js\";\n\n// Reverse each batch once so dequeue is amortized O(1), without retaining consumed entries.\nclass FifoQueue<T> {\n\tprivate incoming: T[] = [];\n\tprivate outgoing: T[] = [];\n\n\tget length(): number {\n\t\treturn this.incoming.length + this.outgoing.length;\n\t}\n\n\tenqueue(value: T): void {\n\t\tthis.incoming.push(value);\n\t}\n\n\tdequeue(): T | undefined {\n\t\tif (this.outgoing.length === 0) {\n\t\t\twhile (this.incoming.length > 0) this.outgoing.push(this.incoming.pop()!);\n\t\t}\n\t\treturn this.outgoing.pop();\n\t}\n}\n\n// Generic event stream class for async iteration\nexport class EventStream<T, R = T> implements AsyncIterable<T> {\n\tprivate queue = new FifoQueue<T>();\n\tprivate waiting = new FifoQueue<(value: IteratorResult<T>) => void>();\n\tprivate done = false;\n\tprivate finalResultPromise: Promise<R>;\n\tprivate resolveFinalResult!: (result: R) => void;\n\n\tconstructor(\n\t\tprivate isComplete: (event: T) => boolean,\n\t\tprivate extractResult: (event: T) => R,\n\t) {\n\t\tthis.finalResultPromise = new Promise((resolve) => {\n\t\t\tthis.resolveFinalResult = resolve;\n\t\t});\n\t}\n\n\tpush(event: T): void {\n\t\tif (this.done) return;\n\n\t\tif (this.isComplete(event)) {\n\t\t\tthis.done = true;\n\t\t\tthis.resolveFinalResult(this.extractResult(event));\n\t\t}\n\n\t\t// Deliver to waiting consumer or queue it\n\t\tconst waiter = this.waiting.dequeue();\n\t\tif (waiter) {\n\t\t\twaiter({ value: event, done: false });\n\t\t} else {\n\t\t\tthis.queue.enqueue(event);\n\t\t}\n\t}\n\n\tend(result?: R): void {\n\t\tthis.done = true;\n\t\tif (result !== undefined) {\n\t\t\tthis.resolveFinalResult(result);\n\t\t}\n\t\t// Notify all waiting consumers that we're done\n\t\twhile (this.waiting.length > 0) {\n\t\t\tconst waiter = this.waiting.dequeue()!;\n\t\t\twaiter({ value: undefined as any, done: true });\n\t\t}\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\twhile (true) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tyield this.queue.dequeue()!;\n\t\t\t} else if (this.done) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tconst result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.enqueue(resolve));\n\t\t\t\tif (result.done) return;\n\t\t\t\tyield result.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tresult(): Promise<R> {\n\t\treturn this.finalResultPromise;\n\t}\n}\n\nexport class AssistantMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.message;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\nexport class AssistantImagesEventStream extends EventStream<AssistantImagesEvent, AssistantImages> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.images;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream(): AssistantMessageEventStream {\n\treturn new AssistantMessageEventStream();\n}\n\n/** Factory function for AssistantImagesEventStream (for use in extensions) */\nexport function createAssistantImagesEventStream(): AssistantImagesEventStream {\n\treturn new AssistantImagesEventStream();\n}\n"]}
@@ -1,9 +1,27 @@
1
+ // Reverse each batch once so dequeue is amortized O(1), without retaining consumed entries.
2
+ class FifoQueue {
3
+ incoming = [];
4
+ outgoing = [];
5
+ get length() {
6
+ return this.incoming.length + this.outgoing.length;
7
+ }
8
+ enqueue(value) {
9
+ this.incoming.push(value);
10
+ }
11
+ dequeue() {
12
+ if (this.outgoing.length === 0) {
13
+ while (this.incoming.length > 0)
14
+ this.outgoing.push(this.incoming.pop());
15
+ }
16
+ return this.outgoing.pop();
17
+ }
18
+ }
1
19
  // Generic event stream class for async iteration
2
20
  export class EventStream {
3
21
  isComplete;
4
22
  extractResult;
5
- queue = [];
6
- waiting = [];
23
+ queue = new FifoQueue();
24
+ waiting = new FifoQueue();
7
25
  done = false;
8
26
  finalResultPromise;
9
27
  resolveFinalResult;
@@ -22,12 +40,12 @@ export class EventStream {
22
40
  this.resolveFinalResult(this.extractResult(event));
23
41
  }
24
42
  // Deliver to waiting consumer or queue it
25
- const waiter = this.waiting.shift();
43
+ const waiter = this.waiting.dequeue();
26
44
  if (waiter) {
27
45
  waiter({ value: event, done: false });
28
46
  }
29
47
  else {
30
- this.queue.push(event);
48
+ this.queue.enqueue(event);
31
49
  }
32
50
  }
33
51
  end(result) {
@@ -37,20 +55,20 @@ export class EventStream {
37
55
  }
38
56
  // Notify all waiting consumers that we're done
39
57
  while (this.waiting.length > 0) {
40
- const waiter = this.waiting.shift();
58
+ const waiter = this.waiting.dequeue();
41
59
  waiter({ value: undefined, done: true });
42
60
  }
43
61
  }
44
62
  async *[Symbol.asyncIterator]() {
45
63
  while (true) {
46
64
  if (this.queue.length > 0) {
47
- yield this.queue.shift();
65
+ yield this.queue.dequeue();
48
66
  }
49
67
  else if (this.done) {
50
68
  return;
51
69
  }
52
70
  else {
53
- const result = await new Promise((resolve) => this.waiting.push(resolve));
71
+ const result = await new Promise((resolve) => this.waiting.enqueue(resolve));
54
72
  if (result.done)
55
73
  return;
56
74
  yield result.value;
@@ -1 +1 @@
1
- {"version":3,"file":"event-stream.js","sourceRoot":"","sources":["../../src/utils/event-stream.ts"],"names":[],"mappings":"AAEA,iDAAiD;AACjD,MAAM,OAAO,WAAW;IAQd,UAAU;IACV,aAAa;IARd,KAAK,GAAQ,EAAE,CAAC;IAChB,OAAO,GAA2C,EAAE,CAAC;IACrD,IAAI,GAAG,KAAK,CAAC;IACb,kBAAkB,CAAa;IAC/B,kBAAkB,CAAuB;IAEjD,YACS,UAAiC,EACjC,aAA8B,EACrC;0BAFO,UAAU;6BACV,aAAa;QAErB,IAAI,CAAC,kBAAkB,GAAG,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC;YAClD,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC;QAAA,CAClC,CAAC,CAAC;IAAA,CACH;IAED,IAAI,CAAC,KAAQ,EAAQ;QACpB,IAAI,IAAI,CAAC,IAAI;YAAE,OAAO;QAEtB,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;YAC5B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;YACjB,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC;QACpD,CAAC;QAED,0CAA0C;QAC1C,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACpC,IAAI,MAAM,EAAE,CAAC;YACZ,MAAM,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QACvC,CAAC;aAAM,CAAC;YACP,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,CAAC;IAAA,CACD;IAED,GAAG,CAAC,MAAU,EAAQ;QAC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CAAC;YACV,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBAC3B,OAAO,KAAK,CAAC,OAAO,CAAC;YACtB,CAAC;iBAAM,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;gBACnC,OAAO,KAAK,CAAC,KAAK,CAAC;YACpB,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAAA,CAC1D,CACD,CAAC;IAAA,CACF;CACD;AAED,MAAM,OAAO,0BAA2B,SAAQ,WAAkD;IACjG,cAAc;QACb,KAAK,CACJ,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAC1D,CAAC,KAAK,EAAE,EAAE,CAAC;YACV,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBAC3B,OAAO,KAAK,CAAC,MAAM,CAAC;YACrB,CAAC;iBAAM,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;gBACnC,OAAO,KAAK,CAAC,KAAK,CAAC;YACpB,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAAA,CAC1D,CACD,CAAC;IAAA,CACF;CACD;AAED,+EAA+E;AAC/E,MAAM,UAAU,iCAAiC,GAAgC;IAChF,OAAO,IAAI,2BAA2B,EAAE,CAAC;AAAA,CACzC;AAED,8EAA8E;AAC9E,MAAM,UAAU,gCAAgC,GAA+B;IAC9E,OAAO,IAAI,0BAA0B,EAAE,CAAC;AAAA,CACxC","sourcesContent":["import type { AssistantImages, AssistantImagesEvent, AssistantMessage, AssistantMessageEvent } from \"../types.js\";\n\n// Generic event stream class for async iteration\nexport class EventStream<T, R = T> implements AsyncIterable<T> {\n\tprivate queue: T[] = [];\n\tprivate waiting: ((value: IteratorResult<T>) => void)[] = [];\n\tprivate done = false;\n\tprivate finalResultPromise: Promise<R>;\n\tprivate resolveFinalResult!: (result: R) => void;\n\n\tconstructor(\n\t\tprivate isComplete: (event: T) => boolean,\n\t\tprivate extractResult: (event: T) => R,\n\t) {\n\t\tthis.finalResultPromise = new Promise((resolve) => {\n\t\t\tthis.resolveFinalResult = resolve;\n\t\t});\n\t}\n\n\tpush(event: T): void {\n\t\tif (this.done) return;\n\n\t\tif (this.isComplete(event)) {\n\t\t\tthis.done = true;\n\t\t\tthis.resolveFinalResult(this.extractResult(event));\n\t\t}\n\n\t\t// Deliver to waiting consumer or queue it\n\t\tconst waiter = this.waiting.shift();\n\t\tif (waiter) {\n\t\t\twaiter({ value: event, done: false });\n\t\t} else {\n\t\t\tthis.queue.push(event);\n\t\t}\n\t}\n\n\tend(result?: R): void {\n\t\tthis.done = true;\n\t\tif (result !== undefined) {\n\t\t\tthis.resolveFinalResult(result);\n\t\t}\n\t\t// Notify all waiting consumers that we're done\n\t\twhile (this.waiting.length > 0) {\n\t\t\tconst waiter = this.waiting.shift()!;\n\t\t\twaiter({ value: undefined as any, done: true });\n\t\t}\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\twhile (true) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tyield this.queue.shift()!;\n\t\t\t} else if (this.done) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tconst result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.push(resolve));\n\t\t\t\tif (result.done) return;\n\t\t\t\tyield result.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tresult(): Promise<R> {\n\t\treturn this.finalResultPromise;\n\t}\n}\n\nexport class AssistantMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.message;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\nexport class AssistantImagesEventStream extends EventStream<AssistantImagesEvent, AssistantImages> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.images;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream(): AssistantMessageEventStream {\n\treturn new AssistantMessageEventStream();\n}\n\n/** Factory function for AssistantImagesEventStream (for use in extensions) */\nexport function createAssistantImagesEventStream(): AssistantImagesEventStream {\n\treturn new AssistantImagesEventStream();\n}\n"]}
1
+ {"version":3,"file":"event-stream.js","sourceRoot":"","sources":["../../src/utils/event-stream.ts"],"names":[],"mappings":"AAEA,4FAA4F;AAC5F,MAAM,SAAS;IACN,QAAQ,GAAQ,EAAE,CAAC;IACnB,QAAQ,GAAQ,EAAE,CAAC;IAE3B,IAAI,MAAM,GAAW;QACpB,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;IAAA,CACnD;IAED,OAAO,CAAC,KAAQ,EAAQ;QACvB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAAA,CAC1B;IAED,OAAO,GAAkB;QACxB,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAChC,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC;gBAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAG,CAAC,CAAC;QAC3E,CAAC;QACD,O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AI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;gBACnC,OAAO,KAAK,CAAC,KAAK,CAAC;YACpB,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAAA,CAC1D,CACD,CAAC;IAAA,CACF;CACD;AAED,MAAM,OAAO,0BAA2B,SAAQ,WAAkD;IACjG,cAAc;QACb,KAAK,CACJ,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAC1D,CAAC,KAAK,EAAE,EAAE,CAAC;YACV,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBAC3B,OAAO,KAAK,CAAC,MAAM,CAAC;YACrB,CAAC;iBAAM,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;gBACnC,OAAO,KAAK,CAAC,KAAK,CAAC;YACpB,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAAA,CAC1D,CACD,CAAC;IAAA,CACF;CACD;AAED,+EAA+E;AAC/E,MAAM,UAAU,iCAAiC,GAAgC;IAChF,OAAO,IAAI,2BAA2B,EAAE,CAAC;AAAA,CACzC;AAED,8EAA8E;AAC9E,MAAM,UAAU,gCAAgC,GAA+B;IAC9E,OAAO,IAAI,0BAA0B,EAAE,CAAC;AAAA,CACxC","sourcesContent":["import type { AssistantImages, AssistantImagesEvent, AssistantMessage, AssistantMessageEvent } from \"../types.js\";\n\n// Reverse each batch once so dequeue is amortized O(1), without retaining consumed entries.\nclass FifoQueue<T> {\n\tprivate incoming: T[] = [];\n\tprivate outgoing: T[] = [];\n\n\tget length(): number {\n\t\treturn this.incoming.length + this.outgoing.length;\n\t}\n\n\tenqueue(value: T): void {\n\t\tthis.incoming.push(value);\n\t}\n\n\tdequeue(): T | undefined {\n\t\tif (this.outgoing.length === 0) {\n\t\t\twhile (this.incoming.length > 0) this.outgoing.push(this.incoming.pop()!);\n\t\t}\n\t\treturn this.outgoing.pop();\n\t}\n}\n\n// Generic event stream class for async iteration\nexport class EventStream<T, R = T> implements AsyncIterable<T> {\n\tprivate queue = new FifoQueue<T>();\n\tprivate waiting = new FifoQueue<(value: IteratorResult<T>) => void>();\n\tprivate done = false;\n\tprivate finalResultPromise: Promise<R>;\n\tprivate resolveFinalResult!: (result: R) => void;\n\n\tconstructor(\n\t\tprivate isComplete: (event: T) => boolean,\n\t\tprivate extractResult: (event: T) => R,\n\t) {\n\t\tthis.finalResultPromise = new Promise((resolve) => {\n\t\t\tthis.resolveFinalResult = resolve;\n\t\t});\n\t}\n\n\tpush(event: T): void {\n\t\tif (this.done) return;\n\n\t\tif (this.isComplete(event)) {\n\t\t\tthis.done = true;\n\t\t\tthis.resolveFinalResult(this.extractResult(event));\n\t\t}\n\n\t\t// Deliver to waiting consumer or queue it\n\t\tconst waiter = this.waiting.dequeue();\n\t\tif (waiter) {\n\t\t\twaiter({ value: event, done: false });\n\t\t} else {\n\t\t\tthis.queue.enqueue(event);\n\t\t}\n\t}\n\n\tend(result?: R): void {\n\t\tthis.done = true;\n\t\tif (result !== undefined) {\n\t\t\tthis.resolveFinalResult(result);\n\t\t}\n\t\t// Notify all waiting consumers that we're done\n\t\twhile (this.waiting.length > 0) {\n\t\t\tconst waiter = this.waiting.dequeue()!;\n\t\t\twaiter({ value: undefined as any, done: true });\n\t\t}\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\twhile (true) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tyield this.queue.dequeue()!;\n\t\t\t} else if (this.done) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tconst result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.enqueue(resolve));\n\t\t\t\tif (result.done) return;\n\t\t\t\tyield result.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tresult(): Promise<R> {\n\t\treturn this.finalResultPromise;\n\t}\n}\n\nexport class AssistantMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.message;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\nexport class AssistantImagesEventStream extends EventStream<AssistantImagesEvent, AssistantImages> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.images;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream(): AssistantMessageEventStream {\n\treturn new AssistantMessageEventStream();\n}\n\n/** Factory function for AssistantImagesEventStream (for use in extensions) */\nexport function createAssistantImagesEventStream(): AssistantImagesEventStream {\n\treturn new AssistantImagesEventStream();\n}\n"]}