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