@aituber-onair/chat 0.49.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.ja.md +42 -15
  2. package/README.md +42 -15
  3. package/dist/cjs/backend.d.ts +20 -0
  4. package/dist/cjs/backend.d.ts.map +1 -0
  5. package/dist/cjs/backend.js +115 -0
  6. package/dist/cjs/backend.js.map +1 -0
  7. package/dist/cjs/constants/deepseek.d.ts +6 -0
  8. package/dist/cjs/constants/deepseek.d.ts.map +1 -1
  9. package/dist/cjs/constants/deepseek.js +47 -0
  10. package/dist/cjs/constants/deepseek.js.map +1 -1
  11. package/dist/cjs/constants/openrouter.d.ts +6 -0
  12. package/dist/cjs/constants/openrouter.d.ts.map +1 -1
  13. package/dist/cjs/constants/openrouter.js +66 -2
  14. package/dist/cjs/constants/openrouter.js.map +1 -1
  15. package/dist/cjs/constants/xai.d.ts +6 -1
  16. package/dist/cjs/constants/xai.d.ts.map +1 -1
  17. package/dist/cjs/constants/xai.js +29 -7
  18. package/dist/cjs/constants/xai.js.map +1 -1
  19. package/dist/cjs/index.d.ts +1 -0
  20. package/dist/cjs/index.d.ts.map +1 -1
  21. package/dist/cjs/index.js +1 -0
  22. package/dist/cjs/index.js.map +1 -1
  23. package/dist/cjs/services/ChatServiceFactory.d.ts.map +1 -1
  24. package/dist/cjs/services/ChatServiceFactory.js +17 -19
  25. package/dist/cjs/services/ChatServiceFactory.js.map +1 -1
  26. package/dist/cjs/services/providers/ChatServiceProvider.d.ts +7 -2
  27. package/dist/cjs/services/providers/ChatServiceProvider.d.ts.map +1 -1
  28. package/dist/cjs/services/providers/deepseek/DeepSeekChatService.d.ts +2 -1
  29. package/dist/cjs/services/providers/deepseek/DeepSeekChatService.d.ts.map +1 -1
  30. package/dist/cjs/services/providers/deepseek/DeepSeekChatService.js +9 -2
  31. package/dist/cjs/services/providers/deepseek/DeepSeekChatService.js.map +1 -1
  32. package/dist/cjs/services/providers/deepseek/DeepSeekChatServiceProvider.d.ts.map +1 -1
  33. package/dist/cjs/services/providers/deepseek/DeepSeekChatServiceProvider.js +1 -1
  34. package/dist/cjs/services/providers/deepseek/DeepSeekChatServiceProvider.js.map +1 -1
  35. package/dist/cjs/services/providers/gemini/GeminiChatService.d.ts.map +1 -1
  36. package/dist/cjs/services/providers/gemini/GeminiChatService.js +3 -0
  37. package/dist/cjs/services/providers/gemini/GeminiChatService.js.map +1 -1
  38. package/dist/cjs/services/providers/gemini/geminiMessageConverter.d.ts +5 -0
  39. package/dist/cjs/services/providers/gemini/geminiMessageConverter.d.ts.map +1 -1
  40. package/dist/cjs/services/providers/gemini/geminiMessageConverter.js +16 -0
  41. package/dist/cjs/services/providers/gemini/geminiMessageConverter.js.map +1 -1
  42. package/dist/cjs/services/providers/geminiNano/GeminiNanoChatService.d.ts +1 -1
  43. package/dist/cjs/services/providers/geminiNano/GeminiNanoChatService.js +2 -2
  44. package/dist/cjs/services/providers/geminiNano/GeminiNanoChatService.js.map +1 -1
  45. package/dist/cjs/services/providers/openai/openaiRequestBuilder.d.ts.map +1 -1
  46. package/dist/cjs/services/providers/openai/openaiRequestBuilder.js +35 -5
  47. package/dist/cjs/services/providers/openai/openaiRequestBuilder.js.map +1 -1
  48. package/dist/cjs/services/providers/openai/responsesParser.d.ts.map +1 -1
  49. package/dist/cjs/services/providers/openai/responsesParser.js +71 -6
  50. package/dist/cjs/services/providers/openai/responsesParser.js.map +1 -1
  51. package/dist/cjs/services/providers/openrouter/OpenRouterChatService.d.ts +2 -1
  52. package/dist/cjs/services/providers/openrouter/OpenRouterChatService.d.ts.map +1 -1
  53. package/dist/cjs/services/providers/openrouter/OpenRouterChatService.js +7 -8
  54. package/dist/cjs/services/providers/openrouter/OpenRouterChatService.js.map +1 -1
  55. package/dist/cjs/services/providers/openrouter/OpenRouterChatServiceProvider.d.ts.map +1 -1
  56. package/dist/cjs/services/providers/openrouter/OpenRouterChatServiceProvider.js +3 -0
  57. package/dist/cjs/services/providers/openrouter/OpenRouterChatServiceProvider.js.map +1 -1
  58. package/dist/cjs/services/providers/xai/XAIChatServiceProvider.d.ts.map +1 -1
  59. package/dist/cjs/services/providers/xai/XAIChatServiceProvider.js +1 -0
  60. package/dist/cjs/services/providers/xai/XAIChatServiceProvider.js.map +1 -1
  61. package/dist/esm/backend.d.ts +20 -0
  62. package/dist/esm/backend.d.ts.map +1 -0
  63. package/dist/esm/backend.js +111 -0
  64. package/dist/esm/backend.js.map +1 -0
  65. package/dist/esm/constants/deepseek.d.ts +6 -0
  66. package/dist/esm/constants/deepseek.d.ts.map +1 -1
  67. package/dist/esm/constants/deepseek.js +43 -0
  68. package/dist/esm/constants/deepseek.js.map +1 -1
  69. package/dist/esm/constants/openrouter.d.ts +6 -0
  70. package/dist/esm/constants/openrouter.d.ts.map +1 -1
  71. package/dist/esm/constants/openrouter.js +61 -0
  72. package/dist/esm/constants/openrouter.js.map +1 -1
  73. package/dist/esm/constants/xai.d.ts +6 -1
  74. package/dist/esm/constants/xai.d.ts.map +1 -1
  75. package/dist/esm/constants/xai.js +27 -6
  76. package/dist/esm/constants/xai.js.map +1 -1
  77. package/dist/esm/index.d.ts +1 -0
  78. package/dist/esm/index.d.ts.map +1 -1
  79. package/dist/esm/index.js +1 -0
  80. package/dist/esm/index.js.map +1 -1
  81. package/dist/esm/services/ChatServiceFactory.d.ts.map +1 -1
  82. package/dist/esm/services/ChatServiceFactory.js +17 -19
  83. package/dist/esm/services/ChatServiceFactory.js.map +1 -1
  84. package/dist/esm/services/providers/ChatServiceProvider.d.ts +7 -2
  85. package/dist/esm/services/providers/ChatServiceProvider.d.ts.map +1 -1
  86. package/dist/esm/services/providers/deepseek/DeepSeekChatService.d.ts +2 -1
  87. package/dist/esm/services/providers/deepseek/DeepSeekChatService.d.ts.map +1 -1
  88. package/dist/esm/services/providers/deepseek/DeepSeekChatService.js +10 -3
  89. package/dist/esm/services/providers/deepseek/DeepSeekChatService.js.map +1 -1
  90. package/dist/esm/services/providers/deepseek/DeepSeekChatServiceProvider.d.ts.map +1 -1
  91. package/dist/esm/services/providers/deepseek/DeepSeekChatServiceProvider.js +1 -1
  92. package/dist/esm/services/providers/deepseek/DeepSeekChatServiceProvider.js.map +1 -1
  93. package/dist/esm/services/providers/gemini/GeminiChatService.d.ts.map +1 -1
  94. package/dist/esm/services/providers/gemini/GeminiChatService.js +4 -1
  95. package/dist/esm/services/providers/gemini/GeminiChatService.js.map +1 -1
  96. package/dist/esm/services/providers/gemini/geminiMessageConverter.d.ts +5 -0
  97. package/dist/esm/services/providers/gemini/geminiMessageConverter.d.ts.map +1 -1
  98. package/dist/esm/services/providers/gemini/geminiMessageConverter.js +15 -0
  99. package/dist/esm/services/providers/gemini/geminiMessageConverter.js.map +1 -1
  100. package/dist/esm/services/providers/geminiNano/GeminiNanoChatService.d.ts +1 -1
  101. package/dist/esm/services/providers/geminiNano/GeminiNanoChatService.js +2 -2
  102. package/dist/esm/services/providers/geminiNano/GeminiNanoChatService.js.map +1 -1
  103. package/dist/esm/services/providers/openai/openaiRequestBuilder.d.ts.map +1 -1
  104. package/dist/esm/services/providers/openai/openaiRequestBuilder.js +35 -5
  105. package/dist/esm/services/providers/openai/openaiRequestBuilder.js.map +1 -1
  106. package/dist/esm/services/providers/openai/responsesParser.d.ts.map +1 -1
  107. package/dist/esm/services/providers/openai/responsesParser.js +71 -6
  108. package/dist/esm/services/providers/openai/responsesParser.js.map +1 -1
  109. package/dist/esm/services/providers/openrouter/OpenRouterChatService.d.ts +2 -1
  110. package/dist/esm/services/providers/openrouter/OpenRouterChatService.d.ts.map +1 -1
  111. package/dist/esm/services/providers/openrouter/OpenRouterChatService.js +8 -9
  112. package/dist/esm/services/providers/openrouter/OpenRouterChatService.js.map +1 -1
  113. package/dist/esm/services/providers/openrouter/OpenRouterChatServiceProvider.d.ts.map +1 -1
  114. package/dist/esm/services/providers/openrouter/OpenRouterChatServiceProvider.js +4 -1
  115. package/dist/esm/services/providers/openrouter/OpenRouterChatServiceProvider.js.map +1 -1
  116. package/dist/esm/services/providers/xai/XAIChatServiceProvider.d.ts.map +1 -1
  117. package/dist/esm/services/providers/xai/XAIChatServiceProvider.js +2 -1
  118. package/dist/esm/services/providers/xai/XAIChatServiceProvider.js.map +1 -1
  119. package/dist/umd/aituber-onair-chat.js +392 -44
  120. package/dist/umd/aituber-onair-chat.min.js +9 -9
  121. package/package.json +6 -1
