@aituber-onair/chat 0.56.0 → 0.58.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 (35) hide show
  1. package/README.ja.md +27 -2
  2. package/README.md +31 -2
  3. package/dist/cjs/constants/claude.d.ts +1 -0
  4. package/dist/cjs/constants/claude.d.ts.map +1 -1
  5. package/dist/cjs/constants/claude.js +4 -1
  6. package/dist/cjs/constants/claude.js.map +1 -1
  7. package/dist/cjs/services/providers/claude/ClaudeChatServiceProvider.d.ts.map +1 -1
  8. package/dist/cjs/services/providers/claude/ClaudeChatServiceProvider.js +1 -0
  9. package/dist/cjs/services/providers/claude/ClaudeChatServiceProvider.js.map +1 -1
  10. package/dist/cjs/utils/index.d.ts +1 -0
  11. package/dist/cjs/utils/index.d.ts.map +1 -1
  12. package/dist/cjs/utils/index.js +1 -0
  13. package/dist/cjs/utils/index.js.map +1 -1
  14. package/dist/cjs/utils/openaiCompatibleEndpoint.d.ts +57 -0
  15. package/dist/cjs/utils/openaiCompatibleEndpoint.d.ts.map +1 -0
  16. package/dist/cjs/utils/openaiCompatibleEndpoint.js +193 -0
  17. package/dist/cjs/utils/openaiCompatibleEndpoint.js.map +1 -0
  18. package/dist/esm/constants/claude.d.ts +1 -0
  19. package/dist/esm/constants/claude.d.ts.map +1 -1
  20. package/dist/esm/constants/claude.js +3 -0
  21. package/dist/esm/constants/claude.js.map +1 -1
  22. package/dist/esm/services/providers/claude/ClaudeChatServiceProvider.d.ts.map +1 -1
  23. package/dist/esm/services/providers/claude/ClaudeChatServiceProvider.js +2 -1
  24. package/dist/esm/services/providers/claude/ClaudeChatServiceProvider.js.map +1 -1
  25. package/dist/esm/utils/index.d.ts +1 -0
  26. package/dist/esm/utils/index.d.ts.map +1 -1
  27. package/dist/esm/utils/index.js +1 -0
  28. package/dist/esm/utils/index.js.map +1 -1
  29. package/dist/esm/utils/openaiCompatibleEndpoint.d.ts +57 -0
  30. package/dist/esm/utils/openaiCompatibleEndpoint.d.ts.map +1 -0
  31. package/dist/esm/utils/openaiCompatibleEndpoint.js +186 -0
  32. package/dist/esm/utils/openaiCompatibleEndpoint.js.map +1 -0
  33. package/dist/umd/aituber-onair-chat.js +199 -3
  34. package/dist/umd/aituber-onair-chat.min.js +8 -8
  35. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- "use strict";var AITuberOnAirChat=(()=>{var Ln=Object.defineProperty;var ts=Object.getOwnPropertyDescriptor;var os=Object.getOwnPropertyNames;var ns=Object.prototype.hasOwnProperty;var is=(o,e)=>{for(var t in e)Ln(o,t,{get:e[t],enumerable:!0})},rs=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of os(e))!ns.call(o,i)&&i!==t&&Ln(o,i,{get:()=>e[i],enumerable:!(n=ts(e,i))||n.enumerable});return o};var ss=o=>rs(Ln({},"__esModule",{value:!0}),o);var Ca={};is(Ca,{CHAT_RESPONSE_LENGTH:()=>L,CLAUDE_DEPRECATED_MODELS:()=>hs,CLAUDE_VISION_SUPPORTED_MODELS:()=>Ft,ChatServiceFactory:()=>Ct,ChatServiceHttpClient:()=>M,ClaudeChatService:()=>Qe,ClaudeChatServiceProvider:()=>et,DEEPSEEK_API_BASE_URL:()=>pr,DEEPSEEK_DEPRECATED_MODELS:()=>Is,DEEPSEEK_SUPPORTED_MODELS:()=>ai,DEEPSEEK_VISION_SUPPORTED_MODELS:()=>hr,DEFAULT_MAX_TOKENS:()=>vi,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>ks,DEFAULT_VISION_PROMPT:()=>ws,DeepSeekChatService:()=>tt,DeepSeekChatServiceProvider:()=>ot,EMOTION_TAG_CLEANUP_REGEX:()=>Ti,EMOTION_TAG_REGEX:()=>Tr,ENDPOINT_CLAUDE_API:()=>Kn,ENDPOINT_DEEPSEEK_CHAT_COMPLETIONS_API:()=>oo,ENDPOINT_GEMINI_API:()=>An,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>$e,ENDPOINT_MISTRAL_CHAT_COMPLETIONS_API:()=>io,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>z,ENDPOINT_OPENAI_RESPONSES_API:()=>N,ENDPOINT_OPENROUTER_API:()=>Ut,ENDPOINT_PLAMO_CHAT_COMPLETIONS_API:()=>ao,ENDPOINT_SAKANA_CHAT_COMPLETIONS_API:()=>so,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>Jt,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>jt,EmotionParser:()=>Ye,GEMINI_DEPRECATED_MODELS:()=>Fi,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>Li,GEMINI_RECOMMENDED_MODELS:()=>Eo,GEMINI_VISION_SUPPORTED_MODELS:()=>xt,GPT5_PRESETS:()=>Ci,GPT_5_MODELS:()=>Ai,GeminiChatService:()=>nt,GeminiChatServiceProvider:()=>it,GeminiNanoChatService:()=>rt,GeminiNanoChatServiceProvider:()=>st,HttpError:()=>oe,KIMI_THINKING_REQUIRED_MODELS:()=>ar,KIMI_VISION_SUPPORTED_MODELS:()=>sr,KimiChatService:()=>at,KimiChatServiceProvider:()=>lt,MAX_TOKENS_BY_LENGTH:()=>Mn,MISTRAL_API_BASE_URL:()=>_r,MISTRAL_DEPRECATED_MODELS:()=>Ds,MISTRAL_REASONING_EFFORT_SUPPORTED_MODELS:()=>fr,MISTRAL_SUPPORTED_MODELS:()=>fi,MISTRAL_VISION_SUPPORTED_MODELS:()=>mr,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>Ji,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>Zi,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>$o,MODEL_ANTHROPIC_CLAUDE_FABLE_5:()=>Ko,MODEL_ANTHROPIC_CLAUDE_FABLE_5_1:()=>ce,MODEL_ANTHROPIC_CLAUDE_HAIKU_LATEST:()=>Uo,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>Bo,MODEL_ANTHROPIC_CLAUDE_OPUS_4_8:()=>Xt,MODEL_ANTHROPIC_CLAUDE_OPUS_5:()=>Ho,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>Wo,MODEL_ANTHROPIC_CLAUDE_SONNET_5:()=>Ie,MODEL_ANTHROPIC_CLAUDE_SONNET_LATEST:()=>Fo,MODEL_CLAUDE_3_5_HAIKU:()=>Hi,MODEL_CLAUDE_3_5_SONNET:()=>Bi,MODEL_CLAUDE_3_7_SONNET:()=>Wi,MODEL_CLAUDE_3_HAIKU:()=>Ki,MODEL_CLAUDE_4_5_HAIKU:()=>V,MODEL_CLAUDE_4_5_OPUS:()=>It,MODEL_CLAUDE_4_5_SONNET:()=>Mo,MODEL_CLAUDE_4_6_OPUS:()=>bt,MODEL_CLAUDE_4_6_SONNET:()=>Dt,MODEL_CLAUDE_4_7_OPUS:()=>Nt,MODEL_CLAUDE_4_8_OPUS:()=>wt,MODEL_CLAUDE_4_OPUS:()=>zi,MODEL_CLAUDE_4_SONNET:()=>$i,MODEL_CLAUDE_5_1_FABLE:()=>At,MODEL_CLAUDE_5_5_OPUS:()=>Oo,MODEL_CLAUDE_5_FABLE:()=>kt,MODEL_CLAUDE_5_OPUS:()=>Vt,MODEL_CLAUDE_5_SONNET:()=>Gt,MODEL_DEEPSEEK_CHAT:()=>cr,MODEL_DEEPSEEK_FLASH:()=>fn,MODEL_DEEPSEEK_REASONER:()=>ur,MODEL_DEEPSEEK_V4_FLASH:()=>me,MODEL_DEEPSEEK_V4_FLASH_VISION_EXP:()=>je,MODEL_DEEPSEEK_V4_PRO:()=>mn,MODEL_FUGU:()=>Ze,MODEL_FUGU_ULTRA:()=>Mr,MODEL_FUGU_ULTRA_20260615:()=>Sr,MODEL_FUGU_ULTRA_V1_1:()=>Or,MODEL_GEMINI_2_5_FLASH:()=>ki,MODEL_GEMINI_2_5_FLASH_LITE:()=>Gi,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>Vi,MODEL_GEMINI_2_5_PRO:()=>wi,MODEL_GEMINI_3_1_FLASH_LITE:()=>Y,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>Gn,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>kn,MODEL_GEMINI_3_5_FLASH:()=>Nn,MODEL_GEMINI_3_5_FLASH_LITE:()=>wn,MODEL_GEMINI_3_6_FLASH:()=>bn,MODEL_GEMINI_3_7_FLASH:()=>Dn,MODEL_GEMINI_3_8_FLASH:()=>In,MODEL_GEMINI_3_FLASH_PREVIEW:()=>Fn,MODEL_GEMINI_3_PRO_PREVIEW:()=>Vn,MODEL_GEMINI_NANO:()=>Me,MODEL_GEMMA_4_26B_A4B_IT:()=>Ni,MODEL_GEMMA_4_31B_IT:()=>bi,MODEL_GLM_4_6:()=>ni,MODEL_GLM_4_6V:()=>ln,MODEL_GLM_4_6V_FLASH:()=>ge,MODEL_GLM_4_6V_FLASHX:()=>pn,MODEL_GLM_4_7:()=>ei,MODEL_GLM_4_7_FLASH:()=>oi,MODEL_GLM_4_7_FLASHX:()=>ti,MODEL_GLM_5:()=>Yn,MODEL_GLM_5V_TURBO:()=>an,MODEL_GLM_5_1:()=>Jn,MODEL_GLM_5_2:()=>ee,MODEL_GLM_5_3:()=>sn,MODEL_GLM_5_3_FLASH:()=>Zt,MODEL_GLM_5_TURBO:()=>Qn,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>Yo,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>Qo,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>Jo,MODEL_GOOGLE_GEMINI_3_5_FLASH_LITE:()=>Zo,MODEL_GOOGLE_GEMINI_3_6_FLASH:()=>jo,MODEL_GOOGLE_GEMINI_3_7_FLASH:()=>qo,MODEL_GOOGLE_GEMINI_3_8_FLASH:()=>Wt,MODEL_GOOGLE_GEMINI_FLASH_LATEST:()=>Xo,MODEL_GOOGLE_GEMINI_PRO_LATEST:()=>zo,MODEL_GPT_4O:()=>go,MODEL_GPT_4O_MINI:()=>le,MODEL_GPT_4_1:()=>uo,MODEL_GPT_4_1_MINI:()=>ho,MODEL_GPT_4_1_NANO:()=>_o,MODEL_GPT_5:()=>ve,MODEL_GPT_5_1:()=>Ce,MODEL_GPT_5_4:()=>ie,MODEL_GPT_5_4_MINI:()=>se,MODEL_GPT_5_4_NANO:()=>ae,MODEL_GPT_5_4_PRO:()=>J,MODEL_GPT_5_5:()=>re,MODEL_GPT_5_6:()=>X,MODEL_GPT_5_6_LUNA:()=>Z,MODEL_GPT_5_6_SOL:()=>q,MODEL_GPT_5_6_TERRA:()=>j,MODEL_GPT_5_MINI:()=>Se,MODEL_GPT_5_NANO:()=>ne,MODEL_GPT_6_ASTRA:()=>R,MODEL_GPT_6_LUNA:()=>I,MODEL_GPT_6_SOL:()=>A,MODEL_GPT_OSS_20B_FREE:()=>K,MODEL_GROK_4_1_FAST_NON_REASONING:()=>nr,MODEL_GROK_4_1_FAST_REASONING:()=>or,MODEL_GROK_4_20_NON_REASONING:()=>hn,MODEL_GROK_4_20_REASONING:()=>un,MODEL_GROK_4_3:()=>F,MODEL_GROK_4_5:()=>He,MODEL_GROK_4_6:()=>Ue,MODEL_GROK_4_7:()=>Ke,MODEL_INCEPTION_MERCURY_2_5:()=>So,MODEL_INCLUSIONAI_LING_3_0_FLASH_VL_FREE:()=>Pe,MODEL_KIMI_K2_5:()=>gn,MODEL_KIMI_K2_6:()=>B,MODEL_KIMI_K2_7_CODE:()=>Qt,MODEL_KIMI_K2_7_CODE_HIGHSPEED:()=>eo,MODEL_KIMI_K3:()=>ze,MODEL_KWAIPILOT_KAT_CODER_AIR_V2_5:()=>zn,MODEL_KWAIPILOT_KAT_CODER_PRO_V2_5:()=>Xn,MODEL_META_MUSE_SPARK_1_3:()=>he,MODEL_MINISTRAL_14B_2512:()=>hi,MODEL_MINISTRAL_3B_2512:()=>ci,MODEL_MINISTRAL_8B_2512:()=>ui,MODEL_MISTRAL_LARGE_2512:()=>gi,MODEL_MISTRAL_LARGE_LATEST:()=>_i,MODEL_MISTRAL_MEDIUM_2508:()=>gr,MODEL_MISTRAL_MEDIUM_3_5:()=>En,MODEL_MISTRAL_SMALL_2603:()=>di,MODEL_MISTRAL_SMALL_LATEST:()=>W,MODEL_MOONSHOTAI_KIMI_K2_5:()=>Lo,MODEL_MOONSHOTAI_KIMI_K2_6:()=>zt,MODEL_MOONSHOTAI_KIMI_K2_7_CODE:()=>Co,MODEL_MOONSHOTAI_KIMI_K3:()=>vo,MODEL_MOONSHOTAI_KIMI_LATEST:()=>To,MODEL_NEX_AGI_NEX_N2_5_MINI_FREE:()=>xe,MODEL_NEX_AGI_NEX_N2_5_PRO_FREE:()=>ye,MODEL_O1:()=>Pn,MODEL_O1_MINI:()=>Rn,MODEL_O3_MINI:()=>Tn,MODEL_OPENAI_GPT_4O:()=>ko,MODEL_OPENAI_GPT_4_1_MINI:()=>Go,MODEL_OPENAI_GPT_4_1_NANO:()=>Vo,MODEL_OPENAI_GPT_5_1_CHAT:()=>ji,MODEL_OPENAI_GPT_5_1_CODEX:()=>bo,MODEL_OPENAI_GPT_5_5:()=>Do,MODEL_OPENAI_GPT_5_5_PRO:()=>Io,MODEL_OPENAI_GPT_5_6_LUNA:()=>Ao,MODEL_OPENAI_GPT_5_6_SOL:()=>xo,MODEL_OPENAI_GPT_5_6_TERRA:()=>yo,MODEL_OPENAI_GPT_5_MINI:()=>No,MODEL_OPENAI_GPT_5_NANO:()=>wo,MODEL_OPENAI_GPT_6_ASTRA:()=>Kt,MODEL_OPENAI_GPT_6_ASTRA_PRO:()=>Ht,MODEL_OPENAI_GPT_LATEST:()=>Ro,MODEL_OPENAI_GPT_MINI_LATEST:()=>Po,MODEL_OPENROUTER_AUTO:()=>$t,MODEL_OPENROUTER_AUTO_BETA:()=>Ae,MODEL_OPENROUTER_DEEPSEEK_V4_1_FLASH:()=>Bt,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH:()=>be,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_0731:()=>Ne,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_VISION_EXP:()=>de,MODEL_OPENROUTER_DEEPSEEK_V4_PRO_0813:()=>we,MODEL_OPENROUTER_FUSION:()=>Bn,MODEL_PLAMO_2_2_PRIME:()=>Lr,MODEL_PLAMO_3_0_PRIME:()=>Je,MODEL_QWEN_QWEN_3_8_FLASH:()=>qt,MODEL_QWEN_QWEN_3_8_MAX_0902:()=>ue,MODEL_SAKANA_NAMAZU:()=>Ee,MODEL_XAI_GROK_4_5:()=>on,MODEL_XAI_GROK_4_6:()=>tn,MODEL_XAI_GROK_LATEST:()=>en,MODEL_ZAI_GLM_4_5_AIR:()=>$n,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>Yi,MODEL_ZAI_GLM_4_7_FLASH:()=>Wn,MODEL_ZAI_GLM_5_2:()=>De,MODEL_ZAI_GLM_5_3:()=>Q,MODEL_ZAI_GLM_5_3_FLASH:()=>H,MistralChatService:()=>pt,MistralChatServiceProvider:()=>ct,OPENROUTER_CREDITS_THRESHOLD:()=>Ts,OPENROUTER_DEPRECATED_MODELS:()=>gs,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>Ls,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>Cs,OPENROUTER_FREE_MODELS:()=>qn,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>jn,OPENROUTER_VISION_SUPPORTED_MODELS:()=>Qi,OpenAIChatService:()=>x,OpenAIChatServiceProvider:()=>ht,OpenAICompatibleChatServiceProvider:()=>ut,OpenRouterChatService:()=>dt,OpenRouterChatServiceProvider:()=>_t,PLAMO_API_BASE_URL:()=>Cr,PLAMO_DEPRECATED_MODELS:()=>Ns,PLAMO_SUPPORTED_MODELS:()=>Si,PlamoChatService:()=>gt,PlamoChatServiceProvider:()=>ft,SAKANA_API_BASE_URL:()=>Er,SAKANA_COMPATIBILITY_MODELS:()=>bs,SAKANA_SUPPORTED_MODELS:()=>Mi,SAKANA_VISION_SUPPORTED_MODELS:()=>vr,SakanaChatService:()=>mt,SakanaChatServiceProvider:()=>Et,StreamTextAccumulator:()=>O,VISION_SUPPORTED_MODELS:()=>Lt,XAIChatService:()=>Mt,XAIChatServiceProvider:()=>Ot,XAI_DEPRECATED_MODELS:()=>xs,XAI_VISION_SUPPORTED_MODELS:()=>ir,ZAIChatService:()=>St,ZAIChatServiceProvider:()=>vt,ZAI_VISION_SUPPORTED_MODELS:()=>tr,allowsReasoningLow:()=>mo,allowsReasoningMax:()=>yn,allowsReasoningMinimal:()=>Rt,allowsReasoningNone:()=>Tt,allowsReasoningXHigh:()=>fo,buildOpenAICompatibleTools:()=>G,buildToolContinuationMessages:()=>ma,getChatBackendProviderCapabilities:()=>yi,getClaudeSupportedReasoningEfforts:()=>U,getDeepSeekSupportedReasoningEfforts:()=>no,getDefaultClaudeReasoningEffort:()=>qi,getDefaultDeepSeekReasoningEffort:()=>si,getDefaultGeminiReasoningEffort:()=>us,getDefaultKimiReasoningEffort:()=>qe,getDefaultOpenRouterReasoningEffort:()=>rn,getDefaultReasoningEffortForGPT5Model:()=>Di,getDefaultReasoningEffortForOpenAIModel:()=>Pt,getDefaultXaiReasoningEffort:()=>_n,getDefaultZaiReasoningEffort:()=>er,getGeminiSupportedReasoningEfforts:()=>Le,getKimiSupportedReasoningEfforts:()=>te,getMaxTokensForResponseLength:()=>P,getOpenRouterSupportedReasoningEfforts:()=>nn,getXaiSupportedReasoningEfforts:()=>We,getZaiSupportedReasoningEfforts:()=>Ve,installGASFetch:()=>Qr,isClaudeReasoningEffortModel:()=>Xi,isDeepSeekReasoningEffortModel:()=>dr,isDeepSeekVisionModel:()=>li,isGPT5Model:()=>Ii,isGeminiReasoningEffortModel:()=>Un,isKimiReasoningEffortModel:()=>fe,isKimiThinkingRequiredModel:()=>to,isKimiVisionModel:()=>Xe,isMistralReasoningEffort:()=>mi,isMistralReasoningEffortModel:()=>ro,isMistralVisionModel:()=>Ei,isOpenAIReasoningModel:()=>pe,isOpenRouterFreeModel:()=>_e,isOpenRouterVisionModel:()=>ke,isResponsesOnlyGPT5Model:()=>xn,isSakanaVisionModel:()=>Oi,isXaiReasoningEffortModel:()=>dn,isXaiReasoningEffortNoneModel:()=>rr,isXaiVisionModel:()=>Be,isZaiAlwaysThinkingModel:()=>Ge,isZaiReasoningEffortModel:()=>cn,isZaiToolStreamModel:()=>ri,isZaiVisionModel:()=>Fe,normalizeClaudeReasoningEffort:()=>_s,normalizeDeepSeekReasoningEffort:()=>pi,normalizeGeminiReasoningEffort:()=>yt,normalizeOpenRouterReasoningEffort:()=>Zn,normalizeXaiReasoningEffort:()=>Yt,normalizeZaiReasoningEffort:()=>ii,parseOpenAICompatibleOneShot:()=>k,parseOpenAICompatibleTextStream:()=>$,parseOpenAICompatibleToolStream:()=>w,processChatWithOptionalTools:()=>S,refreshOpenRouterFreeModels:()=>Zs,resolveVisionModel:()=>T,runOnceText:()=>Us,safeJsonParse:()=>Pr,safeParseToolCallInput:()=>Oe,screenplayToText:()=>Fs,textToScreenplay:()=>Rr,textsToScreenplay:()=>Vs});var z="https://api.openai.com/v1/chat/completions",N="https://api.openai.com/v1/responses",R="gpt-6-astra",A="gpt-6-sol",I="gpt-6-luna",ne="gpt-5-nano",Se="gpt-5-mini",ve="gpt-5",Ce="gpt-5.1",ie="gpt-5.4",re="gpt-5.5",X="gpt-5.6",q="gpt-5.6-sol",j="gpt-5.6-terra",Z="gpt-5.6-luna",se="gpt-5.4-mini",ae="gpt-5.4-nano",J="gpt-5.4-pro",uo="gpt-4.1",ho="gpt-4.1-mini",_o="gpt-4.1-nano",le="gpt-4o-mini",go="gpt-4o",Tn="o3-mini",Rn="o1-mini",Pn="o1",Lt=[R,A,I,ne,Se,ve,Ce,ie,re,X,q,j,Z,se,ae,J,uo,ho,_o,le,go,"o1"],Ai=[ne,Se,ve,Ce,ie,re,X,q,j,Z,se,ae,J];function Ii(o){return Ai.includes(o)}function pe(o){return o===R||o===A||o===I||Ii(o)}function xn(o){return o===J}function fo(o){return o===R||o===A||o===I||o===X||o===q||o===j||o===Z||o===re||o===ie||o===se||o===ae||o===J}function yn(o){return o===R||o===A||o===I||o===X||o===q||o===j||o===Z}function Tt(o){return o===A||o===I||o===X||o===q||o===j||o===Z||o===Ce||o===ie||o===re||o===se||o===ae}function Rt(o){return o===ne||o===Se||o===ve}function mo(o){return o!==J}function Di(o){return Tt(o)?"none":Rt(o)?"minimal":"medium"}function Pt(o){return o===R?"low":o===A?"medium":o===I?"low":Di(o)}var An="https://generativelanguage.googleapis.com",bi="gemma-4-31b-it",Ni="gemma-4-26b-a4b-it",In="gemini-3.8-flash",Dn="gemini-3.7-flash",bn="gemini-3.6-flash",Nn="gemini-3.5-flash",wn="gemini-3.5-flash-lite",kn="gemini-3.1-pro-preview",Y="gemini-3.1-flash-lite",Gn="gemini-3.1-flash-lite-preview",Vn="gemini-3-pro-preview",Fn="gemini-3-flash-preview",wi="gemini-2.5-pro",ki="gemini-2.5-flash",Gi="gemini-2.5-flash-lite",Vi="gemini-2.5-flash-lite-preview-06-17",Eo=[In,Dn,bn,Nn,wn,Y,kn,Fn,wi,ki,Gi,bi,Ni],Fi=[Gn,Vn,Vi],xt=[...Eo,...Fi],as=["minimal","low","medium","high"],ls=["low","medium","high"],ps=[bn,Nn,wn,Y,Gn,Fn],cs=[In,Dn,kn,Vn];function Le(o){return ps.includes(o)?as:cs.includes(o)?ls:[]}function Un(o){return Le(o).length>0}function us(o){return Le(o)[0]}function yt(o,e){let t=Le(o);if(t.length!==0)return e&&t.includes(e)?e:t[0]}var Kn="https://api.anthropic.com/v1/messages",At="claude-fable-5-1",Ki="claude-3-haiku-20240307",Hi="claude-3-5-haiku-20241022",Bi="claude-3-5-sonnet-20241022",Wi="claude-3-7-sonnet-20250219",$i="claude-sonnet-4-20250514",zi="claude-opus-4-20250514",Mo="claude-sonnet-4-5-20250929",V="claude-haiku-4-5-20251001",It="claude-opus-4-5-20251101",Dt="claude-sonnet-4-6",bt="claude-opus-4-6",Nt="claude-opus-4-7",wt="claude-opus-4-8",kt="claude-fable-5",Gt="claude-sonnet-5",Vt="claude-opus-5",Oo="claude-opus-5-5",hs=[Ki,Hi,Bi,Wi,$i,zi],Hn=["low","medium","high"],Ui=[...Hn,"max"],Te=[...Hn,"xhigh","max"],ds={[It]:Hn,[Dt]:Ui,[bt]:Ui,[Nt]:Te,[wt]:Te,[At]:Te,[kt]:Te,[Gt]:Te,[Vt]:Te},Ft=[At,Mo,V,It,Dt,bt,Nt,wt,kt,Gt,Vt,Oo];function U(o){return ds[o]??[]}function Xi(o){return U(o).length>0}function qi(o){return Xi(o)?"high":void 0}function _s(o,e){let t=U(o);if(t.length!==0)return e?t.includes(e)?e:"high":qi(o)}var Ut="https://openrouter.ai/api/v1/chat/completions",Kt="openai/gpt-6-astra",Ht="openai/gpt-6-astra-pro",ce="anthropic/claude-fable-5.1",Bt="deepseek/deepseek-v4.1-flash",Wt="google/gemini-3.8-flash",Pe="inclusionai/ling-3.0-flash-vl:free",So="inception/mercury-2.5",xe="nex-agi/nex-n2.5-mini:free",ye="nex-agi/nex-n2.5-pro:free",ue="qwen/qwen3.8-max-0902",he="meta/muse-spark-1.3",$t="openrouter/auto",Ae="openrouter/auto-beta",Bn="openrouter/fusion",K="openai/gpt-oss-20b:free",vo="moonshotai/kimi-k3",Co="moonshotai/kimi-k2.7-code",zt="moonshotai/kimi-k2.6",Lo="moonshotai/kimi-k2.5",To="~moonshotai/kimi-latest",Ro="~openai/gpt-latest",Po="~openai/gpt-mini-latest",xo="openai/gpt-5.6-sol",yo="openai/gpt-5.6-terra",Ao="openai/gpt-5.6-luna",Io="openai/gpt-5.5-pro",Do="openai/gpt-5.5",ji="openai/gpt-5.1-chat",bo="openai/gpt-5.1-codex",No="openai/gpt-5-mini",wo="openai/gpt-5-nano",ko="openai/gpt-4o",Go="openai/gpt-4.1-mini",Vo="openai/gpt-4.1-nano",Fo="~anthropic/claude-sonnet-latest",Uo="~anthropic/claude-haiku-latest",Ko="anthropic/claude-fable-5",Ie="anthropic/claude-sonnet-5",Ho="anthropic/claude-opus-5",Xt="anthropic/claude-opus-4.8",Bo="anthropic/claude-opus-4",Wo="anthropic/claude-sonnet-4",Zi="anthropic/claude-3.7-sonnet",Ji="anthropic/claude-3.5-sonnet",$o="anthropic/claude-haiku-4.5",zo="~google/gemini-pro-latest",Xo="~google/gemini-flash-latest",qo="google/gemini-3.7-flash",jo="google/gemini-3.6-flash",Zo="google/gemini-3.5-flash-lite",Jo="google/gemini-2.5-pro",Yo="google/gemini-2.5-flash",Qo="google/gemini-2.5-flash-lite-preview-09-2025",De="z-ai/glm-5.2",Q="z-ai/glm-5.3",H="z-ai/glm-5.3-flash",Wn="z-ai/glm-4.7-flash",$n="z-ai/glm-4.5-air",Yi="z-ai/glm-4.5-air:free",zn="kwaipilot/kat-coder-air-v2.5",Xn="kwaipilot/kat-coder-pro-v2.5",en="~x-ai/grok-latest",tn="x-ai/grok-4.6",on="x-ai/grok-4.5",be="deepseek/deepseek-v4-flash",Ne="deepseek/deepseek-v4-flash-0731",we="deepseek/deepseek-v4-pro-0813",de="deepseek/deepseek-v4-flash-vision-exp",qt="qwen/qwen3.8-flash",gs=[ji,Zi,Ji,Yi],fs=["none","minimal","low","medium","high"],ms=["none","high","xhigh"],Es=["none","low","high","max"],Ms=["none","high","xhigh"],Os=["low","high","max"],Ss=["none","low","high","max"],vs=["none","low","medium","high","xhigh","max"],Re={[Kt]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"medium"},[Ht]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"medium"},[ce]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"high"},[Bt]:{efforts:["max","high","low","none"],defaultEffort:"none"},[Wt]:{efforts:["high","medium","low"],defaultEffort:"medium"},[Pe]:{efforts:[],defaultEffort:void 0},[So]:{efforts:["high","medium","low","none"],defaultEffort:"none"},[xe]:{efforts:["high","medium","none"],defaultEffort:"none"},[ye]:{efforts:["high","medium","none"],defaultEffort:"none"},[ue]:{efforts:["xhigh","high","medium","low","minimal"],defaultEffort:"xhigh"},[he]:{efforts:["max","xhigh","high","medium","low","minimal"],defaultEffort:"medium"}},qn=[K,Pe,xe,ye],Qi=[Kt,Ht,ce,Bt,Wt,Pe,xe,ye,ue,he,Ae,vo,zt,To,Ro,Po,xo,yo,Ao,Io,Do,bo,No,wo,ko,Go,Vo,Fo,Uo,Ko,Ie,Ho,Xt,Bo,Wo,$o,zo,Xo,qo,jo,Zo,Jo,Yo,Qo,H,de,qt,Co,Lo,en,tn,on],jn=20,Cs=50,Ls=1e3,Ts=10;function _e(o){return o.trim().endsWith(":free")}function ke(o){return Qi.some(e=>o.includes(e))}function nn(o){let e=o.trim(),t=Object.prototype.hasOwnProperty.call(Re,e)?Re[e]:void 0;return t?t.efforts:e===Q||e===H?Os:e===de?Ss:e===Ie||e===Xt?vs:e===be?ms:e===Ne?Es:e===we?Ms:fs}function rn(o){let e=o.trim(),t=Object.prototype.hasOwnProperty.call(Re,e)?Re[e]:void 0;return t?t.defaultEffort:e===Q||e===H?"low":e===De||e===qt||e===zt||e===Ie||e===de||e===be||e===Ne||e===we?"none":void 0}function Zn(o,e){let t=o.trim(),n=Object.prototype.hasOwnProperty.call(Re,t)?Re[t]:void 0,i=e??rn(o);if(n)return i&&n.efforts.includes(i)?i:n.defaultEffort;if(!i)return;if(t===Q||t===H)return i==="high"?"high":i==="max"||i==="xhigh"?"max":"low";if(nn(o).includes(i))return i;if(t===be)return i==="max"?"xhigh":"none";if(t===Ne){if(i==="minimal"||i==="medium")return"low";if(i==="xhigh")return"high"}if(t===we){if(i==="minimal"||i==="low")return"none";if(i==="medium")return"high";if(i==="max")return"xhigh"}if(t===de){if(i==="minimal"||i==="medium")return"low";if(i==="xhigh")return"high"}return i}var jt="https://api.z.ai/api/paas/v4/chat/completions",sn="glm-5.3",Zt="glm-5.3-flash",ee="glm-5.2",Jn="glm-5.1",Yn="glm-5",Qn="glm-5-turbo",an="glm-5v-turbo",ei="glm-4.7",ti="glm-4.7-FlashX",oi="glm-4.7-Flash",ni="glm-4.6",ln="glm-4.6V",pn="glm-4.6V-FlashX",ge="glm-4.6V-Flash",Rs=["none","minimal","low","medium","high","xhigh","max"],Ps=["low","high","max"];function Ge(o){return o===sn||o===Zt}function Ve(o){return Ge(o)?Ps:o===ee?Rs:[]}function cn(o){return Ve(o).length>0}function er(o){return Ge(o)?"low":o===ee?"none":void 0}function ii(o,e){if(!cn(o))return;let t=e??er(o);return Ge(o)?t==="high"?"high":t==="max"||t==="xhigh"?"max":"low":t==="none"||t==="minimal"?"none":t==="low"||t==="medium"||t==="high"?"high":"max"}var tr=[Zt,an,ln,pn,ge];function Fe(o){return tr.includes(o)}function ri(o){let e=o.toLowerCase();return e.startsWith("glm-5.3")||e.startsWith("glm-4.6")}var Jt="https://api.x.ai/v1/chat/completions",Ue="grok-4.6",Ke="grok-4.7",He="grok-4.5",F="grok-4.3",un="grok-4.20-0309-reasoning",hn="grok-4.20-0309-non-reasoning",or="grok-4-1-fast-reasoning",nr="grok-4-1-fast-non-reasoning",xs=[or,nr],ir=[Ue,Ke,He,F,un,hn];function Be(o){return ir.includes(o)}function dn(o){return We(o).length>0}function We(o){return o===Ue||o===Ke?["low","medium","high","xhigh"]:o===He?["low","medium","high"]:o===F?["none","low","medium","high"]:[]}function rr(o){return We(o).includes("none")}function _n(o){return o===Ke||o===Ue||o===He?"low":rr(o)?"none":void 0}function Yt(o,e){return dn(o)?e===void 0?_n(o):We(o).includes(e)?e:e==="none"?"low":"high":void 0}var $e="https://api.moonshot.ai/v1/chat/completions",ze="kimi-k3",Qt="kimi-k2.7-code",eo="kimi-k2.7-code-highspeed",B="kimi-k2.6",gn="kimi-k2.5",ys={[ze]:["low","high","max"]},sr=[ze,Qt,eo,B,gn],ar=[Qt,eo];function Xe(o){return sr.includes(o)}function to(o){return ar.includes(o)}function te(o){return ys[o]??[]}function qe(o){return o===ze?"max":void 0}function fe(o){return te(o).length>0}var pr="https://api.deepseek.com",oo=`${pr}/chat/completions`,fn="deepseek-flash",me="deepseek-v4-flash",mn="deepseek-v4-pro",je="deepseek-v4-flash-vision-exp",lr=["none","low","high","max"],As=["none","high","max"],cr="deepseek-chat",ur="deepseek-reasoner",ai=[fn,me,mn,je],hr=[fn,je],Is=[cr,ur];function no(o){return o===fn||o===me||o===je?lr:o===mn?As:[]}function li(o){return hr.includes(o)}function dr(o){return no(o).length>0}function si(o){return dr(o)?"none":void 0}function pi(o,e){let t=no(o);if(t.length===0)return;let n=e??si(o);return n&&t.includes(n)?n:o===mn&&n==="low"?"high":si(o)}var _r="https://api.mistral.ai/v1",io=`${_r}/chat/completions`,ci="ministral-3b-2512",ui="ministral-8b-2512",hi="ministral-14b-2512",W="mistral-small-latest",di="mistral-small-2603",En="mistral-medium-3-5",gr="mistral-medium-2508",_i="mistral-large-latest",gi="mistral-large-2512",fi=[W,ci,ui,hi,En,_i,gi,di],Ds=[gr],fr=[W,En],mr=[W,ci,ui,hi,di,En,_i,gi];function ro(o){return fr.includes(o)}function mi(o){return o==="none"||o==="high"}function Ei(o){return mr.includes(o)}var Er="https://api.sakana.ai/v1",so=`${Er}/chat/completions`,Ze="fugu",Mr="fugu-ultra",Or="fugu-ultra-v1.1",Ee="sakana-namazu",Sr="fugu-ultra-20260615",Mi=[Ze,Or,Ee],vr=[Ee];function Oi(o){return vr.includes(o)}var bs=[Mr,Sr];var Cr="https://api.platform.preferredai.jp/v1",ao=`${Cr}/chat/completions`,Je="plamo-3.0-prime",Lr="plamo-2.2-prime",Si=[Je],Ns=[Lr];var L={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Mn={[L.VERY_SHORT]:40,[L.SHORT]:100,[L.MEDIUM]:200,[L.LONG]:300,[L.VERY_LONG]:1e3,[L.DEEP]:5e3},vi=5e3,Ci={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 P(o){return o?Mn[o]??vi:vi}var ws="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",ks=`You are a skilled summarizing assistant.
1
+ "use strict";var AITuberOnAirChat=(()=>{var Rn=Object.defineProperty;var rs=Object.getOwnPropertyDescriptor;var ss=Object.getOwnPropertyNames;var as=Object.prototype.hasOwnProperty;var ls=(o,e)=>{for(var t in e)Rn(o,t,{get:e[t],enumerable:!0})},ps=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ss(e))!as.call(o,i)&&i!==t&&Rn(o,i,{get:()=>e[i],enumerable:!(n=rs(e,i))||n.enumerable});return o};var cs=o=>ps(Rn({},"__esModule",{value:!0}),o);var xa={};ls(xa,{CHAT_RESPONSE_LENGTH:()=>L,CLAUDE_DEPRECATED_MODELS:()=>fs,CLAUDE_VISION_SUPPORTED_MODELS:()=>Kt,ChatServiceFactory:()=>Lt,ChatServiceHttpClient:()=>M,ClaudeChatService:()=>et,ClaudeChatServiceProvider:()=>tt,DEEPSEEK_API_BASE_URL:()=>ur,DEEPSEEK_DEPRECATED_MODELS:()=>ws,DEEPSEEK_SUPPORTED_MODELS:()=>pi,DEEPSEEK_VISION_SUPPORTED_MODELS:()=>mr,DEFAULT_MAX_TOKENS:()=>Li,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>Us,DEFAULT_VISION_PROMPT:()=>Fs,DeepSeekChatService:()=>ot,DeepSeekChatServiceProvider:()=>nt,EMOTION_TAG_CLEANUP_REGEX:()=>yi,EMOTION_TAG_REGEX:()=>yr,ENDPOINT_CLAUDE_API:()=>Bn,ENDPOINT_DEEPSEEK_CHAT_COMPLETIONS_API:()=>io,ENDPOINT_GEMINI_API:()=>Dn,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>ze,ENDPOINT_MISTRAL_CHAT_COMPLETIONS_API:()=>so,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>q,ENDPOINT_OPENAI_RESPONSES_API:()=>w,ENDPOINT_OPENROUTER_API:()=>Ht,ENDPOINT_PLAMO_CHAT_COMPLETIONS_API:()=>po,ENDPOINT_SAKANA_CHAT_COMPLETIONS_API:()=>lo,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>Qt,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>Jt,EmotionParser:()=>Qe,GEMINI_DEPRECATED_MODELS:()=>Ki,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>Ri,GEMINI_RECOMMENDED_MODELS:()=>Oo,GEMINI_VISION_SUPPORTED_MODELS:()=>xt,GPT5_PRESETS:()=>Ti,GPT_5_MODELS:()=>Di,GeminiChatService:()=>it,GeminiChatServiceProvider:()=>rt,GeminiNanoChatService:()=>st,GeminiNanoChatServiceProvider:()=>at,HttpError:()=>ne,KIMI_THINKING_REQUIRED_MODELS:()=>pr,KIMI_VISION_SUPPORTED_MODELS:()=>lr,KimiChatService:()=>lt,KimiChatServiceProvider:()=>pt,MAX_TOKENS_BY_LENGTH:()=>Sn,MISTRAL_API_BASE_URL:()=>fr,MISTRAL_DEPRECATED_MODELS:()=>ks,MISTRAL_REASONING_EFFORT_SUPPORTED_MODELS:()=>Er,MISTRAL_SUPPORTED_MODELS:()=>Ei,MISTRAL_VISION_SUPPORTED_MODELS:()=>Mr,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>Qi,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>Yi,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>qo,MODEL_ANTHROPIC_CLAUDE_FABLE_5:()=>Bo,MODEL_ANTHROPIC_CLAUDE_FABLE_5_1:()=>he,MODEL_ANTHROPIC_CLAUDE_HAIKU_LATEST:()=>Ho,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>$o,MODEL_ANTHROPIC_CLAUDE_OPUS_4_8:()=>jt,MODEL_ANTHROPIC_CLAUDE_OPUS_5:()=>Wo,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>zo,MODEL_ANTHROPIC_CLAUDE_SONNET_5:()=>De,MODEL_ANTHROPIC_CLAUDE_SONNET_LATEST:()=>Ko,MODEL_CLAUDE_3_5_HAIKU:()=>Wi,MODEL_CLAUDE_3_5_SONNET:()=>$i,MODEL_CLAUDE_3_7_SONNET:()=>zi,MODEL_CLAUDE_3_HAIKU:()=>Bi,MODEL_CLAUDE_4_5_HAIKU:()=>F,MODEL_CLAUDE_4_5_OPUS:()=>Dt,MODEL_CLAUDE_4_5_SONNET:()=>So,MODEL_CLAUDE_4_6_OPUS:()=>Nt,MODEL_CLAUDE_4_6_SONNET:()=>bt,MODEL_CLAUDE_4_7_OPUS:()=>wt,MODEL_CLAUDE_4_8_OPUS:()=>kt,MODEL_CLAUDE_4_OPUS:()=>Xi,MODEL_CLAUDE_4_SONNET:()=>qi,MODEL_CLAUDE_5_1_FABLE:()=>It,MODEL_CLAUDE_5_5_OPUS:()=>vo,MODEL_CLAUDE_5_5_SONNET:()=>Ut,MODEL_CLAUDE_5_FABLE:()=>Gt,MODEL_CLAUDE_5_OPUS:()=>Ft,MODEL_CLAUDE_5_SONNET:()=>Vt,MODEL_DEEPSEEK_CHAT:()=>hr,MODEL_DEEPSEEK_FLASH:()=>En,MODEL_DEEPSEEK_REASONER:()=>dr,MODEL_DEEPSEEK_V4_FLASH:()=>Me,MODEL_DEEPSEEK_V4_FLASH_VISION_EXP:()=>Ze,MODEL_DEEPSEEK_V4_PRO:()=>Mn,MODEL_FUGU:()=>Je,MODEL_FUGU_ULTRA:()=>Sr,MODEL_FUGU_ULTRA_20260615:()=>Cr,MODEL_FUGU_ULTRA_V1_1:()=>vr,MODEL_GEMINI_2_5_FLASH:()=>Vi,MODEL_GEMINI_2_5_FLASH_LITE:()=>Fi,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>Ui,MODEL_GEMINI_2_5_PRO:()=>Gi,MODEL_GEMINI_3_1_FLASH_LITE:()=>Q,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>Fn,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>Vn,MODEL_GEMINI_3_5_FLASH:()=>kn,MODEL_GEMINI_3_5_FLASH_LITE:()=>Gn,MODEL_GEMINI_3_6_FLASH:()=>wn,MODEL_GEMINI_3_7_FLASH:()=>Nn,MODEL_GEMINI_3_8_FLASH:()=>bn,MODEL_GEMINI_3_FLASH_PREVIEW:()=>Kn,MODEL_GEMINI_3_PRO_PREVIEW:()=>Un,MODEL_GEMINI_NANO:()=>Se,MODEL_GEMMA_4_26B_A4B_IT:()=>ki,MODEL_GEMMA_4_31B_IT:()=>wi,MODEL_GLM_4_6:()=>ri,MODEL_GLM_4_6V:()=>cn,MODEL_GLM_4_6V_FLASH:()=>_e,MODEL_GLM_4_6V_FLASHX:()=>un,MODEL_GLM_4_7:()=>oi,MODEL_GLM_4_7_FLASH:()=>ii,MODEL_GLM_4_7_FLASHX:()=>ni,MODEL_GLM_5:()=>ei,MODEL_GLM_5V_TURBO:()=>pn,MODEL_GLM_5_1:()=>Qn,MODEL_GLM_5_2:()=>te,MODEL_GLM_5_3:()=>ln,MODEL_GLM_5_3_FLASH:()=>Yt,MODEL_GLM_5_TURBO:()=>ti,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>en,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>tn,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>Qo,MODEL_GOOGLE_GEMINI_3_5_FLASH_LITE:()=>Yo,MODEL_GOOGLE_GEMINI_3_6_FLASH:()=>Jo,MODEL_GOOGLE_GEMINI_3_7_FLASH:()=>Zo,MODEL_GOOGLE_GEMINI_3_8_FLASH:()=>zt,MODEL_GOOGLE_GEMINI_FLASH_LATEST:()=>jo,MODEL_GOOGLE_GEMINI_PRO_LATEST:()=>Xo,MODEL_GPT_4O:()=>_o,MODEL_GPT_4O_MINI:()=>pe,MODEL_GPT_4_1:()=>mo,MODEL_GPT_4_1_MINI:()=>go,MODEL_GPT_4_1_NANO:()=>fo,MODEL_GPT_5:()=>Le,MODEL_GPT_5_1:()=>Te,MODEL_GPT_5_4:()=>re,MODEL_GPT_5_4_MINI:()=>ae,MODEL_GPT_5_4_NANO:()=>le,MODEL_GPT_5_4_PRO:()=>Y,MODEL_GPT_5_5:()=>se,MODEL_GPT_5_6:()=>X,MODEL_GPT_5_6_LUNA:()=>J,MODEL_GPT_5_6_SOL:()=>j,MODEL_GPT_5_6_TERRA:()=>Z,MODEL_GPT_5_MINI:()=>Ce,MODEL_GPT_5_NANO:()=>ie,MODEL_GPT_6_ASTRA:()=>y,MODEL_GPT_6_LUNA:()=>D,MODEL_GPT_6_SOL:()=>I,MODEL_GPT_OSS_20B_FREE:()=>H,MODEL_GROK_4_1_FAST_NON_REASONING:()=>rr,MODEL_GROK_4_1_FAST_REASONING:()=>ir,MODEL_GROK_4_20_NON_REASONING:()=>mn,MODEL_GROK_4_20_REASONING:()=>dn,MODEL_GROK_4_3:()=>U,MODEL_GROK_4_5:()=>Be,MODEL_GROK_4_6:()=>Ke,MODEL_GROK_4_7:()=>He,MODEL_INCEPTION_MERCURY_2_5:()=>Co,MODEL_INCLUSIONAI_LING_3_0_FLASH_VL_FREE:()=>Pe,MODEL_KIMI_K2_5:()=>_n,MODEL_KIMI_K2_6:()=>W,MODEL_KIMI_K2_7_CODE:()=>to,MODEL_KIMI_K2_7_CODE_HIGHSPEED:()=>oo,MODEL_KIMI_K3:()=>qe,MODEL_KWAIPILOT_KAT_CODER_AIR_V2_5:()=>Xn,MODEL_KWAIPILOT_KAT_CODER_PRO_V2_5:()=>jn,MODEL_META_MUSE_SPARK_1_3:()=>me,MODEL_MINISTRAL_14B_2512:()=>mi,MODEL_MINISTRAL_3B_2512:()=>hi,MODEL_MINISTRAL_8B_2512:()=>di,MODEL_MISTRAL_LARGE_2512:()=>_i,MODEL_MISTRAL_LARGE_LATEST:()=>fi,MODEL_MISTRAL_MEDIUM_2508:()=>_r,MODEL_MISTRAL_MEDIUM_3_5:()=>On,MODEL_MISTRAL_SMALL_2603:()=>gi,MODEL_MISTRAL_SMALL_LATEST:()=>$,MODEL_MOONSHOTAI_KIMI_K2_5:()=>Ro,MODEL_MOONSHOTAI_KIMI_K2_6:()=>Xt,MODEL_MOONSHOTAI_KIMI_K2_7_CODE:()=>To,MODEL_MOONSHOTAI_KIMI_K3:()=>Lo,MODEL_MOONSHOTAI_KIMI_LATEST:()=>yo,MODEL_NEX_AGI_NEX_N2_5_MINI_FREE:()=>xe,MODEL_NEX_AGI_NEX_N2_5_PRO_FREE:()=>Ae,MODEL_O1:()=>xn,MODEL_O1_MINI:()=>Pn,MODEL_O3_MINI:()=>yn,MODEL_OPENAI_GPT_4O:()=>Vo,MODEL_OPENAI_GPT_4_1_MINI:()=>Fo,MODEL_OPENAI_GPT_4_1_NANO:()=>Uo,MODEL_OPENAI_GPT_5_1_CHAT:()=>Ji,MODEL_OPENAI_GPT_5_1_CODEX:()=>wo,MODEL_OPENAI_GPT_5_5:()=>No,MODEL_OPENAI_GPT_5_5_PRO:()=>bo,MODEL_OPENAI_GPT_5_6_LUNA:()=>Do,MODEL_OPENAI_GPT_5_6_SOL:()=>Ao,MODEL_OPENAI_GPT_5_6_TERRA:()=>Io,MODEL_OPENAI_GPT_5_MINI:()=>ko,MODEL_OPENAI_GPT_5_NANO:()=>Go,MODEL_OPENAI_GPT_6_ASTRA:()=>Bt,MODEL_OPENAI_GPT_6_ASTRA_PRO:()=>Wt,MODEL_OPENAI_GPT_LATEST:()=>Po,MODEL_OPENAI_GPT_MINI_LATEST:()=>xo,MODEL_OPENROUTER_AUTO:()=>qt,MODEL_OPENROUTER_AUTO_BETA:()=>Ie,MODEL_OPENROUTER_DEEPSEEK_V4_1_FLASH:()=>$t,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH:()=>Ne,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_0731:()=>we,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_VISION_EXP:()=>ge,MODEL_OPENROUTER_DEEPSEEK_V4_PRO_0813:()=>ke,MODEL_OPENROUTER_FUSION:()=>$n,MODEL_PLAMO_2_2_PRIME:()=>Rr,MODEL_PLAMO_3_0_PRIME:()=>Ye,MODEL_QWEN_QWEN_3_8_FLASH:()=>Zt,MODEL_QWEN_QWEN_3_8_MAX_0902:()=>de,MODEL_SAKANA_NAMAZU:()=>Oe,MODEL_XAI_GROK_4_5:()=>rn,MODEL_XAI_GROK_4_6:()=>nn,MODEL_XAI_GROK_LATEST:()=>on,MODEL_ZAI_GLM_4_5_AIR:()=>qn,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>er,MODEL_ZAI_GLM_4_7_FLASH:()=>zn,MODEL_ZAI_GLM_5_2:()=>be,MODEL_ZAI_GLM_5_3:()=>ee,MODEL_ZAI_GLM_5_3_FLASH:()=>B,MistralChatService:()=>ct,MistralChatServiceProvider:()=>ut,OPENAI_COMPATIBLE_LOCAL_PRESETS:()=>$s,OPENROUTER_CREDITS_THRESHOLD:()=>xs,OPENROUTER_DEPRECATED_MODELS:()=>Ms,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>Ps,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>ys,OPENROUTER_FREE_MODELS:()=>Zn,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>Jn,OPENROUTER_VISION_SUPPORTED_MODELS:()=>tr,OpenAIChatService:()=>x,OpenAIChatServiceProvider:()=>dt,OpenAICompatibleChatServiceProvider:()=>ht,OpenAICompatibleEndpointError:()=>R,OpenRouterChatService:()=>mt,OpenRouterChatServiceProvider:()=>gt,PLAMO_API_BASE_URL:()=>Tr,PLAMO_DEPRECATED_MODELS:()=>Vs,PLAMO_SUPPORTED_MODELS:()=>Ci,PlamoChatService:()=>ft,PlamoChatServiceProvider:()=>_t,SAKANA_API_BASE_URL:()=>Or,SAKANA_COMPATIBILITY_MODELS:()=>Gs,SAKANA_SUPPORTED_MODELS:()=>Si,SAKANA_VISION_SUPPORTED_MODELS:()=>Lr,SakanaChatService:()=>Et,SakanaChatServiceProvider:()=>Mt,StreamTextAccumulator:()=>O,VISION_SUPPORTED_MODELS:()=>Tt,XAIChatService:()=>Ot,XAIChatServiceProvider:()=>St,XAI_DEPRECATED_MODELS:()=>Ds,XAI_VISION_SUPPORTED_MODELS:()=>sr,ZAIChatService:()=>vt,ZAIChatServiceProvider:()=>Ct,ZAI_VISION_SUPPORTED_MODELS:()=>nr,allowsReasoningLow:()=>Mo,allowsReasoningMax:()=>In,allowsReasoningMinimal:()=>yt,allowsReasoningNone:()=>Rt,allowsReasoningXHigh:()=>Eo,buildOpenAICompatibleTools:()=>V,buildToolContinuationMessages:()=>Ca,getChatBackendProviderCapabilities:()=>Ii,getClaudeSupportedReasoningEfforts:()=>K,getDeepSeekSupportedReasoningEfforts:()=>ro,getDefaultClaudeReasoningEffort:()=>Zi,getDefaultDeepSeekReasoningEffort:()=>li,getDefaultGeminiReasoningEffort:()=>gs,getDefaultKimiReasoningEffort:()=>je,getDefaultOpenRouterReasoningEffort:()=>an,getDefaultReasoningEffortForGPT5Model:()=>Ni,getDefaultReasoningEffortForOpenAIModel:()=>Pt,getDefaultXaiReasoningEffort:()=>fn,getDefaultZaiReasoningEffort:()=>or,getGeminiSupportedReasoningEfforts:()=>Re,getKimiSupportedReasoningEfforts:()=>oe,getMaxTokensForResponseLength:()=>P,getOpenRouterSupportedReasoningEfforts:()=>sn,getXaiSupportedReasoningEfforts:()=>$e,getZaiSupportedReasoningEfforts:()=>Fe,installGASFetch:()=>ns,isClaudeReasoningEffortModel:()=>ji,isDeepSeekReasoningEffortModel:()=>gr,isDeepSeekVisionModel:()=>ci,isGPT5Model:()=>bi,isGeminiReasoningEffortModel:()=>Hn,isKimiReasoningEffortModel:()=>Ee,isKimiThinkingRequiredModel:()=>no,isKimiVisionModel:()=>Xe,isMistralReasoningEffort:()=>Mi,isMistralReasoningEffortModel:()=>ao,isMistralVisionModel:()=>Oi,isOpenAIReasoningModel:()=>ce,isOpenRouterFreeModel:()=>fe,isOpenRouterVisionModel:()=>Ge,isResponsesOnlyGPT5Model:()=>An,isSakanaVisionModel:()=>vi,isXaiReasoningEffortModel:()=>gn,isXaiReasoningEffortNoneModel:()=>ar,isXaiVisionModel:()=>We,isZaiAlwaysThinkingModel:()=>Ve,isZaiReasoningEffortModel:()=>hn,isZaiToolStreamModel:()=>ai,isZaiVisionModel:()=>Ue,listOpenAICompatibleModels:()=>br,normalizeClaudeReasoningEffort:()=>Es,normalizeDeepSeekReasoningEffort:()=>ui,normalizeGeminiReasoningEffort:()=>At,normalizeOpenRouterReasoningEffort:()=>Yn,normalizeXaiReasoningEffort:()=>eo,normalizeZaiReasoningEffort:()=>si,parseOpenAICompatibleOneShot:()=>G,parseOpenAICompatibleTextStream:()=>z,parseOpenAICompatibleToolStream:()=>k,processChatWithOptionalTools:()=>S,refreshOpenRouterFreeModels:()=>oa,resolveOpenAICompatibleEndpoint:()=>Dr,resolveVisionModel:()=>T,runOnceText:()=>Ws,safeJsonParse:()=>xr,safeParseToolCallInput:()=>ve,screenplayToText:()=>Bs,testOpenAICompatibleConnection:()=>zs,textToScreenplay:()=>Pr,textsToScreenplay:()=>Hs});var q="https://api.openai.com/v1/chat/completions",w="https://api.openai.com/v1/responses",y="gpt-6-astra",I="gpt-6-sol",D="gpt-6-luna",ie="gpt-5-nano",Ce="gpt-5-mini",Le="gpt-5",Te="gpt-5.1",re="gpt-5.4",se="gpt-5.5",X="gpt-5.6",j="gpt-5.6-sol",Z="gpt-5.6-terra",J="gpt-5.6-luna",ae="gpt-5.4-mini",le="gpt-5.4-nano",Y="gpt-5.4-pro",mo="gpt-4.1",go="gpt-4.1-mini",fo="gpt-4.1-nano",pe="gpt-4o-mini",_o="gpt-4o",yn="o3-mini",Pn="o1-mini",xn="o1",Tt=[y,I,D,ie,Ce,Le,Te,re,se,X,j,Z,J,ae,le,Y,mo,go,fo,pe,_o,"o1"],Di=[ie,Ce,Le,Te,re,se,X,j,Z,J,ae,le,Y];function bi(o){return Di.includes(o)}function ce(o){return o===y||o===I||o===D||bi(o)}function An(o){return o===Y}function Eo(o){return o===y||o===I||o===D||o===X||o===j||o===Z||o===J||o===se||o===re||o===ae||o===le||o===Y}function In(o){return o===y||o===I||o===D||o===X||o===j||o===Z||o===J}function Rt(o){return o===I||o===D||o===X||o===j||o===Z||o===J||o===Te||o===re||o===se||o===ae||o===le}function yt(o){return o===ie||o===Ce||o===Le}function Mo(o){return o!==Y}function Ni(o){return Rt(o)?"none":yt(o)?"minimal":"medium"}function Pt(o){return o===y?"low":o===I?"medium":o===D?"low":Ni(o)}var Dn="https://generativelanguage.googleapis.com",wi="gemma-4-31b-it",ki="gemma-4-26b-a4b-it",bn="gemini-3.8-flash",Nn="gemini-3.7-flash",wn="gemini-3.6-flash",kn="gemini-3.5-flash",Gn="gemini-3.5-flash-lite",Vn="gemini-3.1-pro-preview",Q="gemini-3.1-flash-lite",Fn="gemini-3.1-flash-lite-preview",Un="gemini-3-pro-preview",Kn="gemini-3-flash-preview",Gi="gemini-2.5-pro",Vi="gemini-2.5-flash",Fi="gemini-2.5-flash-lite",Ui="gemini-2.5-flash-lite-preview-06-17",Oo=[bn,Nn,wn,kn,Gn,Q,Vn,Kn,Gi,Vi,Fi,wi,ki],Ki=[Fn,Un,Ui],xt=[...Oo,...Ki],us=["minimal","low","medium","high"],hs=["low","medium","high"],ds=[wn,kn,Gn,Q,Fn,Kn],ms=[bn,Nn,Vn,Un];function Re(o){return ds.includes(o)?us:ms.includes(o)?hs:[]}function Hn(o){return Re(o).length>0}function gs(o){return Re(o)[0]}function At(o,e){let t=Re(o);if(t.length!==0)return e&&t.includes(e)?e:t[0]}var Bn="https://api.anthropic.com/v1/messages",It="claude-fable-5-1",Bi="claude-3-haiku-20240307",Wi="claude-3-5-haiku-20241022",$i="claude-3-5-sonnet-20241022",zi="claude-3-7-sonnet-20250219",qi="claude-sonnet-4-20250514",Xi="claude-opus-4-20250514",So="claude-sonnet-4-5-20250929",F="claude-haiku-4-5-20251001",Dt="claude-opus-4-5-20251101",bt="claude-sonnet-4-6",Nt="claude-opus-4-6",wt="claude-opus-4-7",kt="claude-opus-4-8",Gt="claude-fable-5",Vt="claude-sonnet-5",Ft="claude-opus-5",vo="claude-opus-5-5",Ut="claude-sonnet-5-5",fs=[Bi,Wi,$i,zi,qi,Xi],Wn=["low","medium","high"],Hi=[...Wn,"max"],ue=[...Wn,"xhigh","max"],_s={[Dt]:Wn,[bt]:Hi,[Nt]:Hi,[wt]:ue,[kt]:ue,[It]:ue,[Gt]:ue,[Vt]:ue,[Ft]:ue,[Ut]:ue},Kt=[It,So,F,Dt,bt,Nt,wt,kt,Gt,Vt,Ft,vo,Ut];function K(o){return _s[o]??[]}function ji(o){return K(o).length>0}function Zi(o){return ji(o)?"high":void 0}function Es(o,e){let t=K(o);if(t.length!==0)return e?t.includes(e)?e:"high":Zi(o)}var Ht="https://openrouter.ai/api/v1/chat/completions",Bt="openai/gpt-6-astra",Wt="openai/gpt-6-astra-pro",he="anthropic/claude-fable-5.1",$t="deepseek/deepseek-v4.1-flash",zt="google/gemini-3.8-flash",Pe="inclusionai/ling-3.0-flash-vl:free",Co="inception/mercury-2.5",xe="nex-agi/nex-n2.5-mini:free",Ae="nex-agi/nex-n2.5-pro:free",de="qwen/qwen3.8-max-0902",me="meta/muse-spark-1.3",qt="openrouter/auto",Ie="openrouter/auto-beta",$n="openrouter/fusion",H="openai/gpt-oss-20b:free",Lo="moonshotai/kimi-k3",To="moonshotai/kimi-k2.7-code",Xt="moonshotai/kimi-k2.6",Ro="moonshotai/kimi-k2.5",yo="~moonshotai/kimi-latest",Po="~openai/gpt-latest",xo="~openai/gpt-mini-latest",Ao="openai/gpt-5.6-sol",Io="openai/gpt-5.6-terra",Do="openai/gpt-5.6-luna",bo="openai/gpt-5.5-pro",No="openai/gpt-5.5",Ji="openai/gpt-5.1-chat",wo="openai/gpt-5.1-codex",ko="openai/gpt-5-mini",Go="openai/gpt-5-nano",Vo="openai/gpt-4o",Fo="openai/gpt-4.1-mini",Uo="openai/gpt-4.1-nano",Ko="~anthropic/claude-sonnet-latest",Ho="~anthropic/claude-haiku-latest",Bo="anthropic/claude-fable-5",De="anthropic/claude-sonnet-5",Wo="anthropic/claude-opus-5",jt="anthropic/claude-opus-4.8",$o="anthropic/claude-opus-4",zo="anthropic/claude-sonnet-4",Yi="anthropic/claude-3.7-sonnet",Qi="anthropic/claude-3.5-sonnet",qo="anthropic/claude-haiku-4.5",Xo="~google/gemini-pro-latest",jo="~google/gemini-flash-latest",Zo="google/gemini-3.7-flash",Jo="google/gemini-3.6-flash",Yo="google/gemini-3.5-flash-lite",Qo="google/gemini-2.5-pro",en="google/gemini-2.5-flash",tn="google/gemini-2.5-flash-lite-preview-09-2025",be="z-ai/glm-5.2",ee="z-ai/glm-5.3",B="z-ai/glm-5.3-flash",zn="z-ai/glm-4.7-flash",qn="z-ai/glm-4.5-air",er="z-ai/glm-4.5-air:free",Xn="kwaipilot/kat-coder-air-v2.5",jn="kwaipilot/kat-coder-pro-v2.5",on="~x-ai/grok-latest",nn="x-ai/grok-4.6",rn="x-ai/grok-4.5",Ne="deepseek/deepseek-v4-flash",we="deepseek/deepseek-v4-flash-0731",ke="deepseek/deepseek-v4-pro-0813",ge="deepseek/deepseek-v4-flash-vision-exp",Zt="qwen/qwen3.8-flash",Ms=[Ji,Yi,Qi,er],Os=["none","minimal","low","medium","high"],Ss=["none","high","xhigh"],vs=["none","low","high","max"],Cs=["none","high","xhigh"],Ls=["low","high","max"],Ts=["none","low","high","max"],Rs=["none","low","medium","high","xhigh","max"],ye={[Bt]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"medium"},[Wt]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"medium"},[he]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"high"},[$t]:{efforts:["max","high","low","none"],defaultEffort:"none"},[zt]:{efforts:["high","medium","low"],defaultEffort:"medium"},[Pe]:{efforts:[],defaultEffort:void 0},[Co]:{efforts:["high","medium","low","none"],defaultEffort:"none"},[xe]:{efforts:["high","medium","none"],defaultEffort:"none"},[Ae]:{efforts:["high","medium","none"],defaultEffort:"none"},[de]:{efforts:["xhigh","high","medium","low","minimal"],defaultEffort:"xhigh"},[me]:{efforts:["max","xhigh","high","medium","low","minimal"],defaultEffort:"medium"}},Zn=[H,Pe,xe,Ae],tr=[Bt,Wt,he,$t,zt,Pe,xe,Ae,de,me,Ie,Lo,Xt,yo,Po,xo,Ao,Io,Do,bo,No,wo,ko,Go,Vo,Fo,Uo,Ko,Ho,Bo,De,Wo,jt,$o,zo,qo,Xo,jo,Zo,Jo,Yo,Qo,en,tn,B,ge,Zt,To,Ro,on,nn,rn],Jn=20,ys=50,Ps=1e3,xs=10;function fe(o){return o.trim().endsWith(":free")}function Ge(o){return tr.some(e=>o.includes(e))}function sn(o){let e=o.trim(),t=Object.prototype.hasOwnProperty.call(ye,e)?ye[e]:void 0;return t?t.efforts:e===ee||e===B?Ls:e===ge?Ts:e===De||e===jt?Rs:e===Ne?Ss:e===we?vs:e===ke?Cs:Os}function an(o){let e=o.trim(),t=Object.prototype.hasOwnProperty.call(ye,e)?ye[e]:void 0;return t?t.defaultEffort:e===ee||e===B?"low":e===be||e===Zt||e===Xt||e===De||e===ge||e===Ne||e===we||e===ke?"none":void 0}function Yn(o,e){let t=o.trim(),n=Object.prototype.hasOwnProperty.call(ye,t)?ye[t]:void 0,i=e??an(o);if(n)return i&&n.efforts.includes(i)?i:n.defaultEffort;if(!i)return;if(t===ee||t===B)return i==="high"?"high":i==="max"||i==="xhigh"?"max":"low";if(sn(o).includes(i))return i;if(t===Ne)return i==="max"?"xhigh":"none";if(t===we){if(i==="minimal"||i==="medium")return"low";if(i==="xhigh")return"high"}if(t===ke){if(i==="minimal"||i==="low")return"none";if(i==="medium")return"high";if(i==="max")return"xhigh"}if(t===ge){if(i==="minimal"||i==="medium")return"low";if(i==="xhigh")return"high"}return i}var Jt="https://api.z.ai/api/paas/v4/chat/completions",ln="glm-5.3",Yt="glm-5.3-flash",te="glm-5.2",Qn="glm-5.1",ei="glm-5",ti="glm-5-turbo",pn="glm-5v-turbo",oi="glm-4.7",ni="glm-4.7-FlashX",ii="glm-4.7-Flash",ri="glm-4.6",cn="glm-4.6V",un="glm-4.6V-FlashX",_e="glm-4.6V-Flash",As=["none","minimal","low","medium","high","xhigh","max"],Is=["low","high","max"];function Ve(o){return o===ln||o===Yt}function Fe(o){return Ve(o)?Is:o===te?As:[]}function hn(o){return Fe(o).length>0}function or(o){return Ve(o)?"low":o===te?"none":void 0}function si(o,e){if(!hn(o))return;let t=e??or(o);return Ve(o)?t==="high"?"high":t==="max"||t==="xhigh"?"max":"low":t==="none"||t==="minimal"?"none":t==="low"||t==="medium"||t==="high"?"high":"max"}var nr=[Yt,pn,cn,un,_e];function Ue(o){return nr.includes(o)}function ai(o){let e=o.toLowerCase();return e.startsWith("glm-5.3")||e.startsWith("glm-4.6")}var Qt="https://api.x.ai/v1/chat/completions",Ke="grok-4.6",He="grok-4.7",Be="grok-4.5",U="grok-4.3",dn="grok-4.20-0309-reasoning",mn="grok-4.20-0309-non-reasoning",ir="grok-4-1-fast-reasoning",rr="grok-4-1-fast-non-reasoning",Ds=[ir,rr],sr=[Ke,He,Be,U,dn,mn];function We(o){return sr.includes(o)}function gn(o){return $e(o).length>0}function $e(o){return o===Ke||o===He?["low","medium","high","xhigh"]:o===Be?["low","medium","high"]:o===U?["none","low","medium","high"]:[]}function ar(o){return $e(o).includes("none")}function fn(o){return o===He||o===Ke||o===Be?"low":ar(o)?"none":void 0}function eo(o,e){return gn(o)?e===void 0?fn(o):$e(o).includes(e)?e:e==="none"?"low":"high":void 0}var ze="https://api.moonshot.ai/v1/chat/completions",qe="kimi-k3",to="kimi-k2.7-code",oo="kimi-k2.7-code-highspeed",W="kimi-k2.6",_n="kimi-k2.5",bs={[qe]:["low","high","max"]},lr=[qe,to,oo,W,_n],pr=[to,oo];function Xe(o){return lr.includes(o)}function no(o){return pr.includes(o)}function oe(o){return bs[o]??[]}function je(o){return o===qe?"max":void 0}function Ee(o){return oe(o).length>0}var ur="https://api.deepseek.com",io=`${ur}/chat/completions`,En="deepseek-flash",Me="deepseek-v4-flash",Mn="deepseek-v4-pro",Ze="deepseek-v4-flash-vision-exp",cr=["none","low","high","max"],Ns=["none","high","max"],hr="deepseek-chat",dr="deepseek-reasoner",pi=[En,Me,Mn,Ze],mr=[En,Ze],ws=[hr,dr];function ro(o){return o===En||o===Me||o===Ze?cr:o===Mn?Ns:[]}function ci(o){return mr.includes(o)}function gr(o){return ro(o).length>0}function li(o){return gr(o)?"none":void 0}function ui(o,e){let t=ro(o);if(t.length===0)return;let n=e??li(o);return n&&t.includes(n)?n:o===Mn&&n==="low"?"high":li(o)}var fr="https://api.mistral.ai/v1",so=`${fr}/chat/completions`,hi="ministral-3b-2512",di="ministral-8b-2512",mi="ministral-14b-2512",$="mistral-small-latest",gi="mistral-small-2603",On="mistral-medium-3-5",_r="mistral-medium-2508",fi="mistral-large-latest",_i="mistral-large-2512",Ei=[$,hi,di,mi,On,fi,_i,gi],ks=[_r],Er=[$,On],Mr=[$,hi,di,mi,gi,On,fi,_i];function ao(o){return Er.includes(o)}function Mi(o){return o==="none"||o==="high"}function Oi(o){return Mr.includes(o)}var Or="https://api.sakana.ai/v1",lo=`${Or}/chat/completions`,Je="fugu",Sr="fugu-ultra",vr="fugu-ultra-v1.1",Oe="sakana-namazu",Cr="fugu-ultra-20260615",Si=[Je,vr,Oe],Lr=[Oe];function vi(o){return Lr.includes(o)}var Gs=[Sr,Cr];var Tr="https://api.platform.preferredai.jp/v1",po=`${Tr}/chat/completions`,Ye="plamo-3.0-prime",Rr="plamo-2.2-prime",Ci=[Ye],Vs=[Rr];var L={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Sn={[L.VERY_SHORT]:40,[L.SHORT]:100,[L.MEDIUM]:200,[L.LONG]:300,[L.VERY_LONG]:1e3,[L.DEEP]:5e3},Li=5e3,Ti={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 P(o){return o?Sn[o]??Li:Li}var Fs="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",Us=`You are a skilled summarizing assistant.
2
2
  Analyze the following conversation and produce a summary in the **same language** as the majority of the conversation:
3
3
  - Summaries should highlight key points
4
4
  - Stay concise (around {maxLength} characters if possible)
@@ -7,13 +7,13 @@ Analyze the following conversation and produce a summary in the **same language*
7
7
  If the conversation is in Japanese, summarize in Japanese.
8
8
  If it's in English, summarize in English.
9
9
  If it's in another language, summarize in that language.
10
- `;var Me="gemini-nano",Li=20;var oe=class extends Error{constructor(t,n,i){super(`HTTP ${t}: ${n}`);this.status=t;this.statusText=n;this.body=i;this.name="HttpError"}},lo=class lo{static setFetch(e){this.fetchImpl=e}static async post(e,t,n={},i={}){let{timeout:r=3e4,retries:s=0,retryDelay:a=1e3}=i,p={...{"Content-Type":"application/json"},...n},d=null;for(let c=0;c<=s;c++)try{let h=typeof AbortController<"u",f=h?new AbortController:void 0,g=h?setTimeout(()=>f.abort(),r):void 0,_=await lo.fetchImpl(e,{method:"POST",headers:p,body:typeof t=="string"?t:JSON.stringify(t),...f?{signal:f.signal}:{}});if(g&&clearTimeout(g),!_.ok){let v=await _.text();throw new oe(_.status,_.statusText,v)}return _}catch(h){if(d=h,h instanceof oe&&h.status>=400&&h.status<500)throw h;if(h instanceof Error&&h.name==="AbortError")throw new Error(`Request timeout after ${r}ms`);c<s&&await new Promise(f=>setTimeout(f,a*(c+1)))}throw d||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new oe(e.status,e.statusText,t)}static async get(e,t={},n={}){let{timeout:i=3e4,retries:r=0,retryDelay:s=1e3}=n,a=null;for(let l=0;l<=r;l++)try{let p=typeof AbortController<"u",d=p?new AbortController:void 0,c=p?setTimeout(()=>d.abort(),i):void 0,h=await lo.fetchImpl(e,{method:"GET",headers:t,...d?{signal:d.signal}:{}});if(c&&clearTimeout(c),!h.ok){let f=await h.text();throw new oe(h.status,h.statusText,f)}return h}catch(p){if(a=p,p instanceof oe&&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(d=>setTimeout(d,s*(l+1)))}throw a||new Error("Request failed")}};lo.fetchImpl=(e,t)=>fetch(e,t);var M=lo;var O=class{static append(e,t){if(!t)return;let n=e[e.length-1];n&&n.type==="text"?n.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 Gs=["happy","sad","angry","surprised","neutral"],Tr=/\[([a-z]+)\]/i,Ti=/\[[a-z]+\]\s*/gi,Ye=class{static extractEmotion(e){let t=e.match(Tr);if(t){let n=t[1].toLowerCase(),i=e.replace(Ti,"").trim();return{emotion:n,cleanText:i}}return{cleanText:e}}static isValidEmotion(e){return Gs.includes(e)}static cleanEmotionTags(e){return e.replace(Ti,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function Rr(o){let{emotion:e,cleanText:t}=Ye.extractEmotion(o);return e?{emotion:e,text:t}:{text:t}}function Vs(o){return o.map(e=>Rr(e))}function Fs(o){return o.emotion?Ye.addEmotionTag(o.emotion,o.text):o.text}async function Us(o,e){let{blocks:t}=await o.chatOnce(e,!1,()=>{});return O.getFullText(t)}var Pr=(o,e,t)=>{try{return JSON.parse(o)}catch(n){return t?.(o,n),e}},Oe=(o,e)=>o?Pr(o,{},e):{};var xr=(o,e)=>{try{return JSON.parse(o)}catch(t){if(e){e(o,t);return}throw t}},On=o=>typeof o=="string"?o:Array.isArray(o)?o.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&e.type==="text"&&typeof e.text=="string"?e.text:"").join(""):"",Ri=o=>{let e=o.choices?.[0],t=o.error??e?.error;if(!t&&e?.finish_reason!=="error")return;let n=typeof t=="string"?t:typeof t?.message=="string"?t.message:"The provider ended the response with an error.";throw new Error(`Provider response error: ${n}`)},yr=async(o,e)=>{let t=o.body?.getReader();if(!t)throw new Error("Response body is null.");let n=new TextDecoder,i="",r=!1;for(;!r;){let{done:s,value:a}=await t.read();if(s)break;i+=n.decode(a,{stream:!0});let l=i.split(`
11
- `);i=l.pop()||"";for(let p of l){let d=p.trim();if(!d||d.startsWith(":")||!d.startsWith("data:"))continue;let c=d.slice(5).trim();if(c==="[DONE]"){r=!0;break}e(c)}}};async function $(o,e,t={}){let n="";return await yr(o,i=>{let r=xr(i,t.onJsonError);if(!r)return;t.throwOnApiError&&Ri(r);let s=On(r.choices?.[0]?.delta?.content);s&&(e(s),n+=s)}),n}async function w(o,e,t={}){let n=[],i=new Map,r="",s="",a,l,p=t.appendTextBlock??O.append;await yr(o,g=>{let _=xr(g,t.onJsonError);if(!_)return;t.throwOnApiError&&Ri(_);let v=_.choices?.[0];typeof v?.finish_reason=="string"&&(a=v.finish_reason),_.usage&&(l=_.usage);let u=v?.delta,E=On(u?.content);E&&(e(E),p(n,E),r+=E);let b=On(u?.reasoning_content);b&&(s+=b),u?.tool_calls&&u.tool_calls.forEach(m=>{let C=i.get(m.index)??{id:m.id,type:m.type,name:m.function?.name,args:""};m.id&&(C.id=m.id),m.type&&(C.type=m.type),m.function?.name&&(C.name=m.function.name),C.args+=m.function?.arguments||"",i.set(m.index,C)})});let d=Array.from(i.entries()).sort((g,_)=>g[0]-_[0]).map(([g,_])=>({type:"tool_use",id:_.id,name:_.name,input:Oe(_.args,t.onJsonError)})),c=[...n,...d],h=Array.from(i.entries()).sort((g,_)=>g[0]-_[0]).map(([g,_])=>({id:_.id,type:"function",function:{name:_.name,arguments:_.args}})),f={role:"assistant",content:r,...s?{reasoning_content:s}:{},...h.length>0?{tool_calls:h}:{}};return{blocks:c,stop_reason:d.length?"tool_use":"end",truncated:a==="length",finish_reason:a,usage:l,...t.preserveAssistantMessage?{assistant_message:f}:{}}}function k(o,e={}){e.throwOnApiError&&Ri(o);let t=o?.choices?.[0],n=[],i=On(t?.message?.content);t?.message?.tool_calls?.length?t.message.tool_calls.forEach(s=>n.push({type:"tool_use",id:s.id,name:s.function?.name,input:Oe(s.function?.arguments,e.onJsonError)})):i&&n.push({type:"text",text:i});let r=t?.message?{...t.message,role:"assistant",content:i}:void 0;return{blocks:n,stop_reason:t?.finish_reason==="tool_calls"||n.some(s=>s.type==="tool_use")?"tool_use":"end",truncated:t?.finish_reason==="length",finish_reason:t?.finish_reason,usage:o?.usage,...e.preserveAssistantMessage?{assistant_message:r}:{}}}var G=(o,e="chat-completions")=>o.length===0?[]:e==="responses"?o.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):o.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function S(o){if(!o.hasTools){let t=await o.runWithoutTools();if(typeof t=="string"){await o.onCompleteResponse(t);return}let n=O.getFullText(t.blocks);await o.onCompleteResponse(n,t);return}let e=await o.runWithTools();if(o.onToolBlocks&&o.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=O.getFullText(e.blocks);await o.onCompleteResponse(t,e);return}throw new Error(o.toolErrorMessage)}var T=o=>{let e=o.model??o.defaultModel,t=o.visionModel??(o.supportsVisionForModel(e)?e:o.defaultVisionModel);if(o.validate==="explicit"&&o.visionModel&&!o.supportsVisionForModel(o.visionModel))throw new Error(`Model ${o.visionModel} does not support vision capabilities.`);if(o.validate==="resolved"&&!o.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var Ks="https://openrouter.ai/api/v1/models",Hs=2,Bs=12e3,Ws=1,$s=10;function Pi(o){return o instanceof Error?o.message:String(o)}function Sn(o,e){return typeof o!="number"||!Number.isFinite(o)?e:Math.max(1,Math.floor(o))}function zs(o){let e=new Set,t=[];for(let n of o){let i=n.trim();!i||e.has(i)||(e.add(i),t.push(i))}return t}async function Ar(o,e,t){if(!(typeof AbortController<"u"))return fetch(o,e);let i=new AbortController,r=setTimeout(()=>i.abort(),t);try{return await fetch(o,{...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 Ir(o){let e=`HTTP ${o.status} ${o.statusText}`.trim(),t="";try{t=await o.text()}catch{return e}let n=t.replace(/\s+/g," ").trim().slice(0,200);return n?`${e}: ${n}`:e}function Xs(o){if(!o||typeof o!="object")throw new Error("Invalid models response shape");let e=o,t=Array.isArray(e.data)?e.data:Array.isArray(e.models)?e.models:[];if(t.length===0)return[];let n=t.map(i=>i.id).filter(i=>typeof i=="string");return zs(n)}async function qs({modelId:o,apiKey:e,endpoint:t,timeoutMs:n,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 Ar(t,{method:"POST",headers:s,body:JSON.stringify({model:o,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},n);if(!a.ok)return{id:o,ok:!1,reason:await Ir(a)};try{await a.json()}catch(l){return{id:o,ok:!1,reason:`JSON parse failed: ${Pi(l)}`}}return{id:o,ok:!0}}catch(a){return{id:o,ok:!1,reason:Pi(a)}}}async function js(o,e,t){if(o.length===0)return[];let n=new Array(o.length),i=0,r=Math.min(e,o.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<o.length;){let s=i;i+=1,n[s]=await t(o[s])}})),n}async function Zs(o){let e=o.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=o.modelsEndpoint||Ks,n=o.endpoint||Ut,i=Sn(o.timeoutMs,Bs),r=Sn(o.concurrency,Hs),s=Sn(o.maxCandidates,Ws),a=Sn(o.maxWorking,$s),l=await Ar(t,{method:"GET"},i);if(!l.ok)throw new Error(await Ir(l));let p;try{p=await l.json()}catch(g){throw new Error(`JSON parse failed: ${Pi(g)}`)}let d=Xs(p).filter(g=>_e(g)).slice(0,s),c=await js(d,r,g=>qs({modelId:g,apiKey:e,endpoint:n,timeoutMs:i,appName:o.appName,appUrl:o.appUrl})),h=c.filter(g=>g.ok).map(g=>g.id).slice(0,a),f=c.filter(g=>!g.ok).map(g=>({id:g.id,reason:g.reason||"Unknown error"}));return{working:h,failed:f,fetchedAt:Date.now()}}function Dr(o){return o.map(e=>({role:po(e.role),content:e.provider_content??e.content}))}function br(o){return o.map(e=>{if(e.provider_content)return{role:po(e.role),content:e.provider_content};if(typeof e.content=="string")return{role:po(e.role),content:[{type:"text",text:e.content}]};if(Array.isArray(e.content)){let t=e.content.map(n=>{if(n.type==="image_url"){if(n.image_url.url.startsWith("data:")){let i=n.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:n.image_url.url,media_type:Js(n.image_url.url)}}}return n}).filter(n=>n);return{role:po(e.role),content:t}}return{role:po(e.role),content:[]}})}function po(o){switch(o){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}function Js(o){switch(o.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 Qe=class{constructor(e,t=V,n=V,i=[],r=[],s,a){this.provider="claude";if(this.apiKey=e,this.model=t||V,this.visionModel=n||V,this.tools=i,this.mcpServers=r,this.responseLength=s,this.reasoningEffort=a,!Ft.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,n){await S({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callClaude(e,this.model,!0);return this.convertToStandardCompletion(await this.parseStream(i,t))},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){await S({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callClaude(e,this.visionModel,!0);return this.convertToStandardCompletion(await this.parseStream(i,t))},runWithTools:()=>this.visionChatOnce(e),onCompleteResponse:n,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async callClaude(e,t,n,i){let r=e.find(c=>c.role==="system")?.content??"",s=e.filter(c=>c.role!=="system"),a=s.some(c=>Array.isArray(c.content)&&c.content.some(h=>h.type==="image_url"||h.type==="image")),l={model:t,system:r,messages:a?br(s):Dr(s),stream:n,max_tokens:i!==void 0?i:P(this.responseLength)};this.reasoningEffort!==void 0&&U(t).includes(this.reasoningEffort)&&(l.output_config={effort:this.reasoningEffort}),this.tools.length&&(l.tools=this.tools.map(c=>({name:c.name,description:c.description,input_schema:c.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(Kn,l,p)}async parseStream(e,t){let n=e.body.getReader(),i=new TextDecoder,r=[],s=new Map,a=new Map,l,p,d="";for(;;){let{done:h,value:f}=await n.read();if(h)break;d+=i.decode(f,{stream:!0});let g;for(;(g=d.indexOf(`
12
- `))!==-1;){let _=d.slice(0,g).trim();if(d=d.slice(g+1),!_.startsWith("data:"))continue;let v=_.slice(5).trim();if(v==="[DONE]")break;let u=JSON.parse(v);if(u.type==="message_delta"&&(typeof u.delta?.stop_reason=="string"&&(l=u.delta.stop_reason),(u.delta?.stop_details!==void 0||u.stop_details!==void 0)&&(p=u.delta?.stop_details??u.stop_details)),u.type==="content_block_start"&&u.content_block&&typeof u.index=="number"&&s.set(u.index,{...u.content_block}),u.type==="content_block_delta"&&u.delta?.type==="text_delta"){t(u.delta.text),r.push({type:"text",text:u.delta.text});let E=s.get(u.index);E?.type==="text"&&(E.text=`${E.text??""}${u.delta.text}`)}if(u.type==="content_block_delta"&&u.delta?.type==="thinking_delta"){let E=s.get(u.index);E?.type==="thinking"&&(E.thinking=`${E.thinking??""}${u.delta.thinking??""}`)}if(u.type==="content_block_delta"&&u.delta?.type==="signature_delta"){let E=s.get(u.index);E?.type==="thinking"&&(E.signature=`${E.signature??""}${u.delta.signature??""}`)}if(u.type==="content_block_start"&&u.content_block?.type==="tool_use"?a.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"?a.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 E=a.get(u.index);E&&(E.args+=u.delta.partial_json||"")}if(u.type==="content_block_stop"&&a.has(u.index)){let{id:E,name:b,args:m,server_name:C}=a.get(u.index),y=JSON.parse(m||"{}"),D=s.get(u.index);D&&(D.input=y),C?r.push({type:"mcp_tool_use",id:E,name:b,server_name:C,input:y}):r.push({type:"tool_use",id:E,name:b,input:y}),a.delete(u.index)}}}let c=r.some(h=>h.type==="tool_use"||h.type==="mcp_tool_use");return{blocks:r,providerContent:[...s.entries()].sort(([h],[f])=>h-f).map(([,h])=>h),stop_reason:c?"tool_use":"end",finish_reason:l,stop_details:p}}parseOneShot(e){let t=[];(e.content??[]).forEach(i=>{i.type==="text"?t.push({type:"text",text:i.text}):i.type==="tool_use"?t.push({type:"tool_use",id:i.id,name:i.name,input:i.input??{}}):i.type==="mcp_tool_use"?t.push({type:"mcp_tool_use",id:i.id,name:i.name,server_name:i.server_name,input:i.input??{}}):i.type==="tool_result"?t.push({type:"tool_result",tool_use_id:i.tool_use_id,content:i.content??""}):i.type==="mcp_tool_result"&&t.push({type:"mcp_tool_result",tool_use_id:i.tool_use_id,is_error:i.is_error??!1,content:i.content??[]})});let n=t.some(i=>i.type==="tool_use"||i.type==="mcp_tool_use");return{blocks:t,providerContent:(e.content??[]).map(i=>({...i})),stop_reason:n?"tool_use":"end",finish_reason:e.stop_reason,stop_details:e.stop_details}}async chatOnce(e,t=!0,n=()=>{},i){let r=await this.callClaude(e,this.model,t,i),s=t?await this.parseStream(r,n):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}async visionChatOnce(e,t=!1,n=()=>{},i){let r=await this.callClaude(e,this.visionModel,t,i),s=t?await this.parseStream(r,n):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}convertToStandardCompletion(e){let t=e.blocks.filter(n=>n.type==="text"||n.type==="tool_use"||n.type==="tool_result");return{blocks:t,stop_reason:e.stop_reason,finish_reason:e.finish_reason,stop_details:e.stop_details,assistant_message:{role:"assistant",content:t.filter(n=>n.type==="text").map(n=>n.text).join(""),provider_content:e.providerContent}}}};var et=class{createChatService(e){let t=e.model||this.getDefaultModel(),n=U(t);if(e.reasoning_effort!==void 0&&!n.includes(e.reasoning_effort)){let r=n.length>0?`Supported values: ${n.join(", ")}.`:"This model does not expose configurable effort.";throw new Error(`Model ${t} does not support Claude reasoning_effort: ${e.reasoning_effort}. ${r}`)}let i=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"resolved"});return new Qe(e.apiKey,t,i,e.tools??[],e.mcpServers??[],e.responseLength,e.reasoning_effort)}getProviderName(){return"claude"}getSupportedModels(){return[Mo,V,It,Dt,bt,Nt,wt,At,kt,Gt,Vt,Oo]}getDefaultModel(){return V}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ft.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};async function vn(o,e,t={}){let n=o.body.getReader(),i=new TextDecoder,r=[],s=new Map,a=new Map,l,p,d,c="";for(;;){let{done:_,value:v}=await n.read();if(_)break;c+=i.decode(v,{stream:!0});let u="",E="",b=c.split(`
13
- `);c=b.pop()||"";for(let m=0;m<b.length;m++){let C=b[m].trim();if(C.startsWith("event:"))u=C.slice(6).trim();else if(C.startsWith("data:"))E=C.slice(5).trim();else if(C===""&&u&&E){try{let y=JSON.parse(E);Ys(u,y,e,r,s,a,D=>{D.responseStatus!==void 0&&(l=D.responseStatus),D.incompleteDetails!==void 0&&(p=D.incompleteDetails),D.usage!==void 0&&(d=D.usage)})}catch(y){t.onJsonError?.(E,y),console.warn("Failed to parse SSE data:",E)}u="",E=""}}}let h=Array.from(s.values()).map(_=>({type:"tool_use",id:_.id,name:_.name,input:Oe(_.arguments,t.onJsonError)})),f=Array.from(a.values()),g=O.getFullText(r);return{blocks:[...r,...h],stop_reason:h.length?"tool_use":"end",truncated:l==="incomplete",response_status:l,incomplete_details:p,usage:d,...f.length>0?{assistant_message:{role:"assistant",content:g,provider_content:f}}:{}}}function Ys(o,e,t,n,i,r,s){switch(o){case"response.output_item.added":Nr(r,e.item),e.item?.type==="message"&&Array.isArray(e.item.content)?e.item.content.forEach(a=>{a.type==="output_text"&&a.text&&(t(a.text),O.append(n,a.text))}):e.item?.type==="function_call"&&i.set(e.item.id,{id:e.item.call_id??e.item.id,name:e.item.name,arguments:e.item.arguments??""});break;case"response.function_call_arguments.delta":{let a=i.get(e.item_id);a&&typeof e.delta=="string"&&(a.arguments+=e.delta);let l=r.get(e.item_id);l&&typeof e.delta=="string"&&(l.arguments=`${l.arguments??""}${e.delta}`);break}case"response.function_call_arguments.done":{let a=i.get(e.item_id);a&&typeof e.arguments=="string"&&(a.arguments=e.arguments);let l=r.get(e.item_id);l&&typeof e.arguments=="string"&&(l.arguments=e.arguments);break}case"response.output_item.done":Nr(r,e.item),e.item?.type==="function_call"&&i.set(e.item.id,{id:e.item.call_id??e.item.id,name:e.item.name,arguments:e.item.arguments??""});break;case"response.content_part.added":e.part?.type==="output_text"&&typeof e.part.text=="string"&&(t(e.part.text),O.append(n,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(n,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(wr(e,"completed"));break;case"response.incomplete":s(wr(e,"incomplete"));break;default:break}}function Nr(o,e){if(!e||typeof e!="object")return;let t=typeof e.id=="string"&&e.id?e.id:`output-item-${o.size}`;o.set(t,{...e})}function wr(o,e){let t=o?.response??o;return{responseStatus:t?.status??e,incompleteDetails:t?.incomplete_details??null,usage:t?.usage}}function kr(o,e={}){let t=[];return o.output&&Array.isArray(o.output)&&o.output.forEach(n=>{n.type==="message"&&n.content&&n.content.forEach(i=>{i.type==="output_text"&&i.text&&t.push({type:"text",text:i.text})}),n.type==="function_call"&&t.push({type:"tool_use",id:n.call_id??n.id,name:n.name,input:Oe(n.arguments,e.onJsonError)})}),{blocks:t,stop_reason:t.some(n=>n.type==="tool_use")?"tool_use":"end",truncated:o?.status==="incomplete",response_status:o?.status,incomplete_details:o?.incomplete_details??null,usage:o?.usage,...Array.isArray(o?.output)&&o.output.length>0?{assistant_message:{role:"assistant",content:t.filter(n=>n.type==="text").map(n=>n.text).join(""),provider_content:o.output}}:{}}}function Gr({tools:o,mcpServers:e,isResponsesAPI:t}){let n=[];return o.length>0&&n.push(...G(o,t?"responses":"chat-completions")),e.length>0&&t&&n.push(...Qs(e)),n}function Qs(o){return o.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 ea={[L.VERY_SHORT]:800,[L.SHORT]:1200,[L.MEDIUM]:2e3,[L.LONG]:3e3,[L.VERY_LONG]:8e3,[L.DEEP]:25e3},ta={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3,max:25e3},oa=new Set(["openai-compatible","deepseek","mistral","sakana","plamo"]);function na(o){return o.type!=="json_schema"?o:{type:o.type,...o.json_schema}}function Vr({provider:o,endpoint:e,messages:t,model:n,stream:i,tools:r,mcpServers:s,responseLength:a,verbosity:l,reasoning_effort:p,enableReasoningSummary:d,responseFormat:c,chatTemplateThinking:h,maxTokens:f}){n===R&&(!p||p==="none"||p==="minimal")&&(p="low");let g=e===N;ra(e,s);let _={model:n,stream:i},v=ia({provider:o,model:n,responseLength:a,reasoning_effort:p,maxTokens:f});g?v!==void 0&&(_.max_output_tokens=v):v!==void 0&&(Fr(o)?_.max_tokens=v:_.max_completion_tokens=v),g?_.input=sa(t):_.messages=o==="mistral"?aa(t):t,pe(n)&&(g?(p&&(_.reasoning={..._.reasoning,effort:p},d&&(_.reasoning.summary="auto")),l&&(_.text={..._.text,format:{type:"text"},verbosity:l})):(p&&(_.reasoning_effort=p),l&&(_.verbosity=l))),c&&(g?_.text={..._.text,format:na(c)}:_.response_format=c),o==="mistral"&&ro(n)&&p&&mi(p)&&(_.reasoning_effort=p),o==="plamo"&&p&&(_.reasoning_effort=p),o==="deepseek"&&p&&(_.thinking={type:p==="none"?"disabled":"enabled"},p!=="none"&&(_.reasoning_effort=p)),o==="sakana"&&h!==void 0&&(_.chat_template_kwargs={thinking:h});let u=Gr({tools:r,mcpServers:s,isResponsesAPI:g});return u.length>0&&(_.tools=u,g||(_.tool_choice="auto")),_}function ia({provider:o,model:e,responseLength:t,reasoning_effort:n,maxTokens:i}){if(i!==void 0)return i;let r=Fr(o)?t!==void 0?P(t):void 0:P(t);if(o!=="openai"||!pe(e)||t===void 0)return r;let s=n??Pt(e);return Math.max(r??0,ea[t],ta[s])}function ra(o,e){if(e.length>0&&o===z)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${o}. Please use OpenAI Responses API endpoint: ${N}. MCP tools are only available in the Responses API endpoint.`)}function sa(o){return o.flatMap(e=>{if(e.role==="assistant"&&e.provider_content?.length)return e.provider_content;if(e.role==="tool"&&e.tool_call_id)return[{type:"function_call_output",call_id:e.tool_call_id,output:e.content}];let t=[],n={role:e.role==="tool"?"user":e.role};return typeof e.content=="string"?n.content=e.content:Array.isArray(e.content)?n.content=e.content.map(r=>r.type==="text"?{type:"input_text",text:r.text}:r.type==="image_url"?{type:"input_image",image_url:r.image_url.url}:r):n.content=e.content,(typeof n.content!="string"||n.content.length>0)&&t.push(n),e.role==="assistant"&&e.tool_calls&&t.push(...e.tool_calls.map(r=>({type:"function_call",call_id:r.id,name:r.function.name,arguments:r.function.arguments}))),t})}function aa(o){return o.map(e=>{let t={role:e.role};return Array.isArray(e.content)?(t.content=e.content.map(n=>n.type==="image_url"&&typeof n.image_url=="object"&&typeof n.image_url?.url=="string"?{type:"image_url",image_url:n.image_url.url}:n),t):(t.content=e.content,t)})}function Fr(o){return oa.has(o)}var x=class{constructor(e,t=le,n=le,i,r=z,s=[],a,l,p,d=!1,c="openai",h=!0,f,g){if(this.provider=c,this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=(t===R||n===R)&&r===z?N:r,this.mcpServers=s,this.responseLength=a,this.verbosity=l,this.reasoning_effort=p,this.enableReasoningSummary=d,this.responseFormat=f,this.chatTemplateThinking=g,h&&!Lt.includes(n))throw new Error(`Model ${n} does not support vision capabilities.`);this.visionModel=n}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,n){await S({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.model,!0),r=this.endpoint===N;try{if(r){let s=await vn(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:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){try{await S({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.visionModel,!0),r=this.endpoint===N;try{if(r){let s=await vn(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:n,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,n=()=>{},i){let r=await this.callOpenAI(e,this.model,t,i);return this.parseResponse(r,t,n)}async visionChatOnce(e,t=!1,n=()=>{},i){let r=await this.callOpenAI(e,this.visionModel,t,i);return this.parseResponse(r,t,n)}async parseResponse(e,t,n){return this.endpoint===N?t?vn(e,n):kr(await e.json()):t?this.parseStream(e,n):this.parseOneShot(await e.json())}async callOpenAI(e,t,n=!1,i){let r=Vr({provider:this.provider,endpoint:this.endpoint,messages:e,model:t,stream:n,tools:this.tools,mcpServers:this.mcpServers,responseLength:this.responseLength,verbosity:this.verbosity,reasoning_effort:this.reasoning_effort,enableReasoningSummary:this.enableReasoningSummary,responseFormat:this.responseFormat,chatTemplateThinking:this.chatTemplateThinking,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 $(e,t)}async parseStream(e,t){return w(e,t,{appendTextBlock:O.addTextBlock})}parseOneShot(e){return k(e)}};var tt=class extends x{constructor(e,t=me,n=t,i,r=oo,s,a){let l=pi(t,a);if(super(e,t,n,i,r,[],s,void 0,l,!1,"deepseek",!1),i?.length&&l!==void 0&&l!=="none")throw new Error("DeepSeek thinking with tools is not supported yet. Use reasoning_effort: 'none' for tool calling.")}};var ot=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:je,supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"explicit"}),i=e.tools;return new tt(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"deepseek"}getSupportedModels(){return[...ai]}getDefaultModel(){return me}supportsVision(){return!0}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return li(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"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 oo}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Ur=(o,e)=>({name:`mcp_${o.name}_search`,description:e==="schema-fetch-failed"?`Search using ${o.name} MCP server (schema fetch failed)`:`Search using ${o.name} MCP server`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}),Cn=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:[Ur(e)],failures:[]}}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),{schemas:[Ur(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=[],n=[];for(let i of e)try{let r=await this.fetchToolSchemasWithStatus(i);t.push(...r.schemas),n.push(...r.failures)}catch(r){console.error(`Failed to fetch schemas from ${i.name}:`,r),n.push({server:i,error:r})}return{schemas:t,failures:n}}};function Kr(o){switch(o){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}function Hr(o,e={}){let t=[],n=null,i=[],r=()=>{n&&i.length&&(t.push({role:n,parts:[...i]}),i=[]),n=null};for(let s of o){if(s.role==="system")continue;let a=Kr(s.role);if(s.tool_calls){r();let l=s.tool_calls.map(p=>$r(p,e));l.length>0&&t.push({role:"model",parts:l});continue}if(s.role==="tool"){r(),Xr(t,zr(s,e));continue}a!==n&&r(),n=a,i.push({text:s.content})}return r(),t}async function Br(o,e={}){let t=e.imageFetcher??M.get,n=e.blobToBase64??ca,i=[],r=null,s=[],a=()=>{r&&s.length>0&&(i.push({role:r,parts:[...s]}),s=[]),r=null};for(let l of o){if(l.role==="system")continue;let p=Kr(l.role);if(l.tool_calls){a();let d=l.tool_calls.map(c=>$r(c,e));d.length>0&&i.push({role:"model",parts:d});continue}if(l.role==="tool"){a(),Xr(i,zr(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 d of l.content)if(d.type==="text")s.push({text:d.text});else if(d.type==="image_url")try{let h=await(await t(d.image_url.url)).blob(),f=await n(h);s.push({inlineData:{mimeType:h.type||"image/jpeg",data:f.split(",")[1]}})}catch(c){throw console.error("Error processing image:",c),new Error(`Failed to process image: ${c.message}`)}}}return a(),i}function Wr(o){let e=o.flatMap(t=>t.role!=="system"?[]:typeof t.content=="string"?t.content?[{text:t.content}]:[]:t.content.flatMap(n=>n.type==="text"&&n.text?[{text:n.text}]:[]));return e.length>0?{parts:e}:void 0}function $r(o,e){e.callIdMap?.set(o.id,o.function.name);let t=e.functionCallContextMap?.get(o.id),n={functionCall:{...t?.providerCallId?{id:t.providerCallId}:{},name:o.function.name,args:JSON.parse(o.function.arguments||"{}")}};return t?.thoughtSignature&&(n.thoughtSignature=t.thoughtSignature),n}function zr(o,e){let t=o.tool_call_id,n=e.functionCallContextMap?.get(t);return{functionResponse:{...n?.providerCallId?{id:n.providerCallId}:{},name:o.name??n?.name??e.callIdMap?.get(t)??"result",response:pa(la(o.content))}}}function Xr(o,e){let t=o[o.length-1];if(t?.role==="user"&&t.parts.every(i=>i.functionResponse)){t.parts.push(e);return}o.push({role:"user",parts:[e]})}function la(o){try{return JSON.parse(o)}catch{return o}}function pa(o){return o===null?{content:null}:typeof o=="object"?o:{content:o}}function ca(o){return new Promise((e,t)=>{let n=new FileReader;n.onloadend=()=>e(n.result),n.onerror=t,n.readAsDataURL(o)})}function ua(o,e){return[...o,...e].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}function qr(o,e){let t=ua(o,e);if(t.length!==0)return{tools:[{functionDeclarations:t}],toolConfig:{functionCallingConfig:{mode:"AUTO"}}}}function jr(o){return o.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 nt=class{constructor(e,t=Y,n=Y,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,!xt.includes(n))throw new Error(`Model ${n} does not support vision capabilities.`);this.visionModel=n,this.tools=i,this.mcpServers=r}isGemma4Model(e){return/^gemma-4-/.test(e)}resolveThinkingConfig(e){let t=yt(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(n=>this.adaptKeysForApi(n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,i])=>[t[n]??n,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=Cn.fetchAllToolSchemasWithStatus(this.mcpServers),n=await Promise.race([t,e]);this.mcpToolSchemas=n.schemas,this.mcpSchemasInitialized=!0,this.mcpSchemaInitializationError=n.failures[0]?.error}catch(e){console.warn("Failed to initialize MCP schemas, using fallback:",e),this.mcpSchemaInitializationError=e,this.mcpToolSchemas=jr(this.mcpServers),this.mcpSchemasInitialized=!0}}async processChat(e,t,n){try{await S({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 O.getFullText(r)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:n,toolErrorMessage:"Received functionCall. Use chatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processChat:",i),i}}async processVisionChat(e,t,n){try{await S({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 O.getFullText(r)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:i=>{i.filter(r=>r.type==="text").forEach(r=>t(r.text))},onCompleteResponse:n,toolErrorMessage:"Received functionCall. Use visionChatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processVisionChat:",i),i}}async callGemini(e,t,n=!1,i){let a={contents:e.some(m=>Array.isArray(m.content)&&m.content.some(C=>C?.type==="image_url"||C?.inlineData))?await Br(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}):Hr(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}),generationConfig:{maxOutputTokens:i!==void 0?i:P(this.responseLength)}},l=Wr(e);l&&(a.systemInstruction=l);let p=this.resolveThinkingConfig(t);p&&(a.generationConfig.thinkingConfig=p);let d=[];if(this.mcpServers.length>0)try{await this.initializeMCPSchemas(),d=this.mcpToolSchemas}catch(m){console.warn("MCP initialization failed, skipping MCP tools:",m)}let c=qr(this.tools,d);c&&Object.assign(a,c);let h=async(m,C)=>{let y=n?"streamGenerateContent":"generateContent",D=n?"?alt=sse":"",es=`${An}/${m}/models/${t}:${y}${D}${D?"&":"?"}key=${this.apiKey}`;return M.post(es,C)},f=/flash[-_]lite/.test(t),g=this.isGemma4Model(t),_=/gemini-2\.5/.test(t),v=/^gemini-3(?:\.[0-9]+)?-/.test(t),u=f||g||_||v,E=u?"v1beta":"v1",b=async()=>{try{let m=E==="v1"?a:this.adaptKeysForApi(a);return await h(E,m)}catch(m){let C=/Unknown name|Cannot find field|404/.test(m?.message||"")||m?.status===404;if(!u&&C)try{return await h("v1beta",this.adaptKeysForApi(a))}catch(y){throw y instanceof Error&&(y.cause=m),y}throw m}};try{return await b()}catch(m){throw m.body&&(console.error("Gemini API Error Details:",m.body),console.error("Request Body:",JSON.stringify(a,null,2))),m}}createFunctionCallBlock(e){let t=e.functionCall??e.function_call;if(!t)return;let n=t.id??this.genUUID();return this.callIdMap.set(n,t.name),this.functionCallContextMap.set(n,{name:t.name,providerCallId:t.id,thoughtSignature:e.thoughtSignature??e.thought_signature}),{type:"tool_use",id:n,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,n){let i=e.body.getReader(),r=new TextDecoder,s=[],a=[],l="",p=c=>{if(!c||c==="[DONE]")return;let h;try{h=JSON.parse(c)}catch{return}for(let f of h.candidates??[])for(let g of f.content?.parts??[]){this.shouldExposeTextPart(g,n)&&(t(g.text),O.addTextBlock(s,g.text));let _=this.createFunctionCallBlock(g);_&&a.push(_);let v=this.createFunctionResponseBlock(g);v&&a.push(v)}};for(;;){let{done:c,value:h}=await i.read();if(c)break;l+=r.decode(h,{stream:!0});let f;for(;(f=l.indexOf(`
14
- `))!==-1;){let g=l.slice(0,f);if(l=l.slice(f+1),g.endsWith("\r")&&(g=g.slice(0,-1)),!g.trim()){p("");continue}g.startsWith("data:")&&(g=g.slice(5).trim()),g&&p(g)}}return l&&p(l),{blocks:[...s,...a],stop_reason:a.some(c=>c.type==="tool_use")?"tool_use":"end"}}parseOneShot(e,t){let n=[],i=[];for(let s of e.candidates??[])for(let a of s.content?.parts??[]){this.shouldExposeTextPart(a,t)&&n.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:[...n,...i],stop_reason:i.some(s=>s.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,n=()=>{},i){let r=await this.callGemini(e,this.model,t,i);return t?this.parseStream(r,n,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,n=()=>{},i){let r=await this.callGemini(e,this.visionModel,t,i);return t?this.parseStream(r,n,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 it=class{createChatService(e){let t=e.model||this.getDefaultModel();if(e.reasoning_effort!==void 0&&!Un(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 n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"resolved"});return new nt(e.apiKey,t,n,e.tools||[],e.mcpServers||[],e.responseLength,yt(t,e.reasoning_effort))}getProviderName(){return"gemini"}getSupportedModels(){return[...Eo]}getDefaultModel(){return Y}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return xt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function ha(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var rt=class{constructor(e={}){this.provider="gemini-nano";this.consumedTranscript=[];this.expectedInputLanguages=e.expectedInputLanguages??["ja","en"],this.expectedOutputLanguages=e.expectedOutputLanguages??["ja"],this.initialPrompts=(e.initialPrompts??[]).map(t=>({...t})),this._responseLength=e.responseLength,this.sessionMode=e.sessionMode??"stateless"}getModel(){return Me}getVisionModel(){return Me}dispose(){this.destroyPersistentSessions()}async processChat(e,t,n){let i=await this.generateResponse(e,!0,t);await n(i)}async processVisionChat(e,t,n){throw new Error("Gemini Nano does not support vision capabilities.")}async chatOnce(e,t=!1,n=()=>{},i){return{blocks:[{type:"text",text:await this.generateResponse(e,t,n)}],stop_reason:"end"}}async visionChatOnce(e,t=!1,n=()=>{},i){throw new Error("Gemini Nano does not support vision capabilities.")}async generateResponse(e,t,n){let i=ha();if(!i)throw new Error("Gemini Nano is not available in this environment. Chrome 148+ on a supported desktop device is required for web pages.");let r=this.getModelOptions();this.sessionMode==="stateless"&&await this.ensureAvailability(i,r);let a=e.filter(f=>f.role==="system").map(f=>f.content).join(`
15
- `),l=e.filter(f=>f.role==="user"||f.role==="assistant").slice(-20),p=this.findLastUserMessageIndex(l);if(p===-1)throw new Error("No user message found in the provided messages.");let d=l[p],c=l.slice(0,p);if(this.sessionMode==="persistent")return this.generatePersistentResponse(i,a,c,d.content,r,t,n);let h=await this.createSession(i,a,c,r);try{return await this.promptSession(h,d.content,t,n)}finally{try{h.destroy()}catch{}}}async generatePersistentResponse(e,t,n,i,r,s,a){let l=this.getPersistentSessionKey(t,r);this.persistentSessionKey!==l&&this.destroyPersistentSessions(),!this.baseSession&&!this.liveSession&&(await this.ensureAvailability(e,r),await this.createPersistentBaseSession(e,t,n,r),this.persistentSessionKey=l);let p=await this.getPersistentLiveSession(e,t,n,r),d=p===this.liveSession&&this.isHistoryCompatible(n,this.consumedTranscript);this.persistentSessionKey=l;try{let c=await this.promptSession(p,i,s,a);return this.recordConsumedTranscript(n,i,c,d),c}catch(c){if(!this.isQuotaExceededError(c))throw this.destroyPersistentLiveSession(),c;this.destroyPersistentLiveSession(),p=await this.getPersistentLiveSession(e,t,[],r),this.persistentSessionKey=l;try{let h=await this.promptSession(p,i,s,a);return this.recordConsumedTranscript([],i,h,!1),h}catch(h){throw this.destroyPersistentLiveSession(),h}}}async ensureAvailability(e,t){let n=await e.availability(t);if(n!=="available"&&n!=="downloadable")throw new Error(`Gemini Nano Prompt API is not ready in this environment. LanguageModel.availability() returned "${n}". Expected "available" or "downloadable".`)}async createPersistentBaseSession(e,t,n,i){this.baseSession=await this.createSession(e,t,[],i),n.length>0?(this.liveSession=await this.createSession(e,t,n,i),this.consumedTranscript=n.map(r=>({...r}))):typeof this.baseSession.clone=="function"?this.liveSession=await this.baseSession.clone():this.liveSession=this.baseSession}async getPersistentLiveSession(e,t,n,i){if(this.liveSession&&this.isHistoryCompatible(n,this.consumedTranscript))return this.liveSession;if(this.liveSession&&this.liveSession!==this.baseSession&&this.destroyPersistentLiveSession(),n.length===0&&this.baseSession){if(typeof this.baseSession.clone=="function")this.liveSession=await this.baseSession.clone();else{if(this.consumedTranscript.length>0)return this.destroyPersistentSessions(),await this.createPersistentBaseSession(e,t,[],i),this.liveSession;this.liveSession=this.baseSession}return this.liveSession}return this.baseSession&&typeof this.baseSession.clone=="function"?(this.liveSession=await this.createSession(e,t,n,i),this.liveSession):(this.destroyPersistentSessions(),await this.ensureAvailability(e,i),await this.createPersistentBaseSessionWithHistory(e,t,n,i),this.liveSession)}async createPersistentBaseSessionWithHistory(e,t,n,i){this.baseSession=await this.createSession(e,t,n,i),this.liveSession=this.baseSession,this.consumedTranscript=n.map(r=>({...r}))}recordConsumedTranscript(e,t,n,i){let r=i?this.consumedTranscript:e;this.consumedTranscript=[...r,{role:"user",content:t},{role:"assistant",content:n}]}getPersistentSessionKey(e,t){return JSON.stringify({systemPrompt:e,modelOptions:t,initialPrompts:this.initialPrompts,responseLength:this._responseLength})}isHistoryCompatible(e,t){return e.length===0||t.length===0?e.length===0&&t.length===0:this.isSuffix(e,t)||this.isSuffix(t,e)}isSuffix(e,t){if(e.length>t.length)return!1;let n=t.length-e.length;return e.every((i,r)=>i.role===t[n+r].role&&i.content===t[n+r].content)}isQuotaExceededError(e){return typeof e=="object"&&e!==null&&"name"in e&&e.name==="QuotaExceededError"}destroyPersistentLiveSession(){this.liveSession&&(this.destroySession(this.liveSession),this.liveSession===this.baseSession&&(this.baseSession=void 0)),this.liveSession=void 0,this.consumedTranscript=[]}destroyPersistentSessions(){this.liveSession&&this.liveSession!==this.baseSession&&this.destroySession(this.liveSession),this.baseSession&&this.destroySession(this.baseSession),this.baseSession=void 0,this.liveSession=void 0,this.persistentSessionKey=void 0,this.consumedTranscript=[]}destroySession(e){try{e.destroy()}catch{}}async promptSession(e,t,n,i){if(n&&typeof e.promptStreaming=="function"){let s=e.promptStreaming(t).getReader(),a="",l="unknown";for(;;){let{done:p,value:d}=await s.read();if(p)break;let c=String(d??"");l==="unknown"&&a!==""&&(l=c.startsWith(a)?"cumulative":"delta");let h=l==="cumulative",f=h?c.slice(a.length):c;a=h?c:a+c,f&&i(f)}return a}let r=await e.prompt(t);return i(r),r}async createSession(e,t,n,i){let r=this.buildInitialPrompts(t,n),s={...i,...r.length>0?{initialPrompts:r}:{}};return e.create(s)}getModelOptions(){return{expectedInputs:[{type:"text",languages:this.expectedInputLanguages}],expectedOutputs:[{type:"text",languages:this.expectedOutputLanguages}]}}buildInitialPrompts(e,t){let n=this.initialPrompts.filter(s=>s.role==="system").map(s=>s.content),i=this.buildSystemPrompt([e,...n].filter(Boolean).join(`
10
+ `;var Se="gemini-nano",Ri=20;var ne=class extends Error{constructor(t,n,i){super(`HTTP ${t}: ${n}`);this.status=t;this.statusText=n;this.body=i;this.name="HttpError"}},co=class co{static setFetch(e){this.fetchImpl=e}static async post(e,t,n={},i={}){let{timeout:r=3e4,retries:s=0,retryDelay:a=1e3}=i,p={...{"Content-Type":"application/json"},...n},u=null;for(let c=0;c<=s;c++)try{let d=typeof AbortController<"u",f=d?new AbortController:void 0,g=d?setTimeout(()=>f.abort(),r):void 0,m=await co.fetchImpl(e,{method:"POST",headers:p,body:typeof t=="string"?t:JSON.stringify(t),...f?{signal:f.signal}:{}});if(g&&clearTimeout(g),!m.ok){let v=await m.text();throw new ne(m.status,m.statusText,v)}return m}catch(d){if(u=d,d instanceof ne&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError")throw new Error(`Request timeout after ${r}ms`);c<s&&await new Promise(f=>setTimeout(f,a*(c+1)))}throw u||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new ne(e.status,e.statusText,t)}static async get(e,t={},n={}){let{timeout:i=3e4,retries:r=0,retryDelay:s=1e3}=n,a=null;for(let l=0;l<=r;l++)try{let p=typeof AbortController<"u",u=p?new AbortController:void 0,c=p?setTimeout(()=>u.abort(),i):void 0,d=await co.fetchImpl(e,{method:"GET",headers:t,...u?{signal:u.signal}:{}});if(c&&clearTimeout(c),!d.ok){let f=await d.text();throw new ne(d.status,d.statusText,f)}return d}catch(p){if(a=p,p instanceof ne&&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(u=>setTimeout(u,s*(l+1)))}throw a||new Error("Request failed")}};co.fetchImpl=(e,t)=>fetch(e,t);var M=co;var O=class{static append(e,t){if(!t)return;let n=e[e.length-1];n&&n.type==="text"?n.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 Ks=["happy","sad","angry","surprised","neutral"],yr=/\[([a-z]+)\]/i,yi=/\[[a-z]+\]\s*/gi,Qe=class{static extractEmotion(e){let t=e.match(yr);if(t){let n=t[1].toLowerCase(),i=e.replace(yi,"").trim();return{emotion:n,cleanText:i}}return{cleanText:e}}static isValidEmotion(e){return Ks.includes(e)}static cleanEmotionTags(e){return e.replace(yi,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function Pr(o){let{emotion:e,cleanText:t}=Qe.extractEmotion(o);return e?{emotion:e,text:t}:{text:t}}function Hs(o){return o.map(e=>Pr(e))}function Bs(o){return o.emotion?Qe.addEmotionTag(o.emotion,o.text):o.text}async function Ws(o,e){let{blocks:t}=await o.chatOnce(e,!1,()=>{});return O.getFullText(t)}var xr=(o,e,t)=>{try{return JSON.parse(o)}catch(n){return t?.(o,n),e}},ve=(o,e)=>o?xr(o,{},e):{};var Ar=(o,e)=>{try{return JSON.parse(o)}catch(t){if(e){e(o,t);return}throw t}},vn=o=>typeof o=="string"?o:Array.isArray(o)?o.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&e.type==="text"&&typeof e.text=="string"?e.text:"").join(""):"",Pi=o=>{let e=o.choices?.[0],t=o.error??e?.error;if(!t&&e?.finish_reason!=="error")return;let n=typeof t=="string"?t:typeof t?.message=="string"?t.message:"The provider ended the response with an error.";throw new Error(`Provider response error: ${n}`)},Ir=async(o,e)=>{let t=o.body?.getReader();if(!t)throw new Error("Response body is null.");let n=new TextDecoder,i="",r=!1;for(;!r;){let{done:s,value:a}=await t.read();if(s)break;i+=n.decode(a,{stream:!0});let l=i.split(`
11
+ `);i=l.pop()||"";for(let p of l){let u=p.trim();if(!u||u.startsWith(":")||!u.startsWith("data:"))continue;let c=u.slice(5).trim();if(c==="[DONE]"){r=!0;break}e(c)}}};async function z(o,e,t={}){let n="";return await Ir(o,i=>{let r=Ar(i,t.onJsonError);if(!r)return;t.throwOnApiError&&Pi(r);let s=vn(r.choices?.[0]?.delta?.content);s&&(e(s),n+=s)}),n}async function k(o,e,t={}){let n=[],i=new Map,r="",s="",a,l,p=t.appendTextBlock??O.append;await Ir(o,g=>{let m=Ar(g,t.onJsonError);if(!m)return;t.throwOnApiError&&Pi(m);let v=m.choices?.[0];typeof v?.finish_reason=="string"&&(a=v.finish_reason),m.usage&&(l=m.usage);let h=v?.delta,E=vn(h?.content);E&&(e(E),p(n,E),r+=E);let N=vn(h?.reasoning_content);N&&(s+=N),h?.tool_calls&&h.tool_calls.forEach(_=>{let C=i.get(_.index)??{id:_.id,type:_.type,name:_.function?.name,args:""};_.id&&(C.id=_.id),_.type&&(C.type=_.type),_.function?.name&&(C.name=_.function.name),C.args+=_.function?.arguments||"",i.set(_.index,C)})});let u=Array.from(i.entries()).sort((g,m)=>g[0]-m[0]).map(([g,m])=>({type:"tool_use",id:m.id,name:m.name,input:ve(m.args,t.onJsonError)})),c=[...n,...u],d=Array.from(i.entries()).sort((g,m)=>g[0]-m[0]).map(([g,m])=>({id:m.id,type:"function",function:{name:m.name,arguments:m.args}})),f={role:"assistant",content:r,...s?{reasoning_content:s}:{},...d.length>0?{tool_calls:d}:{}};return{blocks:c,stop_reason:u.length?"tool_use":"end",truncated:a==="length",finish_reason:a,usage:l,...t.preserveAssistantMessage?{assistant_message:f}:{}}}function G(o,e={}){e.throwOnApiError&&Pi(o);let t=o?.choices?.[0],n=[],i=vn(t?.message?.content);t?.message?.tool_calls?.length?t.message.tool_calls.forEach(s=>n.push({type:"tool_use",id:s.id,name:s.function?.name,input:ve(s.function?.arguments,e.onJsonError)})):i&&n.push({type:"text",text:i});let r=t?.message?{...t.message,role:"assistant",content:i}:void 0;return{blocks:n,stop_reason:t?.finish_reason==="tool_calls"||n.some(s=>s.type==="tool_use")?"tool_use":"end",truncated:t?.finish_reason==="length",finish_reason:t?.finish_reason,usage:o?.usage,...e.preserveAssistantMessage?{assistant_message:r}:{}}}var $s=[{id:"ollama",label:"Ollama",baseUrl:"http://localhost:11434/v1",docsUrl:"https://docs.ollama.com/api/openai-compatibility",corsHint:"Set OLLAMA_ORIGINS to allow additional browser origins."},{id:"lmStudio",label:"LM Studio",baseUrl:"http://localhost:1234/v1",docsUrl:"https://lmstudio.ai/docs/developer/openai-compat",corsHint:"Start the server with lms server start --cors for browser access."},{id:"llamaCpp",label:"llama.cpp",baseUrl:"http://127.0.0.1:8080/v1",docsUrl:"https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md",corsHint:"All origins are allowed by default; use --cors-origins to restrict them."},{id:"vllm",label:"vLLM",baseUrl:"http://localhost:8000/v1",docsUrl:"https://docs.vllm.ai/en/latest/serving/online_serving/openai_compatible_server/",corsHint:"All origins are allowed by default; use --allowed-origins to restrict them."}],R=class extends Error{constructor(e,t,n){super(t),this.name="OpenAICompatibleEndpointError",this.code=e,this.status=n}};function Dr(o){let e;try{e=new URL(o.trim())}catch{throw new R("invalid-url","Enter a valid HTTP or HTTPS endpoint URL.")}if(e.protocol!=="http:"&&e.protocol!=="https:"||e.search||e.hash||e.username||e.password)throw new R("invalid-url","Use an HTTP or HTTPS endpoint URL without credentials, a query, or a fragment.");let t=e.pathname.replace(/\/+$/,"");if(t.endsWith("/api/chat")||t.endsWith("/api/generate"))throw new R("invalid-url","This looks like Ollama's native API URL. Use the OpenAI-compatible base URL instead, e.g. http://localhost:11434/v1.");let n=!t||t==="/"?"/v1":t.endsWith("/chat/completions")?t.slice(0,-17):t,i=`${e.origin}${n}`;return{baseUrl:i,chatCompletionsUrl:`${i}/chat/completions`,modelsUrl:`${i}/models`}}async function br(o){let{modelsUrl:e}=Dr(o.endpoint),t=o.timeoutMs??8e3;if(!Number.isFinite(t)||t<=0)throw new RangeError("timeoutMs must be a positive finite number.");if(o.signal?.aborted)throw new R("aborted","The models request was aborted by the caller.");let n=new AbortController,i,r=()=>{i||(i="caller"),n.abort()};o.signal?.addEventListener("abort",r,{once:!0}),o.signal?.aborted&&r();let s=setTimeout(()=>{i||(i="timeout"),n.abort()},t);try{let a={};o.apiKey?.trim()&&(a.Authorization=`Bearer ${o.apiKey.trim()}`);let l=await(o.fetch??fetch)(e,{method:"GET",headers:a,signal:n.signal});if(i)throw new R("aborted","The models request was aborted by the caller.");if(!l.ok)throw new R("http",`Model listing failed with HTTP ${l.status}.`,l.status);let p;try{p=await l.json()}catch{throw new R("invalid-response","The models endpoint did not return valid JSON.")}if(!p||typeof p!="object"||!("data"in p)||!Array.isArray(p.data)||!p.data.every(u=>u&&typeof u=="object"&&"id"in u&&typeof u.id=="string"))throw new R("invalid-response","The models response must contain data with model IDs.");if(i)throw new R("aborted","The models request was aborted by the caller.");return[...new Set(p.data.map(u=>u.id))]}catch(a){throw i==="caller"?new R("aborted","The models request was aborted by the caller."):i==="timeout"?new R("timeout",`The models request timed out after ${t} ms.`):a instanceof R?a:new R("network","Could not reach the models endpoint. In a browser, this is usually a CORS restriction or the server is not running.")}finally{clearTimeout(s),o.signal?.removeEventListener("abort",r)}}async function zs(o){let e=Date.now();try{let t=await br(o);return{ok:!0,latencyMs:Date.now()-e,models:t,...o.model!==void 0?{modelFound:t.includes(o.model)}:{}}}catch(t){if(t instanceof RangeError)throw t;return{ok:!1,error:t instanceof R?t:new R("network","Could not reach the models endpoint. In a browser, this is usually a CORS restriction or the server is not running.")}}}var V=(o,e="chat-completions")=>o.length===0?[]:e==="responses"?o.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):o.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function S(o){if(!o.hasTools){let t=await o.runWithoutTools();if(typeof t=="string"){await o.onCompleteResponse(t);return}let n=O.getFullText(t.blocks);await o.onCompleteResponse(n,t);return}let e=await o.runWithTools();if(o.onToolBlocks&&o.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=O.getFullText(e.blocks);await o.onCompleteResponse(t,e);return}throw new Error(o.toolErrorMessage)}var T=o=>{let e=o.model??o.defaultModel,t=o.visionModel??(o.supportsVisionForModel(e)?e:o.defaultVisionModel);if(o.validate==="explicit"&&o.visionModel&&!o.supportsVisionForModel(o.visionModel))throw new Error(`Model ${o.visionModel} does not support vision capabilities.`);if(o.validate==="resolved"&&!o.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var qs="https://openrouter.ai/api/v1/models",Xs=2,js=12e3,Zs=1,Js=10;function xi(o){return o instanceof Error?o.message:String(o)}function Cn(o,e){return typeof o!="number"||!Number.isFinite(o)?e:Math.max(1,Math.floor(o))}function Ys(o){let e=new Set,t=[];for(let n of o){let i=n.trim();!i||e.has(i)||(e.add(i),t.push(i))}return t}async function Nr(o,e,t){if(!(typeof AbortController<"u"))return fetch(o,e);let i=new AbortController,r=setTimeout(()=>i.abort(),t);try{return await fetch(o,{...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 wr(o){let e=`HTTP ${o.status} ${o.statusText}`.trim(),t="";try{t=await o.text()}catch{return e}let n=t.replace(/\s+/g," ").trim().slice(0,200);return n?`${e}: ${n}`:e}function Qs(o){if(!o||typeof o!="object")throw new Error("Invalid models response shape");let e=o,t=Array.isArray(e.data)?e.data:Array.isArray(e.models)?e.models:[];if(t.length===0)return[];let n=t.map(i=>i.id).filter(i=>typeof i=="string");return Ys(n)}async function ea({modelId:o,apiKey:e,endpoint:t,timeoutMs:n,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 Nr(t,{method:"POST",headers:s,body:JSON.stringify({model:o,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},n);if(!a.ok)return{id:o,ok:!1,reason:await wr(a)};try{await a.json()}catch(l){return{id:o,ok:!1,reason:`JSON parse failed: ${xi(l)}`}}return{id:o,ok:!0}}catch(a){return{id:o,ok:!1,reason:xi(a)}}}async function ta(o,e,t){if(o.length===0)return[];let n=new Array(o.length),i=0,r=Math.min(e,o.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<o.length;){let s=i;i+=1,n[s]=await t(o[s])}})),n}async function oa(o){let e=o.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=o.modelsEndpoint||qs,n=o.endpoint||Ht,i=Cn(o.timeoutMs,js),r=Cn(o.concurrency,Xs),s=Cn(o.maxCandidates,Zs),a=Cn(o.maxWorking,Js),l=await Nr(t,{method:"GET"},i);if(!l.ok)throw new Error(await wr(l));let p;try{p=await l.json()}catch(g){throw new Error(`JSON parse failed: ${xi(g)}`)}let u=Qs(p).filter(g=>fe(g)).slice(0,s),c=await ta(u,r,g=>ea({modelId:g,apiKey:e,endpoint:n,timeoutMs:i,appName:o.appName,appUrl:o.appUrl})),d=c.filter(g=>g.ok).map(g=>g.id).slice(0,a),f=c.filter(g=>!g.ok).map(g=>({id:g.id,reason:g.reason||"Unknown error"}));return{working:d,failed:f,fetchedAt:Date.now()}}function kr(o){return o.map(e=>({role:uo(e.role),content:e.provider_content??e.content}))}function Gr(o){return o.map(e=>{if(e.provider_content)return{role:uo(e.role),content:e.provider_content};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(n=>{if(n.type==="image_url"){if(n.image_url.url.startsWith("data:")){let i=n.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:n.image_url.url,media_type:na(n.image_url.url)}}}return n}).filter(n=>n);return{role:uo(e.role),content:t}}return{role:uo(e.role),content:[]}})}function uo(o){switch(o){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}function na(o){switch(o.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 et=class{constructor(e,t=F,n=F,i=[],r=[],s,a){this.provider="claude";if(this.apiKey=e,this.model=t||F,this.visionModel=n||F,this.tools=i,this.mcpServers=r,this.responseLength=s,this.reasoningEffort=a,!Kt.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,n){await S({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callClaude(e,this.model,!0);return this.convertToStandardCompletion(await this.parseStream(i,t))},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){await S({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callClaude(e,this.visionModel,!0);return this.convertToStandardCompletion(await this.parseStream(i,t))},runWithTools:()=>this.visionChatOnce(e),onCompleteResponse:n,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async callClaude(e,t,n,i){let r=e.find(c=>c.role==="system")?.content??"",s=e.filter(c=>c.role!=="system"),a=s.some(c=>Array.isArray(c.content)&&c.content.some(d=>d.type==="image_url"||d.type==="image")),l={model:t,system:r,messages:a?Gr(s):kr(s),stream:n,max_tokens:i!==void 0?i:P(this.responseLength)};this.reasoningEffort!==void 0&&K(t).includes(this.reasoningEffort)&&(l.output_config={effort:this.reasoningEffort}),this.tools.length&&(l.tools=this.tools.map(c=>({name:c.name,description:c.description,input_schema:c.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(Bn,l,p)}async parseStream(e,t){let n=e.body.getReader(),i=new TextDecoder,r=[],s=new Map,a=new Map,l,p,u="";for(;;){let{done:d,value:f}=await n.read();if(d)break;u+=i.decode(f,{stream:!0});let g;for(;(g=u.indexOf(`
12
+ `))!==-1;){let m=u.slice(0,g).trim();if(u=u.slice(g+1),!m.startsWith("data:"))continue;let v=m.slice(5).trim();if(v==="[DONE]")break;let h=JSON.parse(v);if(h.type==="message_delta"&&(typeof h.delta?.stop_reason=="string"&&(l=h.delta.stop_reason),(h.delta?.stop_details!==void 0||h.stop_details!==void 0)&&(p=h.delta?.stop_details??h.stop_details)),h.type==="content_block_start"&&h.content_block&&typeof h.index=="number"&&s.set(h.index,{...h.content_block}),h.type==="content_block_delta"&&h.delta?.type==="text_delta"){t(h.delta.text),r.push({type:"text",text:h.delta.text});let E=s.get(h.index);E?.type==="text"&&(E.text=`${E.text??""}${h.delta.text}`)}if(h.type==="content_block_delta"&&h.delta?.type==="thinking_delta"){let E=s.get(h.index);E?.type==="thinking"&&(E.thinking=`${E.thinking??""}${h.delta.thinking??""}`)}if(h.type==="content_block_delta"&&h.delta?.type==="signature_delta"){let E=s.get(h.index);E?.type==="thinking"&&(E.signature=`${E.signature??""}${h.delta.signature??""}`)}if(h.type==="content_block_start"&&h.content_block?.type==="tool_use"?a.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"?a.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"?r.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"&&r.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 E=a.get(h.index);E&&(E.args+=h.delta.partial_json||"")}if(h.type==="content_block_stop"&&a.has(h.index)){let{id:E,name:N,args:_,server_name:C}=a.get(h.index),A=JSON.parse(_||"{}"),b=s.get(h.index);b&&(b.input=A),C?r.push({type:"mcp_tool_use",id:E,name:N,server_name:C,input:A}):r.push({type:"tool_use",id:E,name:N,input:A}),a.delete(h.index)}}}let c=r.some(d=>d.type==="tool_use"||d.type==="mcp_tool_use");return{blocks:r,providerContent:[...s.entries()].sort(([d],[f])=>d-f).map(([,d])=>d),stop_reason:c?"tool_use":"end",finish_reason:l,stop_details:p}}parseOneShot(e){let t=[];(e.content??[]).forEach(i=>{i.type==="text"?t.push({type:"text",text:i.text}):i.type==="tool_use"?t.push({type:"tool_use",id:i.id,name:i.name,input:i.input??{}}):i.type==="mcp_tool_use"?t.push({type:"mcp_tool_use",id:i.id,name:i.name,server_name:i.server_name,input:i.input??{}}):i.type==="tool_result"?t.push({type:"tool_result",tool_use_id:i.tool_use_id,content:i.content??""}):i.type==="mcp_tool_result"&&t.push({type:"mcp_tool_result",tool_use_id:i.tool_use_id,is_error:i.is_error??!1,content:i.content??[]})});let n=t.some(i=>i.type==="tool_use"||i.type==="mcp_tool_use");return{blocks:t,providerContent:(e.content??[]).map(i=>({...i})),stop_reason:n?"tool_use":"end",finish_reason:e.stop_reason,stop_details:e.stop_details}}async chatOnce(e,t=!0,n=()=>{},i){let r=await this.callClaude(e,this.model,t,i),s=t?await this.parseStream(r,n):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}async visionChatOnce(e,t=!1,n=()=>{},i){let r=await this.callClaude(e,this.visionModel,t,i),s=t?await this.parseStream(r,n):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}convertToStandardCompletion(e){let t=e.blocks.filter(n=>n.type==="text"||n.type==="tool_use"||n.type==="tool_result");return{blocks:t,stop_reason:e.stop_reason,finish_reason:e.finish_reason,stop_details:e.stop_details,assistant_message:{role:"assistant",content:t.filter(n=>n.type==="text").map(n=>n.text).join(""),provider_content:e.providerContent}}}};var tt=class{createChatService(e){let t=e.model||this.getDefaultModel(),n=K(t);if(e.reasoning_effort!==void 0&&!n.includes(e.reasoning_effort)){let r=n.length>0?`Supported values: ${n.join(", ")}.`:"This model does not expose configurable effort.";throw new Error(`Model ${t} does not support Claude reasoning_effort: ${e.reasoning_effort}. ${r}`)}let i=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"resolved"});return new et(e.apiKey,t,i,e.tools??[],e.mcpServers??[],e.responseLength,e.reasoning_effort)}getProviderName(){return"claude"}getSupportedModels(){return[So,F,Dt,bt,Nt,wt,kt,It,Gt,Vt,Ft,vo,Ut]}getDefaultModel(){return F}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Kt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};async function Ln(o,e,t={}){let n=o.body.getReader(),i=new TextDecoder,r=[],s=new Map,a=new Map,l,p,u,c="";for(;;){let{done:m,value:v}=await n.read();if(m)break;c+=i.decode(v,{stream:!0});let h="",E="",N=c.split(`
13
+ `);c=N.pop()||"";for(let _=0;_<N.length;_++){let C=N[_].trim();if(C.startsWith("event:"))h=C.slice(6).trim();else if(C.startsWith("data:"))E=C.slice(5).trim();else if(C===""&&h&&E){try{let A=JSON.parse(E);ia(h,A,e,r,s,a,b=>{b.responseStatus!==void 0&&(l=b.responseStatus),b.incompleteDetails!==void 0&&(p=b.incompleteDetails),b.usage!==void 0&&(u=b.usage)})}catch(A){t.onJsonError?.(E,A),console.warn("Failed to parse SSE data:",E)}h="",E=""}}}let d=Array.from(s.values()).map(m=>({type:"tool_use",id:m.id,name:m.name,input:ve(m.arguments,t.onJsonError)})),f=Array.from(a.values()),g=O.getFullText(r);return{blocks:[...r,...d],stop_reason:d.length?"tool_use":"end",truncated:l==="incomplete",response_status:l,incomplete_details:p,usage:u,...f.length>0?{assistant_message:{role:"assistant",content:g,provider_content:f}}:{}}}function ia(o,e,t,n,i,r,s){switch(o){case"response.output_item.added":Vr(r,e.item),e.item?.type==="message"&&Array.isArray(e.item.content)?e.item.content.forEach(a=>{a.type==="output_text"&&a.text&&(t(a.text),O.append(n,a.text))}):e.item?.type==="function_call"&&i.set(e.item.id,{id:e.item.call_id??e.item.id,name:e.item.name,arguments:e.item.arguments??""});break;case"response.function_call_arguments.delta":{let a=i.get(e.item_id);a&&typeof e.delta=="string"&&(a.arguments+=e.delta);let l=r.get(e.item_id);l&&typeof e.delta=="string"&&(l.arguments=`${l.arguments??""}${e.delta}`);break}case"response.function_call_arguments.done":{let a=i.get(e.item_id);a&&typeof e.arguments=="string"&&(a.arguments=e.arguments);let l=r.get(e.item_id);l&&typeof e.arguments=="string"&&(l.arguments=e.arguments);break}case"response.output_item.done":Vr(r,e.item),e.item?.type==="function_call"&&i.set(e.item.id,{id:e.item.call_id??e.item.id,name:e.item.name,arguments:e.item.arguments??""});break;case"response.content_part.added":e.part?.type==="output_text"&&typeof e.part.text=="string"&&(t(e.part.text),O.append(n,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(n,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(Fr(e,"completed"));break;case"response.incomplete":s(Fr(e,"incomplete"));break;default:break}}function Vr(o,e){if(!e||typeof e!="object")return;let t=typeof e.id=="string"&&e.id?e.id:`output-item-${o.size}`;o.set(t,{...e})}function Fr(o,e){let t=o?.response??o;return{responseStatus:t?.status??e,incompleteDetails:t?.incomplete_details??null,usage:t?.usage}}function Ur(o,e={}){let t=[];return o.output&&Array.isArray(o.output)&&o.output.forEach(n=>{n.type==="message"&&n.content&&n.content.forEach(i=>{i.type==="output_text"&&i.text&&t.push({type:"text",text:i.text})}),n.type==="function_call"&&t.push({type:"tool_use",id:n.call_id??n.id,name:n.name,input:ve(n.arguments,e.onJsonError)})}),{blocks:t,stop_reason:t.some(n=>n.type==="tool_use")?"tool_use":"end",truncated:o?.status==="incomplete",response_status:o?.status,incomplete_details:o?.incomplete_details??null,usage:o?.usage,...Array.isArray(o?.output)&&o.output.length>0?{assistant_message:{role:"assistant",content:t.filter(n=>n.type==="text").map(n=>n.text).join(""),provider_content:o.output}}:{}}}function Kr({tools:o,mcpServers:e,isResponsesAPI:t}){let n=[];return o.length>0&&n.push(...V(o,t?"responses":"chat-completions")),e.length>0&&t&&n.push(...ra(e)),n}function ra(o){return o.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 sa={[L.VERY_SHORT]:800,[L.SHORT]:1200,[L.MEDIUM]:2e3,[L.LONG]:3e3,[L.VERY_LONG]:8e3,[L.DEEP]:25e3},aa={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3,max:25e3},la=new Set(["openai-compatible","deepseek","mistral","sakana","plamo"]);function pa(o){return o.type!=="json_schema"?o:{type:o.type,...o.json_schema}}function Hr({provider:o,endpoint:e,messages:t,model:n,stream:i,tools:r,mcpServers:s,responseLength:a,verbosity:l,reasoning_effort:p,enableReasoningSummary:u,responseFormat:c,chatTemplateThinking:d,maxTokens:f}){n===y&&(!p||p==="none"||p==="minimal")&&(p="low");let g=e===w;ua(e,s);let m={model:n,stream:i},v=ca({provider:o,model:n,responseLength:a,reasoning_effort:p,maxTokens:f});g?v!==void 0&&(m.max_output_tokens=v):v!==void 0&&(Br(o)?m.max_tokens=v:m.max_completion_tokens=v),g?m.input=ha(t):m.messages=o==="mistral"?da(t):t,ce(n)&&(g?(p&&(m.reasoning={...m.reasoning,effort:p},u&&(m.reasoning.summary="auto")),l&&(m.text={...m.text,format:{type:"text"},verbosity:l})):(p&&(m.reasoning_effort=p),l&&(m.verbosity=l))),c&&(g?m.text={...m.text,format:pa(c)}:m.response_format=c),o==="mistral"&&ao(n)&&p&&Mi(p)&&(m.reasoning_effort=p),o==="plamo"&&p&&(m.reasoning_effort=p),o==="deepseek"&&p&&(m.thinking={type:p==="none"?"disabled":"enabled"},p!=="none"&&(m.reasoning_effort=p)),o==="sakana"&&d!==void 0&&(m.chat_template_kwargs={thinking:d});let h=Kr({tools:r,mcpServers:s,isResponsesAPI:g});return h.length>0&&(m.tools=h,g||(m.tool_choice="auto")),m}function ca({provider:o,model:e,responseLength:t,reasoning_effort:n,maxTokens:i}){if(i!==void 0)return i;let r=Br(o)?t!==void 0?P(t):void 0:P(t);if(o!=="openai"||!ce(e)||t===void 0)return r;let s=n??Pt(e);return Math.max(r??0,sa[t],aa[s])}function ua(o,e){if(e.length>0&&o===q)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${o}. Please use OpenAI Responses API endpoint: ${w}. MCP tools are only available in the Responses API endpoint.`)}function ha(o){return o.flatMap(e=>{if(e.role==="assistant"&&e.provider_content?.length)return e.provider_content;if(e.role==="tool"&&e.tool_call_id)return[{type:"function_call_output",call_id:e.tool_call_id,output:e.content}];let t=[],n={role:e.role==="tool"?"user":e.role};return typeof e.content=="string"?n.content=e.content:Array.isArray(e.content)?n.content=e.content.map(r=>r.type==="text"?{type:"input_text",text:r.text}:r.type==="image_url"?{type:"input_image",image_url:r.image_url.url}:r):n.content=e.content,(typeof n.content!="string"||n.content.length>0)&&t.push(n),e.role==="assistant"&&e.tool_calls&&t.push(...e.tool_calls.map(r=>({type:"function_call",call_id:r.id,name:r.function.name,arguments:r.function.arguments}))),t})}function da(o){return o.map(e=>{let t={role:e.role};return Array.isArray(e.content)?(t.content=e.content.map(n=>n.type==="image_url"&&typeof n.image_url=="object"&&typeof n.image_url?.url=="string"?{type:"image_url",image_url:n.image_url.url}:n),t):(t.content=e.content,t)})}function Br(o){return la.has(o)}var x=class{constructor(e,t=pe,n=pe,i,r=q,s=[],a,l,p,u=!1,c="openai",d=!0,f,g){if(this.provider=c,this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=(t===y||n===y)&&r===q?w:r,this.mcpServers=s,this.responseLength=a,this.verbosity=l,this.reasoning_effort=p,this.enableReasoningSummary=u,this.responseFormat=f,this.chatTemplateThinking=g,d&&!Tt.includes(n))throw new Error(`Model ${n} does not support vision capabilities.`);this.visionModel=n}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,n){await S({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.model,!0),r=this.endpoint===w;try{if(r){let s=await Ln(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:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){try{await S({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.visionModel,!0),r=this.endpoint===w;try{if(r){let s=await Ln(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:n,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,n=()=>{},i){let r=await this.callOpenAI(e,this.model,t,i);return this.parseResponse(r,t,n)}async visionChatOnce(e,t=!1,n=()=>{},i){let r=await this.callOpenAI(e,this.visionModel,t,i);return this.parseResponse(r,t,n)}async parseResponse(e,t,n){return this.endpoint===w?t?Ln(e,n):Ur(await e.json()):t?this.parseStream(e,n):this.parseOneShot(await e.json())}async callOpenAI(e,t,n=!1,i){let r=Hr({provider:this.provider,endpoint:this.endpoint,messages:e,model:t,stream:n,tools:this.tools,mcpServers:this.mcpServers,responseLength:this.responseLength,verbosity:this.verbosity,reasoning_effort:this.reasoning_effort,enableReasoningSummary:this.enableReasoningSummary,responseFormat:this.responseFormat,chatTemplateThinking:this.chatTemplateThinking,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 z(e,t)}async parseStream(e,t){return k(e,t,{appendTextBlock:O.addTextBlock})}parseOneShot(e){return G(e)}};var ot=class extends x{constructor(e,t=Me,n=t,i,r=io,s,a){let l=ui(t,a);if(super(e,t,n,i,r,[],s,void 0,l,!1,"deepseek",!1),i?.length&&l!==void 0&&l!=="none")throw new Error("DeepSeek thinking with tools is not supported yet. Use reasoning_effort: 'none' for tool calling.")}};var nt=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:Ze,supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"explicit"}),i=e.tools;return new ot(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"deepseek"}getSupportedModels(){return[...pi]}getDefaultModel(){return Me}supportsVision(){return!0}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ci(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"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 io}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Wr=(o,e)=>({name:`mcp_${o.name}_search`,description:e==="schema-fetch-failed"?`Search using ${o.name} MCP server (schema fetch failed)`:`Search using ${o.name} MCP server`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}),Tn=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:[Wr(e)],failures:[]}}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),{schemas:[Wr(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=[],n=[];for(let i of e)try{let r=await this.fetchToolSchemasWithStatus(i);t.push(...r.schemas),n.push(...r.failures)}catch(r){console.error(`Failed to fetch schemas from ${i.name}:`,r),n.push({server:i,error:r})}return{schemas:t,failures:n}}};function $r(o){switch(o){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}function zr(o,e={}){let t=[],n=null,i=[],r=()=>{n&&i.length&&(t.push({role:n,parts:[...i]}),i=[]),n=null};for(let s of o){if(s.role==="system")continue;let a=$r(s.role);if(s.tool_calls){r();let l=s.tool_calls.map(p=>jr(p,e));l.length>0&&t.push({role:"model",parts:l});continue}if(s.role==="tool"){r(),Jr(t,Zr(s,e));continue}a!==n&&r(),n=a,i.push({text:s.content})}return r(),t}async function qr(o,e={}){let t=e.imageFetcher??M.get,n=e.blobToBase64??fa,i=[],r=null,s=[],a=()=>{r&&s.length>0&&(i.push({role:r,parts:[...s]}),s=[]),r=null};for(let l of o){if(l.role==="system")continue;let p=$r(l.role);if(l.tool_calls){a();let u=l.tool_calls.map(c=>jr(c,e));u.length>0&&i.push({role:"model",parts:u});continue}if(l.role==="tool"){a(),Jr(i,Zr(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 u of l.content)if(u.type==="text")s.push({text:u.text});else if(u.type==="image_url")try{let d=await(await t(u.image_url.url)).blob(),f=await n(d);s.push({inlineData:{mimeType:d.type||"image/jpeg",data:f.split(",")[1]}})}catch(c){throw console.error("Error processing image:",c),new Error(`Failed to process image: ${c.message}`)}}}return a(),i}function Xr(o){let e=o.flatMap(t=>t.role!=="system"?[]:typeof t.content=="string"?t.content?[{text:t.content}]:[]:t.content.flatMap(n=>n.type==="text"&&n.text?[{text:n.text}]:[]));return e.length>0?{parts:e}:void 0}function jr(o,e){e.callIdMap?.set(o.id,o.function.name);let t=e.functionCallContextMap?.get(o.id),n={functionCall:{...t?.providerCallId?{id:t.providerCallId}:{},name:o.function.name,args:JSON.parse(o.function.arguments||"{}")}};return t?.thoughtSignature&&(n.thoughtSignature=t.thoughtSignature),n}function Zr(o,e){let t=o.tool_call_id,n=e.functionCallContextMap?.get(t);return{functionResponse:{...n?.providerCallId?{id:n.providerCallId}:{},name:o.name??n?.name??e.callIdMap?.get(t)??"result",response:ga(ma(o.content))}}}function Jr(o,e){let t=o[o.length-1];if(t?.role==="user"&&t.parts.every(i=>i.functionResponse)){t.parts.push(e);return}o.push({role:"user",parts:[e]})}function ma(o){try{return JSON.parse(o)}catch{return o}}function ga(o){return o===null?{content:null}:typeof o=="object"?o:{content:o}}function fa(o){return new Promise((e,t)=>{let n=new FileReader;n.onloadend=()=>e(n.result),n.onerror=t,n.readAsDataURL(o)})}function _a(o,e){return[...o,...e].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}function Yr(o,e){let t=_a(o,e);if(t.length!==0)return{tools:[{functionDeclarations:t}],toolConfig:{functionCallingConfig:{mode:"AUTO"}}}}function Qr(o){return o.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 it=class{constructor(e,t=Q,n=Q,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,!xt.includes(n))throw new Error(`Model ${n} does not support vision capabilities.`);this.visionModel=n,this.tools=i,this.mcpServers=r}isGemma4Model(e){return/^gemma-4-/.test(e)}resolveThinkingConfig(e){let t=At(e,this.reasoningEffort);if(t)return{includeThoughts:!1,thinkingLevel:t.toUpperCase()};if(this.isGemma4Model(e))return{includeThoughts:!1,thinkingLevel:"MINIMAL"}}shouldExposeTextPart(e,t){return!(!e.text||this.isGemma4Model(t)&&e.thought===!0)}adaptKeysForApi(e){let t={toolConfig:"tool_config",functionCallingConfig:"function_calling_config",functionDeclarations:"function_declarations",functionCall:"function_call",functionResponse:"function_response",thoughtSignature:"thought_signature"};return Array.isArray(e)?e.map(n=>this.adaptKeysForApi(n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,i])=>[t[n]??n,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=Tn.fetchAllToolSchemasWithStatus(this.mcpServers),n=await Promise.race([t,e]);this.mcpToolSchemas=n.schemas,this.mcpSchemasInitialized=!0,this.mcpSchemaInitializationError=n.failures[0]?.error}catch(e){console.warn("Failed to initialize MCP schemas, using fallback:",e),this.mcpSchemaInitializationError=e,this.mcpToolSchemas=Qr(this.mcpServers),this.mcpSchemasInitialized=!0}}async processChat(e,t,n){try{await S({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 O.getFullText(r)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:n,toolErrorMessage:"Received functionCall. Use chatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processChat:",i),i}}async processVisionChat(e,t,n){try{await S({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 O.getFullText(r)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:i=>{i.filter(r=>r.type==="text").forEach(r=>t(r.text))},onCompleteResponse:n,toolErrorMessage:"Received functionCall. Use visionChatOnce() loop when tools are enabled."})}catch(i){throw console.error("Error in processVisionChat:",i),i}}async callGemini(e,t,n=!1,i){let a={contents:e.some(_=>Array.isArray(_.content)&&_.content.some(C=>C?.type==="image_url"||C?.inlineData))?await qr(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}):zr(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}),generationConfig:{maxOutputTokens:i!==void 0?i:P(this.responseLength)}},l=Xr(e);l&&(a.systemInstruction=l);let p=this.resolveThinkingConfig(t);p&&(a.generationConfig.thinkingConfig=p);let u=[];if(this.mcpServers.length>0)try{await this.initializeMCPSchemas(),u=this.mcpToolSchemas}catch(_){console.warn("MCP initialization failed, skipping MCP tools:",_)}let c=Yr(this.tools,u);c&&Object.assign(a,c);let d=async(_,C)=>{let A=n?"streamGenerateContent":"generateContent",b=n?"?alt=sse":"",is=`${Dn}/${_}/models/${t}:${A}${b}${b?"&":"?"}key=${this.apiKey}`;return M.post(is,C)},f=/flash[-_]lite/.test(t),g=this.isGemma4Model(t),m=/gemini-2\.5/.test(t),v=/^gemini-3(?:\.[0-9]+)?-/.test(t),h=f||g||m||v,E=h?"v1beta":"v1",N=async()=>{try{let _=E==="v1"?a:this.adaptKeysForApi(a);return await d(E,_)}catch(_){let C=/Unknown name|Cannot find field|404/.test(_?.message||"")||_?.status===404;if(!h&&C)try{return await d("v1beta",this.adaptKeysForApi(a))}catch(A){throw A instanceof Error&&(A.cause=_),A}throw _}};try{return await N()}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 n=t.id??this.genUUID();return this.callIdMap.set(n,t.name),this.functionCallContextMap.set(n,{name:t.name,providerCallId:t.id,thoughtSignature:e.thoughtSignature??e.thought_signature}),{type:"tool_use",id:n,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,n){let i=e.body.getReader(),r=new TextDecoder,s=[],a=[],l="",p=c=>{if(!c||c==="[DONE]")return;let d;try{d=JSON.parse(c)}catch{return}for(let f of d.candidates??[])for(let g of f.content?.parts??[]){this.shouldExposeTextPart(g,n)&&(t(g.text),O.addTextBlock(s,g.text));let m=this.createFunctionCallBlock(g);m&&a.push(m);let v=this.createFunctionResponseBlock(g);v&&a.push(v)}};for(;;){let{done:c,value:d}=await i.read();if(c)break;l+=r.decode(d,{stream:!0});let f;for(;(f=l.indexOf(`
14
+ `))!==-1;){let g=l.slice(0,f);if(l=l.slice(f+1),g.endsWith("\r")&&(g=g.slice(0,-1)),!g.trim()){p("");continue}g.startsWith("data:")&&(g=g.slice(5).trim()),g&&p(g)}}return l&&p(l),{blocks:[...s,...a],stop_reason:a.some(c=>c.type==="tool_use")?"tool_use":"end"}}parseOneShot(e,t){let n=[],i=[];for(let s of e.candidates??[])for(let a of s.content?.parts??[]){this.shouldExposeTextPart(a,t)&&n.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:[...n,...i],stop_reason:i.some(s=>s.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,n=()=>{},i){let r=await this.callGemini(e,this.model,t,i);return t?this.parseStream(r,n,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,n=()=>{},i){let r=await this.callGemini(e,this.visionModel,t,i);return t?this.parseStream(r,n,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 rt=class{createChatService(e){let t=e.model||this.getDefaultModel();if(e.reasoning_effort!==void 0&&!Hn(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 n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"resolved"});return new it(e.apiKey,t,n,e.tools||[],e.mcpServers||[],e.responseLength,At(t,e.reasoning_effort))}getProviderName(){return"gemini"}getSupportedModels(){return[...Oo]}getDefaultModel(){return Q}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return xt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function Ea(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var st=class{constructor(e={}){this.provider="gemini-nano";this.consumedTranscript=[];this.expectedInputLanguages=e.expectedInputLanguages??["ja","en"],this.expectedOutputLanguages=e.expectedOutputLanguages??["ja"],this.initialPrompts=(e.initialPrompts??[]).map(t=>({...t})),this._responseLength=e.responseLength,this.sessionMode=e.sessionMode??"stateless"}getModel(){return Se}getVisionModel(){return Se}dispose(){this.destroyPersistentSessions()}async processChat(e,t,n){let i=await this.generateResponse(e,!0,t);await n(i)}async processVisionChat(e,t,n){throw new Error("Gemini Nano does not support vision capabilities.")}async chatOnce(e,t=!1,n=()=>{},i){return{blocks:[{type:"text",text:await this.generateResponse(e,t,n)}],stop_reason:"end"}}async visionChatOnce(e,t=!1,n=()=>{},i){throw new Error("Gemini Nano does not support vision capabilities.")}async generateResponse(e,t,n){let i=Ea();if(!i)throw new Error("Gemini Nano is not available in this environment. Chrome 148+ on a supported desktop device is required for web pages.");let r=this.getModelOptions();this.sessionMode==="stateless"&&await this.ensureAvailability(i,r);let a=e.filter(f=>f.role==="system").map(f=>f.content).join(`
15
+ `),l=e.filter(f=>f.role==="user"||f.role==="assistant").slice(-20),p=this.findLastUserMessageIndex(l);if(p===-1)throw new Error("No user message found in the provided messages.");let u=l[p],c=l.slice(0,p);if(this.sessionMode==="persistent")return this.generatePersistentResponse(i,a,c,u.content,r,t,n);let d=await this.createSession(i,a,c,r);try{return await this.promptSession(d,u.content,t,n)}finally{try{d.destroy()}catch{}}}async generatePersistentResponse(e,t,n,i,r,s,a){let l=this.getPersistentSessionKey(t,r);this.persistentSessionKey!==l&&this.destroyPersistentSessions(),!this.baseSession&&!this.liveSession&&(await this.ensureAvailability(e,r),await this.createPersistentBaseSession(e,t,n,r),this.persistentSessionKey=l);let p=await this.getPersistentLiveSession(e,t,n,r),u=p===this.liveSession&&this.isHistoryCompatible(n,this.consumedTranscript);this.persistentSessionKey=l;try{let c=await this.promptSession(p,i,s,a);return this.recordConsumedTranscript(n,i,c,u),c}catch(c){if(!this.isQuotaExceededError(c))throw this.destroyPersistentLiveSession(),c;this.destroyPersistentLiveSession(),p=await this.getPersistentLiveSession(e,t,[],r),this.persistentSessionKey=l;try{let d=await this.promptSession(p,i,s,a);return this.recordConsumedTranscript([],i,d,!1),d}catch(d){throw this.destroyPersistentLiveSession(),d}}}async ensureAvailability(e,t){let n=await e.availability(t);if(n!=="available"&&n!=="downloadable")throw new Error(`Gemini Nano Prompt API is not ready in this environment. LanguageModel.availability() returned "${n}". Expected "available" or "downloadable".`)}async createPersistentBaseSession(e,t,n,i){this.baseSession=await this.createSession(e,t,[],i),n.length>0?(this.liveSession=await this.createSession(e,t,n,i),this.consumedTranscript=n.map(r=>({...r}))):typeof this.baseSession.clone=="function"?this.liveSession=await this.baseSession.clone():this.liveSession=this.baseSession}async getPersistentLiveSession(e,t,n,i){if(this.liveSession&&this.isHistoryCompatible(n,this.consumedTranscript))return this.liveSession;if(this.liveSession&&this.liveSession!==this.baseSession&&this.destroyPersistentLiveSession(),n.length===0&&this.baseSession){if(typeof this.baseSession.clone=="function")this.liveSession=await this.baseSession.clone();else{if(this.consumedTranscript.length>0)return this.destroyPersistentSessions(),await this.createPersistentBaseSession(e,t,[],i),this.liveSession;this.liveSession=this.baseSession}return this.liveSession}return this.baseSession&&typeof this.baseSession.clone=="function"?(this.liveSession=await this.createSession(e,t,n,i),this.liveSession):(this.destroyPersistentSessions(),await this.ensureAvailability(e,i),await this.createPersistentBaseSessionWithHistory(e,t,n,i),this.liveSession)}async createPersistentBaseSessionWithHistory(e,t,n,i){this.baseSession=await this.createSession(e,t,n,i),this.liveSession=this.baseSession,this.consumedTranscript=n.map(r=>({...r}))}recordConsumedTranscript(e,t,n,i){let r=i?this.consumedTranscript:e;this.consumedTranscript=[...r,{role:"user",content:t},{role:"assistant",content:n}]}getPersistentSessionKey(e,t){return JSON.stringify({systemPrompt:e,modelOptions:t,initialPrompts:this.initialPrompts,responseLength:this._responseLength})}isHistoryCompatible(e,t){return e.length===0||t.length===0?e.length===0&&t.length===0:this.isSuffix(e,t)||this.isSuffix(t,e)}isSuffix(e,t){if(e.length>t.length)return!1;let n=t.length-e.length;return e.every((i,r)=>i.role===t[n+r].role&&i.content===t[n+r].content)}isQuotaExceededError(e){return typeof e=="object"&&e!==null&&"name"in e&&e.name==="QuotaExceededError"}destroyPersistentLiveSession(){this.liveSession&&(this.destroySession(this.liveSession),this.liveSession===this.baseSession&&(this.baseSession=void 0)),this.liveSession=void 0,this.consumedTranscript=[]}destroyPersistentSessions(){this.liveSession&&this.liveSession!==this.baseSession&&this.destroySession(this.liveSession),this.baseSession&&this.destroySession(this.baseSession),this.baseSession=void 0,this.liveSession=void 0,this.persistentSessionKey=void 0,this.consumedTranscript=[]}destroySession(e){try{e.destroy()}catch{}}async promptSession(e,t,n,i){if(n&&typeof e.promptStreaming=="function"){let s=e.promptStreaming(t).getReader(),a="",l="unknown";for(;;){let{done:p,value:u}=await s.read();if(p)break;let c=String(u??"");l==="unknown"&&a!==""&&(l=c.startsWith(a)?"cumulative":"delta");let d=l==="cumulative",f=d?c.slice(a.length):c;a=d?c:a+c,f&&i(f)}return a}let r=await e.prompt(t);return i(r),r}async createSession(e,t,n,i){let r=this.buildInitialPrompts(t,n),s={...i,...r.length>0?{initialPrompts:r}:{}};return e.create(s)}getModelOptions(){return{expectedInputs:[{type:"text",languages:this.expectedInputLanguages}],expectedOutputs:[{type:"text",languages:this.expectedOutputLanguages}]}}buildInitialPrompts(e,t){let n=this.initialPrompts.filter(s=>s.role==="system").map(s=>s.content),i=this.buildSystemPrompt([e,...n].filter(Boolean).join(`
16
16
 
17
17
  `)),r=[];return i&&r.push({role:"system",content:i}),r.push(...this.initialPrompts.filter(s=>s.role!=="system").map(s=>({...s})),...t.filter(s=>s.role==="user"||s.role==="assistant").map(({role:s,content:a})=>({role:s,content:a}))),r}findLastUserMessageIndex(e){for(let t=e.length-1;t>=0;t-=1)if(e[t].role==="user")return t;return-1}buildSystemPrompt(e){let t=[];e&&t.push(e);let n=this.getResponseLengthInstruction();return n&&t.push(n),t.join(`
18
18
 
19
- `)}getResponseLengthInstruction(){if(!this._responseLength)return;let e=Mn[this._responseLength];if(e)switch(this._responseLength){case L.VERY_SHORT:return`Reply in no more than one concise sentence. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Stay within approximately ${e} tokens.`;case L.SHORT:return`Reply in no more than two concise sentences. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Use natural conversational language. Stay within approximately ${e} tokens.`;case L.MEDIUM:return`Reply in no more than three concise sentences. Answer directly and include only the context needed to understand the answer. Do not use a preamble, summary, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case L.LONG:return`Reply in no more than five sentences. Explain the important details clearly, but avoid unnecessary preambles, repetition, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case L.VERY_LONG:return`Reply in no more than ten sentences. Give a thorough but focused answer. Use short plain-text paragraphs when helpful, and avoid unnecessary repetition, bullet points, or Markdown. Stay within approximately ${e} tokens.`;case L.DEEP:return`Give a detailed response and organize it in the way that best fits the request. No sentence-count limit applies at this level. Stay within approximately ${e} tokens.`}}};var st=class{createChatService(e){return new rt({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,initialPrompts:e.initialPrompts,responseLength:e.responseLength,sessionMode:e.sessionMode})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[Me]}getDefaultModel(){return Me}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var at=class{constructor(e,t=B,n=B,i,r=$e,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 d=te(t);if(p!==void 0&&!d.includes(p))throw new Error(`Model ${t} does not support reasoning_effort: ${p}.`);this.reasoningEffort=p??qe(t),this.visionModel=n}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,n){await S({hasTools:this.tools.length>0,runWithoutTools:()=>this.chatOnce(e,!0,t),runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){if(!Xe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await S({hasTools:this.tools.length>0,runWithoutTools:()=>this.visionChatOnce(e,!0,t),runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:n,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,n=()=>{},i){let r=await this.callKimi(e,this.model,t,i);return this.parseResponse(r,t,n)}async visionChatOnce(e,t=!1,n=()=>{},i){if(!Xe(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,n)}async parseResponse(e,t,n){return t?this.parseStream(e,n):this.parseOneShot(await e.json())}async callKimi(e,t,n=!1,i){let r=this.buildRequestBody(e,t,n,i);return await M.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,n,i){let r={model:t,stream:n,messages:e},s=i!==void 0?i:P(this.responseLength);s!==void 0&&(fe(t)?r.max_completion_tokens=s:r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),fe(t)&&(r.reasoning_effort=this.reasoningEffort??qe(t));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($e)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveEffectiveThinking(e){if(fe(e)){if(this.thinking)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(to(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 G(this.tools,"chat-completions")}async parseStream(e,t){return w(e,t,{preserveAssistantMessage:!0,onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return k(e,{preserveAssistantMessage:!0})}};var lt=class{constructor(){this.defaultThinking={type:"enabled"}}createChatService(e){let t=this.resolveEndpoint(e),n=e.model||this.getDefaultModel(),i=T({model:n,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:l=>this.supportsVisionForModel(l),validate:"explicit"}),r=e.tools,s=this.resolveThinking(n,r,e.thinking),a=this.resolveReasoningEffort(n,e.reasoning_effort);return new at(e.apiKey,n,i,r,t,e.responseLength,e.responseFormat,s,a)}getProviderName(){return"kimi"}getSupportedModels(){return[ze,Qt,eo,B,gn]}getDefaultModel(){return B}getDefaultVisionModel(){return B}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Xe(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 $e}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveThinking(e,t,n){if(fe(e)){if(n)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(to(e)){if(n?.type==="disabled")throw new Error(`Model ${e} requires thinking mode and does not support thinking: disabled.`);return n??this.defaultThinking}return t&&t.length>0?{type:"disabled"}:n??this.defaultThinking}resolveReasoningEffort(e,t){let n=te(e);if(n.length===0){if(t!==void 0)throw new Error(`Model ${e} does not support the reasoning_effort option.`);return}let i=t??qe(e)??n[0];if(!n.includes(i))throw new Error(`Model ${e} supports reasoning_effort values: ${n.join(", ")}.`);return i}};var pt=class extends x{constructor(e,t=W,n=t,i,r=io,s,a){super(e,t,n,i,r,[],s,void 0,a,!1,"mistral",!1)}};var ct=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=ro(t)?e.reasoning_effort:void 0;return new pt(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"mistral"}getSupportedModels(){return[...fi]}getDefaultModel(){return W}getDefaultVisionModel(){return W}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ei(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 io}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var ut=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 x(...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 n;try{n=new URL(t)}catch{throw new Error("openai-compatible provider requires endpoint to be a full URL.")}if(n.protocol!=="http:"&&n.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 ht=class{createChatService(e){let t=this.optimizeGPT5Options(e),n=T({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:d=>this.supportsVisionForModel(d),validate:"resolved"}),i=t.tools,r=t.mcpServers??[],s=t.model||this.getDefaultModel(),a=!1;r.length>0||s===R||n===R?a=!0:s===A||n===A||s===I||n===I?a=(t.gpt5EndpointPreference||"responses")!=="chat"||t.reasoning_effort!=="none":xn(s)?a=!0:pe(s)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let l=t.endpoint||(a?N:z),p=[t.apiKey,s,n,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 x(...p)}getProviderName(){return"openai"}getSupportedModels(){return[ne,Se,ve,Ce,ie,re,X,R,A,I,q,j,Z,se,ae,J,uo,ho,_o,le,go,Tn,Rn,"o1"]}getDefaultModel(){return ne}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Lt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!pe(t))return e;let n={...e};if(e.gpt5Preset){let i=Ci[e.gpt5Preset];n.reasoning_effort=i.reasoning_effort,n.verbosity=i.verbosity}else e.reasoning_effort||(n.reasoning_effort=Pt(t));return n.reasoning_effort=this.normalizeReasoningEffort(t,n.reasoning_effort),n}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!Tt(e)||t==="minimal"&&!Rt(e)?t==="minimal"&&Tt(e)?"none":t==="none"&&Rt(e)?"minimal":mo(e)?"low":"medium":t==="low"&&!mo(e)?"medium":t==="xhigh"&&!fo(e)?"high":t==="max"&&!yn(e)?fo(e)?"xhigh":"high":t}};var co=o=>[$t,Ae].includes(o.trim()),da=o=>[K,Q,H,De].includes(o.trim()),xi=(o,e)=>{if(co(o)&&!e)throw new Error("OpenRouter Auto Router returned no visible content. Please retry.")},Zr=o=>o.blocks.some(e=>e.type!=="text"||e.text.trim().length>0),dt=class{constructor(e,t=K,n=K,i,r=Ut,s,a,l,p,d,c){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=d,this.reasoningMaxTokens=c,this.visionModel=n}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!_e(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=jn){let n=6e4-t;n>0&&(console.log(`Rate limit reached for free tier. Waiting ${n}ms...`),await new Promise(i=>setTimeout(i,n)),this.requestCount=0)}this.lastRequestTime=e,this.requestCount++}async processChat(e,t,n){await this.applyRateLimiting(),await S({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.model,!0);return this.handleStream(i,t,this.model)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){if(!ke(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await S({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(i,t,this.visionModel)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:n,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,n=()=>{},i){await this.applyRateLimiting();let r=await this.callOpenRouter(e,this.model,t,i);return t?this.parseStream(r,n,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,n=()=>{},i){if(!ke(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,n,this.visionModel):this.parseOneShot(await r.json(),this.visionModel)}async callOpenRouter(e,t,n=!1,i){let r=this.buildRequestBody(e,t,n,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,n,i){let r={model:t,messages:e,stream:n},s=i!==void 0?i:P(this.responseLength),a=da(t)||co(t)&&i===void 0;s&&a?console.warn(`OpenRouter: Token limits are disabled for ${t} because this model can return empty content when a token limit is set.`):s&&(r.max_tokens=s);let l=rn(t),p=Zn(t,this.reasoning_effort);if(p!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens||l){if(r.reasoning={},p){let d=p==="minimal"&&t!==ue&&t!==he?"low":p;r.reasoning.effort=d}else l&&(r.reasoning.effort=l);(p==="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=G(this.tools,"chat-completions"),t!==ce&&(r.tool_choice="auto")),r}async handleStream(e,t,n){let i=await $(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:co(n)});return xi(n,i.trim().length>0),i}async parseStream(e,t,n){let i=await w(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:co(n)});return xi(n,Zr(i)),i}parseOneShot(e,t){let n=k(e,{throwOnApiError:co(t)});return xi(t,Zr(n)),n}};var _t=class{createChatService(e){let t=T({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:e.model||this.getDefaultModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),n=e.tools,i=e.appName,r=e.appUrl;return new dt(e.apiKey,e.model||this.getDefaultModel(),t,n,e.endpoint,e.responseLength,i,r,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[Kt,Ht,ce,Bt,Wt,Pe,So,xe,ye,ue,he,$t,Ae,Bn,K,Ro,Po,xo,yo,Ao,Io,Do,bo,No,wo,ko,Go,Vo,Fo,Uo,Ko,Ie,Ho,Xt,Bo,Wo,$o,zo,Xo,qo,jo,Zo,Jo,Yo,Qo,Q,H,De,Wn,$n,en,tn,on,Ne,be,we,de,qt,To,vo,Co,zt,Lo,zn,Xn]}getDefaultModel(){return K}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return ke(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return qn}isModelFree(e){return _e(e)}};var gt=class extends x{constructor(e,t=Je,n=t,i,r=ao,s,a){super(e,t,n,i,r,[],s,void 0,a,!1,"plamo",!1)}};var ft=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=e.tools;return new gt(e.apiKey,t,e.visionModel??t,n,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"plamo"}getSupportedModels(){return[...Si]}getDefaultModel(){return Je}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 ao}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var mt=class extends x{constructor(e,t=Ze,n=t,i,r=so,s,a){super(e,t,n,i,r,[],s,void 0,void 0,!1,"sakana",!1,void 0,a?.type==="enabled")}};var Et=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:Ee,supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools;if(e.thinking!==void 0&&t!==Ee)throw new Error("Sakana thinking control is only supported for sakana-namazu.");let r=t===Ee?e.thinking??{type:"disabled"}:void 0;return new mt(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"sakana"}getSupportedModels(){return[...Mi]}getDefaultModel(){return Ze}supportsVision(){return!0}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Oi(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"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 so}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Mt=class{constructor(e,t=F,n=F,i,r=Jt,s,a="none"){this.provider="xai";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.visionModel=n,this.reasoningEffort=a}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,n){await S({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:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){if(!Be(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await S({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:n,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,n=()=>{},i){let r=await this.callXAI(e,this.model,t,i);return this.parseResponse(r,t,n)}async visionChatOnce(e,t=!1,n=()=>{},i){if(!Be(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,n)}async parseResponse(e,t,n){return t?this.parseStream(e,n):this.parseOneShot(await e.json())}async callXAI(e,t,n=!1,i){let r=this.buildRequestBody(e,t,n,i);return await M.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,n,i){let r={model:t,stream:n,messages:e},s=i!==void 0?i:P(this.responseLength);s!==void 0&&(r.max_tokens=s),this.reasoningEffort&&dn(t)&&(r.reasoning_effort=Yt(t,this.reasoningEffort));let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto"),r}buildToolsDefinition(){return G(this.tools,"chat-completions")}async handleStream(e,t){return $(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}async parseStream(e,t){return w(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return k(e)}};var Ot=class{createChatService(e){let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"explicit"}),i=e.tools;return new Mt(e.apiKey,t,n,i,e.endpoint||Jt,e.responseLength,Yt(t,e.reasoning_effort??_n(t)))}getProviderName(){return"xai"}getSupportedModels(){return[Ue,Ke,He,F,un,hn]}getDefaultModel(){return F}getDefaultVisionModel(){return F}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Be(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var St=class{constructor(e,t=ee,n=ge,i,r=jt,s,a,l,p){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.reasoningEffort=p,this.visionModel=n}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,n){await S({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:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){if(!Fe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await S({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:n,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,n=()=>{},i){let r=await this.callZAI(e,this.model,t,i);return this.parseResponse(r,t,n)}async visionChatOnce(e,t=!1,n=()=>{},i){if(!Fe(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,n)}async parseResponse(e,t,n){return t?this.parseStream(e,n):this.parseOneShot(await e.json())}async callZAI(e,t,n=!1,i){let r=this.buildRequestBody(e,t,n,i);return await M.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,n,i){let r={model:t,stream:n,messages:e},s=i!==void 0?i:P(this.responseLength);s!==void 0&&(r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),this.thinking&&(r.thinking=this.thinking),cn(t)&&this.reasoningEffort&&(r.reasoning_effort=this.reasoningEffort);let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto",n&&ri(t)&&(r.tool_stream=!0)),r}buildToolsDefinition(){return G(this.tools,"chat-completions")}async handleStream(e,t){return $(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}async parseStream(e,t){return w(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return k(e)}};var vt=class{createChatService(e){let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:c=>this.supportsVisionForModel(c),validate:"explicit"}),i=e.tools,r=Ve(t);if(e.reasoning_effort!==void 0&&!r.includes(e.reasoning_effort)){let c=r.length>0?`Supported values: ${r.join(", ")}.`:"This model does not expose configurable effort.";throw new Error(`Model ${t} does not support Z.ai reasoning_effort: ${e.reasoning_effort}. ${c}`)}let s=ii(t,e.reasoning_effort),a=Ge(t),l=e.thinking!==void 0,p=a?{type:"enabled",clear_thinking:e.thinking?.clear_thinking??!0}:l&&e.reasoning_effort===void 0?e.thinking:s==="high"||s==="max"?{type:"enabled",clear_thinking:e.thinking?.clear_thinking}:{type:"disabled",clear_thinking:e.thinking?.clear_thinking},d=a||p?.type==="enabled"&&e.reasoning_effort!==void 0?s:void 0;return new St(e.apiKey,t,n,i,e.endpoint||jt,e.responseLength,e.responseFormat,p,d)}getProviderName(){return"zai"}getSupportedModels(){return[sn,Zt,ee,Jn,Yn,Qn,an,ei,ti,oi,ni,ln,pn,ge]}getDefaultModel(){return ee}getDefaultVisionModel(){return ge}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Fe(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Jr=[new ht,new ut,new it,new st,new et,new _t,new vt,new Ot,new lt,new ot,new ct,new Et,new ft];var _a=new Set(["claude","claude-agent-sdk","codex-sdk","copilot-sdk","deepseek","gemini","gemini-nano","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),ga=new Set(["claude","deepseek","gemini","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),fa=new Set(["codex-sdk"]);function yi(o){if(_a.has(o))return{text:!0,streaming:!fa.has(o),tools:ga.has(o)}}function ma(o){let e=o.provider==="claude",t=o.messages.filter(r=>!Yr(e,r)),n=o.completion.blocks.filter(r=>r.type==="tool_use"),i=o.completion.assistant_message??Ea(e,n);return Yr(e,i)||t.push({...i}),t.push(...Ma(e,o.toolResults)),t}function Yr(o,e){if(!o||e.role!=="assistant")return!1;let t=e.content;return Array.isArray(t)&&t.length===0}function Ea(o,e){return o?{role:"assistant",content:e.map(t=>({type:"tool_use",id:t.id,name:t.name,input:t.input??{}}))}:{role:"assistant",content:[],tool_calls:e.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.input??{})}}))}}function Ma(o,e){return o?e.map(t=>({role:"user",content:[{type:"tool_result",tool_use_id:t.tool_use_id,content:t.content}]})):e.map(t=>({role:"tool",tool_call_id:t.tool_use_id,content:t.content}))}var Oa=new Set(["openai","gemini","claude"]),Sa=new Set(["openai","openai-compatible","zai","kimi"]),va={openai:["none","minimal","low","medium","high","xhigh","max"],claude:["low","medium","high","xhigh","max"],gemini:["minimal","low","medium","high"],openrouter:["none","minimal","low","medium","high","xhigh","max"],kimi:["low","high","max"],mistral:["low","medium","high"],plamo:["none","medium"],xai:["none","low","medium","high","xhigh"],deepseek:["none","low","high","max"],zai:["none","minimal","low","medium","high","xhigh","max"]},Ct=class{static registerProvider(e){this.providers.set(e.getProviderName(),e)}static createChatService(e,t){let n=this.providers.get(e);if(!n)throw new Error(`Unknown chat provider: ${e}`);return n.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 n=this.providers.get(e);if(!n)return;let i=t?this.getVisionSupportLevelForModel(e,t):n.getVisionSupportLevel(),r=yi(e);return{provider:e,models:n.getSupportedModels(),defaultModel:typeof n.getDefaultModel=="function"?n.getDefaultModel():void 0,text:!0,streaming:r?.streaming??!0,vision:i,tools:r?.tools??!1,mcp:Oa.has(e),jsonMode:Sa.has(e),responseLength:!0,reasoningEffort:e==="openai"&&t===R?["low","medium","high","xhigh","max"]:e==="openai"&&t===A?["none","low","medium","high","xhigh","max"]:e==="openai"&&t===I?["none","low","medium","high","xhigh","max"]:e==="claude"&&t?[...U(t)]:e==="gemini"&&t?[...Le(t)]:e==="kimi"&&t?[...te(t)]:e==="deepseek"&&t?[...no(t)]:e==="openrouter"&&t?[...nn(t)]:e==="xai"&&t?[...We(t)]:e==="zai"&&t?[...Ve(t)]:va[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 n=this.providers.get(e);return n?n.getVisionSupportLevelForModel?n.getVisionSupportLevelForModel(t):n.supportsVisionForModel?n.supportsVisionForModel(t)?"supported":"unsupported":n.getVisionSupportLevel():"unsupported"}};Ct.providers=new Map;Jr.forEach(o=>Ct.registerProvider(o));function Qr(){M.setFetch(async(o,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),n=e.headers,i={};if(Array.isArray(n))for(let[c,h]of n)i[c]=String(h);else if(n&&typeof n=="object")for(let[c,h]of Object.entries(n))i[c]=String(h);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(o,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 ss(Ca);})();
19
+ `)}getResponseLengthInstruction(){if(!this._responseLength)return;let e=Sn[this._responseLength];if(e)switch(this._responseLength){case L.VERY_SHORT:return`Reply in no more than one concise sentence. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Stay within approximately ${e} tokens.`;case L.SHORT:return`Reply in no more than two concise sentences. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Use natural conversational language. Stay within approximately ${e} tokens.`;case L.MEDIUM:return`Reply in no more than three concise sentences. Answer directly and include only the context needed to understand the answer. Do not use a preamble, summary, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case L.LONG:return`Reply in no more than five sentences. Explain the important details clearly, but avoid unnecessary preambles, repetition, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case L.VERY_LONG:return`Reply in no more than ten sentences. Give a thorough but focused answer. Use short plain-text paragraphs when helpful, and avoid unnecessary repetition, bullet points, or Markdown. Stay within approximately ${e} tokens.`;case L.DEEP:return`Give a detailed response and organize it in the way that best fits the request. No sentence-count limit applies at this level. Stay within approximately ${e} tokens.`}}};var at=class{createChatService(e){return new st({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,initialPrompts:e.initialPrompts,responseLength:e.responseLength,sessionMode:e.sessionMode})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[Se]}getDefaultModel(){return Se}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var lt=class{constructor(e,t=W,n=W,i,r=ze,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 u=oe(t);if(p!==void 0&&!u.includes(p))throw new Error(`Model ${t} does not support reasoning_effort: ${p}.`);this.reasoningEffort=p??je(t),this.visionModel=n}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,n){await S({hasTools:this.tools.length>0,runWithoutTools:()=>this.chatOnce(e,!0,t),runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){if(!Xe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await S({hasTools:this.tools.length>0,runWithoutTools:()=>this.visionChatOnce(e,!0,t),runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:n,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,n=()=>{},i){let r=await this.callKimi(e,this.model,t,i);return this.parseResponse(r,t,n)}async visionChatOnce(e,t=!1,n=()=>{},i){if(!Xe(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,n)}async parseResponse(e,t,n){return t?this.parseStream(e,n):this.parseOneShot(await e.json())}async callKimi(e,t,n=!1,i){let r=this.buildRequestBody(e,t,n,i);return await M.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,n,i){let r={model:t,stream:n,messages:e},s=i!==void 0?i:P(this.responseLength);s!==void 0&&(Ee(t)?r.max_completion_tokens=s:r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),Ee(t)&&(r.reasoning_effort=this.reasoningEffort??je(t));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(ze)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveEffectiveThinking(e){if(Ee(e)){if(this.thinking)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(no(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 V(this.tools,"chat-completions")}async parseStream(e,t){return k(e,t,{preserveAssistantMessage:!0,onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return G(e,{preserveAssistantMessage:!0})}};var pt=class{constructor(){this.defaultThinking={type:"enabled"}}createChatService(e){let t=this.resolveEndpoint(e),n=e.model||this.getDefaultModel(),i=T({model:n,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:l=>this.supportsVisionForModel(l),validate:"explicit"}),r=e.tools,s=this.resolveThinking(n,r,e.thinking),a=this.resolveReasoningEffort(n,e.reasoning_effort);return new lt(e.apiKey,n,i,r,t,e.responseLength,e.responseFormat,s,a)}getProviderName(){return"kimi"}getSupportedModels(){return[qe,to,oo,W,_n]}getDefaultModel(){return W}getDefaultVisionModel(){return W}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Xe(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 ze}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveThinking(e,t,n){if(Ee(e)){if(n)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(no(e)){if(n?.type==="disabled")throw new Error(`Model ${e} requires thinking mode and does not support thinking: disabled.`);return n??this.defaultThinking}return t&&t.length>0?{type:"disabled"}:n??this.defaultThinking}resolveReasoningEffort(e,t){let n=oe(e);if(n.length===0){if(t!==void 0)throw new Error(`Model ${e} does not support the reasoning_effort option.`);return}let i=t??je(e)??n[0];if(!n.includes(i))throw new Error(`Model ${e} supports reasoning_effort values: ${n.join(", ")}.`);return i}};var ct=class extends x{constructor(e,t=$,n=t,i,r=so,s,a){super(e,t,n,i,r,[],s,void 0,a,!1,"mistral",!1)}};var ut=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=ao(t)?e.reasoning_effort:void 0;return new ct(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"mistral"}getSupportedModels(){return[...Ei]}getDefaultModel(){return $}getDefaultVisionModel(){return $}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Oi(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 so}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var ht=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 x(...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 n;try{n=new URL(t)}catch{throw new Error("openai-compatible provider requires endpoint to be a full URL.")}if(n.protocol!=="http:"&&n.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 dt=class{createChatService(e){let t=this.optimizeGPT5Options(e),n=T({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:u=>this.supportsVisionForModel(u),validate:"resolved"}),i=t.tools,r=t.mcpServers??[],s=t.model||this.getDefaultModel(),a=!1;r.length>0||s===y||n===y?a=!0:s===I||n===I||s===D||n===D?a=(t.gpt5EndpointPreference||"responses")!=="chat"||t.reasoning_effort!=="none":An(s)?a=!0:ce(s)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let l=t.endpoint||(a?w:q),p=[t.apiKey,s,n,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 x(...p)}getProviderName(){return"openai"}getSupportedModels(){return[ie,Ce,Le,Te,re,se,X,y,I,D,j,Z,J,ae,le,Y,mo,go,fo,pe,_o,yn,Pn,"o1"]}getDefaultModel(){return ie}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Tt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!ce(t))return e;let n={...e};if(e.gpt5Preset){let i=Ti[e.gpt5Preset];n.reasoning_effort=i.reasoning_effort,n.verbosity=i.verbosity}else e.reasoning_effort||(n.reasoning_effort=Pt(t));return n.reasoning_effort=this.normalizeReasoningEffort(t,n.reasoning_effort),n}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!Rt(e)||t==="minimal"&&!yt(e)?t==="minimal"&&Rt(e)?"none":t==="none"&&yt(e)?"minimal":Mo(e)?"low":"medium":t==="low"&&!Mo(e)?"medium":t==="xhigh"&&!Eo(e)?"high":t==="max"&&!In(e)?Eo(e)?"xhigh":"high":t}};var ho=o=>[qt,Ie].includes(o.trim()),Ma=o=>[H,ee,B,be].includes(o.trim()),Ai=(o,e)=>{if(ho(o)&&!e)throw new Error("OpenRouter Auto Router returned no visible content. Please retry.")},es=o=>o.blocks.some(e=>e.type!=="text"||e.text.trim().length>0),mt=class{constructor(e,t=H,n=H,i,r=Ht,s,a,l,p,u,c){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=u,this.reasoningMaxTokens=c,this.visionModel=n}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!fe(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=Jn){let n=6e4-t;n>0&&(console.log(`Rate limit reached for free tier. Waiting ${n}ms...`),await new Promise(i=>setTimeout(i,n)),this.requestCount=0)}this.lastRequestTime=e,this.requestCount++}async processChat(e,t,n){await this.applyRateLimiting(),await S({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.model,!0);return this.handleStream(i,t,this.model)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){if(!Ge(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await S({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(i,t,this.visionModel)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:n,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,n=()=>{},i){await this.applyRateLimiting();let r=await this.callOpenRouter(e,this.model,t,i);return t?this.parseStream(r,n,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,n=()=>{},i){if(!Ge(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,n,this.visionModel):this.parseOneShot(await r.json(),this.visionModel)}async callOpenRouter(e,t,n=!1,i){let r=this.buildRequestBody(e,t,n,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,n,i){let r={model:t,messages:e,stream:n},s=i!==void 0?i:P(this.responseLength),a=Ma(t)||ho(t)&&i===void 0;s&&a?console.warn(`OpenRouter: Token limits are disabled for ${t} because this model can return empty content when a token limit is set.`):s&&(r.max_tokens=s);let l=an(t),p=Yn(t,this.reasoning_effort);if(p!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens||l){if(r.reasoning={},p){let u=p==="minimal"&&t!==de&&t!==me?"low":p;r.reasoning.effort=u}else l&&(r.reasoning.effort=l);(p==="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=V(this.tools,"chat-completions"),t!==he&&(r.tool_choice="auto")),r}async handleStream(e,t,n){let i=await z(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:ho(n)});return Ai(n,i.trim().length>0),i}async parseStream(e,t,n){let i=await k(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:ho(n)});return Ai(n,es(i)),i}parseOneShot(e,t){let n=G(e,{throwOnApiError:ho(t)});return Ai(t,es(n)),n}};var gt=class{createChatService(e){let t=T({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:e.model||this.getDefaultModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),n=e.tools,i=e.appName,r=e.appUrl;return new mt(e.apiKey,e.model||this.getDefaultModel(),t,n,e.endpoint,e.responseLength,i,r,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[Bt,Wt,he,$t,zt,Pe,Co,xe,Ae,de,me,qt,Ie,$n,H,Po,xo,Ao,Io,Do,bo,No,wo,ko,Go,Vo,Fo,Uo,Ko,Ho,Bo,De,Wo,jt,$o,zo,qo,Xo,jo,Zo,Jo,Yo,Qo,en,tn,ee,B,be,zn,qn,on,nn,rn,we,Ne,ke,ge,Zt,yo,Lo,To,Xt,Ro,Xn,jn]}getDefaultModel(){return H}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return Ge(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return Zn}isModelFree(e){return fe(e)}};var ft=class extends x{constructor(e,t=Ye,n=t,i,r=po,s,a){super(e,t,n,i,r,[],s,void 0,a,!1,"plamo",!1)}};var _t=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=e.tools;return new ft(e.apiKey,t,e.visionModel??t,n,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"plamo"}getSupportedModels(){return[...Ci]}getDefaultModel(){return Ye}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 po}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Et=class extends x{constructor(e,t=Je,n=t,i,r=lo,s,a){super(e,t,n,i,r,[],s,void 0,void 0,!1,"sakana",!1,void 0,a?.type==="enabled")}};var Mt=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:Oe,supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools;if(e.thinking!==void 0&&t!==Oe)throw new Error("Sakana thinking control is only supported for sakana-namazu.");let r=t===Oe?e.thinking??{type:"disabled"}:void 0;return new Et(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"sakana"}getSupportedModels(){return[...Si]}getDefaultModel(){return Je}supportsVision(){return!0}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return vi(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"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 lo}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Ot=class{constructor(e,t=U,n=U,i,r=Qt,s,a="none"){this.provider="xai";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.visionModel=n,this.reasoningEffort=a}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,n){await S({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:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){if(!We(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await S({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:n,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,n=()=>{},i){let r=await this.callXAI(e,this.model,t,i);return this.parseResponse(r,t,n)}async visionChatOnce(e,t=!1,n=()=>{},i){if(!We(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,n)}async parseResponse(e,t,n){return t?this.parseStream(e,n):this.parseOneShot(await e.json())}async callXAI(e,t,n=!1,i){let r=this.buildRequestBody(e,t,n,i);return await M.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,n,i){let r={model:t,stream:n,messages:e},s=i!==void 0?i:P(this.responseLength);s!==void 0&&(r.max_tokens=s),this.reasoningEffort&&gn(t)&&(r.reasoning_effort=eo(t,this.reasoningEffort));let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto"),r}buildToolsDefinition(){return V(this.tools,"chat-completions")}async handleStream(e,t){return z(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}async parseStream(e,t){return k(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return G(e)}};var St=class{createChatService(e){let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"explicit"}),i=e.tools;return new Ot(e.apiKey,t,n,i,e.endpoint||Qt,e.responseLength,eo(t,e.reasoning_effort??fn(t)))}getProviderName(){return"xai"}getSupportedModels(){return[Ke,He,Be,U,dn,mn]}getDefaultModel(){return U}getDefaultVisionModel(){return U}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return We(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var vt=class{constructor(e,t=te,n=_e,i,r=Jt,s,a,l,p){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.reasoningEffort=p,this.visionModel=n}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,n){await S({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:n,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,n){if(!Ue(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await S({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:n,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,n=()=>{},i){let r=await this.callZAI(e,this.model,t,i);return this.parseResponse(r,t,n)}async visionChatOnce(e,t=!1,n=()=>{},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,n)}async parseResponse(e,t,n){return t?this.parseStream(e,n):this.parseOneShot(await e.json())}async callZAI(e,t,n=!1,i){let r=this.buildRequestBody(e,t,n,i);return await M.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,n,i){let r={model:t,stream:n,messages:e},s=i!==void 0?i:P(this.responseLength);s!==void 0&&(r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),this.thinking&&(r.thinking=this.thinking),hn(t)&&this.reasoningEffort&&(r.reasoning_effort=this.reasoningEffort);let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto",n&&ai(t)&&(r.tool_stream=!0)),r}buildToolsDefinition(){return V(this.tools,"chat-completions")}async handleStream(e,t){return z(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}async parseStream(e,t){return k(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return G(e)}};var Ct=class{createChatService(e){let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:c=>this.supportsVisionForModel(c),validate:"explicit"}),i=e.tools,r=Fe(t);if(e.reasoning_effort!==void 0&&!r.includes(e.reasoning_effort)){let c=r.length>0?`Supported values: ${r.join(", ")}.`:"This model does not expose configurable effort.";throw new Error(`Model ${t} does not support Z.ai reasoning_effort: ${e.reasoning_effort}. ${c}`)}let s=si(t,e.reasoning_effort),a=Ve(t),l=e.thinking!==void 0,p=a?{type:"enabled",clear_thinking:e.thinking?.clear_thinking??!0}:l&&e.reasoning_effort===void 0?e.thinking:s==="high"||s==="max"?{type:"enabled",clear_thinking:e.thinking?.clear_thinking}:{type:"disabled",clear_thinking:e.thinking?.clear_thinking},u=a||p?.type==="enabled"&&e.reasoning_effort!==void 0?s:void 0;return new vt(e.apiKey,t,n,i,e.endpoint||Jt,e.responseLength,e.responseFormat,p,u)}getProviderName(){return"zai"}getSupportedModels(){return[ln,Yt,te,Qn,ei,ti,pn,oi,ni,ii,ri,cn,un,_e]}getDefaultModel(){return te}getDefaultVisionModel(){return _e}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ue(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var ts=[new dt,new ht,new rt,new at,new tt,new gt,new Ct,new St,new pt,new nt,new ut,new Mt,new _t];var Oa=new Set(["claude","claude-agent-sdk","codex-sdk","copilot-sdk","deepseek","gemini","gemini-nano","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),Sa=new Set(["claude","deepseek","gemini","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),va=new Set(["codex-sdk"]);function Ii(o){if(Oa.has(o))return{text:!0,streaming:!va.has(o),tools:Sa.has(o)}}function Ca(o){let e=o.provider==="claude",t=o.messages.filter(r=>!os(e,r)),n=o.completion.blocks.filter(r=>r.type==="tool_use"),i=o.completion.assistant_message??La(e,n);return os(e,i)||t.push({...i}),t.push(...Ta(e,o.toolResults)),t}function os(o,e){if(!o||e.role!=="assistant")return!1;let t=e.content;return Array.isArray(t)&&t.length===0}function La(o,e){return o?{role:"assistant",content:e.map(t=>({type:"tool_use",id:t.id,name:t.name,input:t.input??{}}))}:{role:"assistant",content:[],tool_calls:e.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.input??{})}}))}}function Ta(o,e){return o?e.map(t=>({role:"user",content:[{type:"tool_result",tool_use_id:t.tool_use_id,content:t.content}]})):e.map(t=>({role:"tool",tool_call_id:t.tool_use_id,content:t.content}))}var Ra=new Set(["openai","gemini","claude"]),ya=new Set(["openai","openai-compatible","zai","kimi"]),Pa={openai:["none","minimal","low","medium","high","xhigh","max"],claude:["low","medium","high","xhigh","max"],gemini:["minimal","low","medium","high"],openrouter:["none","minimal","low","medium","high","xhigh","max"],kimi:["low","high","max"],mistral:["low","medium","high"],plamo:["none","medium"],xai:["none","low","medium","high","xhigh"],deepseek:["none","low","high","max"],zai:["none","minimal","low","medium","high","xhigh","max"]},Lt=class{static registerProvider(e){this.providers.set(e.getProviderName(),e)}static createChatService(e,t){let n=this.providers.get(e);if(!n)throw new Error(`Unknown chat provider: ${e}`);return n.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 n=this.providers.get(e);if(!n)return;let i=t?this.getVisionSupportLevelForModel(e,t):n.getVisionSupportLevel(),r=Ii(e);return{provider:e,models:n.getSupportedModels(),defaultModel:typeof n.getDefaultModel=="function"?n.getDefaultModel():void 0,text:!0,streaming:r?.streaming??!0,vision:i,tools:r?.tools??!1,mcp:Ra.has(e),jsonMode:ya.has(e),responseLength:!0,reasoningEffort:e==="openai"&&t===y?["low","medium","high","xhigh","max"]:e==="openai"&&t===I?["none","low","medium","high","xhigh","max"]:e==="openai"&&t===D?["none","low","medium","high","xhigh","max"]:e==="claude"&&t?[...K(t)]:e==="gemini"&&t?[...Re(t)]:e==="kimi"&&t?[...oe(t)]:e==="deepseek"&&t?[...ro(t)]:e==="openrouter"&&t?[...sn(t)]:e==="xai"&&t?[...$e(t)]:e==="zai"&&t?[...Fe(t)]:Pa[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 n=this.providers.get(e);return n?n.getVisionSupportLevelForModel?n.getVisionSupportLevelForModel(t):n.supportsVisionForModel?n.supportsVisionForModel(t)?"supported":"unsupported":n.getVisionSupportLevel():"unsupported"}};Lt.providers=new Map;ts.forEach(o=>Lt.registerProvider(o));function ns(){M.setFetch(async(o,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),n=e.headers,i={};if(Array.isArray(n))for(let[c,d]of n)i[c]=String(d);else if(n&&typeof n=="object")for(let[c,d]of Object.entries(n))i[c]=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(o,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 cs(xa);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aituber-onair/chat",
3
- "version": "0.56.0",
3
+ "version": "0.58.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",