@@ -1,4 +1,4 @@
1
- "use strict";var AITuberOnAirChat=(()=>{var ko=Object.defineProperty;var Ui=Object.getOwnPropertyDescriptor;var Ki=Object.getOwnPropertyNames;var Hi=Object.prototype.hasOwnProperty;var Bi=(n,e)=>{for(var t in e)ko(n,t,{get:e[t],enumerable:!0})},Wi=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ki(e))!Hi.call(n,i)&&i!==t&&ko(n,i,{get:()=>e[i],enumerable:!(o=Ui(e,i))||o.enumerable});return n};var $i=n=>Wi(ko({},"__esModule",{value:!0}),n);var $r={};Bi($r,{CHAT_RESPONSE_LENGTH:()=>S,CLAUDE_VISION_SUPPORTED_MODELS:()=>ct,ChatServiceFactory:()=>Je,ChatServiceHttpClient:()=>E,ClaudeChatService:()=>Pe,ClaudeChatServiceProvider:()=>ye,DEEPSEEK_API_BASE_URL:()=>ti,DEEPSEEK_DEPRECATED_MODELS:()=>sr,DEEPSEEK_SUPPORTED_MODELS:()=>En,DEFAULT_MAX_TOKENS:()=>An,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>lr,DEFAULT_VISION_PROMPT:()=>ar,DeepSeekChatService:()=>Ie,DeepSeekChatServiceProvider:()=>xe,EMOTION_TAG_CLEANUP_REGEX:()=>Nn,EMOTION_TAG_REGEX:()=>di,ENDPOINT_CLAUDE_API:()=>Yo,ENDPOINT_DEEPSEEK_CHAT_COMPLETIONS_API:()=>Mt,ENDPOINT_GEMINI_API:()=>Bo,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>Ee,ENDPOINT_MISTRAL_CHAT_COMPLETIONS_API:()=>Ot,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>q,ENDPOINT_OPENAI_RESPONSES_API:()=>D,ENDPOINT_OPENROUTER_API:()=>ut,ENDPOINT_PLAMO_CHAT_COMPLETIONS_API:()=>Ct,ENDPOINT_SAKANA_CHAT_COMPLETIONS_API:()=>St,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>mt,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>dt,EmotionParser:()=>Le,GEMINI_DEPRECATED_MODELS:()=>zn,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>bn,GEMINI_RECOMMENDED_MODELS:()=>bt,GEMINI_VISION_SUPPORTED_MODELS:()=>tt,GPT5_PRESETS:()=>Dn,GPT_5_MODELS:()=>Fn,GeminiChatService:()=>Re,GeminiChatServiceProvider:()=>Ae,GeminiNanoChatService:()=>De,GeminiNanoChatServiceProvider:()=>be,HttpError:()=>j,KIMI_THINKING_REQUIRED_MODELS:()=>ei,KIMI_VISION_SUPPORTED_MODELS:()=>Qn,KimiChatService:()=>Ne,KimiChatServiceProvider:()=>we,MAX_TOKENS_BY_LENGTH:()=>Do,MISTRAL_API_BASE_URL:()=>ri,MISTRAL_REASONING_EFFORT_SUPPORTED_MODELS:()=>si,MISTRAL_SUPPORTED_MODELS:()=>Pn,MISTRAL_VISION_SUPPORTED_MODELS:()=>ai,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>tn,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>po,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>co,MODEL_ANTHROPIC_CLAUDE_HAIKU_LATEST:()=>ro,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>ao,MODEL_ANTHROPIC_CLAUDE_OPUS_5:()=>so,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>lo,MODEL_ANTHROPIC_CLAUDE_SONNET_LATEST:()=>io,MODEL_CLAUDE_3_5_HAIKU:()=>Zi,MODEL_CLAUDE_3_5_SONNET:()=>Yi,MODEL_CLAUDE_3_7_SONNET:()=>Qi,MODEL_CLAUDE_3_HAIKU:()=>Gt,MODEL_CLAUDE_4_5_HAIKU:()=>b,MODEL_CLAUDE_4_5_OPUS:()=>nt,MODEL_CLAUDE_4_5_SONNET:()=>Ft,MODEL_CLAUDE_4_6_OPUS:()=>rt,MODEL_CLAUDE_4_6_SONNET:()=>it,MODEL_CLAUDE_4_7_OPUS:()=>st,MODEL_CLAUDE_4_8_OPUS:()=>at,MODEL_CLAUDE_4_OPUS:()=>Vt,MODEL_CLAUDE_4_SONNET:()=>kt,MODEL_CLAUDE_5_OPUS:()=>pt,MODEL_CLAUDE_5_SONNET:()=>lt,MODEL_DEEPSEEK_CHAT:()=>ni,MODEL_DEEPSEEK_REASONER:()=>ii,MODEL_DEEPSEEK_V4_FLASH:()=>Se,MODEL_DEEPSEEK_V4_PRO:()=>oi,MODEL_FUGU:()=>Ce,MODEL_FUGU_ULTRA:()=>pi,MODEL_FUGU_ULTRA_20260615:()=>ci,MODEL_GEMINI_2_5_FLASH:()=>Bn,MODEL_GEMINI_2_5_FLASH_LITE:()=>Wn,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>$n,MODEL_GEMINI_2_5_PRO:()=>Hn,MODEL_GEMINI_3_1_FLASH_LITE:()=>$,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>qo,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>jo,MODEL_GEMINI_3_5_FLASH:()=>$o,MODEL_GEMINI_3_5_FLASH_LITE:()=>zo,MODEL_GEMINI_3_6_FLASH:()=>Wo,MODEL_GEMINI_3_FLASH_PREVIEW:()=>Jo,MODEL_GEMINI_3_PRO_PREVIEW:()=>Xo,MODEL_GEMINI_NANO:()=>re,MODEL_GEMMA_4_26B_A4B_IT:()=>Kn,MODEL_GEMMA_4_31B_IT:()=>Un,MODEL_GLM_4_6:()=>gn,MODEL_GLM_4_6V:()=>Co,MODEL_GLM_4_6V_FLASH:()=>ne,MODEL_GLM_4_6V_FLASHX:()=>To,MODEL_GLM_4_7:()=>hn,MODEL_GLM_4_7_FLASH:()=>mn,MODEL_GLM_4_7_FLASHX:()=>dn,MODEL_GLM_5:()=>cn,MODEL_GLM_5V_TURBO:()=>So,MODEL_GLM_5_1:()=>pn,MODEL_GLM_5_2:()=>de,MODEL_GLM_5_TURBO:()=>un,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>fo,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>Eo,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>_o,MODEL_GOOGLE_GEMINI_3_5_FLASH_LITE:()=>go,MODEL_GOOGLE_GEMINI_3_6_FLASH:()=>mo,MODEL_GOOGLE_GEMINI_FLASH_LATEST:()=>ho,MODEL_GOOGLE_GEMINI_PRO_LATEST:()=>uo,MODEL_GPT_4O:()=>Rt,MODEL_GPT_4O_MINI:()=>ee,MODEL_GPT_4_1:()=>yt,MODEL_GPT_4_1_MINI:()=>It,MODEL_GPT_4_1_NANO:()=>xt,MODEL_GPT_5:()=>le,MODEL_GPT_5_1:()=>pe,MODEL_GPT_5_4:()=>J,MODEL_GPT_5_4_MINI:()=>Y,MODEL_GPT_5_4_NANO:()=>Q,MODEL_GPT_5_4_PRO:()=>W,MODEL_GPT_5_5:()=>Z,MODEL_GPT_5_6:()=>U,MODEL_GPT_5_6_LUNA:()=>B,MODEL_GPT_5_6_SOL:()=>K,MODEL_GPT_5_6_TERRA:()=>H,MODEL_GPT_5_MINI:()=>ae,MODEL_GPT_5_NANO:()=>X,MODEL_GPT_OSS_20B_FREE:()=>w,MODEL_GROK_4_1_FAST_NON_REASONING:()=>G,MODEL_GROK_4_1_FAST_REASONING:()=>yo,MODEL_GROK_4_20_NON_REASONING:()=>Po,MODEL_GROK_4_20_REASONING:()=>Lo,MODEL_GROK_4_3:()=>_e,MODEL_GROK_4_5:()=>ge,MODEL_KIMI_K2_5:()=>Ro,MODEL_KIMI_K2_6:()=>k,MODEL_KIMI_K2_7_CODE:()=>_t,MODEL_KIMI_K2_7_CODE_HIGHSPEED:()=>ft,MODEL_KIMI_K3:()=>Me,MODEL_KWAIPILOT_KAT_CODER_AIR_V2_5:()=>rn,MODEL_KWAIPILOT_KAT_CODER_PRO_V2_5:()=>sn,MODEL_MINISTRAL_14B_2512:()=>vn,MODEL_MINISTRAL_3B_2512:()=>Mn,MODEL_MINISTRAL_8B_2512:()=>On,MODEL_MISTRAL_LARGE_2512:()=>Ln,MODEL_MISTRAL_LARGE_LATEST:()=>Tn,MODEL_MISTRAL_MEDIUM_2508:()=>Cn,MODEL_MISTRAL_MEDIUM_3_5:()=>Ao,MODEL_MISTRAL_SMALL_2603:()=>Sn,MODEL_MISTRAL_SMALL_LATEST:()=>V,MODEL_MOONSHOTAI_KIMI_K2_5:()=>Ht,MODEL_MOONSHOTAI_KIMI_K2_7_CODE:()=>Kt,MODEL_MOONSHOTAI_KIMI_K3:()=>Ut,MODEL_MOONSHOTAI_KIMI_LATEST:()=>Bt,MODEL_O1:()=>Uo,MODEL_O1_MINI:()=>Fo,MODEL_O3_MINI:()=>Vo,MODEL_OPENAI_GPT_4O:()=>to,MODEL_OPENAI_GPT_4_1_MINI:()=>oo,MODEL_OPENAI_GPT_4_1_NANO:()=>no,MODEL_OPENAI_GPT_5_1_CHAT:()=>Zt,MODEL_OPENAI_GPT_5_1_CODEX:()=>Yt,MODEL_OPENAI_GPT_5_5:()=>Jt,MODEL_OPENAI_GPT_5_5_PRO:()=>Xt,MODEL_OPENAI_GPT_5_6_LUNA:()=>qt,MODEL_OPENAI_GPT_5_6_SOL:()=>zt,MODEL_OPENAI_GPT_5_6_TERRA:()=>jt,MODEL_OPENAI_GPT_5_MINI:()=>Qt,MODEL_OPENAI_GPT_5_NANO:()=>eo,MODEL_OPENAI_GPT_LATEST:()=>Wt,MODEL_OPENAI_GPT_MINI_LATEST:()=>$t,MODEL_OPENROUTER_AUTO:()=>ht,MODEL_OPENROUTER_AUTO_BETA:()=>ce,MODEL_OPENROUTER_FUSION:()=>en,MODEL_PLAMO_2_2_PRIME:()=>hi,MODEL_PLAMO_3_0_PRIME:()=>Te,MODEL_XAI_GROK_4_5:()=>vo,MODEL_XAI_GROK_LATEST:()=>Oo,MODEL_ZAI_GLM_4_5_AIR:()=>nn,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>Mo,MODEL_ZAI_GLM_4_7_FLASH:()=>on,MODEL_ZAI_GLM_5_2:()=>ue,MistralChatService:()=>Ge,MistralChatServiceProvider:()=>ke,OPENROUTER_CREDITS_THRESHOLD:()=>ir,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>nr,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>or,OPENROUTER_FREE_MODELS:()=>an,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>ln,OPENROUTER_VISION_SUPPORTED_MODELS:()=>Jn,OpenAIChatService:()=>L,OpenAIChatServiceProvider:()=>Fe,OpenAICompatibleChatServiceProvider:()=>Ve,OpenRouterChatService:()=>Ue,OpenRouterChatServiceProvider:()=>Ke,PLAMO_API_BASE_URL:()=>ui,PLAMO_SUPPORTED_MODELS:()=>Rn,PlamoChatService:()=>He,PlamoChatServiceProvider:()=>Be,SAKANA_API_BASE_URL:()=>li,SAKANA_SUPPORTED_MODELS:()=>xn,SakanaChatService:()=>We,SakanaChatServiceProvider:()=>$e,StreamTextAccumulator:()=>M,VISION_SUPPORTED_MODELS:()=>Ze,XAIChatService:()=>ze,XAIChatServiceProvider:()=>je,XAI_VISION_SUPPORTED_MODELS:()=>Yn,ZAIChatService:()=>qe,ZAIChatServiceProvider:()=>Xe,ZAI_VISION_SUPPORTED_MODELS:()=>Zn,allowsReasoningLow:()=>Dt,allowsReasoningMax:()=>Ho,allowsReasoningMinimal:()=>Qe,allowsReasoningNone:()=>Ye,allowsReasoningXHigh:()=>At,buildOpenAICompatibleTools:()=>A,getClaudeSupportedReasoningEfforts:()=>N,getDefaultClaudeReasoningEffort:()=>Xn,getDefaultGeminiReasoningEffort:()=>Ji,getDefaultKimiReasoningEffort:()=>ve,getDefaultReasoningEffortForGPT5Model:()=>et,getDefaultXaiReasoningEffort:()=>xo,getGeminiSupportedReasoningEfforts:()=>Nt,getKimiSupportedReasoningEfforts:()=>z,getMaxTokensForResponseLength:()=>T,installGASFetch:()=>Vi,isClaudeReasoningEffortModel:()=>qn,isGPT5Model:()=>te,isGeminiReasoningEffortModel:()=>Zo,isKimiReasoningEffortModel:()=>ie,isKimiThinkingRequiredModel:()=>Et,isKimiVisionModel:()=>Oe,isMistralReasoningEffort:()=>yn,isMistralReasoningEffortModel:()=>vt,isMistralVisionModel:()=>In,isOpenRouterFreeModel:()=>oe,isOpenRouterVisionModel:()=>he,isResponsesOnlyGPT5Model:()=>Ko,isXaiReasoningEffortModel:()=>Io,isXaiReasoningEffortNoneModel:()=>fn,isXaiVisionModel:()=>fe,isZaiToolStreamModel:()=>_n,isZaiVisionModel:()=>me,normalizeClaudeReasoningEffort:()=>tr,normalizeGeminiReasoningEffort:()=>ot,normalizeXaiReasoningEffort:()=>gt,parseOpenAICompatibleOneShot:()=>R,parseOpenAICompatibleTextStream:()=>F,parseOpenAICompatibleToolStream:()=>x,processChatWithOptionalTools:()=>O,refreshOpenRouterFreeModels:()=>Sr,resolveVisionModel:()=>C,runOnceText:()=>hr,safeJsonParse:()=>gi,safeParseToolCallInput:()=>se,screenplayToText:()=>ur,textToScreenplay:()=>mi,textsToScreenplay:()=>cr});var q="https://api.openai.com/v1/chat/completions",D="https://api.openai.com/v1/responses",X="gpt-5-nano",ae="gpt-5-mini",le="gpt-5",pe="gpt-5.1",J="gpt-5.4",Z="gpt-5.5",U="gpt-5.6",K="gpt-5.6-sol",H="gpt-5.6-terra",B="gpt-5.6-luna",Y="gpt-5.4-mini",Q="gpt-5.4-nano",W="gpt-5.4-pro",yt="gpt-4.1",It="gpt-4.1-mini",xt="gpt-4.1-nano",ee="gpt-4o-mini",Rt="gpt-4o",Vo="o3-mini",Fo="o1-mini",Uo="o1",Ze=[X,ae,le,pe,J,Z,U,K,H,B,Y,Q,W,yt,It,xt,ee,Rt,"o1"],Fn=[X,ae,le,pe,J,Z,U,K,H,B,Y,Q,W];function te(n){return Fn.includes(n)}function Ko(n){return n===W}function At(n){return n===U||n===K||n===H||n===B||n===Z||n===J||n===Y||n===Q||n===W}function Ho(n){return n===U||n===K||n===H||n===B}function Ye(n){return n===U||n===K||n===H||n===B||n===pe||n===J||n===Z||n===Y||n===Q}function Qe(n){return n===X||n===ae||n===le}function Dt(n){return n!==W}function et(n){return Ye(n)?"none":Qe(n)?"minimal":"medium"}var Bo="https://generativelanguage.googleapis.com",Un="gemma-4-31b-it",Kn="gemma-4-26b-a4b-it",Wo="gemini-3.6-flash",$o="gemini-3.5-flash",zo="gemini-3.5-flash-lite",jo="gemini-3.1-pro-preview",$="gemini-3.1-flash-lite",qo="gemini-3.1-flash-lite-preview",Xo="gemini-3-pro-preview",Jo="gemini-3-flash-preview",Hn="gemini-2.5-pro",Bn="gemini-2.5-flash",Wn="gemini-2.5-flash-lite",$n="gemini-2.5-flash-lite-preview-06-17",bt=[Wo,$o,zo,$,jo,Jo,Hn,Bn,Wn,Un,Kn],zn=[qo,Xo,$n],tt=[...bt,...zn],zi=["minimal","low","medium","high"],ji=["low","medium","high"],qi=[Wo,$o,zo,$,qo,Jo],Xi=[jo,Xo];function Nt(n){return qi.includes(n)?zi:Xi.includes(n)?ji:[]}function Zo(n){return Nt(n).length>0}function Ji(n){return Nt(n)[0]}function ot(n,e){let t=Nt(n);if(t.length!==0)return e&&t.includes(e)?e:t[0]}var Yo="https://api.anthropic.com/v1/messages",Gt="claude-3-haiku-20240307",Zi="claude-3-5-haiku-20241022",Yi="claude-3-5-sonnet-20241022",Qi="claude-3-7-sonnet-20250219",kt="claude-sonnet-4-20250514",Vt="claude-opus-4-20250514",Ft="claude-sonnet-4-5-20250929",b="claude-haiku-4-5-20251001",nt="claude-opus-4-5-20251101",it="claude-sonnet-4-6",rt="claude-opus-4-6",st="claude-opus-4-7",at="claude-opus-4-8",lt="claude-sonnet-5",pt="claude-opus-5",Qo=["low","medium","high"],jn=[...Qo,"max"],wt=[...Qo,"xhigh","max"],er={[nt]:Qo,[it]:jn,[rt]:jn,[st]:wt,[at]:wt,[lt]:wt,[pt]:wt},ct=[Gt,kt,Vt,Ft,b,nt,it,rt,st,at,lt,pt];function N(n){return er[n]??[]}function qn(n){return N(n).length>0}function Xn(n){return qn(n)?"high":void 0}function tr(n,e){let t=N(n);if(t.length!==0)return e?t.includes(e)?e:"high":Xn(n)}var ut="https://openrouter.ai/api/v1/chat/completions",ht="openrouter/auto",ce="openrouter/auto-beta",en="openrouter/fusion",w="openai/gpt-oss-20b:free",Ut="moonshotai/kimi-k3",Kt="moonshotai/kimi-k2.7-code",Ht="moonshotai/kimi-k2.5",Bt="~moonshotai/kimi-latest",Wt="~openai/gpt-latest",$t="~openai/gpt-mini-latest",zt="openai/gpt-5.6-sol",jt="openai/gpt-5.6-terra",qt="openai/gpt-5.6-luna",Xt="openai/gpt-5.5-pro",Jt="openai/gpt-5.5",Zt="openai/gpt-5.1-chat",Yt="openai/gpt-5.1-codex",Qt="openai/gpt-5-mini",eo="openai/gpt-5-nano",to="openai/gpt-4o",oo="openai/gpt-4.1-mini",no="openai/gpt-4.1-nano",io="~anthropic/claude-sonnet-latest",ro="~anthropic/claude-haiku-latest",so="anthropic/claude-opus-5",ao="anthropic/claude-opus-4",lo="anthropic/claude-sonnet-4",po="anthropic/claude-3.7-sonnet",tn="anthropic/claude-3.5-sonnet",co="anthropic/claude-haiku-4.5",uo="~google/gemini-pro-latest",ho="~google/gemini-flash-latest",mo="google/gemini-3.6-flash",go="google/gemini-3.5-flash-lite",_o="google/gemini-2.5-pro",fo="google/gemini-2.5-flash",Eo="google/gemini-2.5-flash-lite-preview-09-2025",ue="z-ai/glm-5.2",on="z-ai/glm-4.7-flash",nn="z-ai/glm-4.5-air",Mo="z-ai/glm-4.5-air:free",rn="kwaipilot/kat-coder-air-v2.5",sn="kwaipilot/kat-coder-pro-v2.5",Oo="~x-ai/grok-latest",vo="x-ai/grok-4.5",an=[w,Mo],Jn=[ce,Ut,Bt,Wt,$t,zt,jt,qt,Xt,Jt,Zt,Yt,Qt,eo,to,oo,no,io,ro,so,ao,lo,po,co,uo,ho,mo,go,_o,fo,Eo,Kt,Ht,Oo,vo],ln=20,or=50,nr=1e3,ir=10;function oe(n){return n.trim().endsWith(":free")}function he(n){return Jn.some(e=>n.includes(e))}var dt="https://api.z.ai/api/paas/v4/chat/completions",de="glm-5.2",pn="glm-5.1",cn="glm-5",un="glm-5-turbo",So="glm-5v-turbo",hn="glm-4.7",dn="glm-4.7-FlashX",mn="glm-4.7-Flash",gn="glm-4.6",Co="glm-4.6V",To="glm-4.6V-FlashX",ne="glm-4.6V-Flash",Zn=[So,Co,To,ne];function me(n){return Zn.includes(n)}function _n(n){return n.toLowerCase().startsWith("glm-4.6")}var mt="https://api.x.ai/v1/chat/completions",ge="grok-4.5",_e="grok-4.3",Lo="grok-4.20-0309-reasoning",Po="grok-4.20-0309-non-reasoning",yo="grok-4-1-fast-reasoning",G="grok-4-1-fast-non-reasoning",Yn=[ge,_e,Lo,Po,yo,G];function fe(n){return Yn.includes(n)}function Io(n){return n===ge||n===_e}function fn(n){return n===_e}function xo(n){return n===ge?"low":fn(n)?"none":void 0}function gt(n,e){if(Io(n))return e==="none"&&!fn(n)?"low":e??xo(n)}var Ee="https://api.moonshot.ai/v1/chat/completions",Me="kimi-k3",_t="kimi-k2.7-code",ft="kimi-k2.7-code-highspeed",k="kimi-k2.6",Ro="kimi-k2.5",rr={[Me]:["low","high","max"]},Qn=[Me,_t,ft,k,Ro],ei=[_t,ft];function Oe(n){return Qn.includes(n)}function Et(n){return ei.includes(n)}function z(n){return rr[n]??[]}function ve(n){return n===Me?"max":void 0}function ie(n){return z(n).length>0}var ti="https://api.deepseek.com",Mt=`${ti}/chat/completions`,Se="deepseek-v4-flash",oi="deepseek-v4-pro",ni="deepseek-chat",ii="deepseek-reasoner",En=[Se,oi],sr=[ni,ii];var ri="https://api.mistral.ai/v1",Ot=`${ri}/chat/completions`,Mn="ministral-3b-2512",On="ministral-8b-2512",vn="ministral-14b-2512",V="mistral-small-latest",Sn="mistral-small-2603",Ao="mistral-medium-3-5",Cn="mistral-medium-2508",Tn="mistral-large-latest",Ln="mistral-large-2512",Pn=[V,Mn,On,vn,Ao,Tn,Ln,Sn,Cn],si=[V,Ao],ai=[V,Mn,On,vn,Sn,Ao,Cn,Tn,Ln];function vt(n){return si.includes(n)}function yn(n){return n==="none"||n==="high"}function In(n){return ai.includes(n)}var li="https://api.sakana.ai/v1",St=`${li}/chat/completions`,Ce="fugu",pi="fugu-ultra",ci="fugu-ultra-20260615",xn=[Ce,pi,ci];var ui="https://api.platform.preferredai.jp/v1",Ct=`${ui}/chat/completions`,Te="plamo-3.0-prime",hi="plamo-2.2-prime",Rn=[Te,hi];var S={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Do={[S.VERY_SHORT]:40,[S.SHORT]:100,[S.MEDIUM]:200,[S.LONG]:300,[S.VERY_LONG]:1e3,[S.DEEP]:5e3},An=5e3,Dn={casual:{reasoning_effort:"minimal",verbosity:"low",description:"Fast responses for casual chat, quick questions (GPT-4 like experience)"},balanced:{reasoning_effort:"medium",verbosity:"medium",description:"Balanced reasoning for business tasks, learning, general problem solving"},expert:{reasoning_effort:"high",verbosity:"high",description:"Deep reasoning for research, complex analysis, expert-level tasks"}};function T(n){return n?Do[n]??An:An}var ar="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",lr=`You are a skilled summarizing assistant.
1
+ "use strict";var AITuberOnAirChat=(()=>{var jo=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var nr=Object.getOwnPropertyNames;var ir=Object.prototype.hasOwnProperty;var rr=(n,e)=>{for(var t in e)jo(n,t,{get:e[t],enumerable:!0})},sr=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nr(e))!ir.call(n,i)&&i!==t&&jo(n,i,{get:()=>e[i],enumerable:!(o=or(e,i))||o.enumerable});return n};var ar=n=>sr(jo({},"__esModule",{value:!0}),n);var fs={};rr(fs,{CHAT_RESPONSE_LENGTH:()=>O,CLAUDE_VISION_SUPPORTED_MODELS:()=>gt,ChatServiceFactory:()=>tt,ChatServiceHttpClient:()=>_,ClaudeChatService:()=>De,ClaudeChatServiceProvider:()=>Ae,DEEPSEEK_API_BASE_URL:()=>mi,DEEPSEEK_DEPRECATED_MODELS:()=>Pr,DEEPSEEK_SUPPORTED_MODELS:()=>xn,DEFAULT_MAX_TOKENS:()=>Bn,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>xr,DEFAULT_VISION_PROMPT:()=>Rr,DeepSeekChatService:()=>be,DeepSeekChatServiceProvider:()=>Ne,EMOTION_TAG_CLEANUP_REGEX:()=>zn,EMOTION_TAG_REGEX:()=>yi,ENDPOINT_CLAUDE_API:()=>pn,ENDPOINT_DEEPSEEK_CHAT_COMPLETIONS_API:()=>Lt,ENDPOINT_GEMINI_API:()=>Qo,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>Te,ENDPOINT_MISTRAL_CHAT_COMPLETIONS_API:()=>Pt,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>J,ENDPOINT_OPENAI_RESPONSES_API:()=>A,ENDPOINT_OPENROUTER_API:()=>ft,ENDPOINT_PLAMO_CHAT_COMPLETIONS_API:()=>It,ENDPOINT_SAKANA_CHAT_COMPLETIONS_API:()=>xt,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>Mt,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>Et,EmotionParser:()=>Ie,GEMINI_DEPRECATED_MODELS:()=>ii,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>$n,GEMINI_RECOMMENDED_MODELS:()=>Ut,GEMINI_VISION_SUPPORTED_MODELS:()=>st,GPT5_PRESETS:()=>Wn,GPT_5_MODELS:()=>Zn,GeminiChatService:()=>we,GeminiChatServiceProvider:()=>ke,GeminiNanoChatService:()=>Ge,GeminiNanoChatServiceProvider:()=>Ve,HttpError:()=>X,KIMI_THINKING_REQUIRED_MODELS:()=>di,KIMI_VISION_SUPPORTED_MODELS:()=>hi,KimiChatService:()=>Fe,KimiChatServiceProvider:()=>Ue,MAX_TOKENS_BY_LENGTH:()=>Ho,MISTRAL_API_BASE_URL:()=>Ei,MISTRAL_REASONING_EFFORT_SUPPORTED_MODELS:()=>Mi,MISTRAL_SUPPORTED_MODELS:()=>Vn,MISTRAL_VISION_SUPPORTED_MODELS:()=>Oi,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>hn,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>_o,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>Eo,MODEL_ANTHROPIC_CLAUDE_HAIKU_LATEST:()=>ho,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>go,MODEL_ANTHROPIC_CLAUDE_OPUS_5:()=>mo,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>fo,MODEL_ANTHROPIC_CLAUDE_SONNET_LATEST:()=>uo,MODEL_CLAUDE_3_5_HAIKU:()=>dr,MODEL_CLAUDE_3_5_SONNET:()=>mr,MODEL_CLAUDE_3_7_SONNET:()=>gr,MODEL_CLAUDE_3_HAIKU:()=>Bt,MODEL_CLAUDE_4_5_HAIKU:()=>b,MODEL_CLAUDE_4_5_OPUS:()=>lt,MODEL_CLAUDE_4_5_SONNET:()=>zt,MODEL_CLAUDE_4_6_OPUS:()=>ct,MODEL_CLAUDE_4_6_SONNET:()=>pt,MODEL_CLAUDE_4_7_OPUS:()=>ut,MODEL_CLAUDE_4_8_OPUS:()=>ht,MODEL_CLAUDE_4_OPUS:()=>$t,MODEL_CLAUDE_4_SONNET:()=>Wt,MODEL_CLAUDE_5_OPUS:()=>mt,MODEL_CLAUDE_5_SONNET:()=>dt,MODEL_DEEPSEEK_CHAT:()=>gi,MODEL_DEEPSEEK_REASONER:()=>fi,MODEL_DEEPSEEK_V4_FLASH:()=>ae,MODEL_DEEPSEEK_V4_PRO:()=>Uo,MODEL_FUGU:()=>Re,MODEL_FUGU_ULTRA:()=>Si,MODEL_FUGU_ULTRA_20260615:()=>Ci,MODEL_GEMINI_2_5_FLASH:()=>ti,MODEL_GEMINI_2_5_FLASH_LITE:()=>oi,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>ni,MODEL_GEMINI_2_5_PRO:()=>ei,MODEL_GEMINI_3_1_FLASH_LITE:()=>j,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>rn,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>nn,MODEL_GEMINI_3_5_FLASH:()=>tn,MODEL_GEMINI_3_5_FLASH_LITE:()=>on,MODEL_GEMINI_3_6_FLASH:()=>en,MODEL_GEMINI_3_FLASH_PREVIEW:()=>an,MODEL_GEMINI_3_PRO_PREVIEW:()=>sn,MODEL_GEMINI_NANO:()=>le,MODEL_GEMMA_4_26B_A4B_IT:()=>Qn,MODEL_GEMMA_4_31B_IT:()=>Yn,MODEL_GLM_4_6:()=>yn,MODEL_GLM_4_6V:()=>Ao,MODEL_GLM_4_6V_FLASH:()=>re,MODEL_GLM_4_6V_FLASHX:()=>bo,MODEL_GLM_4_7:()=>Cn,MODEL_GLM_4_7_FLASH:()=>Ln,MODEL_GLM_4_7_FLASHX:()=>Tn,MODEL_GLM_5:()=>vn,MODEL_GLM_5V_TURBO:()=>Do,MODEL_GLM_5_1:()=>On,MODEL_GLM_5_2:()=>Ee,MODEL_GLM_5_TURBO:()=>Sn,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>To,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>Lo,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>Co,MODEL_GOOGLE_GEMINI_3_5_FLASH_LITE:()=>So,MODEL_GOOGLE_GEMINI_3_6_FLASH:()=>vo,MODEL_GOOGLE_GEMINI_FLASH_LATEST:()=>Oo,MODEL_GOOGLE_GEMINI_PRO_LATEST:()=>Mo,MODEL_GPT_4O:()=>Gt,MODEL_GPT_4O_MINI:()=>oe,MODEL_GPT_4_1:()=>Nt,MODEL_GPT_4_1_MINI:()=>wt,MODEL_GPT_4_1_NANO:()=>kt,MODEL_GPT_5:()=>ue,MODEL_GPT_5_1:()=>he,MODEL_GPT_5_4:()=>Y,MODEL_GPT_5_4_MINI:()=>ee,MODEL_GPT_5_4_NANO:()=>te,MODEL_GPT_5_4_PRO:()=>z,MODEL_GPT_5_5:()=>Q,MODEL_GPT_5_6:()=>H,MODEL_GPT_5_6_LUNA:()=>$,MODEL_GPT_5_6_SOL:()=>B,MODEL_GPT_5_6_TERRA:()=>W,MODEL_GPT_5_MINI:()=>ce,MODEL_GPT_5_NANO:()=>Z,MODEL_GPT_OSS_20B_FREE:()=>G,MODEL_GROK_4_1_FAST_NON_REASONING:()=>V,MODEL_GROK_4_1_FAST_REASONING:()=>ko,MODEL_GROK_4_20_NON_REASONING:()=>wo,MODEL_GROK_4_20_REASONING:()=>No,MODEL_GROK_4_3:()=>Ot,MODEL_GROK_4_5:()=>ve,MODEL_GROK_4_6:()=>Oe,MODEL_KIMI_K2_5:()=>Fo,MODEL_KIMI_K2_6:()=>F,MODEL_KIMI_K2_7_CODE:()=>St,MODEL_KIMI_K2_7_CODE_HIGHSPEED:()=>Ct,MODEL_KIMI_K3:()=>Le,MODEL_KWAIPILOT_KAT_CODER_AIR_V2_5:()=>gn,MODEL_KWAIPILOT_KAT_CODER_PRO_V2_5:()=>fn,MODEL_MINISTRAL_14B_2512:()=>bn,MODEL_MINISTRAL_3B_2512:()=>Dn,MODEL_MINISTRAL_8B_2512:()=>An,MODEL_MISTRAL_LARGE_2512:()=>Gn,MODEL_MISTRAL_LARGE_LATEST:()=>kn,MODEL_MISTRAL_MEDIUM_2508:()=>wn,MODEL_MISTRAL_MEDIUM_3_5:()=>Ko,MODEL_MISTRAL_SMALL_2603:()=>Nn,MODEL_MISTRAL_SMALL_LATEST:()=>U,MODEL_MOONSHOTAI_KIMI_K2_5:()=>Xt,MODEL_MOONSHOTAI_KIMI_K2_7_CODE:()=>qt,MODEL_MOONSHOTAI_KIMI_K3:()=>jt,MODEL_MOONSHOTAI_KIMI_LATEST:()=>Jt,MODEL_O1:()=>Jo,MODEL_O1_MINI:()=>Xo,MODEL_O3_MINI:()=>qo,MODEL_OPENAI_GPT_4O:()=>lo,MODEL_OPENAI_GPT_4_1_MINI:()=>po,MODEL_OPENAI_GPT_4_1_NANO:()=>co,MODEL_OPENAI_GPT_5_1_CHAT:()=>io,MODEL_OPENAI_GPT_5_1_CODEX:()=>ro,MODEL_OPENAI_GPT_5_5:()=>no,MODEL_OPENAI_GPT_5_5_PRO:()=>oo,MODEL_OPENAI_GPT_5_6_LUNA:()=>to,MODEL_OPENAI_GPT_5_6_SOL:()=>Qt,MODEL_OPENAI_GPT_5_6_TERRA:()=>eo,MODEL_OPENAI_GPT_5_MINI:()=>so,MODEL_OPENAI_GPT_5_NANO:()=>ao,MODEL_OPENAI_GPT_LATEST:()=>Zt,MODEL_OPENAI_GPT_MINI_LATEST:()=>Yt,MODEL_OPENROUTER_AUTO:()=>_t,MODEL_OPENROUTER_AUTO_BETA:()=>de,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH:()=>ge,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_0731:()=>fe,MODEL_OPENROUTER_FUSION:()=>un,MODEL_PLAMO_2_2_PRIME:()=>Li,MODEL_PLAMO_3_0_PRIME:()=>xe,MODEL_XAI_GROK_4_5:()=>Ro,MODEL_XAI_GROK_LATEST:()=>Po,MODEL_ZAI_GLM_4_5_AIR:()=>mn,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>yo,MODEL_ZAI_GLM_4_7_FLASH:()=>dn,MODEL_ZAI_GLM_5_2:()=>me,MistralChatService:()=>Ke,MistralChatServiceProvider:()=>He,OPENROUTER_CREDITS_THRESHOLD:()=>Cr,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>Sr,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>vr,OPENROUTER_FREE_MODELS:()=>_n,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>En,OPENROUTER_VISION_SUPPORTED_MODELS:()=>li,OpenAIChatService:()=>y,OpenAIChatServiceProvider:()=>We,OpenAICompatibleChatServiceProvider:()=>Be,OpenRouterChatService:()=>$e,OpenRouterChatServiceProvider:()=>ze,PLAMO_API_BASE_URL:()=>Ti,PLAMO_SUPPORTED_MODELS:()=>Hn,PlamoChatService:()=>je,PlamoChatServiceProvider:()=>qe,SAKANA_API_BASE_URL:()=>vi,SAKANA_SUPPORTED_MODELS:()=>Kn,SakanaChatService:()=>Xe,SakanaChatServiceProvider:()=>Je,StreamTextAccumulator:()=>E,VISION_SUPPORTED_MODELS:()=>ot,XAIChatService:()=>Ze,XAIChatServiceProvider:()=>Ye,XAI_VISION_SUPPORTED_MODELS:()=>ci,ZAIChatService:()=>Qe,ZAIChatServiceProvider:()=>et,ZAI_VISION_SUPPORTED_MODELS:()=>pi,allowsReasoningLow:()=>Ft,allowsReasoningMax:()=>Yo,allowsReasoningMinimal:()=>it,allowsReasoningNone:()=>nt,allowsReasoningXHigh:()=>Vt,buildOpenAICompatibleTools:()=>D,buildToolContinuationMessages:()=>cs,getChatBackendProviderCapabilities:()=>Jn,getClaudeSupportedReasoningEfforts:()=>k,getDeepSeekSupportedReasoningEfforts:()=>yt,getDefaultClaudeReasoningEffort:()=>ai,getDefaultDeepSeekReasoningEffort:()=>Rn,getDefaultGeminiReasoningEffort:()=>hr,getDefaultKimiReasoningEffort:()=>Pe,getDefaultOpenRouterReasoningEffort:()=>Io,getDefaultReasoningEffortForGPT5Model:()=>rt,getDefaultXaiReasoningEffort:()=>Vo,getGeminiSupportedReasoningEfforts:()=>Kt,getKimiSupportedReasoningEfforts:()=>q,getMaxTokensForResponseLength:()=>L,getOpenRouterSupportedReasoningEfforts:()=>xo,getXaiSupportedReasoningEfforts:()=>Ce,installGASFetch:()=>er,isClaudeReasoningEffortModel:()=>si,isDeepSeekReasoningEffortModel:()=>_i,isGPT5Model:()=>ne,isGeminiReasoningEffortModel:()=>ln,isKimiReasoningEffortModel:()=>se,isKimiThinkingRequiredModel:()=>Tt,isKimiVisionModel:()=>ye,isMistralReasoningEffort:()=>Fn,isMistralReasoningEffortModel:()=>Rt,isMistralVisionModel:()=>Un,isOpenRouterFreeModel:()=>ie,isOpenRouterVisionModel:()=>_e,isResponsesOnlyGPT5Model:()=>Zo,isXaiReasoningEffortModel:()=>Go,isXaiReasoningEffortNoneModel:()=>ui,isXaiVisionModel:()=>Se,isZaiToolStreamModel:()=>Pn,isZaiVisionModel:()=>Me,normalizeClaudeReasoningEffort:()=>_r,normalizeDeepSeekReasoningEffort:()=>In,normalizeGeminiReasoningEffort:()=>at,normalizeOpenRouterReasoningEffort:()=>Mn,normalizeXaiReasoningEffort:()=>vt,parseOpenAICompatibleOneShot:()=>I,parseOpenAICompatibleTextStream:()=>K,parseOpenAICompatibleToolStream:()=>x,processChatWithOptionalTools:()=>M,refreshOpenRouterFreeModels:()=>Br,resolveVisionModel:()=>T,runOnceText:()=>br,safeJsonParse:()=>Ri,safeParseToolCallInput:()=>pe,screenplayToText:()=>Ar,textToScreenplay:()=>Pi,textsToScreenplay:()=>Dr});var J="https://api.openai.com/v1/chat/completions",A="https://api.openai.com/v1/responses",Z="gpt-5-nano",ce="gpt-5-mini",ue="gpt-5",he="gpt-5.1",Y="gpt-5.4",Q="gpt-5.5",H="gpt-5.6",B="gpt-5.6-sol",W="gpt-5.6-terra",$="gpt-5.6-luna",ee="gpt-5.4-mini",te="gpt-5.4-nano",z="gpt-5.4-pro",Nt="gpt-4.1",wt="gpt-4.1-mini",kt="gpt-4.1-nano",oe="gpt-4o-mini",Gt="gpt-4o",qo="o3-mini",Xo="o1-mini",Jo="o1",ot=[Z,ce,ue,he,Y,Q,H,B,W,$,ee,te,z,Nt,wt,kt,oe,Gt,"o1"],Zn=[Z,ce,ue,he,Y,Q,H,B,W,$,ee,te,z];function ne(n){return Zn.includes(n)}function Zo(n){return n===z}function Vt(n){return n===H||n===B||n===W||n===$||n===Q||n===Y||n===ee||n===te||n===z}function Yo(n){return n===H||n===B||n===W||n===$}function nt(n){return n===H||n===B||n===W||n===$||n===he||n===Y||n===Q||n===ee||n===te}function it(n){return n===Z||n===ce||n===ue}function Ft(n){return n!==z}function rt(n){return nt(n)?"none":it(n)?"minimal":"medium"}var Qo="https://generativelanguage.googleapis.com",Yn="gemma-4-31b-it",Qn="gemma-4-26b-a4b-it",en="gemini-3.6-flash",tn="gemini-3.5-flash",on="gemini-3.5-flash-lite",nn="gemini-3.1-pro-preview",j="gemini-3.1-flash-lite",rn="gemini-3.1-flash-lite-preview",sn="gemini-3-pro-preview",an="gemini-3-flash-preview",ei="gemini-2.5-pro",ti="gemini-2.5-flash",oi="gemini-2.5-flash-lite",ni="gemini-2.5-flash-lite-preview-06-17",Ut=[en,tn,on,j,nn,an,ei,ti,oi,Yn,Qn],ii=[rn,sn,ni],st=[...Ut,...ii],lr=["minimal","low","medium","high"],pr=["low","medium","high"],cr=[en,tn,on,j,rn,an],ur=[nn,sn];function Kt(n){return cr.includes(n)?lr:ur.includes(n)?pr:[]}function ln(n){return Kt(n).length>0}function hr(n){return Kt(n)[0]}function at(n,e){let t=Kt(n);if(t.length!==0)return e&&t.includes(e)?e:t[0]}var pn="https://api.anthropic.com/v1/messages",Bt="claude-3-haiku-20240307",dr="claude-3-5-haiku-20241022",mr="claude-3-5-sonnet-20241022",gr="claude-3-7-sonnet-20250219",Wt="claude-sonnet-4-20250514",$t="claude-opus-4-20250514",zt="claude-sonnet-4-5-20250929",b="claude-haiku-4-5-20251001",lt="claude-opus-4-5-20251101",pt="claude-sonnet-4-6",ct="claude-opus-4-6",ut="claude-opus-4-7",ht="claude-opus-4-8",dt="claude-sonnet-5",mt="claude-opus-5",cn=["low","medium","high"],ri=[...cn,"max"],Ht=[...cn,"xhigh","max"],fr={[lt]:cn,[pt]:ri,[ct]:ri,[ut]:Ht,[ht]:Ht,[dt]:Ht,[mt]:Ht},gt=[Bt,Wt,$t,zt,b,lt,pt,ct,ut,ht,dt,mt];function k(n){return fr[n]??[]}function si(n){return k(n).length>0}function ai(n){return si(n)?"high":void 0}function _r(n,e){let t=k(n);if(t.length!==0)return e?t.includes(e)?e:"high":ai(n)}var ft="https://openrouter.ai/api/v1/chat/completions",_t="openrouter/auto",de="openrouter/auto-beta",un="openrouter/fusion",G="openai/gpt-oss-20b:free",jt="moonshotai/kimi-k3",qt="moonshotai/kimi-k2.7-code",Xt="moonshotai/kimi-k2.5",Jt="~moonshotai/kimi-latest",Zt="~openai/gpt-latest",Yt="~openai/gpt-mini-latest",Qt="openai/gpt-5.6-sol",eo="openai/gpt-5.6-terra",to="openai/gpt-5.6-luna",oo="openai/gpt-5.5-pro",no="openai/gpt-5.5",io="openai/gpt-5.1-chat",ro="openai/gpt-5.1-codex",so="openai/gpt-5-mini",ao="openai/gpt-5-nano",lo="openai/gpt-4o",po="openai/gpt-4.1-mini",co="openai/gpt-4.1-nano",uo="~anthropic/claude-sonnet-latest",ho="~anthropic/claude-haiku-latest",mo="anthropic/claude-opus-5",go="anthropic/claude-opus-4",fo="anthropic/claude-sonnet-4",_o="anthropic/claude-3.7-sonnet",hn="anthropic/claude-3.5-sonnet",Eo="anthropic/claude-haiku-4.5",Mo="~google/gemini-pro-latest",Oo="~google/gemini-flash-latest",vo="google/gemini-3.6-flash",So="google/gemini-3.5-flash-lite",Co="google/gemini-2.5-pro",To="google/gemini-2.5-flash",Lo="google/gemini-2.5-flash-lite-preview-09-2025",me="z-ai/glm-5.2",dn="z-ai/glm-4.7-flash",mn="z-ai/glm-4.5-air",yo="z-ai/glm-4.5-air:free",gn="kwaipilot/kat-coder-air-v2.5",fn="kwaipilot/kat-coder-pro-v2.5",Po="~x-ai/grok-latest",Ro="x-ai/grok-4.5",ge="deepseek/deepseek-v4-flash",fe="deepseek/deepseek-v4-flash-0731",Er=["none","minimal","low","medium","high"],Mr=["none","high","xhigh"],Or=["none","low","high","max"],_n=[G,yo],li=[de,jt,Jt,Zt,Yt,Qt,eo,to,oo,no,io,ro,so,ao,lo,po,co,uo,ho,mo,go,fo,_o,Eo,Mo,Oo,vo,So,Co,To,Lo,qt,Xt,Po,Ro],En=20,vr=50,Sr=1e3,Cr=10;function ie(n){return n.trim().endsWith(":free")}function _e(n){return li.some(e=>n.includes(e))}function xo(n){let e=n.trim();return e===ge?Mr:e===fe?Or:Er}function Io(n){let e=n.trim();return e===me||e===ge||e===fe?"none":void 0}function Mn(n,e){let t=n.trim(),o=e??Io(n);if(!o)return;if(xo(n).includes(o))return o;if(t===ge)return o==="max"?"xhigh":"none";if(t===fe){if(o==="minimal"||o==="medium")return"low";if(o==="xhigh")return"high"}return o}var Et="https://api.z.ai/api/paas/v4/chat/completions",Ee="glm-5.2",On="glm-5.1",vn="glm-5",Sn="glm-5-turbo",Do="glm-5v-turbo",Cn="glm-4.7",Tn="glm-4.7-FlashX",Ln="glm-4.7-Flash",yn="glm-4.6",Ao="glm-4.6V",bo="glm-4.6V-FlashX",re="glm-4.6V-Flash",pi=[Do,Ao,bo,re];function Me(n){return pi.includes(n)}function Pn(n){return n.toLowerCase().startsWith("glm-4.6")}var Mt="https://api.x.ai/v1/chat/completions",Oe="grok-4.6",ve="grok-4.5",Ot="grok-4.3",No="grok-4.20-0309-reasoning",wo="grok-4.20-0309-non-reasoning",ko="grok-4-1-fast-reasoning",V="grok-4-1-fast-non-reasoning",ci=[Oe,ve,Ot,No,wo,ko,V];function Se(n){return ci.includes(n)}function Go(n){return Ce(n).length>0}function Ce(n){return n===Oe?["low","medium","high","xhigh"]:n===ve?["low","medium","high"]:n===Ot?["none","low","medium","high"]:[]}function ui(n){return Ce(n).includes("none")}function Vo(n){return n===Oe||n===ve?"low":ui(n)?"none":void 0}function vt(n,e){return Go(n)?e===void 0?Vo(n):Ce(n).includes(e)?e:e==="none"?"low":"high":void 0}var Te="https://api.moonshot.ai/v1/chat/completions",Le="kimi-k3",St="kimi-k2.7-code",Ct="kimi-k2.7-code-highspeed",F="kimi-k2.6",Fo="kimi-k2.5",Tr={[Le]:["low","high","max"]},hi=[Le,St,Ct,F,Fo],di=[St,Ct];function ye(n){return hi.includes(n)}function Tt(n){return di.includes(n)}function q(n){return Tr[n]??[]}function Pe(n){return n===Le?"max":void 0}function se(n){return q(n).length>0}var mi="https://api.deepseek.com",Lt=`${mi}/chat/completions`,ae="deepseek-v4-flash",Uo="deepseek-v4-pro",Lr=["none","low","high","max"],yr=["none","high","max"],gi="deepseek-chat",fi="deepseek-reasoner",xn=[ae,Uo],Pr=[gi,fi];function yt(n){return n===ae?Lr:n===Uo?yr:[]}function _i(n){return yt(n).length>0}function Rn(n){return _i(n)?"none":void 0}function In(n,e){let t=yt(n);if(t.length===0)return;let o=e??Rn(n);return o&&t.includes(o)?o:n===Uo&&o==="low"?"high":Rn(n)}var Ei="https://api.mistral.ai/v1",Pt=`${Ei}/chat/completions`,Dn="ministral-3b-2512",An="ministral-8b-2512",bn="ministral-14b-2512",U="mistral-small-latest",Nn="mistral-small-2603",Ko="mistral-medium-3-5",wn="mistral-medium-2508",kn="mistral-large-latest",Gn="mistral-large-2512",Vn=[U,Dn,An,bn,Ko,kn,Gn,Nn,wn],Mi=[U,Ko],Oi=[U,Dn,An,bn,Nn,Ko,wn,kn,Gn];function Rt(n){return Mi.includes(n)}function Fn(n){return n==="none"||n==="high"}function Un(n){return Oi.includes(n)}var vi="https://api.sakana.ai/v1",xt=`${vi}/chat/completions`,Re="fugu",Si="fugu-ultra",Ci="fugu-ultra-20260615",Kn=[Re,Si,Ci];var Ti="https://api.platform.preferredai.jp/v1",It=`${Ti}/chat/completions`,xe="plamo-3.0-prime",Li="plamo-2.2-prime",Hn=[xe,Li];var O={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Ho={[O.VERY_SHORT]:40,[O.SHORT]:100,[O.MEDIUM]:200,[O.LONG]:300,[O.VERY_LONG]:1e3,[O.DEEP]:5e3},Bn=5e3,Wn={casual:{reasoning_effort:"minimal",verbosity:"low",description:"Fast responses for casual chat, quick questions (GPT-4 like experience)"},balanced:{reasoning_effort:"medium",verbosity:"medium",description:"Balanced reasoning for business tasks, learning, general problem solving"},expert:{reasoning_effort:"high",verbosity:"high",description:"Deep reasoning for research, complex analysis, expert-level tasks"}};function L(n){return n?Ho[n]??Bn:Bn}var Rr="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",xr=`You are a skilled summarizing assistant.
2
2
  Analyze the following conversation and produce a summary in the **same language** as the majority of the conversation:
3
3
  - Summaries should highlight key points
4
4
  - Stay concise (around {maxLength} characters if possible)
@@ -7,13 +7,13 @@ Analyze the following conversation and produce a summary in the **same language*
7
7
  If the conversation is in Japanese, summarize in Japanese.
8
8
  If it's in English, summarize in English.
9
9
  If it's in another language, summarize in that language.
10
- `;var re="gemini-nano",bn=20;var j=class extends Error{constructor(t,o,i){super(`HTTP ${t}: ${o}`);this.status=t;this.statusText=o;this.body=i;this.name="HttpError"}},Tt=class Tt{static setFetch(e){this.fetchImpl=e}static async post(e,t,o={},i={}){let{timeout:r=3e4,retries:s=0,retryDelay:l=1e3}=i,c={...{"Content-Type":"application/json"},...o},d=null;for(let u=0;u<=s;u++)try{let m=typeof AbortController<"u",g=m?new AbortController:void 0,a=m?setTimeout(()=>g.abort(),r):void 0,h=await Tt.fetchImpl(e,{method:"POST",headers:c,body:typeof t=="string"?t:JSON.stringify(t),...g?{signal:g.signal}:{}});if(a&&clearTimeout(a),!h.ok){let v=await h.text();throw new j(h.status,h.statusText,v)}return h}catch(m){if(d=m,m instanceof j&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError")throw new Error(`Request timeout after ${r}ms`);u<s&&await new Promise(g=>setTimeout(g,l*(u+1)))}throw d||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new j(e.status,e.statusText,t)}static async get(e,t={},o={}){let{timeout:i=3e4,retries:r=0,retryDelay:s=1e3}=o,l=null;for(let p=0;p<=r;p++)try{let c=typeof AbortController<"u",d=c?new AbortController:void 0,u=c?setTimeout(()=>d.abort(),i):void 0,m=await Tt.fetchImpl(e,{method:"GET",headers:t,...d?{signal:d.signal}:{}});if(u&&clearTimeout(u),!m.ok){let g=await m.text();throw new j(m.status,m.statusText,g)}return m}catch(c){if(l=c,c instanceof j&&c.status>=400&&c.status<500)throw c;if(c instanceof Error&&c.name==="AbortError")throw new Error(`Request timeout after ${i}ms`);p<r&&await new Promise(d=>setTimeout(d,s*(p+1)))}throw l||new Error("Request failed")}};Tt.fetchImpl=(e,t)=>fetch(e,t);var E=Tt;var M=class{static append(e,t){if(!t)return;let o=e[e.length-1];o&&o.type==="text"?o.text+=t:e.push({type:"text",text:t})}static getFullText(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}static addTextBlock(e,t){t&&e.push({type:"text",text:t})}};var pr=["happy","sad","angry","surprised","neutral"],di=/\[([a-z]+)\]/i,Nn=/\[[a-z]+\]\s*/gi,Le=class{static extractEmotion(e){let t=e.match(di);if(t){let o=t[1].toLowerCase(),i=e.replace(Nn,"").trim();return{emotion:o,cleanText:i}}return{cleanText:e}}static isValidEmotion(e){return pr.includes(e)}static cleanEmotionTags(e){return e.replace(Nn,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function mi(n){let{emotion:e,cleanText:t}=Le.extractEmotion(n);return e?{emotion:e,text:t}:{text:t}}function cr(n){return n.map(e=>mi(e))}function ur(n){return n.emotion?Le.addEmotionTag(n.emotion,n.text):n.text}async function hr(n,e){let{blocks:t}=await n.chatOnce(e,!1,()=>{});return M.getFullText(t)}var gi=(n,e,t)=>{try{return JSON.parse(n)}catch(o){return t?.(n,o),e}},se=(n,e)=>n?gi(n,{},e):{};var _i=(n,e)=>{try{return JSON.parse(n)}catch(t){if(e){e(n,t);return}throw t}},bo=n=>typeof n=="string"?n:Array.isArray(n)?n.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&e.type==="text"&&typeof e.text=="string"?e.text:"").join(""):"",wn=n=>{let e=n.choices?.[0],t=n.error??e?.error;if(!t&&e?.finish_reason!=="error")return;let o=typeof t=="string"?t:typeof t?.message=="string"?t.message:"The provider ended the response with an error.";throw new Error(`Provider response error: ${o}`)},fi=async(n,e)=>{let t=n.body?.getReader();if(!t)throw new Error("Response body is null.");let o=new TextDecoder,i="",r=!1;for(;!r;){let{done:s,value:l}=await t.read();if(s)break;i+=o.decode(l,{stream:!0});let p=i.split(`
11
- `);i=p.pop()||"";for(let c of p){let d=c.trim();if(!d||d.startsWith(":")||!d.startsWith("data:"))continue;let u=d.slice(5).trim();if(u==="[DONE]"){r=!0;break}e(u)}}};async function F(n,e,t={}){let o="";return await fi(n,i=>{let r=_i(i,t.onJsonError);if(!r)return;t.throwOnApiError&&wn(r);let s=bo(r.choices?.[0]?.delta?.content);s&&(e(s),o+=s)}),o}async function x(n,e,t={}){let o=[],i=new Map,r="",s="",l,p,c=t.appendTextBlock??M.append;await fi(n,a=>{let h=_i(a,t.onJsonError);if(!h)return;t.throwOnApiError&&wn(h);let v=h.choices?.[0];typeof v?.finish_reason=="string"&&(l=v.finish_reason),h.usage&&(p=h.usage);let y=v?.delta,P=bo(y?.content);P&&(e(P),c(o,P),r+=P);let _=bo(y?.reasoning_content);_&&(s+=_),y?.tool_calls&&y.tool_calls.forEach(f=>{let I=i.get(f.index)??{id:f.id,type:f.type,name:f.function?.name,args:""};f.id&&(I.id=f.id),f.type&&(I.type=f.type),f.function?.name&&(I.name=f.function.name),I.args+=f.function?.arguments||"",i.set(f.index,I)})});let d=Array.from(i.entries()).sort((a,h)=>a[0]-h[0]).map(([a,h])=>({type:"tool_use",id:h.id,name:h.name,input:se(h.args,t.onJsonError)})),u=[...o,...d],m=Array.from(i.entries()).sort((a,h)=>a[0]-h[0]).map(([a,h])=>({id:h.id,type:"function",function:{name:h.name,arguments:h.args}})),g={role:"assistant",content:r,...s?{reasoning_content:s}:{},...m.length>0?{tool_calls:m}:{}};return{blocks:u,stop_reason:d.length?"tool_use":"end",truncated:l==="length",finish_reason:l,usage:p,...t.preserveAssistantMessage?{assistant_message:g}:{}}}function R(n,e={}){e.throwOnApiError&&wn(n);let t=n?.choices?.[0],o=[],i=bo(t?.message?.content);t?.message?.tool_calls?.length?t.message.tool_calls.forEach(s=>o.push({type:"tool_use",id:s.id,name:s.function?.name,input:se(s.function?.arguments,e.onJsonError)})):i&&o.push({type:"text",text:i});let r=t?.message?{...t.message,role:"assistant",content:i}:void 0;return{blocks:o,stop_reason:t?.finish_reason==="tool_calls"||o.some(s=>s.type==="tool_use")?"tool_use":"end",truncated:t?.finish_reason==="length",finish_reason:t?.finish_reason,usage:n?.usage,...e.preserveAssistantMessage?{assistant_message:r}:{}}}var A=(n,e="chat-completions")=>n.length===0?[]:e==="responses"?n.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):n.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function O(n){if(!n.hasTools){let t=await n.runWithoutTools();if(typeof t=="string"){await n.onCompleteResponse(t);return}let o=M.getFullText(t.blocks);await n.onCompleteResponse(o,t);return}let e=await n.runWithTools();if(n.onToolBlocks&&n.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=M.getFullText(e.blocks);await n.onCompleteResponse(t,e);return}throw new Error(n.toolErrorMessage)}var C=n=>{let e=n.model??n.defaultModel,t=n.visionModel??(n.supportsVisionForModel(e)?e:n.defaultVisionModel);if(n.validate==="explicit"&&n.visionModel&&!n.supportsVisionForModel(n.visionModel))throw new Error(`Model ${n.visionModel} does not support vision capabilities.`);if(n.validate==="resolved"&&!n.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var dr="https://openrouter.ai/api/v1/models",mr=2,gr=12e3,_r=1,fr=10;function Gn(n){return n instanceof Error?n.message:String(n)}function No(n,e){return typeof n!="number"||!Number.isFinite(n)?e:Math.max(1,Math.floor(n))}function Er(n){let e=new Set,t=[];for(let o of n){let i=o.trim();!i||e.has(i)||(e.add(i),t.push(i))}return t}async function Ei(n,e,t){if(!(typeof AbortController<"u"))return fetch(n,e);let i=new AbortController,r=setTimeout(()=>i.abort(),t);try{return await fetch(n,{...e,signal:i.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?new Error(`Timeout after ${t}ms`):s}finally{clearTimeout(r)}}async function Mi(n){let e=`HTTP ${n.status} ${n.statusText}`.trim(),t="";try{t=await n.text()}catch{return e}let o=t.replace(/\s+/g," ").trim().slice(0,200);return o?`${e}: ${o}`:e}function Mr(n){if(!n||typeof n!="object")throw new Error("Invalid models response shape");let e=n,t=Array.isArray(e.data)?e.data:Array.isArray(e.models)?e.models:[];if(t.length===0)return[];let o=t.map(i=>i.id).filter(i=>typeof i=="string");return Er(o)}async function Or({modelId:n,apiKey:e,endpoint:t,timeoutMs:o,appName:i,appUrl:r}){let s={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};i&&(s["X-Title"]=i),r&&(s["HTTP-Referer"]=r);try{let l=await Ei(t,{method:"POST",headers:s,body:JSON.stringify({model:n,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},o);if(!l.ok)return{id:n,ok:!1,reason:await Mi(l)};try{await l.json()}catch(p){return{id:n,ok:!1,reason:`JSON parse failed: ${Gn(p)}`}}return{id:n,ok:!0}}catch(l){return{id:n,ok:!1,reason:Gn(l)}}}async function vr(n,e,t){if(n.length===0)return[];let o=new Array(n.length),i=0,r=Math.min(e,n.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<n.length;){let s=i;i+=1,o[s]=await t(n[s])}})),o}async function Sr(n){let e=n.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=n.modelsEndpoint||dr,o=n.endpoint||ut,i=No(n.timeoutMs,gr),r=No(n.concurrency,mr),s=No(n.maxCandidates,_r),l=No(n.maxWorking,fr),p=await Ei(t,{method:"GET"},i);if(!p.ok)throw new Error(await Mi(p));let c;try{c=await p.json()}catch(a){throw new Error(`JSON parse failed: ${Gn(a)}`)}let d=Mr(c).filter(a=>oe(a)).slice(0,s),u=await vr(d,r,a=>Or({modelId:a,apiKey:e,endpoint:o,timeoutMs:i,appName:n.appName,appUrl:n.appUrl})),m=u.filter(a=>a.ok).map(a=>a.id).slice(0,l),g=u.filter(a=>!a.ok).map(a=>({id:a.id,reason:a.reason||"Unknown error"}));return{working:m,failed:g,fetchedAt:Date.now()}}function Oi(n){return n.map(e=>({role:Lt(e.role),content:e.provider_content??e.content}))}function vi(n){return n.map(e=>{if(e.provider_content)return{role:Lt(e.role),content:e.provider_content};if(typeof e.content=="string")return{role:Lt(e.role),content:[{type:"text",text:e.content}]};if(Array.isArray(e.content)){let t=e.content.map(o=>{if(o.type==="image_url"){if(o.image_url.url.startsWith("data:")){let i=o.image_url.url.match(/^data:([^;]+);base64,(.+)$/);return i?{type:"image",source:{type:"base64",media_type:i[1],data:i[2]}}:null}return{type:"image",source:{type:"url",url:o.image_url.url,media_type:Cr(o.image_url.url)}}}return o}).filter(o=>o);return{role:Lt(e.role),content:t}}return{role:Lt(e.role),content:[]}})}function Lt(n){switch(n){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}function Cr(n){switch(n.split(".").pop()?.toLowerCase()){case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"gif":return"image/gif";case"webp":return"image/webp";default:return"image/jpeg"}}var Pe=class{constructor(e,t=b,o=b,i=[],r=[],s,l){this.provider="claude";if(this.apiKey=e,this.model=t||b,this.visionModel=o||b,this.tools=i,this.mcpServers=r,this.responseLength=s,this.reasoningEffort=l,!ct.includes(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`)}getModel(){return this.model}getVisionModel(){return this.visionModel}getMCPServers(){return this.mcpServers}addMCPServer(e){this.mcpServers.push(e)}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e)}hasMCPServers(){return this.mcpServers.length>0}async processChat(e,t,o){await O({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callClaude(e,this.model,!0);return this.parsePureStream(i,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){await O({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callClaude(e,this.visionModel,!0);return this.parsePureStream(i,t)},runWithTools:()=>this.visionChatOnce(e),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async callClaude(e,t,o,i){let r=e.find(u=>u.role==="system")?.content??"",s=e.filter(u=>u.role!=="system"),l=s.some(u=>Array.isArray(u.content)&&u.content.some(m=>m.type==="image_url"||m.type==="image")),p={model:t,system:r,messages:l?vi(s):Oi(s),stream:o,max_tokens:i!==void 0?i:T(this.responseLength)};this.reasoningEffort!==void 0&&N(t).includes(this.reasoningEffort)&&(p.output_config={effort:this.reasoningEffort}),this.tools.length&&(p.tools=this.tools.map(u=>({name:u.name,description:u.description,input_schema:u.parameters})),p.tool_choice={type:"auto"}),this.mcpServers.length>0&&(p.mcp_servers=this.mcpServers);let c={"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"};return this.mcpServers.length>0&&(c["anthropic-beta"]="mcp-client-2025-04-04"),await E.post(Yo,p,c)}async parseStream(e,t){let o=e.body.getReader(),i=new TextDecoder,r=[],s=new Map,l=new Map,p="";for(;;){let{done:c,value:d}=await o.read();if(c)break;p+=i.decode(d,{stream:!0});let u;for(;(u=p.indexOf(`
12
- `))!==-1;){let m=p.slice(0,u).trim();if(p=p.slice(u+1),!m.startsWith("data:"))continue;let g=m.slice(5).trim();if(g==="[DONE]")break;let a=JSON.parse(g);if(a.type==="content_block_start"&&a.content_block&&typeof a.index=="number"&&s.set(a.index,{...a.content_block}),a.type==="content_block_delta"&&a.delta?.type==="text_delta"){t(a.delta.text),r.push({type:"text",text:a.delta.text});let h=s.get(a.index);h?.type==="text"&&(h.text=`${h.text??""}${a.delta.text}`)}if(a.type==="content_block_delta"&&a.delta?.type==="thinking_delta"){let h=s.get(a.index);h?.type==="thinking"&&(h.thinking=`${h.thinking??""}${a.delta.thinking??""}`)}if(a.type==="content_block_delta"&&a.delta?.type==="signature_delta"){let h=s.get(a.index);h?.type==="thinking"&&(h.signature=`${h.signature??""}${a.delta.signature??""}`)}if(a.type==="content_block_start"&&a.content_block?.type==="tool_use"?l.set(a.index,{id:a.content_block.id,name:a.content_block.name,args:""}):a.type==="content_block_start"&&a.content_block?.type==="mcp_tool_use"?l.set(a.index,{id:a.content_block.id,name:a.content_block.name,args:"",server_name:a.content_block.server_name}):a.type==="content_block_start"&&a.content_block?.type==="tool_result"?r.push({type:"tool_result",tool_use_id:a.content_block.tool_use_id,content:a.content_block.content??""}):a.type==="content_block_start"&&a.content_block?.type==="mcp_tool_result"&&r.push({type:"mcp_tool_result",tool_use_id:a.content_block.tool_use_id,is_error:a.content_block.is_error??!1,content:a.content_block.content??[]}),a.type==="content_block_delta"&&a.delta?.type==="input_json_delta"){let h=l.get(a.index);h&&(h.args+=a.delta.partial_json||"")}if(a.type==="content_block_stop"&&l.has(a.index)){let{id:h,name:v,args:y,server_name:P}=l.get(a.index),_=JSON.parse(y||"{}"),f=s.get(a.index);f&&(f.input=_),P?r.push({type:"mcp_tool_use",id:h,name:v,server_name:P,input:_}):r.push({type:"tool_use",id:h,name:v,input:_}),l.delete(a.index)}}}return{blocks:r,providerContent:[...s.entries()].sort(([c],[d])=>c-d).map(([,c])=>c),stop_reason:r.some(c=>c.type==="tool_use"||c.type==="mcp_tool_use")?"tool_use":"end"}}async parsePureStream(e,t){let{blocks:o}=await this.parseStream(e,t);return o.filter(i=>i.type==="text").map(i=>i.text).join("")}parseOneShot(e){let t=[];return(e.content??[]).forEach(o=>{o.type==="text"?t.push({type:"text",text:o.text}):o.type==="tool_use"?t.push({type:"tool_use",id:o.id,name:o.name,input:o.input??{}}):o.type==="mcp_tool_use"?t.push({type:"mcp_tool_use",id:o.id,name:o.name,server_name:o.server_name,input:o.input??{}}):o.type==="tool_result"?t.push({type:"tool_result",tool_use_id:o.tool_use_id,content:o.content??""}):o.type==="mcp_tool_result"&&t.push({type:"mcp_tool_result",tool_use_id:o.tool_use_id,is_error:o.is_error??!1,content:o.content??[]})}),{blocks:t,providerContent:(e.content??[]).map(o=>({...o})),stop_reason:t.some(o=>o.type==="tool_use"||o.type==="mcp_tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callClaude(e,this.model,t,i),s=t?await this.parseStream(r,o):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callClaude(e,this.visionModel,t,i),s=t?await this.parseStream(r,o):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}convertToStandardCompletion(e){let t=e.blocks.filter(o=>o.type==="text"||o.type==="tool_use"||o.type==="tool_result");return{blocks:t,stop_reason:e.stop_reason,assistant_message:{role:"assistant",content:t.filter(o=>o.type==="text").map(o=>o.text).join(""),provider_content:e.providerContent}}}};var ye=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=N(t);if(e.reasoning_effort!==void 0&&!o.includes(e.reasoning_effort)){let r=o.length>0?`Supported values: ${o.join(", ")}.`:"This model does not expose configurable effort.";throw new Error(`Model ${t} does not support Claude reasoning_effort: ${e.reasoning_effort}. ${r}`)}let i=C({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"resolved"});return new Pe(e.apiKey,t,i,e.tools??[],e.mcpServers??[],e.responseLength,e.reasoning_effort)}getProviderName(){return"claude"}getSupportedModels(){return[kt,Vt,Ft,b,nt,it,rt,st,at,lt,pt,Gt]}getDefaultModel(){return b}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ct.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};async function wo(n,e,t={}){let o=n.body.getReader(),i=new TextDecoder,r=[],s=new Map,l,p,c,d="";for(;;){let{done:m,value:g}=await o.read();if(m)break;d+=i.decode(g,{stream:!0});let a="",h="",v=d.split(`
13
- `);d=v.pop()||"";for(let y=0;y<v.length;y++){let P=v[y].trim();if(P.startsWith("event:"))a=P.slice(6).trim();else if(P.startsWith("data:"))h=P.slice(5).trim();else if(P===""&&a&&h){try{let _=JSON.parse(h);Tr(a,_,e,r,s,t,f=>{f.responseStatus!==void 0&&(l=f.responseStatus),f.incompleteDetails!==void 0&&(p=f.incompleteDetails),f.usage!==void 0&&(c=f.usage)})}catch(_){t.onJsonError?.(h,_),console.warn("Failed to parse SSE data:",h)}a="",h=""}}}let u=Array.from(s.values()).map(m=>({type:"tool_use",id:m.id,name:m.name,input:m.input||{}}));return{blocks:[...r,...u],stop_reason:u.length?"tool_use":"end",truncated:l==="incomplete",response_status:l,incomplete_details:p,usage:c}}function Tr(n,e,t,o,i,r,s){switch(n){case"response.output_item.added":e.item?.type==="message"&&Array.isArray(e.item.content)?e.item.content.forEach(l=>{l.type==="output_text"&&l.text&&(t(l.text),M.append(o,l.text))}):e.item?.type==="function_call"&&i.set(e.item.id,{id:e.item.id,name:e.item.name,input:se(e.item.arguments,r.onJsonError)});break;case"response.content_part.added":e.part?.type==="output_text"&&typeof e.part.text=="string"&&(t(e.part.text),M.append(o,e.part.text));break;case"response.output_text.delta":case"response.content_part.delta":{let l=typeof e.delta=="string"?e.delta:e.delta?.text??"";l&&(t(l),M.append(o,l));break}case"response.output_text.done":case"response.content_part.done":case"response.reasoning.started":case"response.reasoning.delta":case"response.reasoning.done":break;case"response.completed":s(Si(e,"completed"));break;case"response.incomplete":s(Si(e,"incomplete"));break;default:break}}function Si(n,e){let t=n?.response??n;return{responseStatus:t?.status??e,incompleteDetails:t?.incomplete_details??null,usage:t?.usage}}function Ci(n,e={}){let t=[];return n.output&&Array.isArray(n.output)&&n.output.forEach(o=>{o.type==="message"&&o.content&&o.content.forEach(i=>{i.type==="output_text"&&i.text&&t.push({type:"text",text:i.text})}),o.type==="function_call"&&t.push({type:"tool_use",id:o.id,name:o.name,input:se(o.arguments,e.onJsonError)})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use")?"tool_use":"end",truncated:n?.status==="incomplete",response_status:n?.status,incomplete_details:n?.incomplete_details??null,usage:n?.usage}}function Ti({tools:n,mcpServers:e,isResponsesAPI:t}){let o=[];return n.length>0&&o.push(...A(n,t?"responses":"chat-completions")),e.length>0&&t&&o.push(...Lr(e)),o}function Lr(n){return n.map(e=>{let t={type:"mcp",server_label:e.name,server_url:e.url};return e.require_approval&&(t.require_approval=e.require_approval),e.tool_configuration?.allowed_tools&&(t.allowed_tools=e.tool_configuration.allowed_tools),e.authorization_token&&(t.headers={Authorization:`Bearer ${e.authorization_token}`}),t})}var Pr={[S.VERY_SHORT]:800,[S.SHORT]:1200,[S.MEDIUM]:2e3,[S.LONG]:3e3,[S.VERY_LONG]:8e3,[S.DEEP]:25e3},yr={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3,max:25e3},Ir=new Set(["openai-compatible","deepseek","mistral","sakana","plamo"]);function xr(n){return n.type!=="json_schema"?n:{type:n.type,...n.json_schema}}function Li({provider:n,endpoint:e,messages:t,model:o,stream:i,tools:r,mcpServers:s,responseLength:l,verbosity:p,reasoning_effort:c,enableReasoningSummary:d,responseFormat:u,maxTokens:m}){let g=e===D;Ar(e,s);let a={model:o,stream:i},h=Rr({provider:n,model:o,responseLength:l,reasoning_effort:c,maxTokens:m});g?h!==void 0&&(a.max_output_tokens=h):h!==void 0&&(Pi(n)?a.max_tokens=h:a.max_completion_tokens=h),g?a.input=Dr(t):a.messages=n==="mistral"?br(t):t,te(o)&&(g?(c&&(a.reasoning={...a.reasoning,effort:c},d&&(a.reasoning.summary="auto")),p&&(a.text={...a.text,format:{type:"text"},verbosity:p})):(c&&(a.reasoning_effort=c),p&&(a.verbosity=p))),u&&(g?a.text={...a.text,format:xr(u)}:a.response_format=u),n==="mistral"&&vt(o)&&c&&yn(c)&&(a.reasoning_effort=c),n==="plamo"&&c&&(a.reasoning_effort=c);let v=Ti({tools:r,mcpServers:s,isResponsesAPI:g});return v.length>0&&(a.tools=v,g||(a.tool_choice="auto")),a}function Rr({provider:n,model:e,responseLength:t,reasoning_effort:o,maxTokens:i}){if(i!==void 0)return i;let r=Pi(n)?t!==void 0?T(t):void 0:T(t);if(n!=="openai"||!te(e)||t===void 0)return r;let s=o??et(e);return Math.max(r??0,Pr[t],yr[s])}function Ar(n,e){if(e.length>0&&n===q)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${n}. Please use OpenAI Responses API endpoint: ${D}. MCP tools are only available in the Responses API endpoint.`)}function Dr(n){return n.map(e=>{let o={role:e.role==="tool"?"user":e.role};return typeof e.content=="string"?o.content=e.content:Array.isArray(e.content)?o.content=e.content.map(i=>i.type==="text"?{type:"input_text",text:i.text}:i.type==="image_url"?{type:"input_image",image_url:i.image_url.url}:i):o.content=e.content,o})}function br(n){return n.map(e=>{let t={role:e.role};return Array.isArray(e.content)?(t.content=e.content.map(o=>o.type==="image_url"&&typeof o.image_url=="object"&&typeof o.image_url?.url=="string"?{type:"image_url",image_url:o.image_url.url}:o),t):(t.content=e.content,t)})}function Pi(n){return Ir.has(n)}var L=class{constructor(e,t=ee,o=ee,i,r=q,s=[],l,p,c,d=!1,u="openai",m=!0,g){if(this.provider=u,this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.mcpServers=s,this.responseLength=l,this.verbosity=p,this.reasoning_effort=c,this.enableReasoningSummary=d,this.responseFormat=g,m&&!Ze.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await O({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.model,!0),r=this.endpoint===D;try{if(r){let s=await wo(i,t);return M.getFullText(s.blocks)}return this.handleStream(i,t)}catch(s){throw console.error("[processChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){try{await O({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.visionModel,!0),r=this.endpoint===D;try{if(r){let s=await wo(i,t);return M.getFullText(s.blocks)}return this.handleStream(i,t)}catch(s){throw console.error("[processVisionChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processVisionChat:",i),i}}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callOpenAI(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callOpenAI(e,this.visionModel,t,i);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return this.endpoint===D?t?wo(e,o):Ci(await e.json()):t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callOpenAI(e,t,o=!1,i){let r=Li({provider:this.provider,endpoint:this.endpoint,messages:e,model:t,stream:o,tools:this.tools,mcpServers:this.mcpServers,responseLength:this.responseLength,verbosity:this.verbosity,reasoning_effort:this.reasoning_effort,enableReasoningSummary:this.enableReasoningSummary,responseFormat:this.responseFormat,maxTokens:i}),s={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(s.Authorization=`Bearer ${this.apiKey}`),await E.post(this.endpoint,r,s)}async handleStream(e,t){return F(e,t)}async parseStream(e,t){return x(e,t,{appendTextBlock:M.addTextBlock})}parseOneShot(e){return R(e)}};var Ie=class extends L{constructor(e,t=Se,o=t,i,r=Mt,s){super(e,t,o,i,r,[],s,void 0,void 0,!1,"deepseek",!1)}};var xe=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new Ie(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength)}getProviderName(){return"deepseek"}getSupportedModels(){return[...En]}getDefaultModel(){return Se}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("deepseek provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return Mt}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var yi=(n,e)=>({name:`mcp_${n.name}_search`,description:e==="schema-fetch-failed"?`Search using ${n.name} MCP server (schema fetch failed)`:`Search using ${n.name} MCP server`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}),Go=class{static async fetchToolSchemas(e){return(await this.fetchToolSchemasWithStatus(e)).schemas}static async fetchToolSchemasWithStatus(e){try{let t={"Content-Type":"application/json"};e.authorization_token&&(t.Authorization=`Bearer ${e.authorization_token}`);let i=await(await E.post(`${e.url}/tools`,{},t)).json();return Array.isArray(i.tools)?{schemas:i.tools.map(r=>({name:`mcp_${e.name}_${r.name}`,description:r.description||`Tool from ${e.name} MCP server`,parameters:r.inputSchema||{type:"object",properties:{},required:[]}})),failures:[]}:{schemas:[yi(e)],failures:[]}}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),{schemas:[yi(e,"schema-fetch-failed")],failures:[{server:e,error:t}]}}}static async fetchAllToolSchemas(e){return(await this.fetchAllToolSchemasWithStatus(e)).schemas}static async fetchAllToolSchemasWithStatus(e){let t=[],o=[];for(let i of e)try{let r=await this.fetchToolSchemasWithStatus(i);t.push(...r.schemas),o.push(...r.failures)}catch(r){console.error(`Failed to fetch schemas from ${i.name}:`,r),o.push({server:i,error:r})}return{schemas:t,failures:o}}};function Ii(n){switch(n){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}function xi(n,e={}){let t=[],o=null,i=[],r=()=>{o&&i.length&&(t.push({role:o,parts:[...i]}),i=[]),o=null};for(let s of n){let l=Ii(s.role);if(s.tool_calls){r();let p=s.tool_calls.map(c=>Ai(c,e));p.length>0&&t.push({role:"model",parts:p});continue}if(s.role==="tool"){r(),bi(t,Di(s,e));continue}l!==o&&r(),o=l,i.push({text:s.content})}return r(),t}async function Ri(n,e={}){let t=e.imageFetcher??E.get,o=e.blobToBase64??Gr,i=[],r=null,s=[],l=()=>{r&&s.length>0&&(i.push({role:r,parts:[...s]}),s=[]),r=null};for(let p of n){let c=Ii(p.role);if(p.tool_calls){l();let d=p.tool_calls.map(u=>Ai(u,e));d.length>0&&i.push({role:"model",parts:d});continue}if(p.role==="tool"){l(),bi(i,Di(p,e));continue}if(c!==r&&s.length>0&&l(),r=c,typeof p.content=="string")s.push({text:p.content});else if(Array.isArray(p.content)){for(let d of p.content)if(d.type==="text")s.push({text:d.text});else if(d.type==="image_url")try{let m=await(await t(d.image_url.url)).blob(),g=await o(m);s.push({inlineData:{mimeType:m.type||"image/jpeg",data:g.split(",")[1]}})}catch(u){throw console.error("Error processing image:",u),new Error(`Failed to process image: ${u.message}`)}}}return l(),i}function Ai(n,e){e.callIdMap?.set(n.id,n.function.name);let t=e.functionCallContextMap?.get(n.id),o={functionCall:{...t?.providerCallId?{id:t.providerCallId}:{},name:n.function.name,args:JSON.parse(n.function.arguments||"{}")}};return t?.thoughtSignature&&(o.thoughtSignature=t.thoughtSignature),o}function Di(n,e){let t=n.tool_call_id,o=e.functionCallContextMap?.get(t);return{functionResponse:{...o?.providerCallId?{id:o.providerCallId}:{},name:n.name??o?.name??e.callIdMap?.get(t)??"result",response:wr(Nr(n.content))}}}function bi(n,e){let t=n[n.length-1];if(t?.role==="user"&&t.parts.every(i=>i.functionResponse)){t.parts.push(e);return}n.push({role:"user",parts:[e]})}function Nr(n){try{return JSON.parse(n)}catch{return n}}function wr(n){return n===null?{content:null}:typeof n=="object"?n:{content:n}}function Gr(n){return new Promise((e,t)=>{let o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=t,o.readAsDataURL(n)})}function kr(n,e){return[...n,...e].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}function Ni(n,e){let t=kr(n,e);if(t.length!==0)return{tools:[{functionDeclarations:t}],toolConfig:{functionCallingConfig:{mode:"AUTO"}}}}function wi(n){return n.map(e=>({name:`mcp_${e.name}_search`,description:`Search using ${e.name} MCP server (fallback)`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}))}var Re=class{constructor(e,t=$,o=$,i=[],r=[],s,l){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;this.functionCallContextMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=s,this.reasoningEffort=l,!tt.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=i,this.mcpServers=r}isGemma4Model(e){return/^gemma-4-/.test(e)}resolveThinkingConfig(e){let t=ot(e,this.reasoningEffort);if(t)return{includeThoughts:!1,thinkingLevel:t.toUpperCase()};if(this.isGemma4Model(e))return{includeThoughts:!1,thinkingLevel:"MINIMAL"}}shouldExposeTextPart(e,t){return!(!e.text||this.isGemma4Model(t)&&e.thought===!0)}adaptKeysForApi(e){let t={toolConfig:"tool_config",functionCallingConfig:"function_calling_config",functionDeclarations:"function_declarations",functionCall:"function_call",functionResponse:"function_response",thoughtSignature:"thought_signature"};return Array.isArray(e)?e.map(o=>this.adaptKeysForApi(o)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([o,i])=>[t[o]??o,this.adaptKeysForApi(i)])):e}getModel(){return this.model}getVisionModel(){return this.visionModel}getMCPServers(){return this.mcpServers}addMCPServer(e){this.mcpServers.push(e),this.mcpSchemasInitialized=!1,this.mcpSchemaInitializationError=void 0}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e),this.mcpSchemasInitialized=!1,this.mcpSchemaInitializationError=void 0}hasMCPServers(){return this.mcpServers.length>0}getMCPSchemaInitializationError(){return this.mcpSchemaInitializationError}async initializeMCPSchemas(){if(!(this.mcpSchemasInitialized||this.mcpServers.length===0))try{let e=new Promise((i,r)=>setTimeout(()=>r(new Error("MCP schema fetch timeout")),5e3)),t=Go.fetchAllToolSchemasWithStatus(this.mcpServers),o=await Promise.race([t,e]);this.mcpToolSchemas=o.schemas,this.mcpSchemasInitialized=!0,this.mcpSchemaInitializationError=o.failures[0]?.error}catch(e){console.warn("Failed to initialize MCP schemas, using fallback:",e),this.mcpSchemaInitializationError=e,this.mcpToolSchemas=wi(this.mcpServers),this.mcpSchemasInitialized=!0}}async processChat(e,t,o){try{await O({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callGemini(e,this.model,!0),{blocks:r}=await this.parseStream(i,t,this.model);return M.getFullText(r)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use chatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processChat:",i),i}}async processVisionChat(e,t,o){try{await O({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callGemini(e,this.visionModel,!0),{blocks:r}=await this.parseStream(i,t,this.visionModel);return M.getFullText(r)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:i=>{i.filter(r=>r.type==="text").forEach(r=>t(r.text))},onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use visionChatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processVisionChat:",i),i}}async callGemini(e,t,o=!1,i){let l={contents:e.some(_=>Array.isArray(_.content)&&_.content.some(f=>f?.type==="image_url"||f?.inlineData))?await Ri(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}):xi(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}),generationConfig:{maxOutputTokens:i!==void 0?i:T(this.responseLength)}},p=this.resolveThinkingConfig(t);p&&(l.generationConfig.thinkingConfig=p);let c=[];if(this.mcpServers.length>0)try{await this.initializeMCPSchemas(),c=this.mcpToolSchemas}catch(_){console.warn("MCP initialization failed, skipping MCP tools:",_)}let d=Ni(this.tools,c);d&&Object.assign(l,d);let u=async(_,f)=>{let I=o?"streamGenerateContent":"generateContent",Vn=o?"?alt=sse":"",Fi=`${Bo}/${_}/models/${t}:${I}${Vn}${Vn?"&":"?"}key=${this.apiKey}`;return E.post(Fi,f)},m=/flash[-_]lite/.test(t),g=this.isGemma4Model(t),a=/gemini-2\.5/.test(t),h=/^gemini-3(?:\.[0-9]+)?-/.test(t),v=m||g||a||h,y=v?"v1beta":"v1",P=async()=>{try{let _=y==="v1"?l:this.adaptKeysForApi(l);return await u(y,_)}catch(_){let f=/Unknown name|Cannot find field|404/.test(_?.message||"")||_?.status===404;if(!v&&f)try{return await u("v1beta",this.adaptKeysForApi(l))}catch(I){throw I instanceof Error&&(I.cause=_),I}throw _}};try{return await P()}catch(_){throw _.body&&(console.error("Gemini API Error Details:",_.body),console.error("Request Body:",JSON.stringify(l,null,2))),_}}createFunctionCallBlock(e){let t=e.functionCall??e.function_call;if(!t)return;let o=t.id??this.genUUID();return this.callIdMap.set(o,t.name),this.functionCallContextMap.set(o,{name:t.name,providerCallId:t.id,thoughtSignature:e.thoughtSignature??e.thought_signature}),{type:"tool_use",id:o,name:t.name,input:t.args??{}}}createFunctionResponseBlock(e){let t=e.functionResponse??e.function_response;if(t)return{type:"tool_result",tool_use_id:t.id??t.name,content:JSON.stringify(t.response)}}async parseStream(e,t,o){let i=e.body.getReader(),r=new TextDecoder,s=[],l=[],p="",c=u=>{if(!u||u==="[DONE]")return;let m;try{m=JSON.parse(u)}catch{return}for(let g of m.candidates??[])for(let a of g.content?.parts??[]){this.shouldExposeTextPart(a,o)&&(t(a.text),M.addTextBlock(s,a.text));let h=this.createFunctionCallBlock(a);h&&l.push(h);let v=this.createFunctionResponseBlock(a);v&&l.push(v)}};for(;;){let{done:u,value:m}=await i.read();if(u)break;p+=r.decode(m,{stream:!0});let g;for(;(g=p.indexOf(`
14
- `))!==-1;){let a=p.slice(0,g);if(p=p.slice(g+1),a.endsWith("\r")&&(a=a.slice(0,-1)),!a.trim()){c("");continue}a.startsWith("data:")&&(a=a.slice(5).trim()),a&&c(a)}}return p&&c(p),{blocks:[...s,...l],stop_reason:l.some(u=>u.type==="tool_use")?"tool_use":"end"}}parseOneShot(e,t){let o=[],i=[];for(let s of e.candidates??[])for(let l of s.content?.parts??[]){this.shouldExposeTextPart(l,t)&&o.push({type:"text",text:l.text});let p=this.createFunctionCallBlock(l);p&&i.push(p);let c=this.createFunctionResponseBlock(l);c&&i.push(c)}return{blocks:[...o,...i],stop_reason:i.some(s=>s.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callGemini(e,this.model,t,i);return t?this.parseStream(r,o,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callGemini(e,this.visionModel,t,i);return t?this.parseStream(r,o,this.visionModel):this.parseOneShot(await r.json(),this.visionModel)}genUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}};var Ae=class{createChatService(e){let t=e.model||this.getDefaultModel();if(e.reasoning_effort!==void 0&&!Zo(t))throw new Error(`Model ${t} does not support Gemini reasoning_effort. Use it with Gemini 3 thinkingLevel models; Gemini 2.5 models use thinkingBudget instead.`);let o=C({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"resolved"});return new Re(e.apiKey,t,o,e.tools||[],e.mcpServers||[],e.responseLength,ot(t,e.reasoning_effort))}getProviderName(){return"gemini"}getSupportedModels(){return[...bt]}getDefaultModel(){return $}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return tt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function Vr(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var De=class{constructor(e={}){this.provider="gemini-nano";this.expectedInputLanguages=e.expectedInputLanguages??["ja","en"],this.expectedOutputLanguages=e.expectedOutputLanguages??["ja"],this.initialPrompts=(e.initialPrompts??[]).map(t=>({...t})),this._responseLength=e.responseLength}getModel(){return re}getVisionModel(){return re}async processChat(e,t,o){let i=await this.generateResponse(e);t(i),await o(i)}async processVisionChat(e,t,o){throw new Error("Gemini Nano does not support vision capabilities.")}async chatOnce(e,t=!1,o=()=>{},i){let r=await this.generateResponse(e);return o(r),{blocks:[{type:"text",text:r}],stop_reason:"end"}}async visionChatOnce(e,t=!1,o=()=>{},i){throw new Error("Gemini Nano does not support vision capabilities.")}async generateResponse(e){let t=Vr();if(!t)throw new Error("Gemini Nano is not available in this environment. Chrome 138+ with Prompt API enabled is required.");let o=this.getModelOptions(),i=await t.availability(o);if(i!=="available"&&i!=="downloadable")throw new Error(`Gemini Nano Prompt API is not ready in this environment. LanguageModel.availability() returned "${i}". Expected "available" or "downloadable".`);let s=e.filter(u=>u.role==="system").map(u=>u.content).join(`
15
- `),l=e.filter(u=>u.role==="user"||u.role==="assistant").slice(-20),p=this.findLastUserMessageIndex(l);if(p===-1)throw new Error("No user message found in the provided messages.");let c=l[p],d=await this.createSession(t,s,l.slice(0,p),o);try{return await d.prompt(c.content)}finally{try{d.destroy()}catch{}}}async createSession(e,t,o,i){let r=this.buildInitialPrompts(t,o),s={...i,...r.length>0?{initialPrompts:r}:{}};return e.create(s)}getModelOptions(){return{expectedInputs:[{type:"text",languages:this.expectedInputLanguages}],expectedOutputs:[{type:"text",languages:this.expectedOutputLanguages}]}}buildInitialPrompts(e,t){let o=this.initialPrompts.filter(s=>s.role==="system").map(s=>s.content),i=this.buildSystemPrompt([e,...o].filter(Boolean).join(`
10
+ `;var le="gemini-nano",$n=20;var X=class extends Error{constructor(t,o,i){super(`HTTP ${t}: ${o}`);this.status=t;this.statusText=o;this.body=i;this.name="HttpError"}},Dt=class Dt{static setFetch(e){this.fetchImpl=e}static async post(e,t,o={},i={}){let{timeout:r=3e4,retries:s=0,retryDelay:a=1e3}=i,c={...{"Content-Type":"application/json"},...o},d=null;for(let u=0;u<=s;u++)try{let m=typeof AbortController<"u",f=m?new AbortController:void 0,l=m?setTimeout(()=>f.abort(),r):void 0,h=await Dt.fetchImpl(e,{method:"POST",headers:c,body:typeof t=="string"?t:JSON.stringify(t),...f?{signal:f.signal}:{}});if(l&&clearTimeout(l),!h.ok){let v=await h.text();throw new X(h.status,h.statusText,v)}return h}catch(m){if(d=m,m instanceof X&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError")throw new Error(`Request timeout after ${r}ms`);u<s&&await new Promise(f=>setTimeout(f,a*(u+1)))}throw d||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new X(e.status,e.statusText,t)}static async get(e,t={},o={}){let{timeout:i=3e4,retries:r=0,retryDelay:s=1e3}=o,a=null;for(let p=0;p<=r;p++)try{let c=typeof AbortController<"u",d=c?new AbortController:void 0,u=c?setTimeout(()=>d.abort(),i):void 0,m=await Dt.fetchImpl(e,{method:"GET",headers:t,...d?{signal:d.signal}:{}});if(u&&clearTimeout(u),!m.ok){let f=await m.text();throw new X(m.status,m.statusText,f)}return m}catch(c){if(a=c,c instanceof X&&c.status>=400&&c.status<500)throw c;if(c instanceof Error&&c.name==="AbortError")throw new Error(`Request timeout after ${i}ms`);p<r&&await new Promise(d=>setTimeout(d,s*(p+1)))}throw a||new Error("Request failed")}};Dt.fetchImpl=(e,t)=>fetch(e,t);var _=Dt;var E=class{static append(e,t){if(!t)return;let o=e[e.length-1];o&&o.type==="text"?o.text+=t:e.push({type:"text",text:t})}static getFullText(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}static addTextBlock(e,t){t&&e.push({type:"text",text:t})}};var Ir=["happy","sad","angry","surprised","neutral"],yi=/\[([a-z]+)\]/i,zn=/\[[a-z]+\]\s*/gi,Ie=class{static extractEmotion(e){let t=e.match(yi);if(t){let o=t[1].toLowerCase(),i=e.replace(zn,"").trim();return{emotion:o,cleanText:i}}return{cleanText:e}}static isValidEmotion(e){return Ir.includes(e)}static cleanEmotionTags(e){return e.replace(zn,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function Pi(n){let{emotion:e,cleanText:t}=Ie.extractEmotion(n);return e?{emotion:e,text:t}:{text:t}}function Dr(n){return n.map(e=>Pi(e))}function Ar(n){return n.emotion?Ie.addEmotionTag(n.emotion,n.text):n.text}async function br(n,e){let{blocks:t}=await n.chatOnce(e,!1,()=>{});return E.getFullText(t)}var Ri=(n,e,t)=>{try{return JSON.parse(n)}catch(o){return t?.(n,o),e}},pe=(n,e)=>n?Ri(n,{},e):{};var xi=(n,e)=>{try{return JSON.parse(n)}catch(t){if(e){e(n,t);return}throw t}},Bo=n=>typeof n=="string"?n:Array.isArray(n)?n.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&e.type==="text"&&typeof e.text=="string"?e.text:"").join(""):"",jn=n=>{let e=n.choices?.[0],t=n.error??e?.error;if(!t&&e?.finish_reason!=="error")return;let o=typeof t=="string"?t:typeof t?.message=="string"?t.message:"The provider ended the response with an error.";throw new Error(`Provider response error: ${o}`)},Ii=async(n,e)=>{let t=n.body?.getReader();if(!t)throw new Error("Response body is null.");let o=new TextDecoder,i="",r=!1;for(;!r;){let{done:s,value:a}=await t.read();if(s)break;i+=o.decode(a,{stream:!0});let p=i.split(`
11
+ `);i=p.pop()||"";for(let c of p){let d=c.trim();if(!d||d.startsWith(":")||!d.startsWith("data:"))continue;let u=d.slice(5).trim();if(u==="[DONE]"){r=!0;break}e(u)}}};async function K(n,e,t={}){let o="";return await Ii(n,i=>{let r=xi(i,t.onJsonError);if(!r)return;t.throwOnApiError&&jn(r);let s=Bo(r.choices?.[0]?.delta?.content);s&&(e(s),o+=s)}),o}async function x(n,e,t={}){let o=[],i=new Map,r="",s="",a,p,c=t.appendTextBlock??E.append;await Ii(n,l=>{let h=xi(l,t.onJsonError);if(!h)return;t.throwOnApiError&&jn(h);let v=h.choices?.[0];typeof v?.finish_reason=="string"&&(a=v.finish_reason),h.usage&&(p=h.usage);let P=v?.delta,C=Bo(P?.content);C&&(e(C),c(o,C),r+=C);let R=Bo(P?.reasoning_content);R&&(s+=R),P?.tool_calls&&P.tool_calls.forEach(g=>{let S=i.get(g.index)??{id:g.id,type:g.type,name:g.function?.name,args:""};g.id&&(S.id=g.id),g.type&&(S.type=g.type),g.function?.name&&(S.name=g.function.name),S.args+=g.function?.arguments||"",i.set(g.index,S)})});let d=Array.from(i.entries()).sort((l,h)=>l[0]-h[0]).map(([l,h])=>({type:"tool_use",id:h.id,name:h.name,input:pe(h.args,t.onJsonError)})),u=[...o,...d],m=Array.from(i.entries()).sort((l,h)=>l[0]-h[0]).map(([l,h])=>({id:h.id,type:"function",function:{name:h.name,arguments:h.args}})),f={role:"assistant",content:r,...s?{reasoning_content:s}:{},...m.length>0?{tool_calls:m}:{}};return{blocks:u,stop_reason:d.length?"tool_use":"end",truncated:a==="length",finish_reason:a,usage:p,...t.preserveAssistantMessage?{assistant_message:f}:{}}}function I(n,e={}){e.throwOnApiError&&jn(n);let t=n?.choices?.[0],o=[],i=Bo(t?.message?.content);t?.message?.tool_calls?.length?t.message.tool_calls.forEach(s=>o.push({type:"tool_use",id:s.id,name:s.function?.name,input:pe(s.function?.arguments,e.onJsonError)})):i&&o.push({type:"text",text:i});let r=t?.message?{...t.message,role:"assistant",content:i}:void 0;return{blocks:o,stop_reason:t?.finish_reason==="tool_calls"||o.some(s=>s.type==="tool_use")?"tool_use":"end",truncated:t?.finish_reason==="length",finish_reason:t?.finish_reason,usage:n?.usage,...e.preserveAssistantMessage?{assistant_message:r}:{}}}var D=(n,e="chat-completions")=>n.length===0?[]:e==="responses"?n.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):n.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function M(n){if(!n.hasTools){let t=await n.runWithoutTools();if(typeof t=="string"){await n.onCompleteResponse(t);return}let o=E.getFullText(t.blocks);await n.onCompleteResponse(o,t);return}let e=await n.runWithTools();if(n.onToolBlocks&&n.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=E.getFullText(e.blocks);await n.onCompleteResponse(t,e);return}throw new Error(n.toolErrorMessage)}var T=n=>{let e=n.model??n.defaultModel,t=n.visionModel??(n.supportsVisionForModel(e)?e:n.defaultVisionModel);if(n.validate==="explicit"&&n.visionModel&&!n.supportsVisionForModel(n.visionModel))throw new Error(`Model ${n.visionModel} does not support vision capabilities.`);if(n.validate==="resolved"&&!n.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var Nr="https://openrouter.ai/api/v1/models",wr=2,kr=12e3,Gr=1,Vr=10;function qn(n){return n instanceof Error?n.message:String(n)}function Wo(n,e){return typeof n!="number"||!Number.isFinite(n)?e:Math.max(1,Math.floor(n))}function Fr(n){let e=new Set,t=[];for(let o of n){let i=o.trim();!i||e.has(i)||(e.add(i),t.push(i))}return t}async function Di(n,e,t){if(!(typeof AbortController<"u"))return fetch(n,e);let i=new AbortController,r=setTimeout(()=>i.abort(),t);try{return await fetch(n,{...e,signal:i.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?new Error(`Timeout after ${t}ms`):s}finally{clearTimeout(r)}}async function Ai(n){let e=`HTTP ${n.status} ${n.statusText}`.trim(),t="";try{t=await n.text()}catch{return e}let o=t.replace(/\s+/g," ").trim().slice(0,200);return o?`${e}: ${o}`:e}function Ur(n){if(!n||typeof n!="object")throw new Error("Invalid models response shape");let e=n,t=Array.isArray(e.data)?e.data:Array.isArray(e.models)?e.models:[];if(t.length===0)return[];let o=t.map(i=>i.id).filter(i=>typeof i=="string");return Fr(o)}async function Kr({modelId:n,apiKey:e,endpoint:t,timeoutMs:o,appName:i,appUrl:r}){let s={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};i&&(s["X-Title"]=i),r&&(s["HTTP-Referer"]=r);try{let a=await Di(t,{method:"POST",headers:s,body:JSON.stringify({model:n,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},o);if(!a.ok)return{id:n,ok:!1,reason:await Ai(a)};try{await a.json()}catch(p){return{id:n,ok:!1,reason:`JSON parse failed: ${qn(p)}`}}return{id:n,ok:!0}}catch(a){return{id:n,ok:!1,reason:qn(a)}}}async function Hr(n,e,t){if(n.length===0)return[];let o=new Array(n.length),i=0,r=Math.min(e,n.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<n.length;){let s=i;i+=1,o[s]=await t(n[s])}})),o}async function Br(n){let e=n.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=n.modelsEndpoint||Nr,o=n.endpoint||ft,i=Wo(n.timeoutMs,kr),r=Wo(n.concurrency,wr),s=Wo(n.maxCandidates,Gr),a=Wo(n.maxWorking,Vr),p=await Di(t,{method:"GET"},i);if(!p.ok)throw new Error(await Ai(p));let c;try{c=await p.json()}catch(l){throw new Error(`JSON parse failed: ${qn(l)}`)}let d=Ur(c).filter(l=>ie(l)).slice(0,s),u=await Hr(d,r,l=>Kr({modelId:l,apiKey:e,endpoint:o,timeoutMs:i,appName:n.appName,appUrl:n.appUrl})),m=u.filter(l=>l.ok).map(l=>l.id).slice(0,a),f=u.filter(l=>!l.ok).map(l=>({id:l.id,reason:l.reason||"Unknown error"}));return{working:m,failed:f,fetchedAt:Date.now()}}function bi(n){return n.map(e=>({role:At(e.role),content:e.provider_content??e.content}))}function Ni(n){return n.map(e=>{if(e.provider_content)return{role:At(e.role),content:e.provider_content};if(typeof e.content=="string")return{role:At(e.role),content:[{type:"text",text:e.content}]};if(Array.isArray(e.content)){let t=e.content.map(o=>{if(o.type==="image_url"){if(o.image_url.url.startsWith("data:")){let i=o.image_url.url.match(/^data:([^;]+);base64,(.+)$/);return i?{type:"image",source:{type:"base64",media_type:i[1],data:i[2]}}:null}return{type:"image",source:{type:"url",url:o.image_url.url,media_type:Wr(o.image_url.url)}}}return o}).filter(o=>o);return{role:At(e.role),content:t}}return{role:At(e.role),content:[]}})}function At(n){switch(n){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}function Wr(n){switch(n.split(".").pop()?.toLowerCase()){case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"gif":return"image/gif";case"webp":return"image/webp";default:return"image/jpeg"}}var De=class{constructor(e,t=b,o=b,i=[],r=[],s,a){this.provider="claude";if(this.apiKey=e,this.model=t||b,this.visionModel=o||b,this.tools=i,this.mcpServers=r,this.responseLength=s,this.reasoningEffort=a,!gt.includes(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`)}getModel(){return this.model}getVisionModel(){return this.visionModel}getMCPServers(){return this.mcpServers}addMCPServer(e){this.mcpServers.push(e)}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e)}hasMCPServers(){return this.mcpServers.length>0}async processChat(e,t,o){await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callClaude(e,this.model,!0);return this.parsePureStream(i,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callClaude(e,this.visionModel,!0);return this.parsePureStream(i,t)},runWithTools:()=>this.visionChatOnce(e),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async callClaude(e,t,o,i){let r=e.find(u=>u.role==="system")?.content??"",s=e.filter(u=>u.role!=="system"),a=s.some(u=>Array.isArray(u.content)&&u.content.some(m=>m.type==="image_url"||m.type==="image")),p={model:t,system:r,messages:a?Ni(s):bi(s),stream:o,max_tokens:i!==void 0?i:L(this.responseLength)};this.reasoningEffort!==void 0&&k(t).includes(this.reasoningEffort)&&(p.output_config={effort:this.reasoningEffort}),this.tools.length&&(p.tools=this.tools.map(u=>({name:u.name,description:u.description,input_schema:u.parameters})),p.tool_choice={type:"auto"}),this.mcpServers.length>0&&(p.mcp_servers=this.mcpServers);let c={"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"};return this.mcpServers.length>0&&(c["anthropic-beta"]="mcp-client-2025-04-04"),await _.post(pn,p,c)}async parseStream(e,t){let o=e.body.getReader(),i=new TextDecoder,r=[],s=new Map,a=new Map,p="";for(;;){let{done:c,value:d}=await o.read();if(c)break;p+=i.decode(d,{stream:!0});let u;for(;(u=p.indexOf(`
12
+ `))!==-1;){let m=p.slice(0,u).trim();if(p=p.slice(u+1),!m.startsWith("data:"))continue;let f=m.slice(5).trim();if(f==="[DONE]")break;let l=JSON.parse(f);if(l.type==="content_block_start"&&l.content_block&&typeof l.index=="number"&&s.set(l.index,{...l.content_block}),l.type==="content_block_delta"&&l.delta?.type==="text_delta"){t(l.delta.text),r.push({type:"text",text:l.delta.text});let h=s.get(l.index);h?.type==="text"&&(h.text=`${h.text??""}${l.delta.text}`)}if(l.type==="content_block_delta"&&l.delta?.type==="thinking_delta"){let h=s.get(l.index);h?.type==="thinking"&&(h.thinking=`${h.thinking??""}${l.delta.thinking??""}`)}if(l.type==="content_block_delta"&&l.delta?.type==="signature_delta"){let h=s.get(l.index);h?.type==="thinking"&&(h.signature=`${h.signature??""}${l.delta.signature??""}`)}if(l.type==="content_block_start"&&l.content_block?.type==="tool_use"?a.set(l.index,{id:l.content_block.id,name:l.content_block.name,args:""}):l.type==="content_block_start"&&l.content_block?.type==="mcp_tool_use"?a.set(l.index,{id:l.content_block.id,name:l.content_block.name,args:"",server_name:l.content_block.server_name}):l.type==="content_block_start"&&l.content_block?.type==="tool_result"?r.push({type:"tool_result",tool_use_id:l.content_block.tool_use_id,content:l.content_block.content??""}):l.type==="content_block_start"&&l.content_block?.type==="mcp_tool_result"&&r.push({type:"mcp_tool_result",tool_use_id:l.content_block.tool_use_id,is_error:l.content_block.is_error??!1,content:l.content_block.content??[]}),l.type==="content_block_delta"&&l.delta?.type==="input_json_delta"){let h=a.get(l.index);h&&(h.args+=l.delta.partial_json||"")}if(l.type==="content_block_stop"&&a.has(l.index)){let{id:h,name:v,args:P,server_name:C}=a.get(l.index),R=JSON.parse(P||"{}"),g=s.get(l.index);g&&(g.input=R),C?r.push({type:"mcp_tool_use",id:h,name:v,server_name:C,input:R}):r.push({type:"tool_use",id:h,name:v,input:R}),a.delete(l.index)}}}return{blocks:r,providerContent:[...s.entries()].sort(([c],[d])=>c-d).map(([,c])=>c),stop_reason:r.some(c=>c.type==="tool_use"||c.type==="mcp_tool_use")?"tool_use":"end"}}async parsePureStream(e,t){let{blocks:o}=await this.parseStream(e,t);return o.filter(i=>i.type==="text").map(i=>i.text).join("")}parseOneShot(e){let t=[];return(e.content??[]).forEach(o=>{o.type==="text"?t.push({type:"text",text:o.text}):o.type==="tool_use"?t.push({type:"tool_use",id:o.id,name:o.name,input:o.input??{}}):o.type==="mcp_tool_use"?t.push({type:"mcp_tool_use",id:o.id,name:o.name,server_name:o.server_name,input:o.input??{}}):o.type==="tool_result"?t.push({type:"tool_result",tool_use_id:o.tool_use_id,content:o.content??""}):o.type==="mcp_tool_result"&&t.push({type:"mcp_tool_result",tool_use_id:o.tool_use_id,is_error:o.is_error??!1,content:o.content??[]})}),{blocks:t,providerContent:(e.content??[]).map(o=>({...o})),stop_reason:t.some(o=>o.type==="tool_use"||o.type==="mcp_tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callClaude(e,this.model,t,i),s=t?await this.parseStream(r,o):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callClaude(e,this.visionModel,t,i),s=t?await this.parseStream(r,o):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}convertToStandardCompletion(e){let t=e.blocks.filter(o=>o.type==="text"||o.type==="tool_use"||o.type==="tool_result");return{blocks:t,stop_reason:e.stop_reason,assistant_message:{role:"assistant",content:t.filter(o=>o.type==="text").map(o=>o.text).join(""),provider_content:e.providerContent}}}};var Ae=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=k(t);if(e.reasoning_effort!==void 0&&!o.includes(e.reasoning_effort)){let r=o.length>0?`Supported values: ${o.join(", ")}.`:"This model does not expose configurable effort.";throw new Error(`Model ${t} does not support Claude reasoning_effort: ${e.reasoning_effort}. ${r}`)}let i=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"resolved"});return new De(e.apiKey,t,i,e.tools??[],e.mcpServers??[],e.responseLength,e.reasoning_effort)}getProviderName(){return"claude"}getSupportedModels(){return[Wt,$t,zt,b,lt,pt,ct,ut,ht,dt,mt,Bt]}getDefaultModel(){return b}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return gt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};async function $o(n,e,t={}){let o=n.body.getReader(),i=new TextDecoder,r=[],s=new Map,a=new Map,p,c,d,u="";for(;;){let{done:h,value:v}=await o.read();if(h)break;u+=i.decode(v,{stream:!0});let P="",C="",R=u.split(`
13
+ `);u=R.pop()||"";for(let g=0;g<R.length;g++){let S=R[g].trim();if(S.startsWith("event:"))P=S.slice(6).trim();else if(S.startsWith("data:"))C=S.slice(5).trim();else if(S===""&&P&&C){try{let N=JSON.parse(C);$r(P,N,e,r,s,a,w=>{w.responseStatus!==void 0&&(p=w.responseStatus),w.incompleteDetails!==void 0&&(c=w.incompleteDetails),w.usage!==void 0&&(d=w.usage)})}catch(N){t.onJsonError?.(C,N),console.warn("Failed to parse SSE data:",C)}P="",C=""}}}let m=Array.from(s.values()).map(h=>({type:"tool_use",id:h.id,name:h.name,input:pe(h.arguments,t.onJsonError)})),f=Array.from(a.values()),l=E.getFullText(r);return{blocks:[...r,...m],stop_reason:m.length?"tool_use":"end",truncated:p==="incomplete",response_status:p,incomplete_details:c,usage:d,...f.length>0?{assistant_message:{role:"assistant",content:l,provider_content:f}}:{}}}function $r(n,e,t,o,i,r,s){switch(n){case"response.output_item.added":wi(r,e.item),e.item?.type==="message"&&Array.isArray(e.item.content)?e.item.content.forEach(a=>{a.type==="output_text"&&a.text&&(t(a.text),E.append(o,a.text))}):e.item?.type==="function_call"&&i.set(e.item.id,{id:e.item.call_id??e.item.id,name:e.item.name,arguments:e.item.arguments??""});break;case"response.function_call_arguments.delta":{let a=i.get(e.item_id);a&&typeof e.delta=="string"&&(a.arguments+=e.delta);let p=r.get(e.item_id);p&&typeof e.delta=="string"&&(p.arguments=`${p.arguments??""}${e.delta}`);break}case"response.function_call_arguments.done":{let a=i.get(e.item_id);a&&typeof e.arguments=="string"&&(a.arguments=e.arguments);let p=r.get(e.item_id);p&&typeof e.arguments=="string"&&(p.arguments=e.arguments);break}case"response.output_item.done":wi(r,e.item),e.item?.type==="function_call"&&i.set(e.item.id,{id:e.item.call_id??e.item.id,name:e.item.name,arguments:e.item.arguments??""});break;case"response.content_part.added":e.part?.type==="output_text"&&typeof e.part.text=="string"&&(t(e.part.text),E.append(o,e.part.text));break;case"response.output_text.delta":case"response.content_part.delta":{let a=typeof e.delta=="string"?e.delta:e.delta?.text??"";a&&(t(a),E.append(o,a));break}case"response.output_text.done":case"response.content_part.done":case"response.reasoning.started":case"response.reasoning.delta":case"response.reasoning.done":break;case"response.completed":s(ki(e,"completed"));break;case"response.incomplete":s(ki(e,"incomplete"));break;default:break}}function wi(n,e){if(!e||typeof e!="object")return;let t=typeof e.id=="string"&&e.id?e.id:`output-item-${n.size}`;n.set(t,{...e})}function ki(n,e){let t=n?.response??n;return{responseStatus:t?.status??e,incompleteDetails:t?.incomplete_details??null,usage:t?.usage}}function Gi(n,e={}){let t=[];return n.output&&Array.isArray(n.output)&&n.output.forEach(o=>{o.type==="message"&&o.content&&o.content.forEach(i=>{i.type==="output_text"&&i.text&&t.push({type:"text",text:i.text})}),o.type==="function_call"&&t.push({type:"tool_use",id:o.call_id??o.id,name:o.name,input:pe(o.arguments,e.onJsonError)})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use")?"tool_use":"end",truncated:n?.status==="incomplete",response_status:n?.status,incomplete_details:n?.incomplete_details??null,usage:n?.usage,...Array.isArray(n?.output)&&n.output.length>0?{assistant_message:{role:"assistant",content:t.filter(o=>o.type==="text").map(o=>o.text).join(""),provider_content:n.output}}:{}}}function Vi({tools:n,mcpServers:e,isResponsesAPI:t}){let o=[];return n.length>0&&o.push(...D(n,t?"responses":"chat-completions")),e.length>0&&t&&o.push(...zr(e)),o}function zr(n){return n.map(e=>{let t={type:"mcp",server_label:e.name,server_url:e.url};return e.require_approval&&(t.require_approval=e.require_approval),e.tool_configuration?.allowed_tools&&(t.allowed_tools=e.tool_configuration.allowed_tools),e.authorization_token&&(t.headers={Authorization:`Bearer ${e.authorization_token}`}),t})}var jr={[O.VERY_SHORT]:800,[O.SHORT]:1200,[O.MEDIUM]:2e3,[O.LONG]:3e3,[O.VERY_LONG]:8e3,[O.DEEP]:25e3},qr={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3,max:25e3},Xr=new Set(["openai-compatible","deepseek","mistral","sakana","plamo"]);function Jr(n){return n.type!=="json_schema"?n:{type:n.type,...n.json_schema}}function Fi({provider:n,endpoint:e,messages:t,model:o,stream:i,tools:r,mcpServers:s,responseLength:a,verbosity:p,reasoning_effort:c,enableReasoningSummary:d,responseFormat:u,maxTokens:m}){let f=e===A;Yr(e,s);let l={model:o,stream:i},h=Zr({provider:n,model:o,responseLength:a,reasoning_effort:c,maxTokens:m});f?h!==void 0&&(l.max_output_tokens=h):h!==void 0&&(Ui(n)?l.max_tokens=h:l.max_completion_tokens=h),f?l.input=Qr(t):l.messages=n==="mistral"?es(t):t,ne(o)&&(f?(c&&(l.reasoning={...l.reasoning,effort:c},d&&(l.reasoning.summary="auto")),p&&(l.text={...l.text,format:{type:"text"},verbosity:p})):(c&&(l.reasoning_effort=c),p&&(l.verbosity=p))),u&&(f?l.text={...l.text,format:Jr(u)}:l.response_format=u),n==="mistral"&&Rt(o)&&c&&Fn(c)&&(l.reasoning_effort=c),n==="plamo"&&c&&(l.reasoning_effort=c),n==="deepseek"&&c&&(l.thinking={type:c==="none"?"disabled":"enabled"},c!=="none"&&(l.reasoning_effort=c));let v=Vi({tools:r,mcpServers:s,isResponsesAPI:f});return v.length>0&&(l.tools=v,f||(l.tool_choice="auto")),l}function Zr({provider:n,model:e,responseLength:t,reasoning_effort:o,maxTokens:i}){if(i!==void 0)return i;let r=Ui(n)?t!==void 0?L(t):void 0:L(t);if(n!=="openai"||!ne(e)||t===void 0)return r;let s=o??rt(e);return Math.max(r??0,jr[t],qr[s])}function Yr(n,e){if(e.length>0&&n===J)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${n}. Please use OpenAI Responses API endpoint: ${A}. MCP tools are only available in the Responses API endpoint.`)}function Qr(n){return n.flatMap(e=>{if(e.role==="assistant"&&e.provider_content?.length)return e.provider_content;if(e.role==="tool"&&e.tool_call_id)return[{type:"function_call_output",call_id:e.tool_call_id,output:e.content}];let t=[],o={role:e.role==="tool"?"user":e.role};return typeof e.content=="string"?o.content=e.content:Array.isArray(e.content)?o.content=e.content.map(r=>r.type==="text"?{type:"input_text",text:r.text}:r.type==="image_url"?{type:"input_image",image_url:r.image_url.url}:r):o.content=e.content,(typeof o.content!="string"||o.content.length>0)&&t.push(o),e.role==="assistant"&&e.tool_calls&&t.push(...e.tool_calls.map(r=>({type:"function_call",call_id:r.id,name:r.function.name,arguments:r.function.arguments}))),t})}function es(n){return n.map(e=>{let t={role:e.role};return Array.isArray(e.content)?(t.content=e.content.map(o=>o.type==="image_url"&&typeof o.image_url=="object"&&typeof o.image_url?.url=="string"?{type:"image_url",image_url:o.image_url.url}:o),t):(t.content=e.content,t)})}function Ui(n){return Xr.has(n)}var y=class{constructor(e,t=oe,o=oe,i,r=J,s=[],a,p,c,d=!1,u="openai",m=!0,f){if(this.provider=u,this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.mcpServers=s,this.responseLength=a,this.verbosity=p,this.reasoning_effort=c,this.enableReasoningSummary=d,this.responseFormat=f,m&&!ot.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.model,!0),r=this.endpoint===A;try{if(r){let s=await $o(i,t);return E.getFullText(s.blocks)}return this.handleStream(i,t)}catch(s){throw console.error("[processChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){try{await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.visionModel,!0),r=this.endpoint===A;try{if(r){let s=await $o(i,t);return E.getFullText(s.blocks)}return this.handleStream(i,t)}catch(s){throw console.error("[processVisionChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processVisionChat:",i),i}}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callOpenAI(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callOpenAI(e,this.visionModel,t,i);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return this.endpoint===A?t?$o(e,o):Gi(await e.json()):t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callOpenAI(e,t,o=!1,i){let r=Fi({provider:this.provider,endpoint:this.endpoint,messages:e,model:t,stream:o,tools:this.tools,mcpServers:this.mcpServers,responseLength:this.responseLength,verbosity:this.verbosity,reasoning_effort:this.reasoning_effort,enableReasoningSummary:this.enableReasoningSummary,responseFormat:this.responseFormat,maxTokens:i}),s={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(s.Authorization=`Bearer ${this.apiKey}`),await _.post(this.endpoint,r,s)}async handleStream(e,t){return K(e,t)}async parseStream(e,t){return x(e,t,{appendTextBlock:E.addTextBlock})}parseOneShot(e){return I(e)}};var be=class extends y{constructor(e,t=ae,o=t,i,r=Lt,s,a){let p=In(t,a);if(super(e,t,o,i,r,[],s,void 0,p,!1,"deepseek",!1),i?.length&&p!==void 0&&p!=="none")throw new Error("DeepSeek thinking with tools is not supported yet. Use reasoning_effort: 'none' for tool calling.")}};var Ne=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new be(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"deepseek"}getSupportedModels(){return[...xn]}getDefaultModel(){return ae}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("deepseek provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return Lt}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Ki=(n,e)=>({name:`mcp_${n.name}_search`,description:e==="schema-fetch-failed"?`Search using ${n.name} MCP server (schema fetch failed)`:`Search using ${n.name} MCP server`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}),zo=class{static async fetchToolSchemas(e){return(await this.fetchToolSchemasWithStatus(e)).schemas}static async fetchToolSchemasWithStatus(e){try{let t={"Content-Type":"application/json"};e.authorization_token&&(t.Authorization=`Bearer ${e.authorization_token}`);let i=await(await _.post(`${e.url}/tools`,{},t)).json();return Array.isArray(i.tools)?{schemas:i.tools.map(r=>({name:`mcp_${e.name}_${r.name}`,description:r.description||`Tool from ${e.name} MCP server`,parameters:r.inputSchema||{type:"object",properties:{},required:[]}})),failures:[]}:{schemas:[Ki(e)],failures:[]}}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),{schemas:[Ki(e,"schema-fetch-failed")],failures:[{server:e,error:t}]}}}static async fetchAllToolSchemas(e){return(await this.fetchAllToolSchemasWithStatus(e)).schemas}static async fetchAllToolSchemasWithStatus(e){let t=[],o=[];for(let i of e)try{let r=await this.fetchToolSchemasWithStatus(i);t.push(...r.schemas),o.push(...r.failures)}catch(r){console.error(`Failed to fetch schemas from ${i.name}:`,r),o.push({server:i,error:r})}return{schemas:t,failures:o}}};function Hi(n){switch(n){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}function Bi(n,e={}){let t=[],o=null,i=[],r=()=>{o&&i.length&&(t.push({role:o,parts:[...i]}),i=[]),o=null};for(let s of n){if(s.role==="system")continue;let a=Hi(s.role);if(s.tool_calls){r();let p=s.tool_calls.map(c=>zi(c,e));p.length>0&&t.push({role:"model",parts:p});continue}if(s.role==="tool"){r(),qi(t,ji(s,e));continue}a!==o&&r(),o=a,i.push({text:s.content})}return r(),t}async function Wi(n,e={}){let t=e.imageFetcher??_.get,o=e.blobToBase64??ns,i=[],r=null,s=[],a=()=>{r&&s.length>0&&(i.push({role:r,parts:[...s]}),s=[]),r=null};for(let p of n){if(p.role==="system")continue;let c=Hi(p.role);if(p.tool_calls){a();let d=p.tool_calls.map(u=>zi(u,e));d.length>0&&i.push({role:"model",parts:d});continue}if(p.role==="tool"){a(),qi(i,ji(p,e));continue}if(c!==r&&s.length>0&&a(),r=c,typeof p.content=="string")s.push({text:p.content});else if(Array.isArray(p.content)){for(let d of p.content)if(d.type==="text")s.push({text:d.text});else if(d.type==="image_url")try{let m=await(await t(d.image_url.url)).blob(),f=await o(m);s.push({inlineData:{mimeType:m.type||"image/jpeg",data:f.split(",")[1]}})}catch(u){throw console.error("Error processing image:",u),new Error(`Failed to process image: ${u.message}`)}}}return a(),i}function $i(n){let e=n.flatMap(t=>t.role!=="system"?[]:typeof t.content=="string"?t.content?[{text:t.content}]:[]:t.content.flatMap(o=>o.type==="text"&&o.text?[{text:o.text}]:[]));return e.length>0?{parts:e}:void 0}function zi(n,e){e.callIdMap?.set(n.id,n.function.name);let t=e.functionCallContextMap?.get(n.id),o={functionCall:{...t?.providerCallId?{id:t.providerCallId}:{},name:n.function.name,args:JSON.parse(n.function.arguments||"{}")}};return t?.thoughtSignature&&(o.thoughtSignature=t.thoughtSignature),o}function ji(n,e){let t=n.tool_call_id,o=e.functionCallContextMap?.get(t);return{functionResponse:{...o?.providerCallId?{id:o.providerCallId}:{},name:n.name??o?.name??e.callIdMap?.get(t)??"result",response:os(ts(n.content))}}}function qi(n,e){let t=n[n.length-1];if(t?.role==="user"&&t.parts.every(i=>i.functionResponse)){t.parts.push(e);return}n.push({role:"user",parts:[e]})}function ts(n){try{return JSON.parse(n)}catch{return n}}function os(n){return n===null?{content:null}:typeof n=="object"?n:{content:n}}function ns(n){return new Promise((e,t)=>{let o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=t,o.readAsDataURL(n)})}function is(n,e){return[...n,...e].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}function Xi(n,e){let t=is(n,e);if(t.length!==0)return{tools:[{functionDeclarations:t}],toolConfig:{functionCallingConfig:{mode:"AUTO"}}}}function Ji(n){return n.map(e=>({name:`mcp_${e.name}_search`,description:`Search using ${e.name} MCP server (fallback)`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}))}var we=class{constructor(e,t=j,o=j,i=[],r=[],s,a){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;this.functionCallContextMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=s,this.reasoningEffort=a,!st.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=i,this.mcpServers=r}isGemma4Model(e){return/^gemma-4-/.test(e)}resolveThinkingConfig(e){let t=at(e,this.reasoningEffort);if(t)return{includeThoughts:!1,thinkingLevel:t.toUpperCase()};if(this.isGemma4Model(e))return{includeThoughts:!1,thinkingLevel:"MINIMAL"}}shouldExposeTextPart(e,t){return!(!e.text||this.isGemma4Model(t)&&e.thought===!0)}adaptKeysForApi(e){let t={toolConfig:"tool_config",functionCallingConfig:"function_calling_config",functionDeclarations:"function_declarations",functionCall:"function_call",functionResponse:"function_response",thoughtSignature:"thought_signature"};return Array.isArray(e)?e.map(o=>this.adaptKeysForApi(o)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([o,i])=>[t[o]??o,this.adaptKeysForApi(i)])):e}getModel(){return this.model}getVisionModel(){return this.visionModel}getMCPServers(){return this.mcpServers}addMCPServer(e){this.mcpServers.push(e),this.mcpSchemasInitialized=!1,this.mcpSchemaInitializationError=void 0}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e),this.mcpSchemasInitialized=!1,this.mcpSchemaInitializationError=void 0}hasMCPServers(){return this.mcpServers.length>0}getMCPSchemaInitializationError(){return this.mcpSchemaInitializationError}async initializeMCPSchemas(){if(!(this.mcpSchemasInitialized||this.mcpServers.length===0))try{let e=new Promise((i,r)=>setTimeout(()=>r(new Error("MCP schema fetch timeout")),5e3)),t=zo.fetchAllToolSchemasWithStatus(this.mcpServers),o=await Promise.race([t,e]);this.mcpToolSchemas=o.schemas,this.mcpSchemasInitialized=!0,this.mcpSchemaInitializationError=o.failures[0]?.error}catch(e){console.warn("Failed to initialize MCP schemas, using fallback:",e),this.mcpSchemaInitializationError=e,this.mcpToolSchemas=Ji(this.mcpServers),this.mcpSchemasInitialized=!0}}async processChat(e,t,o){try{await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callGemini(e,this.model,!0),{blocks:r}=await this.parseStream(i,t,this.model);return E.getFullText(r)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use chatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processChat:",i),i}}async processVisionChat(e,t,o){try{await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callGemini(e,this.visionModel,!0),{blocks:r}=await this.parseStream(i,t,this.visionModel);return E.getFullText(r)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:i=>{i.filter(r=>r.type==="text").forEach(r=>t(r.text))},onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use visionChatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processVisionChat:",i),i}}async callGemini(e,t,o=!1,i){let a={contents:e.some(g=>Array.isArray(g.content)&&g.content.some(S=>S?.type==="image_url"||S?.inlineData))?await Wi(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}):Bi(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}),generationConfig:{maxOutputTokens:i!==void 0?i:L(this.responseLength)}},p=$i(e);p&&(a.systemInstruction=p);let c=this.resolveThinkingConfig(t);c&&(a.generationConfig.thinkingConfig=c);let d=[];if(this.mcpServers.length>0)try{await this.initializeMCPSchemas(),d=this.mcpToolSchemas}catch(g){console.warn("MCP initialization failed, skipping MCP tools:",g)}let u=Xi(this.tools,d);u&&Object.assign(a,u);let m=async(g,S)=>{let N=o?"streamGenerateContent":"generateContent",w=o?"?alt=sse":"",tr=`${Qo}/${g}/models/${t}:${N}${w}${w?"&":"?"}key=${this.apiKey}`;return _.post(tr,S)},f=/flash[-_]lite/.test(t),l=this.isGemma4Model(t),h=/gemini-2\.5/.test(t),v=/^gemini-3(?:\.[0-9]+)?-/.test(t),P=f||l||h||v,C=P?"v1beta":"v1",R=async()=>{try{let g=C==="v1"?a:this.adaptKeysForApi(a);return await m(C,g)}catch(g){let S=/Unknown name|Cannot find field|404/.test(g?.message||"")||g?.status===404;if(!P&&S)try{return await m("v1beta",this.adaptKeysForApi(a))}catch(N){throw N instanceof Error&&(N.cause=g),N}throw g}};try{return await R()}catch(g){throw g.body&&(console.error("Gemini API Error Details:",g.body),console.error("Request Body:",JSON.stringify(a,null,2))),g}}createFunctionCallBlock(e){let t=e.functionCall??e.function_call;if(!t)return;let o=t.id??this.genUUID();return this.callIdMap.set(o,t.name),this.functionCallContextMap.set(o,{name:t.name,providerCallId:t.id,thoughtSignature:e.thoughtSignature??e.thought_signature}),{type:"tool_use",id:o,name:t.name,input:t.args??{}}}createFunctionResponseBlock(e){let t=e.functionResponse??e.function_response;if(t)return{type:"tool_result",tool_use_id:t.id??t.name,content:JSON.stringify(t.response)}}async parseStream(e,t,o){let i=e.body.getReader(),r=new TextDecoder,s=[],a=[],p="",c=u=>{if(!u||u==="[DONE]")return;let m;try{m=JSON.parse(u)}catch{return}for(let f of m.candidates??[])for(let l of f.content?.parts??[]){this.shouldExposeTextPart(l,o)&&(t(l.text),E.addTextBlock(s,l.text));let h=this.createFunctionCallBlock(l);h&&a.push(h);let v=this.createFunctionResponseBlock(l);v&&a.push(v)}};for(;;){let{done:u,value:m}=await i.read();if(u)break;p+=r.decode(m,{stream:!0});let f;for(;(f=p.indexOf(`
14
+ `))!==-1;){let l=p.slice(0,f);if(p=p.slice(f+1),l.endsWith("\r")&&(l=l.slice(0,-1)),!l.trim()){c("");continue}l.startsWith("data:")&&(l=l.slice(5).trim()),l&&c(l)}}return p&&c(p),{blocks:[...s,...a],stop_reason:a.some(u=>u.type==="tool_use")?"tool_use":"end"}}parseOneShot(e,t){let o=[],i=[];for(let s of e.candidates??[])for(let a of s.content?.parts??[]){this.shouldExposeTextPart(a,t)&&o.push({type:"text",text:a.text});let p=this.createFunctionCallBlock(a);p&&i.push(p);let c=this.createFunctionResponseBlock(a);c&&i.push(c)}return{blocks:[...o,...i],stop_reason:i.some(s=>s.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callGemini(e,this.model,t,i);return t?this.parseStream(r,o,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callGemini(e,this.visionModel,t,i);return t?this.parseStream(r,o,this.visionModel):this.parseOneShot(await r.json(),this.visionModel)}genUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}};var ke=class{createChatService(e){let t=e.model||this.getDefaultModel();if(e.reasoning_effort!==void 0&&!ln(t))throw new Error(`Model ${t} does not support Gemini reasoning_effort. Use it with Gemini 3 thinkingLevel models; Gemini 2.5 models use thinkingBudget instead.`);let o=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"resolved"});return new we(e.apiKey,t,o,e.tools||[],e.mcpServers||[],e.responseLength,at(t,e.reasoning_effort))}getProviderName(){return"gemini"}getSupportedModels(){return[...Ut]}getDefaultModel(){return j}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return st.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function rs(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var Ge=class{constructor(e={}){this.provider="gemini-nano";this.expectedInputLanguages=e.expectedInputLanguages??["ja","en"],this.expectedOutputLanguages=e.expectedOutputLanguages??["ja"],this.initialPrompts=(e.initialPrompts??[]).map(t=>({...t})),this._responseLength=e.responseLength}getModel(){return le}getVisionModel(){return le}async processChat(e,t,o){let i=await this.generateResponse(e);t(i),await o(i)}async processVisionChat(e,t,o){throw new Error("Gemini Nano does not support vision capabilities.")}async chatOnce(e,t=!1,o=()=>{},i){let r=await this.generateResponse(e);return o(r),{blocks:[{type:"text",text:r}],stop_reason:"end"}}async visionChatOnce(e,t=!1,o=()=>{},i){throw new Error("Gemini Nano does not support vision capabilities.")}async generateResponse(e){let t=rs();if(!t)throw new Error("Gemini Nano is not available in this environment. Chrome 148+ on a supported desktop device is required for web pages.");let o=this.getModelOptions(),i=await t.availability(o);if(i!=="available"&&i!=="downloadable")throw new Error(`Gemini Nano Prompt API is not ready in this environment. LanguageModel.availability() returned "${i}". Expected "available" or "downloadable".`);let s=e.filter(u=>u.role==="system").map(u=>u.content).join(`
15
+ `),a=e.filter(u=>u.role==="user"||u.role==="assistant").slice(-20),p=this.findLastUserMessageIndex(a);if(p===-1)throw new Error("No user message found in the provided messages.");let c=a[p],d=await this.createSession(t,s,a.slice(0,p),o);try{return await d.prompt(c.content)}finally{try{d.destroy()}catch{}}}async createSession(e,t,o,i){let r=this.buildInitialPrompts(t,o),s={...i,...r.length>0?{initialPrompts:r}:{}};return e.create(s)}getModelOptions(){return{expectedInputs:[{type:"text",languages:this.expectedInputLanguages}],expectedOutputs:[{type:"text",languages:this.expectedOutputLanguages}]}}buildInitialPrompts(e,t){let o=this.initialPrompts.filter(s=>s.role==="system").map(s=>s.content),i=this.buildSystemPrompt([e,...o].filter(Boolean).join(`
16
16
 
17
- `)),r=[];return i&&r.push({role:"system",content:i}),r.push(...this.initialPrompts.filter(s=>s.role!=="system").map(s=>({...s})),...t.filter(s=>s.role==="user"||s.role==="assistant").map(({role:s,content:l})=>({role:s,content:l}))),r}findLastUserMessageIndex(e){for(let t=e.length-1;t>=0;t-=1)if(e[t].role==="user")return t;return-1}buildSystemPrompt(e){let t=[];e&&t.push(e);let o=this.getResponseLengthInstruction();return o&&t.push(o),t.join(`
17
+ `)),r=[];return i&&r.push({role:"system",content:i}),r.push(...this.initialPrompts.filter(s=>s.role!=="system").map(s=>({...s})),...t.filter(s=>s.role==="user"||s.role==="assistant").map(({role:s,content:a})=>({role:s,content:a}))),r}findLastUserMessageIndex(e){for(let t=e.length-1;t>=0;t-=1)if(e[t].role==="user")return t;return-1}buildSystemPrompt(e){let t=[];e&&t.push(e);let o=this.getResponseLengthInstruction();return o&&t.push(o),t.join(`
18
18
 
19
- `)}getResponseLengthInstruction(){if(!this._responseLength)return;let e=Do[this._responseLength];if(e)switch(this._responseLength){case S.VERY_SHORT:return`Reply in no more than one concise sentence. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Stay within approximately ${e} tokens.`;case S.SHORT:return`Reply in no more than two concise sentences. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Use natural conversational language. Stay within approximately ${e} tokens.`;case S.MEDIUM:return`Reply in no more than three concise sentences. Answer directly and include only the context needed to understand the answer. Do not use a preamble, summary, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case S.LONG:return`Reply in no more than five sentences. Explain the important details clearly, but avoid unnecessary preambles, repetition, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case S.VERY_LONG:return`Reply in no more than ten sentences. Give a thorough but focused answer. Use short plain-text paragraphs when helpful, and avoid unnecessary repetition, bullet points, or Markdown. Stay within approximately ${e} tokens.`;case S.DEEP:return`Give a detailed response and organize it in the way that best fits the request. No sentence-count limit applies at this level. Stay within approximately ${e} tokens.`}}};var be=class{createChatService(e){return new De({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,initialPrompts:e.initialPrompts,responseLength:e.responseLength})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[re]}getDefaultModel(){return re}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var Ne=class{constructor(e,t=k,o=k,i,r=Ee,s,l,p,c){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.responseFormat=l,this.thinking=p;let d=z(t);if(c!==void 0&&!d.includes(c))throw new Error(`Model ${t} does not support reasoning_effort: ${c}.`);this.reasoningEffort=c??ve(t),this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await O({hasTools:this.tools.length>0,runWithoutTools:()=>this.chatOnce(e,!0,t),runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!Oe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await O({hasTools:this.tools.length>0,runWithoutTools:()=>this.visionChatOnce(e,!0,t),runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callKimi(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!Oe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callKimi(e,this.visionModel,t,i);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callKimi(e,t,o=!1,i){let r=this.buildRequestBody(e,t,o,i);return await E.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:T(this.responseLength);s!==void 0&&(ie(t)?r.max_completion_tokens=s:r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),ie(t)&&(r.reasoning_effort=this.reasoningEffort??ve(t));let l=this.resolveEffectiveThinking(t);l&&(this.isSelfHostedEndpoint()?l.type==="disabled"&&(r.chat_template_kwargs={thinking:!1}):r.thinking=l);let p=this.buildToolsDefinition();return p.length>0&&(r.tools=p,r.tool_choice="auto"),r}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(Ee)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveEffectiveThinking(e){if(ie(e)){if(this.thinking)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(Et(e)){if(this.thinking?.type==="disabled")throw new Error(`Model ${e} requires thinking mode and does not support thinking: disabled.`);return this.thinking??{type:"enabled"}}return this.tools.length>0?{type:"disabled"}:this.thinking??{type:"enabled"}}buildToolsDefinition(){return A(this.tools,"chat-completions")}async parseStream(e,t){return x(e,t,{preserveAssistantMessage:!0,onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return R(e,{preserveAssistantMessage:!0})}};var we=class{constructor(){this.defaultThinking={type:"enabled"}}createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),i=C({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:p=>this.supportsVisionForModel(p),validate:"explicit"}),r=e.tools,s=this.resolveThinking(o,r,e.thinking),l=this.resolveReasoningEffort(o,e.reasoning_effort);return new Ne(e.apiKey,o,i,r,t,e.responseLength,e.responseFormat,s,l)}getProviderName(){return"kimi"}getSupportedModels(){return[Me,_t,ft,k,Ro]}getDefaultModel(){return k}getDefaultVisionModel(){return k}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Oe(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}resolveEndpoint(e){if(e.endpoint)return this.normalizeEndpoint(e.endpoint);if(e.baseUrl){let t=this.normalizeEndpoint(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return Ee}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveThinking(e,t,o){if(ie(e)){if(o)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(Et(e)){if(o?.type==="disabled")throw new Error(`Model ${e} requires thinking mode and does not support thinking: disabled.`);return o??this.defaultThinking}return t&&t.length>0?{type:"disabled"}:o??this.defaultThinking}resolveReasoningEffort(e,t){let o=z(e);if(o.length===0){if(t!==void 0)throw new Error(`Model ${e} does not support the reasoning_effort option.`);return}let i=t??ve(e)??o[0];if(!o.includes(i))throw new Error(`Model ${e} supports reasoning_effort values: ${o.join(", ")}.`);return i}};var Ge=class extends L{constructor(e,t=V,o=t,i,r=Ot,s,l){super(e,t,o,i,r,[],s,void 0,l,!1,"mistral",!1)}};var ke=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=C({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=vt(t)?e.reasoning_effort:void 0;return new Ge(e.apiKey,t,o,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"mistral"}getSupportedModels(){return[...Pn]}getDefaultModel(){return V}getDefaultVisionModel(){return V}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return In(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("mistral provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return Ot}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Ve=class{createChatService(e){this.validateRequiredOptions(e);let t=[e.apiKey?.trim()??"",e.model,e.visionModel??e.model,e.tools,e.endpoint,[],e.responseLength,e.verbosity,e.reasoning_effort,e.enableReasoningSummary,this.getProviderName(),!1];return e.responseFormat!==void 0&&t.push(e.responseFormat),new L(...t)}getProviderName(){return"openai-compatible"}getSupportedModels(){return[]}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"unknown"}supportsVisionForModel(e){return!0}getVisionSupportLevelForModel(e){return"unknown"}getDefaultModel(){return"local-model"}validateRequiredOptions(e){if(e.mcpServers!==void 0)throw new Error("openai-compatible provider does not support mcpServers.");let t=e.endpoint?.trim();if(!t)throw new Error("openai-compatible provider requires endpoint (full URL).");let o;try{o=new URL(t)}catch{throw new Error("openai-compatible provider requires endpoint to be a full URL.")}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error("openai-compatible provider requires endpoint to be a full URL.");if(!e.model?.trim())throw new Error("openai-compatible provider requires model.")}};var Fe=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=C({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:d=>this.supportsVisionForModel(d),validate:"resolved"}),i=t.tools,r=t.mcpServers??[],s=t.model||this.getDefaultModel(),l=!1;r.length>0||Ko(s)?l=!0:te(s)&&(l=(t.gpt5EndpointPreference||"chat")==="responses");let p=t.endpoint||(l?D:q),c=[t.apiKey,s,o,i,p,r,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName()];return t.responseFormat!==void 0&&c.push(!0,t.responseFormat),new L(...c)}getProviderName(){return"openai"}getSupportedModels(){return[X,ae,le,pe,J,Z,U,K,H,B,Y,Q,W,yt,It,xt,ee,Rt,Vo,Fo,"o1"]}getDefaultModel(){return X}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ze.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!te(t))return e;let o={...e};if(e.gpt5Preset){let i=Dn[e.gpt5Preset];o.reasoning_effort=i.reasoning_effort,o.verbosity=i.verbosity}else e.reasoning_effort||(o.reasoning_effort=et(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!Ye(e)||t==="minimal"&&!Qe(e)?t==="minimal"&&Ye(e)?"none":t==="none"&&Qe(e)?"minimal":Dt(e)?"low":"medium":t==="low"&&!Dt(e)?"medium":t==="xhigh"&&!At(e)?"high":t==="max"&&!Ho(e)?At(e)?"xhigh":"high":t}};var Pt=n=>[ht,ce].includes(n.trim()),Fr=n=>[w,ue].includes(n.trim()),Ur=n=>n.trim()===ue?"none":void 0,kn=(n,e)=>{if(Pt(n)&&!e)throw new Error("OpenRouter Auto Router returned no visible content. Please retry.")},Gi=n=>n.blocks.some(e=>e.type!=="text"||e.text.trim().length>0),Ue=class{constructor(e,t=w,o=w,i,r=ut,s,l,p,c,d,u){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.appName=l,this.appUrl=p,this.reasoning_effort=c,this.includeReasoning=d,this.reasoningMaxTokens=u,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!oe(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=ln){let o=6e4-t;o>0&&(console.log(`Rate limit reached for free tier. Waiting ${o}ms...`),await new Promise(i=>setTimeout(i,o)),this.requestCount=0)}this.lastRequestTime=e,this.requestCount++}async processChat(e,t,o){await this.applyRateLimiting(),await O({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.model,!0);return this.handleStream(i,t,this.model)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!he(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await O({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(i,t,this.visionModel)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processVisionChat:",i),i}}async chatOnce(e,t=!0,o=()=>{},i){await this.applyRateLimiting();let r=await this.callOpenRouter(e,this.model,t,i);return t?this.parseStream(r,o,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!he(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let r=await this.callOpenRouter(e,this.visionModel,t,i);return t?this.parseStream(r,o,this.visionModel):this.parseOneShot(await r.json(),this.visionModel)}async callOpenRouter(e,t,o=!1,i){let r=this.buildRequestBody(e,t,o,i),s={Authorization:`Bearer ${this.apiKey}`};return this.appUrl&&(s["HTTP-Referer"]=this.appUrl),this.appName&&(s["X-Title"]=this.appName),await E.post(this.endpoint,r,s)}buildRequestBody(e,t,o,i){let r={model:t,messages:e,stream:o},s=i!==void 0?i:T(this.responseLength),l=Fr(t)||Pt(t)&&i===void 0;s&&l?console.warn(`OpenRouter: Token limits are disabled for ${t} because this model can return empty content when a token limit is set.`):s&&(r.max_tokens=s);let p=Ur(t);if(this.reasoning_effort!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens||p){if(r.reasoning={},this.reasoning_effort&&this.reasoning_effort!=="none"){let c=this.reasoning_effort==="minimal"?"low":this.reasoning_effort;r.reasoning.effort=c}else this.reasoning_effort===void 0&&p&&(r.reasoning.effort=p);(this.reasoning_effort==="none"||this.includeReasoning!==!0)&&(r.reasoning.exclude=!0),this.reasoningMaxTokens&&(r.reasoning.max_tokens=this.reasoningMaxTokens)}else r.reasoning={exclude:!0};return this.tools.length>0&&(r.tools=A(this.tools,"chat-completions"),r.tool_choice="auto"),r}async handleStream(e,t,o){let i=await F(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:Pt(o)});return kn(o,i.trim().length>0),i}async parseStream(e,t,o){let i=await x(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:Pt(o)});return kn(o,Gi(i)),i}parseOneShot(e,t){let o=R(e,{throwOnApiError:Pt(t)});return kn(t,Gi(o)),o}};var Ke=class{createChatService(e){let t=C({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:e.model||this.getDefaultModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),o=e.tools,i=e.appName,r=e.appUrl;return new Ue(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,i,r,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[ht,ce,en,w,Mo,Wt,$t,zt,jt,qt,Xt,Jt,Zt,Yt,Qt,eo,to,oo,no,io,ro,so,ao,lo,po,tn,co,uo,ho,mo,go,_o,fo,Eo,ue,on,nn,Oo,vo,Bt,Ut,Kt,Ht,rn,sn]}getDefaultModel(){return w}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return he(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return an}isModelFree(e){return oe(e)}};var He=class extends L{constructor(e,t=Te,o=t,i,r=Ct,s,l){super(e,t,o,i,r,[],s,void 0,l,!1,"plamo",!1)}};var Be=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new He(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"plamo"}getSupportedModels(){return[...Rn]}getDefaultModel(){return Te}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("plamo provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return Ct}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var We=class extends L{constructor(e,t=Ce,o=t,i,r=St,s){super(e,t,o,i,r,[],s,void 0,void 0,!1,"sakana",!1)}};var $e=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new We(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength)}getProviderName(){return"sakana"}getSupportedModels(){return[...xn]}getDefaultModel(){return Ce}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("sakana provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return St}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var ze=class{constructor(e,t=G,o=G,i,r=mt,s,l){this.provider="xai";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.visionModel=o,this.reasoningEffort=l}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await O({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callXAI(e,this.model,!0);return this.handleStream(i,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!fe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await O({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callXAI(e,this.visionModel,!0);return this.handleStream(i,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callXAI(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!fe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callXAI(e,this.visionModel,t,i);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callXAI(e,t,o=!1,i){let r=this.buildRequestBody(e,t,o,i);return await E.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:T(this.responseLength);s!==void 0&&(r.max_tokens=s),this.reasoningEffort&&Io(t)&&(r.reasoning_effort=gt(t,this.reasoningEffort));let l=this.buildToolsDefinition();return l.length>0&&(r.tools=l,r.tool_choice="auto"),r}buildToolsDefinition(){return A(this.tools,"chat-completions")}async handleStream(e,t){return F(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return R(e)}};var je=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=C({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"explicit"}),i=e.tools;return new ze(e.apiKey,t,o,i,e.endpoint||mt,e.responseLength,gt(t,e.reasoning_effort??xo(t)))}getProviderName(){return"xai"}getSupportedModels(){return[ge,_e,Lo,Po,yo,G]}getDefaultModel(){return G}getDefaultVisionModel(){return G}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return fe(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var qe=class{constructor(e,t=de,o=ne,i,r=dt,s,l,p){this.provider="zai";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.responseFormat=l,this.thinking=p??{type:"disabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await O({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callZAI(e,this.model,!0);return this.handleStream(i,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!me(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await O({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callZAI(e,this.visionModel,!0);return this.handleStream(i,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callZAI(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!me(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callZAI(e,this.visionModel,t,i);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callZAI(e,t,o=!1,i){let r=this.buildRequestBody(e,t,o,i);return await E.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:T(this.responseLength);s!==void 0&&(r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),this.thinking&&(r.thinking=this.thinking);let l=this.buildToolsDefinition();return l.length>0&&(r.tools=l,r.tool_choice="auto",o&&_n(t)&&(r.tool_stream=!0)),r}buildToolsDefinition(){return A(this.tools,"chat-completions")}async handleStream(e,t){return F(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return R(e)}};var Xe=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=C({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=e.thinking??{type:"disabled"};return new qe(e.apiKey,t,o,i,e.endpoint||dt,e.responseLength,e.responseFormat,r)}getProviderName(){return"zai"}getSupportedModels(){return[de,pn,cn,un,So,hn,dn,mn,gn,Co,To,ne]}getDefaultModel(){return de}getDefaultVisionModel(){return ne}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return me(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var ki=[new Fe,new Ve,new Ae,new be,new ye,new Ke,new Xe,new je,new we,new xe,new ke,new $e,new Be];var Kr=new Set(["openai","openai-compatible","openrouter","gemini","claude","zai","xai","kimi","deepseek","mistral","sakana","plamo"]),Hr=new Set(["openai","gemini","claude"]),Br=new Set(["openai","openai-compatible","zai","kimi"]),Wr={openai:["none","minimal","low","medium","high","xhigh","max"],claude:["low","medium","high","xhigh","max"],gemini:["minimal","low","medium","high"],openrouter:["none","minimal","low","medium","high"],kimi:["low","high","max"],mistral:["low","medium","high"],plamo:["none","medium"],xai:["none","low","medium","high"]},Je=class{static registerProvider(e){this.providers.set(e.getProviderName(),e)}static createChatService(e,t){let o=this.providers.get(e);if(!o)throw new Error(`Unknown chat provider: ${e}`);return o.createChatService(t)}static getProviders(){return this.providers}static getAvailableProviders(){return Array.from(this.providers.keys())}static getSupportedModels(e){let t=this.providers.get(e);return t?t.getSupportedModels():[]}static getProviderCapabilities(e,t){let o=this.providers.get(e);if(!o)return;let i=t?this.getVisionSupportLevelForModel(e,t):o.getVisionSupportLevel();return{provider:e,models:o.getSupportedModels(),defaultModel:typeof o.getDefaultModel=="function"?o.getDefaultModel():void 0,text:!0,streaming:!0,vision:i,tools:Kr.has(e),mcp:Hr.has(e),jsonMode:Br.has(e),responseLength:!0,reasoningEffort:e==="claude"&&t?[...N(t)]:e==="kimi"&&t?[...z(t)]:Wr[e]??[]}}static getAllProviderCapabilities(){return this.getAvailableProviders().map(e=>this.getProviderCapabilities(e)).filter(e=>e!==void 0)}static getVisionSupportLevel(e){let t=this.providers.get(e);return t?t.getVisionSupportLevel():"unsupported"}static getVisionSupportLevelForModel(e,t){let o=this.providers.get(e);return o?o.getVisionSupportLevelForModel?o.getVisionSupportLevelForModel(t):o.supportsVisionForModel?o.supportsVisionForModel(t)?"supported":"unsupported":o.getVisionSupportLevel():"unsupported"}};Je.providers=new Map;ki.forEach(n=>Je.registerProvider(n));function Vi(){E.setFetch(async(n,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,i={};if(Array.isArray(o))for(let[u,m]of o)i[u]=String(m);else if(o&&typeof o=="object")for(let[u,m]of Object.entries(o))i[u]=String(m);let r={method:t,headers:i,muteHttpExceptions:!0},s=e.body;typeof s=="string"?r.payload=s:s!=null&&(i["Content-Type"]||(i["Content-Type"]="application/json"),r.payload=JSON.stringify(s));let l=UrlFetchApp.fetch(n,r),p=l.getResponseCode(),c=l.getContentText();return{ok:p>=200&&p<300,status:p,statusText:String(p),text:async()=>c,json:async()=>c?JSON.parse(c):null}})}return $i($r);})();
19
+ `)}getResponseLengthInstruction(){if(!this._responseLength)return;let e=Ho[this._responseLength];if(e)switch(this._responseLength){case O.VERY_SHORT:return`Reply in no more than one concise sentence. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Stay within approximately ${e} tokens.`;case O.SHORT:return`Reply in no more than two concise sentences. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Use natural conversational language. Stay within approximately ${e} tokens.`;case O.MEDIUM:return`Reply in no more than three concise sentences. Answer directly and include only the context needed to understand the answer. Do not use a preamble, summary, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case O.LONG:return`Reply in no more than five sentences. Explain the important details clearly, but avoid unnecessary preambles, repetition, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case O.VERY_LONG:return`Reply in no more than ten sentences. Give a thorough but focused answer. Use short plain-text paragraphs when helpful, and avoid unnecessary repetition, bullet points, or Markdown. Stay within approximately ${e} tokens.`;case O.DEEP:return`Give a detailed response and organize it in the way that best fits the request. No sentence-count limit applies at this level. Stay within approximately ${e} tokens.`}}};var Ve=class{createChatService(e){return new Ge({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,initialPrompts:e.initialPrompts,responseLength:e.responseLength})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[le]}getDefaultModel(){return le}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var Fe=class{constructor(e,t=F,o=F,i,r=Te,s,a,p,c){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.responseFormat=a,this.thinking=p;let d=q(t);if(c!==void 0&&!d.includes(c))throw new Error(`Model ${t} does not support reasoning_effort: ${c}.`);this.reasoningEffort=c??Pe(t),this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:()=>this.chatOnce(e,!0,t),runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!ye(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({hasTools:this.tools.length>0,runWithoutTools:()=>this.visionChatOnce(e,!0,t),runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callKimi(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!ye(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callKimi(e,this.visionModel,t,i);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callKimi(e,t,o=!1,i){let r=this.buildRequestBody(e,t,o,i);return await _.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:L(this.responseLength);s!==void 0&&(se(t)?r.max_completion_tokens=s:r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),se(t)&&(r.reasoning_effort=this.reasoningEffort??Pe(t));let a=this.resolveEffectiveThinking(t);a&&(this.isSelfHostedEndpoint()?a.type==="disabled"&&(r.chat_template_kwargs={thinking:!1}):r.thinking=a);let p=this.buildToolsDefinition();return p.length>0&&(r.tools=p,r.tool_choice="auto"),r}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(Te)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveEffectiveThinking(e){if(se(e)){if(this.thinking)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(Tt(e)){if(this.thinking?.type==="disabled")throw new Error(`Model ${e} requires thinking mode and does not support thinking: disabled.`);return this.thinking??{type:"enabled"}}return this.tools.length>0?{type:"disabled"}:this.thinking??{type:"enabled"}}buildToolsDefinition(){return D(this.tools,"chat-completions")}async parseStream(e,t){return x(e,t,{preserveAssistantMessage:!0,onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e,{preserveAssistantMessage:!0})}};var Ue=class{constructor(){this.defaultThinking={type:"enabled"}}createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),i=T({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:p=>this.supportsVisionForModel(p),validate:"explicit"}),r=e.tools,s=this.resolveThinking(o,r,e.thinking),a=this.resolveReasoningEffort(o,e.reasoning_effort);return new Fe(e.apiKey,o,i,r,t,e.responseLength,e.responseFormat,s,a)}getProviderName(){return"kimi"}getSupportedModels(){return[Le,St,Ct,F,Fo]}getDefaultModel(){return F}getDefaultVisionModel(){return F}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ye(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}resolveEndpoint(e){if(e.endpoint)return this.normalizeEndpoint(e.endpoint);if(e.baseUrl){let t=this.normalizeEndpoint(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return Te}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveThinking(e,t,o){if(se(e)){if(o)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(Tt(e)){if(o?.type==="disabled")throw new Error(`Model ${e} requires thinking mode and does not support thinking: disabled.`);return o??this.defaultThinking}return t&&t.length>0?{type:"disabled"}:o??this.defaultThinking}resolveReasoningEffort(e,t){let o=q(e);if(o.length===0){if(t!==void 0)throw new Error(`Model ${e} does not support the reasoning_effort option.`);return}let i=t??Pe(e)??o[0];if(!o.includes(i))throw new Error(`Model ${e} supports reasoning_effort values: ${o.join(", ")}.`);return i}};var Ke=class extends y{constructor(e,t=U,o=t,i,r=Pt,s,a){super(e,t,o,i,r,[],s,void 0,a,!1,"mistral",!1)}};var He=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=Rt(t)?e.reasoning_effort:void 0;return new Ke(e.apiKey,t,o,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"mistral"}getSupportedModels(){return[...Vn]}getDefaultModel(){return U}getDefaultVisionModel(){return U}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Un(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("mistral provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return Pt}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Be=class{createChatService(e){this.validateRequiredOptions(e);let t=[e.apiKey?.trim()??"",e.model,e.visionModel??e.model,e.tools,e.endpoint,[],e.responseLength,e.verbosity,e.reasoning_effort,e.enableReasoningSummary,this.getProviderName(),!1];return e.responseFormat!==void 0&&t.push(e.responseFormat),new y(...t)}getProviderName(){return"openai-compatible"}getSupportedModels(){return[]}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"unknown"}supportsVisionForModel(e){return!0}getVisionSupportLevelForModel(e){return"unknown"}getDefaultModel(){return"local-model"}validateRequiredOptions(e){if(e.mcpServers!==void 0)throw new Error("openai-compatible provider does not support mcpServers.");let t=e.endpoint?.trim();if(!t)throw new Error("openai-compatible provider requires endpoint (full URL).");let o;try{o=new URL(t)}catch{throw new Error("openai-compatible provider requires endpoint to be a full URL.")}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error("openai-compatible provider requires endpoint to be a full URL.");if(!e.model?.trim())throw new Error("openai-compatible provider requires model.")}};var We=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=T({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:d=>this.supportsVisionForModel(d),validate:"resolved"}),i=t.tools,r=t.mcpServers??[],s=t.model||this.getDefaultModel(),a=!1;r.length>0||Zo(s)?a=!0:ne(s)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let p=t.endpoint||(a?A:J),c=[t.apiKey,s,o,i,p,r,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName()];return t.responseFormat!==void 0&&c.push(!0,t.responseFormat),new y(...c)}getProviderName(){return"openai"}getSupportedModels(){return[Z,ce,ue,he,Y,Q,H,B,W,$,ee,te,z,Nt,wt,kt,oe,Gt,qo,Xo,"o1"]}getDefaultModel(){return Z}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ot.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!ne(t))return e;let o={...e};if(e.gpt5Preset){let i=Wn[e.gpt5Preset];o.reasoning_effort=i.reasoning_effort,o.verbosity=i.verbosity}else e.reasoning_effort||(o.reasoning_effort=rt(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!nt(e)||t==="minimal"&&!it(e)?t==="minimal"&&nt(e)?"none":t==="none"&&it(e)?"minimal":Ft(e)?"low":"medium":t==="low"&&!Ft(e)?"medium":t==="xhigh"&&!Vt(e)?"high":t==="max"&&!Yo(e)?Vt(e)?"xhigh":"high":t}};var bt=n=>[_t,de].includes(n.trim()),ss=n=>[G,me].includes(n.trim()),Xn=(n,e)=>{if(bt(n)&&!e)throw new Error("OpenRouter Auto Router returned no visible content. Please retry.")},Zi=n=>n.blocks.some(e=>e.type!=="text"||e.text.trim().length>0),$e=class{constructor(e,t=G,o=G,i,r=ft,s,a,p,c,d,u){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.appName=a,this.appUrl=p,this.reasoning_effort=c,this.includeReasoning=d,this.reasoningMaxTokens=u,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!ie(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=En){let o=6e4-t;o>0&&(console.log(`Rate limit reached for free tier. Waiting ${o}ms...`),await new Promise(i=>setTimeout(i,o)),this.requestCount=0)}this.lastRequestTime=e,this.requestCount++}async processChat(e,t,o){await this.applyRateLimiting(),await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.model,!0);return this.handleStream(i,t,this.model)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!_e(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(i,t,this.visionModel)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processVisionChat:",i),i}}async chatOnce(e,t=!0,o=()=>{},i){await this.applyRateLimiting();let r=await this.callOpenRouter(e,this.model,t,i);return t?this.parseStream(r,o,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!_e(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let r=await this.callOpenRouter(e,this.visionModel,t,i);return t?this.parseStream(r,o,this.visionModel):this.parseOneShot(await r.json(),this.visionModel)}async callOpenRouter(e,t,o=!1,i){let r=this.buildRequestBody(e,t,o,i),s={Authorization:`Bearer ${this.apiKey}`};return this.appUrl&&(s["HTTP-Referer"]=this.appUrl),this.appName&&(s["X-Title"]=this.appName),await _.post(this.endpoint,r,s)}buildRequestBody(e,t,o,i){let r={model:t,messages:e,stream:o},s=i!==void 0?i:L(this.responseLength),a=ss(t)||bt(t)&&i===void 0;s&&a?console.warn(`OpenRouter: Token limits are disabled for ${t} because this model can return empty content when a token limit is set.`):s&&(r.max_tokens=s);let p=Io(t),c=Mn(t,this.reasoning_effort);if(c!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens||p){if(r.reasoning={},c){let d=c==="minimal"?"low":c;r.reasoning.effort=d}else p&&(r.reasoning.effort=p);(c==="none"||this.includeReasoning!==!0)&&(r.reasoning.exclude=!0),this.reasoningMaxTokens&&(r.reasoning.max_tokens=this.reasoningMaxTokens)}else r.reasoning={exclude:!0};return this.tools.length>0&&(r.tools=D(this.tools,"chat-completions"),r.tool_choice="auto"),r}async handleStream(e,t,o){let i=await K(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:bt(o)});return Xn(o,i.trim().length>0),i}async parseStream(e,t,o){let i=await x(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:bt(o)});return Xn(o,Zi(i)),i}parseOneShot(e,t){let o=I(e,{throwOnApiError:bt(t)});return Xn(t,Zi(o)),o}};var ze=class{createChatService(e){let t=T({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:e.model||this.getDefaultModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),o=e.tools,i=e.appName,r=e.appUrl;return new $e(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,i,r,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[_t,de,un,G,yo,Zt,Yt,Qt,eo,to,oo,no,io,ro,so,ao,lo,po,co,uo,ho,mo,go,fo,_o,hn,Eo,Mo,Oo,vo,So,Co,To,Lo,me,dn,mn,Po,Ro,fe,ge,Jt,jt,qt,Xt,gn,fn]}getDefaultModel(){return G}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return _e(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return _n}isModelFree(e){return ie(e)}};var je=class extends y{constructor(e,t=xe,o=t,i,r=It,s,a){super(e,t,o,i,r,[],s,void 0,a,!1,"plamo",!1)}};var qe=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new je(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"plamo"}getSupportedModels(){return[...Hn]}getDefaultModel(){return xe}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("plamo provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return It}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Xe=class extends y{constructor(e,t=Re,o=t,i,r=xt,s){super(e,t,o,i,r,[],s,void 0,void 0,!1,"sakana",!1)}};var Je=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new Xe(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength)}getProviderName(){return"sakana"}getSupportedModels(){return[...Kn]}getDefaultModel(){return Re}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("sakana provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return xt}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Ze=class{constructor(e,t=V,o=V,i,r=Mt,s,a){this.provider="xai";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.visionModel=o,this.reasoningEffort=a}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callXAI(e,this.model,!0);return this.handleStream(i,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!Se(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callXAI(e,this.visionModel,!0);return this.handleStream(i,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callXAI(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!Se(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callXAI(e,this.visionModel,t,i);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callXAI(e,t,o=!1,i){let r=this.buildRequestBody(e,t,o,i);return await _.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:L(this.responseLength);s!==void 0&&(r.max_tokens=s),this.reasoningEffort&&Go(t)&&(r.reasoning_effort=vt(t,this.reasoningEffort));let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto"),r}buildToolsDefinition(){return D(this.tools,"chat-completions")}async handleStream(e,t){return K(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var Ye=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"explicit"}),i=e.tools;return new Ze(e.apiKey,t,o,i,e.endpoint||Mt,e.responseLength,vt(t,e.reasoning_effort??Vo(t)))}getProviderName(){return"xai"}getSupportedModels(){return[Oe,ve,Ot,No,wo,ko,V]}getDefaultModel(){return V}getDefaultVisionModel(){return V}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Se(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Qe=class{constructor(e,t=Ee,o=re,i,r=Et,s,a,p){this.provider="zai";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.responseFormat=a,this.thinking=p??{type:"disabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callZAI(e,this.model,!0);return this.handleStream(i,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!Me(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callZAI(e,this.visionModel,!0);return this.handleStream(i,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callZAI(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!Me(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callZAI(e,this.visionModel,t,i);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callZAI(e,t,o=!1,i){let r=this.buildRequestBody(e,t,o,i);return await _.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:L(this.responseLength);s!==void 0&&(r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),this.thinking&&(r.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto",o&&Pn(t)&&(r.tool_stream=!0)),r}buildToolsDefinition(){return D(this.tools,"chat-completions")}async handleStream(e,t){return K(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var et=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=e.thinking??{type:"disabled"};return new Qe(e.apiKey,t,o,i,e.endpoint||Et,e.responseLength,e.responseFormat,r)}getProviderName(){return"zai"}getSupportedModels(){return[Ee,On,vn,Sn,Do,Cn,Tn,Ln,yn,Ao,bo,re]}getDefaultModel(){return Ee}getDefaultVisionModel(){return re}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Me(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Yi=[new We,new Be,new ke,new Ve,new Ae,new ze,new et,new Ye,new Ue,new Ne,new He,new Je,new qe];var as=new Set(["claude","claude-agent-sdk","codex-sdk","copilot-sdk","deepseek","gemini","gemini-nano","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),ls=new Set(["claude","deepseek","gemini","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),ps=new Set(["codex-sdk"]);function Jn(n){if(as.has(n))return{text:!0,streaming:!ps.has(n),tools:ls.has(n)}}function cs(n){let e=n.provider==="claude",t=n.messages.filter(r=>!Qi(e,r)),o=n.completion.blocks.filter(r=>r.type==="tool_use"),i=n.completion.assistant_message??us(e,o);return Qi(e,i)||t.push({...i}),t.push(...hs(e,n.toolResults)),t}function Qi(n,e){if(!n||e.role!=="assistant")return!1;let t=e.content;return Array.isArray(t)&&t.length===0}function us(n,e){return n?{role:"assistant",content:e.map(t=>({type:"tool_use",id:t.id,name:t.name,input:t.input??{}}))}:{role:"assistant",content:[],tool_calls:e.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.input??{})}}))}}function hs(n,e){return n?e.map(t=>({role:"user",content:[{type:"tool_result",tool_use_id:t.tool_use_id,content:t.content}]})):e.map(t=>({role:"tool",tool_call_id:t.tool_use_id,content:t.content}))}var ds=new Set(["openai","gemini","claude"]),ms=new Set(["openai","openai-compatible","zai","kimi"]),gs={openai:["none","minimal","low","medium","high","xhigh","max"],claude:["low","medium","high","xhigh","max"],gemini:["minimal","low","medium","high"],openrouter:["none","minimal","low","medium","high","xhigh","max"],kimi:["low","high","max"],mistral:["low","medium","high"],plamo:["none","medium"],xai:["none","low","medium","high","xhigh"],deepseek:["none","low","high","max"]},tt=class{static registerProvider(e){this.providers.set(e.getProviderName(),e)}static createChatService(e,t){let o=this.providers.get(e);if(!o)throw new Error(`Unknown chat provider: ${e}`);return o.createChatService(t)}static getProviders(){return this.providers}static getAvailableProviders(){return Array.from(this.providers.keys())}static getSupportedModels(e){let t=this.providers.get(e);return t?t.getSupportedModels():[]}static getProviderCapabilities(e,t){let o=this.providers.get(e);if(!o)return;let i=t?this.getVisionSupportLevelForModel(e,t):o.getVisionSupportLevel(),r=Jn(e);return{provider:e,models:o.getSupportedModels(),defaultModel:typeof o.getDefaultModel=="function"?o.getDefaultModel():void 0,text:!0,streaming:r?.streaming??!0,vision:i,tools:r?.tools??!1,mcp:ds.has(e),jsonMode:ms.has(e),responseLength:!0,reasoningEffort:e==="claude"&&t?[...k(t)]:e==="kimi"&&t?[...q(t)]:e==="deepseek"&&t?[...yt(t)]:e==="openrouter"&&t?[...xo(t)]:e==="xai"&&t?[...Ce(t)]:gs[e]??[]}}static getAllProviderCapabilities(){return this.getAvailableProviders().map(e=>this.getProviderCapabilities(e)).filter(e=>e!==void 0)}static getVisionSupportLevel(e){let t=this.providers.get(e);return t?t.getVisionSupportLevel():"unsupported"}static getVisionSupportLevelForModel(e,t){let o=this.providers.get(e);return o?o.getVisionSupportLevelForModel?o.getVisionSupportLevelForModel(t):o.supportsVisionForModel?o.supportsVisionForModel(t)?"supported":"unsupported":o.getVisionSupportLevel():"unsupported"}};tt.providers=new Map;Yi.forEach(n=>tt.registerProvider(n));function er(){_.setFetch(async(n,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,i={};if(Array.isArray(o))for(let[u,m]of o)i[u]=String(m);else if(o&&typeof o=="object")for(let[u,m]of Object.entries(o))i[u]=String(m);let r={method:t,headers:i,muteHttpExceptions:!0},s=e.body;typeof s=="string"?r.payload=s:s!=null&&(i["Content-Type"]||(i["Content-Type"]="application/json"),r.payload=JSON.stringify(s));let a=UrlFetchApp.fetch(n,r),p=a.getResponseCode(),c=a.getContentText();return{ok:p>=200&&p<300,status:p,statusText:String(p),text:async()=>c,json:async()=>c?JSON.parse(c):null}})}return ar(fs);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aituber-onair/chat",
3
- "version": "0.49.0",
3
+ "version": "0.51.0",
4
4
  "description": "Chat and LLM API integration library for AITuber OnAir",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",
@@ -17,6 +17,11 @@
17
17
  "import": "./dist/esm/agent.js",
18
18
  "require": "./dist/cjs/agent.js"
19
19
  },
20
+ "./backend": {
21
+ "types": "./dist/cjs/backend.d.ts",
22
+ "import": "./dist/cjs/backend.js",
23
+ "require": "./dist/cjs/backend.js"
24
+ },
20
25
  "./dist/cjs/*": "./dist/cjs/*",
21
26
  "./dist/esm/*": "./dist/esm/*",
22
27
  "./umd": "./dist/umd/aituber-onair-chat.js"