@aituber-onair/chat 0.65.0 → 0.66.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.
- package/README.ja.md +105 -50
- package/README.md +105 -55
- package/dist/cjs/constants/claude.d.ts +1 -0
- package/dist/cjs/constants/claude.d.ts.map +1 -1
- package/dist/cjs/constants/claude.js +4 -1
- package/dist/cjs/constants/claude.js.map +1 -1
- package/dist/cjs/constants/gemini.d.ts +2 -0
- package/dist/cjs/constants/gemini.d.ts.map +1 -1
- package/dist/cjs/constants/gemini.js +4 -2
- package/dist/cjs/constants/gemini.js.map +1 -1
- package/dist/cjs/constants/kimi.d.ts +4 -0
- package/dist/cjs/constants/kimi.d.ts.map +1 -1
- package/dist/cjs/constants/kimi.js +10 -2
- package/dist/cjs/constants/kimi.js.map +1 -1
- package/dist/cjs/constants/mistral.d.ts +1 -1
- package/dist/cjs/constants/mistral.d.ts.map +1 -1
- package/dist/cjs/constants/mistral.js +1 -1
- package/dist/cjs/constants/mistral.js.map +1 -1
- package/dist/cjs/constants/openai.d.ts +12 -1
- package/dist/cjs/constants/openai.d.ts.map +1 -1
- package/dist/cjs/constants/openai.js +34 -4
- package/dist/cjs/constants/openai.js.map +1 -1
- package/dist/cjs/constants/openrouter.d.ts +12 -0
- package/dist/cjs/constants/openrouter.d.ts.map +1 -1
- package/dist/cjs/constants/openrouter.js +84 -7
- package/dist/cjs/constants/openrouter.js.map +1 -1
- package/dist/cjs/constants/plamo.d.ts +1 -1
- package/dist/cjs/constants/plamo.d.ts.map +1 -1
- package/dist/cjs/constants/plamo.js +1 -1
- package/dist/cjs/constants/plamo.js.map +1 -1
- package/dist/cjs/services/ChatServiceFactory.d.ts.map +1 -1
- package/dist/cjs/services/ChatServiceFactory.js +2 -1
- package/dist/cjs/services/ChatServiceFactory.js.map +1 -1
- package/dist/cjs/services/providers/claude/ClaudeChatServiceProvider.d.ts.map +1 -1
- package/dist/cjs/services/providers/claude/ClaudeChatServiceProvider.js +0 -1
- package/dist/cjs/services/providers/claude/ClaudeChatServiceProvider.js.map +1 -1
- package/dist/cjs/services/providers/kimi/KimiChatServiceProvider.d.ts.map +1 -1
- package/dist/cjs/services/providers/kimi/KimiChatServiceProvider.js +2 -1
- package/dist/cjs/services/providers/kimi/KimiChatServiceProvider.js.map +1 -1
- package/dist/cjs/services/providers/openai/OpenAIChatService.d.ts.map +1 -1
- package/dist/cjs/services/providers/openai/OpenAIChatService.js +6 -3
- package/dist/cjs/services/providers/openai/OpenAIChatService.js.map +1 -1
- package/dist/cjs/services/providers/openai/OpenAIChatServiceProvider.d.ts.map +1 -1
- package/dist/cjs/services/providers/openai/OpenAIChatServiceProvider.js +6 -12
- package/dist/cjs/services/providers/openai/OpenAIChatServiceProvider.js.map +1 -1
- package/dist/cjs/services/providers/openai/openaiRequestBuilder.d.ts.map +1 -1
- package/dist/cjs/services/providers/openai/openaiRequestBuilder.js +6 -2
- package/dist/cjs/services/providers/openai/openaiRequestBuilder.js.map +1 -1
- package/dist/cjs/services/providers/openrouter/OpenRouterChatService.d.ts.map +1 -1
- package/dist/cjs/services/providers/openrouter/OpenRouterChatService.js +6 -2
- package/dist/cjs/services/providers/openrouter/OpenRouterChatService.js.map +1 -1
- package/dist/cjs/services/providers/openrouter/OpenRouterChatServiceProvider.d.ts +2 -2
- package/dist/cjs/services/providers/openrouter/OpenRouterChatServiceProvider.d.ts.map +1 -1
- package/dist/cjs/services/providers/openrouter/OpenRouterChatServiceProvider.js +15 -16
- package/dist/cjs/services/providers/openrouter/OpenRouterChatServiceProvider.js.map +1 -1
- package/dist/esm/constants/claude.d.ts +1 -0
- package/dist/esm/constants/claude.d.ts.map +1 -1
- package/dist/esm/constants/claude.js +4 -1
- package/dist/esm/constants/claude.js.map +1 -1
- package/dist/esm/constants/gemini.d.ts +2 -0
- package/dist/esm/constants/gemini.d.ts.map +1 -1
- package/dist/esm/constants/gemini.js +4 -2
- package/dist/esm/constants/gemini.js.map +1 -1
- package/dist/esm/constants/kimi.d.ts +4 -0
- package/dist/esm/constants/kimi.d.ts.map +1 -1
- package/dist/esm/constants/kimi.js +9 -1
- package/dist/esm/constants/kimi.js.map +1 -1
- package/dist/esm/constants/mistral.d.ts +1 -1
- package/dist/esm/constants/mistral.d.ts.map +1 -1
- package/dist/esm/constants/mistral.js +1 -1
- package/dist/esm/constants/mistral.js.map +1 -1
- package/dist/esm/constants/openai.d.ts +12 -1
- package/dist/esm/constants/openai.d.ts.map +1 -1
- package/dist/esm/constants/openai.js +33 -3
- package/dist/esm/constants/openai.js.map +1 -1
- package/dist/esm/constants/openrouter.d.ts +12 -0
- package/dist/esm/constants/openrouter.d.ts.map +1 -1
- package/dist/esm/constants/openrouter.js +81 -5
- package/dist/esm/constants/openrouter.js.map +1 -1
- package/dist/esm/constants/plamo.d.ts +1 -1
- package/dist/esm/constants/plamo.d.ts.map +1 -1
- package/dist/esm/constants/plamo.js +1 -1
- package/dist/esm/constants/plamo.js.map +1 -1
- package/dist/esm/services/ChatServiceFactory.d.ts.map +1 -1
- package/dist/esm/services/ChatServiceFactory.js +3 -2
- package/dist/esm/services/ChatServiceFactory.js.map +1 -1
- package/dist/esm/services/providers/claude/ClaudeChatServiceProvider.d.ts.map +1 -1
- package/dist/esm/services/providers/claude/ClaudeChatServiceProvider.js +1 -2
- package/dist/esm/services/providers/claude/ClaudeChatServiceProvider.js.map +1 -1
- package/dist/esm/services/providers/kimi/KimiChatServiceProvider.d.ts.map +1 -1
- package/dist/esm/services/providers/kimi/KimiChatServiceProvider.js +3 -2
- package/dist/esm/services/providers/kimi/KimiChatServiceProvider.js.map +1 -1
- package/dist/esm/services/providers/openai/OpenAIChatService.d.ts.map +1 -1
- package/dist/esm/services/providers/openai/OpenAIChatService.js +7 -4
- package/dist/esm/services/providers/openai/OpenAIChatService.js.map +1 -1
- package/dist/esm/services/providers/openai/OpenAIChatServiceProvider.d.ts.map +1 -1
- package/dist/esm/services/providers/openai/OpenAIChatServiceProvider.js +7 -13
- package/dist/esm/services/providers/openai/OpenAIChatServiceProvider.js.map +1 -1
- package/dist/esm/services/providers/openai/openaiRequestBuilder.d.ts.map +1 -1
- package/dist/esm/services/providers/openai/openaiRequestBuilder.js +7 -3
- package/dist/esm/services/providers/openai/openaiRequestBuilder.js.map +1 -1
- package/dist/esm/services/providers/openrouter/OpenRouterChatService.d.ts.map +1 -1
- package/dist/esm/services/providers/openrouter/OpenRouterChatService.js +7 -3
- package/dist/esm/services/providers/openrouter/OpenRouterChatService.js.map +1 -1
- package/dist/esm/services/providers/openrouter/OpenRouterChatServiceProvider.d.ts +2 -2
- package/dist/esm/services/providers/openrouter/OpenRouterChatServiceProvider.d.ts.map +1 -1
- package/dist/esm/services/providers/openrouter/OpenRouterChatServiceProvider.js +16 -17
- package/dist/esm/services/providers/openrouter/OpenRouterChatServiceProvider.js.map +1 -1
- package/dist/umd/aituber-onair-chat.js +167 -55
- package/dist/umd/aituber-onair-chat.min.js +7 -7
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var AITuberOnAirChat=(()=>{var Xn=Object.defineProperty;var As=Object.getOwnPropertyDescriptor;var xs=Object.getOwnPropertyNames;var Is=Object.prototype.hasOwnProperty;var ys=(o,e)=>{for(var t in e)Xn(o,t,{get:e[t],enumerable:!0})},Ds=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of xs(e))!Is.call(o,i)&&i!==t&&Xn(o,i,{get:()=>e[i],enumerable:!(n=As(e,i))||n.enumerable});return o};var bs=o=>Ds(Xn({},"__esModule",{value:!0}),o);var Ya={};ys(Ya,{CHAT_RESPONSE_LENGTH:()=>C,CLAUDE_DEPRECATED_MODELS:()=>Fs,CLAUDE_VISION_SUPPORTED_MODELS:()=>Qt,ChatServiceFactory:()=>wt,ChatServiceHttpClient:()=>O,ClaudeChatService:()=>ut,ClaudeChatServiceProvider:()=>ht,DEEPSEEK_API_BASE_URL:()=>yr,DEEPSEEK_DEPRECATED_MODELS:()=>ia,DEEPSEEK_SUPPORTED_MODELS:()=>Ii,DEEPSEEK_VISION_SUPPORTED_MODELS:()=>Nr,DEFAULT_MAX_TOKENS:()=>$i,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>pa,DEFAULT_VISION_PROMPT:()=>la,DeepSeekChatService:()=>dt,DeepSeekChatServiceProvider:()=>_t,EMOTION_TAG_CLEANUP_REGEX:()=>qi,EMOTION_TAG_REGEX:()=>qr,ENDPOINT_CLAUDE_API:()=>ci,ENDPOINT_DEEPSEEK_CHAT_COMPLETIONS_API:()=>Ro,ENDPOINT_GEMINI_API:()=>Qn,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>nt,ENDPOINT_MISTRAL_CHAT_COMPLETIONS_API:()=>Ao,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>q,ENDPOINT_OPENAI_RESPONSES_API:()=>w,ENDPOINT_OPENROUTER_API:()=>eo,ENDPOINT_PLAMO_CHAT_COMPLETIONS_API:()=>yo,ENDPOINT_SAKANA_CHAT_COMPLETIONS_API:()=>Io,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>So,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>Eo,EmotionParser:()=>ct,GEMINI_DEPRECATED_MODELS:()=>lr,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>Xi,GEMINI_RECOMMENDED_MODELS:()=>Uo,GEMINI_VISION_SUPPORTED_MODELS:()=>Ut,GPT5_PRESETS:()=>zi,GPT_5_MODELS:()=>Qi,GeminiChatService:()=>ft,GeminiChatServiceProvider:()=>mt,GeminiNanoChatService:()=>gt,GeminiNanoChatServiceProvider:()=>Et,HttpError:()=>ae,KIMI_THINKING_REQUIRED_MODELS:()=>xr,KIMI_VISION_SUPPORTED_MODELS:()=>Ar,KimiChatService:()=>Ot,KimiChatServiceProvider:()=>Mt,MAX_TOKENS_BY_LENGTH:()=>Hn,MISTRAL_API_BASE_URL:()=>kr,MISTRAL_DEPRECATED_MODELS:()=>ra,MISTRAL_REASONING_EFFORT_SUPPORTED_MODELS:()=>Fr,MISTRAL_SUPPORTED_MODELS:()=>Fi,MISTRAL_VISION_SUPPORTED_MODELS:()=>Ur,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>Or,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>Er,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>fn,MODEL_ANTHROPIC_CLAUDE_FABLE_5:()=>un,MODEL_ANTHROPIC_CLAUDE_FABLE_5_1:()=>ge,MODEL_ANTHROPIC_CLAUDE_HAIKU_LATEST:()=>cn,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>dn,MODEL_ANTHROPIC_CLAUDE_OPUS_4_8:()=>mo,MODEL_ANTHROPIC_CLAUDE_OPUS_5:()=>hn,MODEL_ANTHROPIC_CLAUDE_OPUS_5_5:()=>so,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>_n,MODEL_ANTHROPIC_CLAUDE_SONNET_5:()=>Be,MODEL_ANTHROPIC_CLAUDE_SONNET_5_5:()=>ro,MODEL_ANTHROPIC_CLAUDE_SONNET_LATEST:()=>pn,MODEL_APODEX_1_1_MINI_FREE:()=>ke,MODEL_CLAUDE_3_5_HAIKU:()=>ur,MODEL_CLAUDE_3_5_SONNET:()=>hr,MODEL_CLAUDE_3_7_SONNET:()=>dr,MODEL_CLAUDE_3_HAIKU:()=>cr,MODEL_CLAUDE_4_5_HAIKU:()=>U,MODEL_CLAUDE_4_5_OPUS:()=>Bt,MODEL_CLAUDE_4_5_SONNET:()=>Ko,MODEL_CLAUDE_4_6_OPUS:()=>$t,MODEL_CLAUDE_4_6_SONNET:()=>Wt,MODEL_CLAUDE_4_7_OPUS:()=>zt,MODEL_CLAUDE_4_8_OPUS:()=>Xt,MODEL_CLAUDE_4_OPUS:()=>fr,MODEL_CLAUDE_4_SONNET:()=>_r,MODEL_CLAUDE_5_1_FABLE:()=>Ht,MODEL_CLAUDE_5_5_HAIKU:()=>Yt,MODEL_CLAUDE_5_5_OPUS:()=>Ho,MODEL_CLAUDE_5_5_SONNET:()=>Jt,MODEL_CLAUDE_5_FABLE:()=>qt,MODEL_CLAUDE_5_OPUS:()=>Zt,MODEL_CLAUDE_5_SONNET:()=>jt,MODEL_DEEPSEEK_CHAT:()=>Dr,MODEL_DEEPSEEK_FLASH:()=>Fn,MODEL_DEEPSEEK_REASONER:()=>br,MODEL_DEEPSEEK_V4_FLASH:()=>Te,MODEL_DEEPSEEK_V4_FLASH_VISION_EXP:()=>at,MODEL_DEEPSEEK_V4_PRO:()=>Un,MODEL_FUGU:()=>lt,MODEL_FUGU_ULTRA:()=>Hr,MODEL_FUGU_ULTRA_20260615:()=>Wr,MODEL_FUGU_ULTRA_V1_1:()=>Br,MODEL_GEMINI_2_5_FLASH:()=>rr,MODEL_GEMINI_2_5_FLASH_LITE:()=>sr,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>ar,MODEL_GEMINI_2_5_PRO:()=>ir,MODEL_GEMINI_3_1_FLASH_LITE:()=>ee,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>si,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>ri,MODEL_GEMINI_3_5_FLASH:()=>ni,MODEL_GEMINI_3_5_FLASH_LITE:()=>ii,MODEL_GEMINI_3_6_FLASH:()=>oi,MODEL_GEMINI_3_7_FLASH:()=>ti,MODEL_GEMINI_3_8_FLASH:()=>ei,MODEL_GEMINI_3_FLASH_PREVIEW:()=>li,MODEL_GEMINI_3_PRO_PREVIEW:()=>ai,MODEL_GEMINI_NANO:()=>Pe,MODEL_GEMMA_4_26B_A4B_IT:()=>nr,MODEL_GEMMA_4_31B_IT:()=>or,MODEL_GLM_4_6:()=>Pi,MODEL_GLM_4_6V:()=>yn,MODEL_GLM_4_6V_FLASH:()=>Le,MODEL_GLM_4_6V_FLASHX:()=>Dn,MODEL_GLM_4_7:()=>Ci,MODEL_GLM_4_7_FLASH:()=>Ri,MODEL_GLM_4_7_FLASHX:()=>Ti,MODEL_GLM_5:()=>vi,MODEL_GLM_5V_TURBO:()=>In,MODEL_GLM_5_1:()=>Si,MODEL_GLM_5_2:()=>re,MODEL_GLM_5_3:()=>xn,MODEL_GLM_5_3_FLASH:()=>Oo,MODEL_GLM_5_3_FLASHX:()=>ie,MODEL_GLM_5_TURBO:()=>Li,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>vn,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>Ln,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>Sn,MODEL_GOOGLE_GEMINI_3_5_FLASH_LITE:()=>Mn,MODEL_GOOGLE_GEMINI_3_6_FLASH:()=>On,MODEL_GOOGLE_GEMINI_3_7_FLASH:()=>En,MODEL_GOOGLE_GEMINI_3_8_FLASH:()=>uo,MODEL_GOOGLE_GEMINI_FLASH_LATEST:()=>gn,MODEL_GOOGLE_GEMINI_PRO_LATEST:()=>mn,MODEL_GPT_4O:()=>Go,MODEL_GPT_4O_MINI:()=>de,MODEL_GPT_4_1:()=>No,MODEL_GPT_4_1_MINI:()=>wo,MODEL_GPT_4_1_NANO:()=>ko,MODEL_GPT_5:()=>Ie,MODEL_GPT_5_1:()=>ye,MODEL_GPT_5_4:()=>pe,MODEL_GPT_5_4_MINI:()=>ue,MODEL_GPT_5_4_NANO:()=>he,MODEL_GPT_5_4_PRO:()=>Q,MODEL_GPT_5_5:()=>ce,MODEL_GPT_5_6:()=>j,MODEL_GPT_5_6_LUNA:()=>Y,MODEL_GPT_5_6_SOL:()=>Z,MODEL_GPT_5_6_TERRA:()=>J,MODEL_GPT_5_MINI:()=>xe,MODEL_GPT_5_NANO:()=>le,MODEL_GPT_6_1_SOL:()=>R,MODEL_GPT_6_ASTRA:()=>A,MODEL_GPT_6_LUNA:()=>N,MODEL_GPT_6_SOL:()=>b,MODEL_GPT_OSS_20B_FREE:()=>B,MODEL_GROK_4_1_FAST_NON_REASONING:()=>Tr,MODEL_GROK_4_1_FAST_REASONING:()=>Cr,MODEL_GROK_4_20_NON_REASONING:()=>wn,MODEL_GROK_4_20_REASONING:()=>Nn,MODEL_GROK_4_3:()=>K,MODEL_GROK_4_5:()=>et,MODEL_GROK_4_6:()=>Ye,MODEL_GROK_4_7:()=>Qe,MODEL_INCEPTION_MERCURY_2_5:()=>Wo,MODEL_INCLUSIONAI_LING_3_0_FLASH_VL_FREE:()=>Ge,MODEL_INCLUSIONAI_LING_3_1_FLASH:()=>to,MODEL_KIMI_K2_5:()=>Vn,MODEL_KIMI_K2_6:()=>$,MODEL_KIMI_K2_7_CODE:()=>Lo,MODEL_KIMI_K2_7_CODE_HIGHSPEED:()=>Co,MODEL_KIMI_K3:()=>it,MODEL_KWAIPILOT_KAT_CODER_AIR_V2_5:()=>mi,MODEL_KWAIPILOT_KAT_CODER_PRO_V2_5:()=>gi,MODEL_META_MUSE_SPARK_1_3:()=>Oe,MODEL_MINISTRAL_14B_2512:()=>wi,MODEL_MINISTRAL_3B_2512:()=>bi,MODEL_MINISTRAL_8B_2512:()=>Ni,MODEL_MISTRAL_LARGE_2512:()=>Vi,MODEL_MISTRAL_LARGE_LATEST:()=>Gi,MODEL_MISTRAL_MEDIUM_2508:()=>Gr,MODEL_MISTRAL_MEDIUM_3_5:()=>Kn,MODEL_MISTRAL_SMALL_2603:()=>ki,MODEL_MISTRAL_SMALL_LATEST:()=>z,MODEL_MISTRAL_ZAI_GLM_5_3:()=>Vr,MODEL_MOONSHOTAI_KIMI_K2_5:()=>Xo,MODEL_MOONSHOTAI_KIMI_K2_6:()=>fo,MODEL_MOONSHOTAI_KIMI_K2_7_CODE:()=>zo,MODEL_MOONSHOTAI_KIMI_K3:()=>$o,MODEL_MOONSHOTAI_KIMI_LATEST:()=>qo,MODEL_NEX_AGI_NEX_N2_5_MINI_FREE:()=>Ve,MODEL_NEX_AGI_NEX_N2_5_PRO_FREE:()=>Fe,MODEL_NVIDIA_NEMOTRON_3_5_LIGHTNING:()=>ho,MODEL_O1:()=>Zn,MODEL_O1_MINI:()=>jn,MODEL_O3_MINI:()=>qn,MODEL_OPENAI_GPT_4O:()=>sn,MODEL_OPENAI_GPT_4_1_MINI:()=>an,MODEL_OPENAI_GPT_4_1_NANO:()=>ln,MODEL_OPENAI_GPT_5_1_CHAT:()=>gr,MODEL_OPENAI_GPT_5_1_CODEX:()=>on,MODEL_OPENAI_GPT_5_5:()=>tn,MODEL_OPENAI_GPT_5_5_PRO:()=>en,MODEL_OPENAI_GPT_5_6_LUNA:()=>Qo,MODEL_OPENAI_GPT_5_6_SOL:()=>Jo,MODEL_OPENAI_GPT_5_6_TERRA:()=>Yo,MODEL_OPENAI_GPT_5_MINI:()=>nn,MODEL_OPENAI_GPT_5_NANO:()=>rn,MODEL_OPENAI_GPT_6_1_SOL:()=>oo,MODEL_OPENAI_GPT_6_ASTRA:()=>lo,MODEL_OPENAI_GPT_6_ASTRA_PRO:()=>po,MODEL_OPENAI_GPT_6_LUNA:()=>io,MODEL_OPENAI_GPT_6_SOL:()=>no,MODEL_OPENAI_GPT_LATEST:()=>jo,MODEL_OPENAI_GPT_MINI_LATEST:()=>Zo,MODEL_OPENROUTER_AUTO:()=>_o,MODEL_OPENROUTER_AUTO_BETA:()=>He,MODEL_OPENROUTER_DEEPSEEK_V4_1_FLASH:()=>co,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH:()=>$e,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_0731:()=>ze,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_VISION_EXP:()=>Se,MODEL_OPENROUTER_DEEPSEEK_V4_PRO_0813:()=>Xe,MODEL_OPENROUTER_FUSION:()=>di,MODEL_OPENROUTER_MISTRAL_LARGE_4_0:()=>Ne,MODEL_PLAMO_2_2_PRIME:()=>Xr,MODEL_PLAMO_3_0_PRIME:()=>pt,MODEL_QWEN_QWEN_3_8_27B:()=>Ue,MODEL_QWEN_QWEN_3_8_FLASH:()=>go,MODEL_QWEN_QWEN_3_8_MAX_0902:()=>Ee,MODEL_QWEN_QWEN_3_8_OMNI_FLASH:()=>Ke,MODEL_SAKANA_NAMAZU:()=>Re,MODEL_UNBIASED_PARETO_26_10_PREVIEW:()=>oe,MODEL_UPSTAGE_SOLAR_MINI4:()=>me,MODEL_UPSTAGE_SOLAR_PRO4:()=>fe,MODEL_XAI_GROK_4_5:()=>Rn,MODEL_XAI_GROK_4_6:()=>Tn,MODEL_XAI_GROK_4_7:()=>ao,MODEL_XAI_GROK_LATEST:()=>Cn,MODEL_XIAOMI_MIMO_V2_6_FLASH:()=>we,MODEL_ZAI_GLM_4_5_AIR:()=>fi,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>Mr,MODEL_ZAI_GLM_4_7_FLASH:()=>_i,MODEL_ZAI_GLM_5_2:()=>We,MODEL_ZAI_GLM_5_3:()=>ne,MODEL_ZAI_GLM_5_3_FLASH:()=>W,MODEL_ZAI_GLM_5_3_FLASHX:()=>Me,MistralChatService:()=>St,MistralChatServiceProvider:()=>vt,OPENAI_COMPATIBLE_LOCAL_PRESETS:()=>_a,OPENROUTER_CREDITS_THRESHOLD:()=>Ys,OPENROUTER_DEPRECATED_MODELS:()=>Hs,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>Js,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>Zs,OPENROUTER_FREE_MODELS:()=>Ei,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>Oi,OPENROUTER_MODELS_WITHOUT_REASONING_BUDGET:()=>hi,OPENROUTER_VISION_SUPPORTED_MODELS:()=>Sr,OpenAIChatService:()=>I,OpenAIChatServiceProvider:()=>Ct,OpenAICompatibleChatServiceProvider:()=>Lt,OpenAICompatibleEndpointError:()=>P,OpenRouterChatService:()=>Tt,OpenRouterChatServiceProvider:()=>Rt,PLAMO_API_BASE_URL:()=>zr,PLAMO_DEPRECATED_MODELS:()=>aa,PLAMO_SUPPORTED_MODELS:()=>Wi,PlamoChatService:()=>Pt,PlamoChatServiceProvider:()=>At,SAKANA_API_BASE_URL:()=>Kr,SAKANA_COMPATIBILITY_MODELS:()=>sa,SAKANA_SUPPORTED_MODELS:()=>Hi,SAKANA_VISION_SUPPORTED_MODELS:()=>$r,SakanaChatService:()=>xt,SakanaChatServiceProvider:()=>It,StreamTextAccumulator:()=>M,VISION_SUPPORTED_MODELS:()=>kt,XAIChatService:()=>yt,XAIChatServiceProvider:()=>Dt,XAI_DEPRECATED_MODELS:()=>ta,XAI_VISION_SUPPORTED_MODELS:()=>Rr,ZAIChatService:()=>bt,ZAIChatServiceProvider:()=>Nt,ZAI_VISION_SUPPORTED_MODELS:()=>Lr,allowsReasoningLow:()=>Fo,allowsReasoningMax:()=>Yn,allowsReasoningMinimal:()=>Vt,allowsReasoningNone:()=>Gt,allowsReasoningXHigh:()=>Vo,buildOpenAICompatibleTools:()=>F,buildToolContinuationMessages:()=>za,getChatBackendProviderCapabilities:()=>Yi,getClaudeSupportedReasoningEfforts:()=>H,getDeepSeekSupportedReasoningEfforts:()=>Po,getDefaultClaudeReasoningEffort:()=>Bo,getDefaultDeepSeekReasoningEffort:()=>xi,getDefaultGeminiReasoningEffort:()=>Vs,getDefaultKimiReasoningEffort:()=>st,getDefaultOpenRouterReasoningEffort:()=>An,getDefaultReasoningEffortForGPT5Model:()=>tr,getDefaultReasoningEffortForOpenAIModel:()=>Ft,getDefaultXaiReasoningEffort:()=>Gn,getDefaultZaiReasoningEffort:()=>vr,getGeminiSupportedReasoningEfforts:()=>De,getKimiSupportedReasoningEfforts:()=>se,getMaxTokensForResponseLength:()=>x,getOpenRouterSupportedReasoningEfforts:()=>Pn,getXaiSupportedReasoningEfforts:()=>ot,getZaiSupportedReasoningEfforts:()=>Ze,installGASFetch:()=>Rs,isClaudeReasoningEffortModel:()=>mr,isDeepSeekReasoningEffortModel:()=>wr,isDeepSeekVisionModel:()=>yi,isGPT5Model:()=>er,isGeminiReasoningEffortModel:()=>pi,isKimiReasoningEffortModel:()=>Ce,isKimiThinkingRequiredModel:()=>To,isKimiVisionModel:()=>rt,isMistralReasoningEffort:()=>Ui,isMistralReasoningEffortModel:()=>xo,isMistralVisionModel:()=>Ki,isOpenAIReasoningModel:()=>_e,isOpenRouterFreeModel:()=>ve,isOpenRouterVisionModel:()=>qe,isResponsesOnlyGPT5Model:()=>Jn,isSakanaVisionModel:()=>Bi,isXaiReasoningEffortModel:()=>kn,isXaiReasoningEffortNoneModel:()=>Pr,isXaiVisionModel:()=>tt,isZaiAlwaysThinkingModel:()=>je,isZaiReasoningEffortModel:()=>bn,isZaiToolStreamModel:()=>Ai,isZaiVisionModel:()=>Je,listOpenAICompatibleModels:()=>es,normalizeClaudeReasoningEffort:()=>Ks,normalizeDeepSeekReasoningEffort:()=>Di,normalizeGeminiReasoningEffort:()=>Kt,normalizeOpenRouterReasoningEffort:()=>Mi,normalizeXaiReasoningEffort:()=>vo,normalizeZaiReasoningEffort:()=>Mo,parseOpenAICompatibleOneShot:()=>V,parseOpenAICompatibleTextStream:()=>X,parseOpenAICompatibleToolStream:()=>G,processChatWithOptionalTools:()=>S,refreshOpenRouterFreeModels:()=>Ta,resolveOpenAICompatibleEndpoint:()=>Qr,resolveVisionModel:()=>T,runOnceText:()=>da,safeJsonParse:()=>Zr,safeParseToolCallInput:()=>Ae,screenplayToText:()=>ha,testOpenAICompatibleConnection:()=>fa,textToScreenplay:()=>jr,textsToScreenplay:()=>ua});var q="https://api.openai.com/v1/chat/completions",w="https://api.openai.com/v1/responses",R="gpt-6.1-sol",A="gpt-6-astra",b="gpt-6-sol",N="gpt-6-luna",le="gpt-5-nano",xe="gpt-5-mini",Ie="gpt-5",ye="gpt-5.1",pe="gpt-5.4",ce="gpt-5.5",j="gpt-5.6",Z="gpt-5.6-sol",J="gpt-5.6-terra",Y="gpt-5.6-luna",ue="gpt-5.4-mini",he="gpt-5.4-nano",Q="gpt-5.4-pro",No="gpt-4.1",wo="gpt-4.1-mini",ko="gpt-4.1-nano",de="gpt-4o-mini",Go="gpt-4o",qn="o3-mini",jn="o1-mini",Zn="o1",kt=[R,A,b,N,le,xe,Ie,ye,pe,ce,j,Z,J,Y,ue,he,Q,No,wo,ko,de,Go,"o1"],Qi=[le,xe,Ie,ye,pe,ce,j,Z,J,Y,ue,he,Q];function er(o){return Qi.includes(o)}function _e(o){return o===R||o===A||o===b||o===N||er(o)}function Jn(o){return o===Q}function Vo(o){return o===R||o===A||o===b||o===N||o===j||o===Z||o===J||o===Y||o===ce||o===pe||o===ue||o===he||o===Q}function Yn(o){return o===R||o===A||o===b||o===N||o===j||o===Z||o===J||o===Y}function Gt(o){return o===b||o===N||o===j||o===Z||o===J||o===Y||o===ye||o===pe||o===ce||o===ue||o===he}function Vt(o){return o===le||o===xe||o===Ie}function Fo(o){return o!==Q}function tr(o){return Gt(o)?"none":Vt(o)?"minimal":"medium"}function Ft(o){return o===R||o===A?"low":o===b?"medium":o===N?"low":tr(o)}var Qn="https://generativelanguage.googleapis.com",or="gemma-4-31b-it",nr="gemma-4-26b-a4b-it",ei="gemini-3.8-flash",ti="gemini-3.7-flash",oi="gemini-3.6-flash",ni="gemini-3.5-flash",ii="gemini-3.5-flash-lite",ri="gemini-3.1-pro-preview",ee="gemini-3.1-flash-lite",si="gemini-3.1-flash-lite-preview",ai="gemini-3-pro-preview",li="gemini-3-flash-preview",ir="gemini-2.5-pro",rr="gemini-2.5-flash",sr="gemini-2.5-flash-lite",ar="gemini-2.5-flash-lite-preview-06-17",Uo=[ei,ti,oi,ni,ii,ee,ri,li,ir,rr,sr,or,nr],lr=[si,ai,ar],Ut=[...Uo,...lr],Ns=["minimal","low","medium","high"],ws=["low","medium","high"],ks=[oi,ni,ii,ee,si,li],Gs=[ei,ti,ri,ai];function De(o){return ks.includes(o)?Ns:Gs.includes(o)?ws:[]}function pi(o){return De(o).length>0}function Vs(o){return De(o)[0]}function Kt(o,e){let t=De(o);if(t.length!==0)return e&&t.includes(e)?e:t[0]}var ci="https://api.anthropic.com/v1/messages",Ht="claude-fable-5-1",cr="claude-3-haiku-20240307",ur="claude-3-5-haiku-20241022",hr="claude-3-5-sonnet-20241022",dr="claude-3-7-sonnet-20250219",_r="claude-sonnet-4-20250514",fr="claude-opus-4-20250514",Ko="claude-sonnet-4-5-20250929",U="claude-haiku-4-5-20251001",Bt="claude-opus-4-5-20251101",Wt="claude-sonnet-4-6",$t="claude-opus-4-6",zt="claude-opus-4-7",Xt="claude-opus-4-8",qt="claude-fable-5",jt="claude-sonnet-5",Zt="claude-opus-5",Ho="claude-opus-5-5",Jt="claude-sonnet-5-5",Yt="claude-haiku-5-5",Fs=[cr,ur,hr,dr,_r,fr],ui=["low","medium","high"],pr=[...ui,"max"],te=[...ui,"xhigh","max"],Us={[Bt]:ui,[Wt]:pr,[$t]:pr,[zt]:te,[Xt]:te,[Ht]:te,[qt]:te,[jt]:te,[Zt]:te,[Jt]:te,[Yt]:te},Qt=[Ht,Ko,U,Bt,Wt,$t,zt,Xt,qt,jt,Zt,Ho,Jt,Yt];function H(o){return Us[o]??[]}function mr(o){return H(o).length>0}function Bo(o){return mr(o)?"low":void 0}function Ks(o,e){let t=H(o);if(t.length!==0)return e?t.includes(e)?e:"high":Bo(o)}var eo="https://openrouter.ai/api/v1/chat/completions",Ne="mistralai/mistral-large-4-0",oe="unbiased/pareto-26.10-preview",to="inclusionai/ling-3.1-flash",fe="upstage/solar-pro4",me="upstage/solar-mini4",we="xiaomi/mimo-v2.6-flash",ke="apodex/apodex-1.1-mini:free",oo="openai/gpt-6.1-sol",no="openai/gpt-6-sol",io="openai/gpt-6-luna",ro="anthropic/claude-sonnet-5.5",so="anthropic/claude-opus-5.5",ao="x-ai/grok-4.7",lo="openai/gpt-6-astra",po="openai/gpt-6-astra-pro",ge="anthropic/claude-fable-5.1",co="deepseek/deepseek-v4.1-flash",uo="google/gemini-3.8-flash",Ge="inclusionai/ling-3.0-flash-vl:free",Wo="inception/mercury-2.5",Ve="nex-agi/nex-n2.5-mini:free",Fe="nex-agi/nex-n2.5-pro:free",Ee="qwen/qwen3.8-max-0902",Oe="meta/muse-spark-1.3",ho="nvidia/nemotron-3.5-lightning",Ue="qwen/qwen3.8-27b",Ke="qwen/qwen3.8-omni-flash",hi=[to,fe,me,we,ke,ho,Ue,Ke,oe,Ne],_o="openrouter/auto",He="openrouter/auto-beta",di="openrouter/fusion",B="openai/gpt-oss-20b:free",$o="moonshotai/kimi-k3",zo="moonshotai/kimi-k2.7-code",fo="moonshotai/kimi-k2.6",Xo="moonshotai/kimi-k2.5",qo="~moonshotai/kimi-latest",jo="~openai/gpt-latest",Zo="~openai/gpt-mini-latest",Jo="openai/gpt-5.6-sol",Yo="openai/gpt-5.6-terra",Qo="openai/gpt-5.6-luna",en="openai/gpt-5.5-pro",tn="openai/gpt-5.5",gr="openai/gpt-5.1-chat",on="openai/gpt-5.1-codex",nn="openai/gpt-5-mini",rn="openai/gpt-5-nano",sn="openai/gpt-4o",an="openai/gpt-4.1-mini",ln="openai/gpt-4.1-nano",pn="~anthropic/claude-sonnet-latest",cn="~anthropic/claude-haiku-latest",un="anthropic/claude-fable-5",Be="anthropic/claude-sonnet-5",hn="anthropic/claude-opus-5",mo="anthropic/claude-opus-4.8",dn="anthropic/claude-opus-4",_n="anthropic/claude-sonnet-4",Er="anthropic/claude-3.7-sonnet",Or="anthropic/claude-3.5-sonnet",fn="anthropic/claude-haiku-4.5",mn="~google/gemini-pro-latest",gn="~google/gemini-flash-latest",En="google/gemini-3.7-flash",On="google/gemini-3.6-flash",Mn="google/gemini-3.5-flash-lite",Sn="google/gemini-2.5-pro",vn="google/gemini-2.5-flash",Ln="google/gemini-2.5-flash-lite-preview-09-2025",We="z-ai/glm-5.2",ne="z-ai/glm-5.3",W="z-ai/glm-5.3-flash",Me="z-ai/glm-5.3-flashx",_i="z-ai/glm-4.7-flash",fi="z-ai/glm-4.5-air",Mr="z-ai/glm-4.5-air:free",mi="kwaipilot/kat-coder-air-v2.5",gi="kwaipilot/kat-coder-pro-v2.5",Cn="~x-ai/grok-latest",Tn="x-ai/grok-4.6",Rn="x-ai/grok-4.5",$e="deepseek/deepseek-v4-flash",ze="deepseek/deepseek-v4-flash-0731",Xe="deepseek/deepseek-v4-pro-0813",Se="deepseek/deepseek-v4-flash-vision-exp",go="qwen/qwen3.8-flash",Hs=[gr,Er,Or,Mr],Bs=["none","minimal","low","medium","high"],Ws=["none","high","xhigh"],$s=["none","low","high","max"],zs=["none","high","xhigh"],Xs=["low","high","max"],qs=["none","low","high","max"],js=["none","low","medium","high","xhigh","max"],be={[Ne]:{efforts:["none","high"],defaultEffort:"none"},[oe]:{efforts:[],defaultEffort:void 0},[to]:{efforts:[],defaultEffort:void 0},[fe]:{efforts:["none","minimal","low","medium","high","xhigh","max"],defaultEffort:"none"},[me]:{efforts:["none","minimal","low","medium","high","xhigh","max"],defaultEffort:"none"},[we]:{efforts:[],defaultEffort:void 0},[ke]:{efforts:[],defaultEffort:void 0},[ho]:{efforts:[],defaultEffort:void 0},[Ue]:{efforts:[],defaultEffort:void 0},[Ke]:{efforts:[],defaultEffort:void 0},[oo]:{efforts:["low","medium","high","xhigh","max"],defaultEffort:"low"},[no]:{efforts:["none","low","medium","high","xhigh","max"],defaultEffort:"none"},[io]:{efforts:["none","low","medium","high","xhigh","max"],defaultEffort:"none"},[ro]:{efforts:["low","medium","high","xhigh","max"],defaultEffort:"low"},[so]:{efforts:["low","medium","high","xhigh","max"],defaultEffort:"low"},[ao]:{efforts:["low","medium","high","xhigh"],defaultEffort:"low"},[lo]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"medium"},[po]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"medium"},[ge]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"high"},[co]:{efforts:["max","high","low","none"],defaultEffort:"none"},[uo]:{efforts:["high","medium","low"],defaultEffort:"medium"},[Ge]:{efforts:[],defaultEffort:void 0},[Wo]:{efforts:["high","medium","low","none"],defaultEffort:"none"},[Ve]:{efforts:["high","medium","none"],defaultEffort:"none"},[Fe]:{efforts:["high","medium","none"],defaultEffort:"none"},[Ee]:{efforts:["xhigh","high","medium","low","minimal"],defaultEffort:"xhigh"},[Oe]:{efforts:["max","xhigh","high","medium","low","minimal"],defaultEffort:"medium"}},Ei=[ke,B,Ge,Ve,Fe],Sr=[we,Ue,Ke,oo,no,io,ro,so,ao,lo,po,ge,co,uo,Ge,Ve,Fe,Ee,Oe,He,$o,fo,qo,jo,Zo,Jo,Yo,Qo,en,tn,on,nn,rn,sn,an,ln,pn,cn,un,Be,hn,mo,dn,_n,fn,mn,gn,En,On,Mn,Sn,vn,Ln,W,Me,Se,go,zo,Xo,Cn,Tn,Rn,oe,Ne],Oi=20,Zs=50,Js=1e3,Ys=10;function ve(o){return o.trim().endsWith(":free")}function qe(o){return Sr.some(e=>o.includes(e))}function Pn(o){let e=o.trim(),t=Object.prototype.hasOwnProperty.call(be,e)?be[e]:void 0;return t?t.efforts:e===ne||e===W||e===Me?Xs:e===Se?qs:e===Be||e===mo?js:e===$e?Ws:e===ze?$s:e===Xe?zs:Bs}function An(o){let e=o.trim(),t=Object.prototype.hasOwnProperty.call(be,e)?be[e]:void 0;return t?t.defaultEffort:e===ne||e===W||e===Me?"low":e===We||e===go||e===fo||e===Be||e===Se||e===$e||e===ze||e===Xe?"none":void 0}function Mi(o,e){let t=o.trim(),n=Object.prototype.hasOwnProperty.call(be,t)?be[t]:void 0,i=e??An(o);if(n)return i&&n.efforts.includes(i)?i:n.defaultEffort;if(!i)return;if(t===ne||t===W||t===Me)return i==="high"?"high":i==="max"||i==="xhigh"?"max":"low";if(Pn(o).includes(i))return i;if(t===$e)return i==="max"?"xhigh":"none";if(t===ze){if(i==="minimal"||i==="medium")return"low";if(i==="xhigh")return"high"}if(t===Xe){if(i==="minimal"||i==="low")return"none";if(i==="medium")return"high";if(i==="max")return"xhigh"}if(t===Se){if(i==="minimal"||i==="medium")return"low";if(i==="xhigh")return"high"}return i}var Eo="https://api.z.ai/api/paas/v4/chat/completions",xn="glm-5.3",Oo="glm-5.3-flash",ie="glm-5.3-flashx",re="glm-5.2",Si="glm-5.1",vi="glm-5",Li="glm-5-turbo",In="glm-5v-turbo",Ci="glm-4.7",Ti="glm-4.7-FlashX",Ri="glm-4.7-Flash",Pi="glm-4.6",yn="glm-4.6V",Dn="glm-4.6V-FlashX",Le="glm-4.6V-Flash",Qs=["none","minimal","low","medium","high","xhigh","max"],ea=["low","high","max"];function je(o){return o===xn||o===Oo||o===ie}function Ze(o){return je(o)?ea:o===re?Qs:[]}function bn(o){return Ze(o).length>0}function vr(o){return je(o)?"low":o===re?"none":void 0}function Mo(o,e){if(!bn(o))return;let t=e??vr(o);return je(o)?t==="high"?"high":t==="max"||t==="xhigh"?"max":"low":t==="none"||t==="minimal"?"none":t==="low"||t==="medium"||t==="high"?"high":"max"}var Lr=[ie,Oo,In,yn,Dn,Le];function Je(o){return Lr.includes(o)}function Ai(o){let e=o.toLowerCase();return e.startsWith("glm-5.3")||e.startsWith("glm-4.6")}var So="https://api.x.ai/v1/chat/completions",Ye="grok-4.6",Qe="grok-4.7",et="grok-4.5",K="grok-4.3",Nn="grok-4.20-0309-reasoning",wn="grok-4.20-0309-non-reasoning",Cr="grok-4-1-fast-reasoning",Tr="grok-4-1-fast-non-reasoning",ta=[Cr,Tr],Rr=[Ye,Qe,et,K,Nn,wn];function tt(o){return Rr.includes(o)}function kn(o){return ot(o).length>0}function ot(o){return o===Ye||o===Qe?["low","medium","high","xhigh"]:o===et?["low","medium","high"]:o===K?["none","low","medium","high"]:[]}function Pr(o){return ot(o).includes("none")}function Gn(o){return o===Qe||o===Ye||o===et?"low":Pr(o)?"none":void 0}function vo(o,e){return kn(o)?e===void 0?Gn(o):ot(o).includes(e)?e:e==="none"?"low":"high":void 0}var nt="https://api.moonshot.ai/v1/chat/completions",it="kimi-k3",Lo="kimi-k2.7-code",Co="kimi-k2.7-code-highspeed",$="kimi-k2.6",Vn="kimi-k2.5",oa={[it]:["low","high","max"]},Ar=[it,Lo,Co,$,Vn],xr=[Lo,Co];function rt(o){return Ar.includes(o)}function To(o){return xr.includes(o)}function se(o){return oa[o]??[]}function st(o){return o===it?"max":void 0}function Ce(o){return se(o).length>0}var yr="https://api.deepseek.com",Ro=`${yr}/chat/completions`,Fn="deepseek-flash",Te="deepseek-v4-flash",Un="deepseek-v4-pro",at="deepseek-v4-flash-vision-exp",Ir=["none","low","high","max"],na=["none","high","max"],Dr="deepseek-chat",br="deepseek-reasoner",Ii=[Fn,Te,Un,at],Nr=[Fn,at],ia=[Dr,br];function Po(o){return o===Fn||o===Te||o===at?Ir:o===Un?na:[]}function yi(o){return Nr.includes(o)}function wr(o){return Po(o).length>0}function xi(o){return wr(o)?"none":void 0}function Di(o,e){let t=Po(o);if(t.length===0)return;let n=e??xi(o);return n&&t.includes(n)?n:o===Un&&n==="low"?"high":xi(o)}var kr="https://api.mistral.ai/v1",Ao=`${kr}/chat/completions`,bi="ministral-3b-2512",Ni="ministral-8b-2512",wi="ministral-14b-2512",z="mistral-small-latest",ki="mistral-small-2603",Kn="mistral-medium-3-5",Gr="mistral-medium-2508",Gi="mistral-large-latest",Vi="mistral-large-2512",Vr="zai-glm-5-3",Fi=[z,bi,Ni,wi,Kn,Gi,Vi,ki,Vr],ra=[Gr],Fr=[z,Kn],Ur=[z,bi,Ni,wi,ki,Kn,Gi,Vi];function xo(o){return Fr.includes(o)}function Ui(o){return o==="none"||o==="high"}function Ki(o){return Ur.includes(o)}var Kr="https://api.sakana.ai/v1",Io=`${Kr}/chat/completions`,lt="fugu",Hr="fugu-ultra",Br="fugu-ultra-v1.1",Re="sakana-namazu",Wr="fugu-ultra-20260615",Hi=[lt,Br,Re],$r=[Re];function Bi(o){return $r.includes(o)}var sa=[Hr,Wr];var zr="https://api.platform.preferredai.jp/v1",yo=`${zr}/chat/completions`,pt="plamo-3.0-prime",Xr="plamo-2.2-prime",Wi=[pt],aa=[Xr];var C={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Hn={[C.VERY_SHORT]:40,[C.SHORT]:100,[C.MEDIUM]:200,[C.LONG]:300,[C.VERY_LONG]:1e3,[C.DEEP]:5e3},$i=5e3,zi={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 x(o){return o?Hn[o]??$i:$i}var la="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",pa=`You are a skilled summarizing assistant.
|
|
1
|
+
"use strict";var AITuberOnAirChat=(()=>{var ti=Object.defineProperty;var Hs=Object.getOwnPropertyDescriptor;var Bs=Object.getOwnPropertyNames;var Ws=Object.prototype.hasOwnProperty;var $s=(o,e)=>{for(var t in e)ti(o,t,{get:e[t],enumerable:!0})},zs=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bs(e))!Ws.call(o,i)&&i!==t&&ti(o,i,{get:()=>e[i],enumerable:!(n=Hs(e,i))||n.enumerable});return o};var Xs=o=>zs(ti({},"__esModule",{value:!0}),o);var fl={};$s(fl,{CHAT_RESPONSE_LENGTH:()=>C,CLAUDE_DEPRECATED_MODELS:()=>ta,CLAUDE_VISION_SUPPORTED_MODELS:()=>Qt,ChatServiceFactory:()=>yt,ChatServiceHttpClient:()=>O,ClaudeChatService:()=>at,ClaudeChatServiceProvider:()=>lt,DEEPSEEK_API_BASE_URL:()=>$r,DEEPSEEK_DEPRECATED_MODELS:()=>Sa,DEEPSEEK_SUPPORTED_MODELS:()=>Fi,DEEPSEEK_VISION_SUPPORTED_MODELS:()=>qr,DEFAULT_MAX_TOKENS:()=>tr,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>Ra,DEFAULT_VISION_PROMPT:()=>Ta,DeepSeekChatService:()=>pt,DeepSeekChatServiceProvider:()=>ct,EMOTION_TAG_CLEANUP_REGEX:()=>ir,EMOTION_TAG_REGEX:()=>ls,ENDPOINT_CLAUDE_API:()=>mi,ENDPOINT_DEEPSEEK_CHAT_COMPLETIONS_API:()=>wo,ENDPOINT_GEMINI_API:()=>ri,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>et,ENDPOINT_MISTRAL_CHAT_COMPLETIONS_API:()=>Go,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>Z,ENDPOINT_OPENAI_RESPONSES_API:()=>k,ENDPOINT_OPENROUTER_API:()=>eo,ENDPOINT_PLAMO_CHAT_COMPLETIONS_API:()=>Fo,ENDPOINT_SAKANA_CHAT_COMPLETIONS_API:()=>Vo,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>Ao,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>Co,EmotionParser:()=>st,GEMINI_DEPRECATED_MODELS:()=>Mr,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>nr,GEMINI_RECOMMENDED_MODELS:()=>qo,GEMINI_VISION_SUPPORTED_MODELS:()=>Ft,GPT5_PRESETS:()=>or,GPT_5_MODELS:()=>ur,GeminiChatService:()=>ut,GeminiChatServiceProvider:()=>ht,GeminiNanoChatService:()=>_t,GeminiNanoChatServiceProvider:()=>dt,HttpError:()=>ce,KIMI_DEPRECATED_MODELS:()=>Ea,KIMI_THINKING_REQUIRED_MODELS:()=>Br,KIMI_VISION_SUPPORTED_MODELS:()=>Hr,KimiChatService:()=>ft,KimiChatServiceProvider:()=>mt,MAX_TOKENS_BY_LENGTH:()=>Zn,MISTRAL_API_BASE_URL:()=>Zr,MISTRAL_DEPRECATED_MODELS:()=>va,MISTRAL_REASONING_EFFORT_SUPPORTED_MODELS:()=>Qr,MISTRAL_SUPPORTED_MODELS:()=>ji,MISTRAL_VISION_SUPPORTED_MODELS:()=>es,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>yr,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>Ir,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>Tn,MODEL_ANTHROPIC_CLAUDE_FABLE_5:()=>Ln,MODEL_ANTHROPIC_CLAUDE_FABLE_5_1:()=>Oe,MODEL_ANTHROPIC_CLAUDE_HAIKU_5_5:()=>fo,MODEL_ANTHROPIC_CLAUDE_HAIKU_LATEST:()=>vn,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>vi,MODEL_ANTHROPIC_CLAUDE_OPUS_4_8:()=>vo,MODEL_ANTHROPIC_CLAUDE_OPUS_5:()=>Cn,MODEL_ANTHROPIC_CLAUDE_OPUS_5_5:()=>ao,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>Li,MODEL_ANTHROPIC_CLAUDE_SONNET_5:()=>Fe,MODEL_ANTHROPIC_CLAUDE_SONNET_5_5:()=>so,MODEL_ANTHROPIC_CLAUDE_SONNET_LATEST:()=>Sn,MODEL_APODEX_1_1_MINI_FREE:()=>Jo,MODEL_CLAUDE_3_5_HAIKU:()=>Lr,MODEL_CLAUDE_3_5_SONNET:()=>Cr,MODEL_CLAUDE_3_7_SONNET:()=>Tr,MODEL_CLAUDE_3_HAIKU:()=>vr,MODEL_CLAUDE_4_5_HAIKU:()=>H,MODEL_CLAUDE_4_5_OPUS:()=>Bt,MODEL_CLAUDE_4_5_SONNET:()=>gi,MODEL_CLAUDE_4_6_OPUS:()=>$t,MODEL_CLAUDE_4_6_SONNET:()=>Wt,MODEL_CLAUDE_4_7_OPUS:()=>zt,MODEL_CLAUDE_4_8_OPUS:()=>Xt,MODEL_CLAUDE_4_OPUS:()=>Ar,MODEL_CLAUDE_4_SONNET:()=>Rr,MODEL_CLAUDE_5_1_FABLE:()=>Ht,MODEL_CLAUDE_5_5_HAIKU:()=>Yt,MODEL_CLAUDE_5_5_OPUS:()=>jo,MODEL_CLAUDE_5_5_SONNET:()=>Jt,MODEL_CLAUDE_5_FABLE:()=>qt,MODEL_CLAUDE_5_OPUS:()=>Zt,MODEL_CLAUDE_5_SONNET:()=>jt,MODEL_DEEPSEEK_CHAT:()=>zr,MODEL_DEEPSEEK_FLASH:()=>Xn,MODEL_DEEPSEEK_REASONER:()=>Xr,MODEL_DEEPSEEK_V4_FLASH:()=>Ae,MODEL_DEEPSEEK_V4_FLASH_VISION_EXP:()=>nt,MODEL_DEEPSEEK_V4_PRO:()=>qn,MODEL_FUGU:()=>it,MODEL_FUGU_ULTRA:()=>os,MODEL_FUGU_ULTRA_20260615:()=>is,MODEL_FUGU_ULTRA_V1_1:()=>ns,MODEL_GEMINI_2_5_FLASH:()=>gr,MODEL_GEMINI_2_5_FLASH_LITE:()=>Er,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>Or,MODEL_GEMINI_2_5_PRO:()=>mr,MODEL_GEMINI_3_1_FLASH_LITE:()=>te,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>hi,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>ui,MODEL_GEMINI_3_5_FLASH:()=>pi,MODEL_GEMINI_3_5_FLASH_LITE:()=>ci,MODEL_GEMINI_3_6_FLASH:()=>li,MODEL_GEMINI_3_7_FLASH:()=>ai,MODEL_GEMINI_3_8_FLASH:()=>si,MODEL_GEMINI_3_FLASH_PREVIEW:()=>di,MODEL_GEMINI_3_PRO_PREVIEW:()=>_i,MODEL_GEMINI_NANO:()=>xe,MODEL_GEMMA_4_26B_A4B_IT:()=>fr,MODEL_GEMMA_4_31B_IT:()=>dr,MODEL_GLM_4_6:()=>ki,MODEL_GLM_4_6V:()=>Fn,MODEL_GLM_4_6V_FLASH:()=>Re,MODEL_GLM_4_6V_FLASHX:()=>Kn,MODEL_GLM_4_7:()=>bi,MODEL_GLM_4_7_FLASH:()=>wi,MODEL_GLM_4_7_FLASHX:()=>Ni,MODEL_GLM_5:()=>yi,MODEL_GLM_5V_TURBO:()=>Vn,MODEL_GLM_5_1:()=>Ii,MODEL_GLM_5_2:()=>ae,MODEL_GLM_5_3:()=>Un,MODEL_GLM_5_3_FLASH:()=>To,MODEL_GLM_5_3_FLASHX:()=>se,MODEL_GLM_5_TURBO:()=>Di,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>Dn,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>Ci,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>yn,MODEL_GOOGLE_GEMINI_3_5_FLASH_LITE:()=>In,MODEL_GOOGLE_GEMINI_3_6_FLASH:()=>xn,MODEL_GOOGLE_GEMINI_3_7_FLASH:()=>Pn,MODEL_GOOGLE_GEMINI_3_8_FLASH:()=>ho,MODEL_GOOGLE_GEMINI_FLASH_LATEST:()=>An,MODEL_GOOGLE_GEMINI_PRO_LATEST:()=>Rn,MODEL_GOOGLE_GEMMA_4_31B_IT_FREE:()=>U,MODEL_GPT_4O:()=>$o,MODEL_GPT_4O_MINI:()=>de,MODEL_GPT_4_1:()=>Bo,MODEL_GPT_4_1_MINI:()=>Wo,MODEL_GPT_4_1_NANO:()=>oi,MODEL_GPT_5:()=>Nt,MODEL_GPT_5_1:()=>wt,MODEL_GPT_5_4:()=>ue,MODEL_GPT_5_4_MINI:()=>_e,MODEL_GPT_5_4_NANO:()=>ye,MODEL_GPT_5_4_PRO:()=>ee,MODEL_GPT_5_5:()=>he,MODEL_GPT_5_6:()=>J,MODEL_GPT_5_6_LUNA:()=>W,MODEL_GPT_5_6_SOL:()=>Y,MODEL_GPT_5_6_TERRA:()=>Q,MODEL_GPT_5_MINI:()=>bt,MODEL_GPT_5_NANO:()=>Dt,MODEL_GPT_6_1_SOL:()=>A,MODEL_GPT_6_1_TERRA:()=>R,MODEL_GPT_6_ASTRA:()=>x,MODEL_GPT_6_LUNA:()=>w,MODEL_GPT_6_SOL:()=>N,MODEL_GPT_OSS_20B_FREE:()=>nn,MODEL_GROK_4_1_FAST_NON_REASONING:()=>Vr,MODEL_GROK_4_1_FAST_REASONING:()=>Ur,MODEL_GROK_4_20_NON_REASONING:()=>Wn,MODEL_GROK_4_20_REASONING:()=>Bn,MODEL_GROK_4_3:()=>B,MODEL_GROK_4_5:()=>Je,MODEL_GROK_4_6:()=>je,MODEL_GROK_4_7:()=>Ze,MODEL_INCEPTION_MERCURY_2_5:()=>Qo,MODEL_INCEPTION_MERCURY_3:()=>on,MODEL_INCLUSIONAI_LING_3_0_FLASH_VL:()=>Ue,MODEL_INCLUSIONAI_LING_3_0_FLASH_VL_FREE:()=>Yo,MODEL_INCLUSIONAI_LING_3_1_FLASH:()=>to,MODEL_KIMI_K2_5:()=>Ui,MODEL_KIMI_K2_6:()=>X,MODEL_KIMI_K2_7_CODE:()=>Io,MODEL_KIMI_K2_7_CODE_HIGHSPEED:()=>yo,MODEL_KIMI_K3:()=>xo,MODEL_KIMI_K3_1_PRO:()=>Do,MODEL_KIMI_K3_1_PRO_HIGHSPEED:()=>bo,MODEL_KWAIPILOT_KAT_CODER_AIR_V2_5:()=>br,MODEL_KWAIPILOT_KAT_CODER_PRO_V2_5:()=>Nr,MODEL_META_MUSE_SPARK_1_3:()=>Se,MODEL_MINIMAX_M3_1_FLASH:()=>Eo,MODEL_MINISTRAL_14B_2512:()=>$i,MODEL_MINISTRAL_3B_2512:()=>Bi,MODEL_MINISTRAL_8B_2512:()=>Wi,MODEL_MISTRAL_LARGE_2512:()=>qi,MODEL_MISTRAL_LARGE_LATEST:()=>Xi,MODEL_MISTRAL_MEDIUM_2508:()=>Jr,MODEL_MISTRAL_MEDIUM_3_5:()=>jn,MODEL_MISTRAL_SMALL_2603:()=>zi,MODEL_MISTRAL_SMALL_LATEST:()=>q,MODEL_MISTRAL_ZAI_GLM_5_3:()=>Yr,MODEL_MOONSHOTAI_KIMI_K2_5:()=>an,MODEL_MOONSHOTAI_KIMI_K2_6:()=>So,MODEL_MOONSHOTAI_KIMI_K2_7_CODE:()=>sn,MODEL_MOONSHOTAI_KIMI_K3:()=>rn,MODEL_MOONSHOTAI_KIMI_K3_1_PRO:()=>go,MODEL_MOONSHOTAI_KIMI_LATEST:()=>ln,MODEL_NEX_AGI_NEX_N2_5_MINI_FREE:()=>en,MODEL_NEX_AGI_NEX_N2_5_PRO:()=>Oo,MODEL_NEX_AGI_NEX_N2_5_PRO_FREE:()=>tn,MODEL_NVIDIA_NEMOTRON_3_5_LIGHTNING:()=>_o,MODEL_NVIDIA_NEMOTRON_3_5_SUPER_VL_FREE:()=>ve,MODEL_O1:()=>qs,MODEL_O1_MINI:()=>cr,MODEL_O3_MINI:()=>pr,MODEL_OPENAI_GPT_4O:()=>En,MODEL_OPENAI_GPT_4_1_MINI:()=>On,MODEL_OPENAI_GPT_4_1_NANO:()=>Mn,MODEL_OPENAI_GPT_5_1_CHAT:()=>xr,MODEL_OPENAI_GPT_5_1_CODEX:()=>fn,MODEL_OPENAI_GPT_5_5:()=>dn,MODEL_OPENAI_GPT_5_5_PRO:()=>_n,MODEL_OPENAI_GPT_5_6_LUNA:()=>hn,MODEL_OPENAI_GPT_5_6_SOL:()=>cn,MODEL_OPENAI_GPT_5_6_TERRA:()=>un,MODEL_OPENAI_GPT_5_MINI:()=>mn,MODEL_OPENAI_GPT_5_NANO:()=>gn,MODEL_OPENAI_GPT_6_1_SOL:()=>no,MODEL_OPENAI_GPT_6_1_TERRA:()=>oo,MODEL_OPENAI_GPT_6_ASTRA:()=>po,MODEL_OPENAI_GPT_6_ASTRA_PRO:()=>co,MODEL_OPENAI_GPT_6_LUNA:()=>ro,MODEL_OPENAI_GPT_6_SOL:()=>io,MODEL_OPENAI_GPT_LATEST:()=>Si,MODEL_OPENAI_GPT_MINI_LATEST:()=>pn,MODEL_OPENROUTER_AUTO:()=>Mo,MODEL_OPENROUTER_AUTO_BETA:()=>Ve,MODEL_OPENROUTER_DEEPSEEK_V4_1_FLASH:()=>uo,MODEL_OPENROUTER_DEEPSEEK_V4_1_FLASH_1017:()=>mo,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH:()=>He,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_0731:()=>Be,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_VISION_EXP:()=>Ce,MODEL_OPENROUTER_DEEPSEEK_V4_PRO_0813:()=>We,MODEL_OPENROUTER_FUSION:()=>Mi,MODEL_OPENROUTER_MISTRAL_LARGE_4_0:()=>Ne,MODEL_PLAMO_2_2_PRIME:()=>as,MODEL_PLAMO_3_0_PRIME:()=>rt,MODEL_QWEN_QWEN_3_8_27B:()=>ke,MODEL_QWEN_QWEN_3_8_FLASH:()=>Lo,MODEL_QWEN_QWEN_3_8_MAX_0902:()=>Me,MODEL_QWEN_QWEN_3_8_OMNI_FLASH:()=>Ge,MODEL_SAKANA_NAMAZU:()=>Pe,MODEL_UNBIASED_PARETO_26_10:()=>ie,MODEL_UNBIASED_PARETO_26_10_PREVIEW:()=>me,MODEL_UNBIASED_PARETO_26_9:()=>ne,MODEL_UPSTAGE_SOLAR_MINI4:()=>Ee,MODEL_UPSTAGE_SOLAR_PRO4:()=>ge,MODEL_XAI_GROK_4_5:()=>wn,MODEL_XAI_GROK_4_6:()=>Nn,MODEL_XAI_GROK_4_7:()=>lo,MODEL_XAI_GROK_LATEST:()=>bn,MODEL_XIAOMI_MIMO_V2_6_FLASH:()=>we,MODEL_ZAI_GLM_4_5_AIR:()=>Ri,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>Dr,MODEL_ZAI_GLM_4_7_FLASH:()=>Ti,MODEL_ZAI_GLM_5_2:()=>Ke,MODEL_ZAI_GLM_5_3:()=>re,MODEL_ZAI_GLM_5_3_FLASH:()=>z,MODEL_ZAI_GLM_5_3_FLASHX:()=>Le,MistralChatService:()=>gt,MistralChatServiceProvider:()=>Et,OPENAI_COMPATIBLE_LOCAL_PRESETS:()=>ya,OPENAI_DEPRECATED_MODELS:()=>js,OPENROUTER_CREDITS_THRESHOLD:()=>da,OPENROUTER_DEPRECATED_MODELS:()=>ia,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>_a,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>ha,OPENROUTER_FREE_MODELS:()=>Ai,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>Pi,OPENROUTER_MODELS_WITHOUT_REASONING_BUDGET:()=>Oi,OPENROUTER_VISION_SUPPORTED_MODELS:()=>wr,OpenAIChatService:()=>y,OpenAIChatServiceProvider:()=>Mt,OpenAICompatibleChatServiceProvider:()=>Ot,OpenAICompatibleEndpointError:()=>P,OpenRouterChatService:()=>St,OpenRouterChatServiceProvider:()=>vt,PLAMO_API_BASE_URL:()=>ss,PLAMO_DEPRECATED_MODELS:()=>Ca,PLAMO_SUPPORTED_MODELS:()=>er,PlamoChatService:()=>Lt,PlamoChatServiceProvider:()=>Ct,SAKANA_API_BASE_URL:()=>ts,SAKANA_COMPATIBILITY_MODELS:()=>La,SAKANA_SUPPORTED_MODELS:()=>Yi,SAKANA_VISION_SUPPORTED_MODELS:()=>rs,SakanaChatService:()=>Tt,SakanaChatServiceProvider:()=>Rt,StreamTextAccumulator:()=>M,VISION_SUPPORTED_MODELS:()=>kt,XAIChatService:()=>At,XAIChatServiceProvider:()=>Pt,XAI_DEPRECATED_MODELS:()=>ga,XAI_VISION_SUPPORTED_MODELS:()=>Fr,ZAIChatService:()=>xt,ZAIChatServiceProvider:()=>It,ZAI_VISION_SUPPORTED_MODELS:()=>Gr,allowsReasoningLow:()=>Xo,allowsReasoningMax:()=>ii,allowsReasoningMinimal:()=>Ut,allowsReasoningNone:()=>Gt,allowsReasoningXHigh:()=>zo,buildOpenAICompatibleTools:()=>K,buildToolContinuationMessages:()=>pl,getChatBackendProviderCapabilities:()=>lr,getClaudeSupportedReasoningEfforts:()=>$,getDeepSeekSupportedReasoningEfforts:()=>ko,getDefaultClaudeReasoningEffort:()=>Zo,getDefaultDeepSeekReasoningEffort:()=>Vi,getDefaultGeminiReasoningEffort:()=>ea,getDefaultKimiReasoningEffort:()=>ot,getDefaultOpenRouterReasoningEffort:()=>Gn,getDefaultReasoningEffortForGPT5Model:()=>_r,getDefaultReasoningEffortForOpenAIModel:()=>Vt,getDefaultXaiReasoningEffort:()=>zn,getDefaultZaiReasoningEffort:()=>kr,getGeminiSupportedReasoningEfforts:()=>De,getKimiSupportedReasoningEfforts:()=>le,getMaxTokensForResponseLength:()=>I,getOpenRouterSupportedReasoningEfforts:()=>kn,getXaiSupportedReasoningEfforts:()=>Qe,getZaiSupportedReasoningEfforts:()=>Xe,installGASFetch:()=>Fs,isClaudeReasoningEffortModel:()=>Pr,isDeepSeekReasoningEffortModel:()=>jr,isDeepSeekVisionModel:()=>Ki,isGPT5Model:()=>hr,isGeminiReasoningEffortModel:()=>fi,isKimiReasoningEffortModel:()=>pe,isKimiThinkingRequiredModel:()=>No,isKimiVisionModel:()=>tt,isMistralReasoningEffort:()=>Zi,isMistralReasoningEffortModel:()=>Uo,isMistralVisionModel:()=>Ji,isOpenAIReasoningModel:()=>fe,isOpenRouterFreeModel:()=>Te,isOpenRouterVisionModel:()=>$e,isResponsesOnlyGPT5Model:()=>ni,isSakanaVisionModel:()=>Qi,isXaiReasoningEffortModel:()=>$n,isXaiReasoningEffortNoneModel:()=>Kr,isXaiVisionModel:()=>Ye,isZaiAlwaysThinkingModel:()=>ze,isZaiReasoningEffortModel:()=>Hn,isZaiToolStreamModel:()=>Gi,isZaiVisionModel:()=>qe,listOpenAICompatibleModels:()=>ds,normalizeClaudeReasoningEffort:()=>na,normalizeDeepSeekReasoningEffort:()=>Hi,normalizeGeminiReasoningEffort:()=>Kt,normalizeOpenRouterReasoningEffort:()=>xi,normalizeXaiReasoningEffort:()=>Po,normalizeZaiReasoningEffort:()=>Ro,parseOpenAICompatibleOneShot:()=>F,parseOpenAICompatibleTextStream:()=>j,parseOpenAICompatibleToolStream:()=>V,processChatWithOptionalTools:()=>S,refreshOpenRouterFreeModels:()=>Ha,resolveOpenAICompatibleEndpoint:()=>_s,resolveVisionModel:()=>T,runOnceText:()=>Ia,safeJsonParse:()=>cs,safeParseToolCallInput:()=>Ie,screenplayToText:()=>xa,testOpenAICompatibleConnection:()=>Da,textToScreenplay:()=>ps,textsToScreenplay:()=>Pa});var Z="https://api.openai.com/v1/chat/completions",k="https://api.openai.com/v1/responses",A="gpt-6.1-sol",R="gpt-6.1-terra",x="gpt-6-astra",N="gpt-6-sol",w="gpt-6-luna",Dt="gpt-5-nano",bt="gpt-5-mini",Nt="gpt-5",wt="gpt-5.1",ue="gpt-5.4",he="gpt-5.5",J="gpt-5.6",Y="gpt-5.6-sol",Q="gpt-5.6-terra",W="gpt-5.6-luna",_e="gpt-5.4-mini",ye="gpt-5.4-nano",ee="gpt-5.4-pro",Bo="gpt-4.1",Wo="gpt-4.1-mini",oi="gpt-4.1-nano",de="gpt-4o-mini",$o="gpt-4o",pr="o3-mini",cr="o1-mini",qs="o1",js=[Dt,bt,Nt,wt,ye,oi,pr,cr,"o1"],kt=[A,x,N,w,Dt,bt,Nt,wt,ue,he,J,Y,Q,W,_e,ye,ee,Bo,Wo,oi,de,$o,"o1",R],ur=[Dt,bt,Nt,wt,ue,he,J,Y,Q,W,_e,ye,ee];function hr(o){return ur.includes(o)}function fe(o){return o===A||o===R||o===x||o===N||o===w||hr(o)}function ni(o){return o===ee}function zo(o){return o===A||o===R||o===x||o===N||o===w||o===J||o===Y||o===Q||o===W||o===he||o===ue||o===_e||o===ye||o===ee}function ii(o){return o===A||o===R||o===x||o===N||o===w||o===J||o===Y||o===Q||o===W}function Gt(o){return o===R||o===N||o===w||o===J||o===Y||o===Q||o===W||o===wt||o===ue||o===he||o===_e||o===ye}function Ut(o){return o===Dt||o===bt||o===Nt}function Xo(o){return o!==ee}function _r(o){return Gt(o)?"none":Ut(o)?"minimal":"medium"}function Vt(o){return o===A||o===R||o===x?"low":o===N?"medium":o===w?"low":_r(o)}var ri="https://generativelanguage.googleapis.com",dr="gemma-4-31b-it",fr="gemma-4-26b-a4b-it",si="gemini-3.8-flash",ai="gemini-3.7-flash",li="gemini-3.6-flash",pi="gemini-3.5-flash",ci="gemini-3.5-flash-lite",ui="gemini-3.1-pro-preview",te="gemini-3.1-flash-lite",hi="gemini-3.1-flash-lite-preview",_i="gemini-3-pro-preview",di="gemini-3-flash-preview",mr="gemini-2.5-pro",gr="gemini-2.5-flash",Er="gemini-2.5-flash-lite",Or="gemini-2.5-flash-lite-preview-06-17",qo=[si,li,ci,te,ui,di,mr,gr,Er,dr,fr],Mr=[ai,pi,hi,_i,Or],Ft=[...qo,...Mr],Zs=["minimal","low","medium","high"],Js=["low","medium","high"],Ys=[li,pi,ci,te,hi,di],Qs=[si,ai,ui,_i];function De(o){return Ys.includes(o)?Zs:Qs.includes(o)?Js:[]}function fi(o){return De(o).length>0}function ea(o){return De(o)[0]}function Kt(o,e){let t=De(o);if(t.length!==0)return e&&t.includes(e)?e:t[0]}var mi="https://api.anthropic.com/v1/messages",Ht="claude-fable-5-1",vr="claude-3-haiku-20240307",Lr="claude-3-5-haiku-20241022",Cr="claude-3-5-sonnet-20241022",Tr="claude-3-7-sonnet-20250219",Rr="claude-sonnet-4-20250514",Ar="claude-opus-4-20250514",gi="claude-sonnet-4-5-20250929",H="claude-haiku-4-5-20251001",Bt="claude-opus-4-5-20251101",Wt="claude-sonnet-4-6",$t="claude-opus-4-6",zt="claude-opus-4-7",Xt="claude-opus-4-8",qt="claude-fable-5",jt="claude-sonnet-5",Zt="claude-opus-5",jo="claude-opus-5-5",Jt="claude-sonnet-5-5",Yt="claude-haiku-5-5",ta=[gi,vr,Lr,Cr,Tr,Rr,Ar],Ei=["low","medium","high"],Sr=[...Ei,"max"],oe=[...Ei,"xhigh","max"],oa={[Bt]:Ei,[Wt]:Sr,[$t]:Sr,[zt]:oe,[Xt]:oe,[Ht]:oe,[qt]:oe,[jt]:oe,[Zt]:oe,[Jt]:oe,[Yt]:oe},Qt=[Ht,gi,H,Bt,Wt,$t,zt,Xt,qt,jt,Zt,jo,Jt,Yt];function $(o){return oa[o]??[]}function Pr(o){return $(o).length>0}function Zo(o){return Pr(o)?"low":void 0}function na(o,e){let t=$(o);if(t.length!==0)return e?t.includes(e)?e:"high":Zo(o)}var eo="https://openrouter.ai/api/v1/chat/completions",Ne="mistralai/mistral-large-4-0",ne="unbiased/pareto-26.9",me="unbiased/pareto-26.10-preview",to="inclusionai/ling-3.1-flash",ge="upstage/solar-pro4",Ee="upstage/solar-mini4",we="xiaomi/mimo-v2.6-flash",Jo="apodex/apodex-1.1-mini:free",oo="openai/gpt-6.1-terra",no="openai/gpt-6.1-sol",io="openai/gpt-6-sol",ro="openai/gpt-6-luna",so="anthropic/claude-sonnet-5.5",ao="anthropic/claude-opus-5.5",lo="x-ai/grok-4.7",po="openai/gpt-6-astra",co="openai/gpt-6-astra-pro",Oe="anthropic/claude-fable-5.1",uo="deepseek/deepseek-v4.1-flash",ho="google/gemini-3.8-flash",Yo="inclusionai/ling-3.0-flash-vl:free",Qo="inception/mercury-2.5",en="nex-agi/nex-n2.5-mini:free",tn="nex-agi/nex-n2.5-pro:free",Me="qwen/qwen3.8-max-0902",Se="meta/muse-spark-1.3",_o="nvidia/nemotron-3.5-lightning",ke="qwen/qwen3.8-27b",Ge="qwen/qwen3.8-omni-flash",U="google/gemma-4-31b-it:free",ve="nvidia/nemotron-3.5-super-vl:free",fo="anthropic/claude-haiku-5.5",on="inception/mercury-3",mo="deepseek/deepseek-v4.1-flash-1017",go="moonshotai/kimi-k3.1-pro",Eo="minimax/minimax-m3.1-flash",ie="unbiased/pareto-26.10",Ue="inclusionai/ling-3.0-flash-vl",Oo="nex-agi/nex-n2.5-pro",Oi=[ie,Ue,to,ge,Ee,we,Jo,_o,ke,Ge,me,Ne,ne,U,ve],Mo="openrouter/auto",Ve="openrouter/auto-beta",Mi="openrouter/fusion",nn="openai/gpt-oss-20b:free",rn="moonshotai/kimi-k3",sn="moonshotai/kimi-k2.7-code",So="moonshotai/kimi-k2.6",an="moonshotai/kimi-k2.5",ln="~moonshotai/kimi-latest",Si="~openai/gpt-latest",pn="~openai/gpt-mini-latest",cn="openai/gpt-5.6-sol",un="openai/gpt-5.6-terra",hn="openai/gpt-5.6-luna",_n="openai/gpt-5.5-pro",dn="openai/gpt-5.5",xr="openai/gpt-5.1-chat",fn="openai/gpt-5.1-codex",mn="openai/gpt-5-mini",gn="openai/gpt-5-nano",En="openai/gpt-4o",On="openai/gpt-4.1-mini",Mn="openai/gpt-4.1-nano",Sn="~anthropic/claude-sonnet-latest",vn="~anthropic/claude-haiku-latest",Ln="anthropic/claude-fable-5",Fe="anthropic/claude-sonnet-5",Cn="anthropic/claude-opus-5",vo="anthropic/claude-opus-4.8",vi="anthropic/claude-opus-4",Li="anthropic/claude-sonnet-4",Ir="anthropic/claude-3.7-sonnet",yr="anthropic/claude-3.5-sonnet",Tn="anthropic/claude-haiku-4.5",Rn="~google/gemini-pro-latest",An="~google/gemini-flash-latest",Pn="google/gemini-3.7-flash",xn="google/gemini-3.6-flash",In="google/gemini-3.5-flash-lite",yn="google/gemini-2.5-pro",Dn="google/gemini-2.5-flash",Ci="google/gemini-2.5-flash-lite-preview-09-2025",Ke="z-ai/glm-5.2",re="z-ai/glm-5.3",z="z-ai/glm-5.3-flash",Le="z-ai/glm-5.3-flashx",Ti="z-ai/glm-4.7-flash",Ri="z-ai/glm-4.5-air",Dr="z-ai/glm-4.5-air:free",br="kwaipilot/kat-coder-air-v2.5",Nr="kwaipilot/kat-coder-pro-v2.5",bn="~x-ai/grok-latest",Nn="x-ai/grok-4.6",wn="x-ai/grok-4.5",He="deepseek/deepseek-v4-flash",Be="deepseek/deepseek-v4-flash-0731",We="deepseek/deepseek-v4-pro-0813",Ce="deepseek/deepseek-v4-flash-vision-exp",Lo="qwen/qwen3.8-flash",ia=[xr,Ir,yr,Dr,Si,vi,Li,Ci,br,Nr,me,Jo,Yo,en,tn,nn],ra=["none","minimal","low","medium","high"],sa=["none","high","xhigh"],aa=["none","low","high","max"],la=["none","high","xhigh"],pa=["low","high","max"],ca=["none","low","high","max"],ua=["none","low","medium","high","xhigh","max"],be={[oo]:{efforts:["none","low","medium","high","xhigh","max"],defaultEffort:"none"},[fo]:{efforts:["none","low","medium","high","xhigh","max"],defaultEffort:"low"},[on]:{efforts:["none","low","medium","high"],defaultEffort:"none"},[mo]:{efforts:["none","low","high","max"],defaultEffort:"none"},[go]:{efforts:["none","low","high","max"],defaultEffort:"none"},[Eo]:{efforts:["low","medium","high","xhigh","max"],defaultEffort:"low"},[ie]:{efforts:[],defaultEffort:void 0},[Ue]:{efforts:[],defaultEffort:void 0},[Oo]:{efforts:["none","medium","high"],defaultEffort:"none"},[Ne]:{efforts:["none","high"],defaultEffort:"none"},[ne]:{efforts:[],defaultEffort:void 0},[me]:{efforts:[],defaultEffort:void 0},[to]:{efforts:[],defaultEffort:void 0},[ge]:{efforts:["none","minimal","low","medium","high","xhigh","max"],defaultEffort:"none"},[Ee]:{efforts:["none","minimal","low","medium","high","xhigh","max"],defaultEffort:"none"},[we]:{efforts:[],defaultEffort:void 0},[Jo]:{efforts:[],defaultEffort:void 0},[_o]:{efforts:[],defaultEffort:void 0},[ke]:{efforts:[],defaultEffort:void 0},[Ge]:{efforts:[],defaultEffort:void 0},[U]:{efforts:[],defaultEffort:void 0},[ve]:{efforts:[],defaultEffort:void 0},[no]:{efforts:["low","medium","high","xhigh","max"],defaultEffort:"low"},[io]:{efforts:["none","low","medium","high","xhigh","max"],defaultEffort:"none"},[ro]:{efforts:["none","low","medium","high","xhigh","max"],defaultEffort:"none"},[so]:{efforts:["low","medium","high","xhigh","max"],defaultEffort:"low"},[ao]:{efforts:["low","medium","high","xhigh","max"],defaultEffort:"low"},[lo]:{efforts:["low","medium","high","xhigh"],defaultEffort:"low"},[po]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"medium"},[co]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"medium"},[Oe]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"high"},[uo]:{efforts:["max","high","low","none"],defaultEffort:"none"},[ho]:{efforts:["high","medium","low"],defaultEffort:"medium"},[Yo]:{efforts:[],defaultEffort:void 0},[Qo]:{efforts:["high","medium","low","none"],defaultEffort:"none"},[en]:{efforts:["high","medium","none"],defaultEffort:"none"},[tn]:{efforts:["high","medium","none"],defaultEffort:"none"},[Me]:{efforts:["xhigh","high","medium","low","minimal"],defaultEffort:"xhigh"},[Se]:{efforts:["max","xhigh","high","medium","low","minimal"],defaultEffort:"medium"}},Ai=[U,ve],wr=[fo,mo,go,Eo,ie,Ue,Oo,we,ke,Ge,no,io,ro,so,ao,lo,po,co,Oe,uo,ho,Yo,en,tn,Me,Se,Ve,rn,So,ln,Si,pn,cn,un,hn,_n,dn,fn,mn,gn,En,On,Mn,Sn,vn,Ln,Fe,Cn,vo,vi,Li,Tn,Rn,An,Pn,xn,In,yn,Dn,Ci,z,Le,Ce,Lo,sn,an,bn,Nn,wn,me,Ne,ne,U,ve,oo],Pi=20,ha=50,_a=1e3,da=10;function Te(o){return o.trim().endsWith(":free")}function $e(o){return wr.some(e=>o.includes(e))}function kn(o){let e=o.trim(),t=Object.prototype.hasOwnProperty.call(be,e)?be[e]:void 0;return t?t.efforts:e===re||e===z||e===Le?pa:e===Ce?ca:e===Fe||e===vo?ua:e===He?sa:e===Be?aa:e===We?la:ra}function Gn(o){let e=o.trim(),t=Object.prototype.hasOwnProperty.call(be,e)?be[e]:void 0;return t?t.defaultEffort:e===re||e===z||e===Le?"low":e===Ke||e===Lo||e===So||e===Fe||e===Ce||e===He||e===Be||e===We?"none":void 0}function xi(o,e){let t=o.trim(),n=Object.prototype.hasOwnProperty.call(be,t)?be[t]:void 0,i=e??Gn(o);if(n)return i&&n.efforts.includes(i)?i:n.defaultEffort;if(!i)return;if(t===re||t===z||t===Le)return i==="high"?"high":i==="max"||i==="xhigh"?"max":"low";if(kn(o).includes(i))return i;if(t===He)return i==="max"?"xhigh":"none";if(t===Be){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===Ce){if(i==="minimal"||i==="medium")return"low";if(i==="xhigh")return"high"}return i}var Co="https://api.z.ai/api/paas/v4/chat/completions",Un="glm-5.3",To="glm-5.3-flash",se="glm-5.3-flashx",ae="glm-5.2",Ii="glm-5.1",yi="glm-5",Di="glm-5-turbo",Vn="glm-5v-turbo",bi="glm-4.7",Ni="glm-4.7-FlashX",wi="glm-4.7-Flash",ki="glm-4.6",Fn="glm-4.6V",Kn="glm-4.6V-FlashX",Re="glm-4.6V-Flash",fa=["none","minimal","low","medium","high","xhigh","max"],ma=["low","high","max"];function ze(o){return o===Un||o===To||o===se}function Xe(o){return ze(o)?ma:o===ae?fa:[]}function Hn(o){return Xe(o).length>0}function kr(o){return ze(o)?"low":o===ae?"none":void 0}function Ro(o,e){if(!Hn(o))return;let t=e??kr(o);return ze(o)?t==="high"?"high":t==="max"||t==="xhigh"?"max":"low":t==="none"||t==="minimal"?"none":t==="low"||t==="medium"||t==="high"?"high":"max"}var Gr=[se,To,Vn,Fn,Kn,Re];function qe(o){return Gr.includes(o)}function Gi(o){let e=o.toLowerCase();return e.startsWith("glm-5.3")||e.startsWith("glm-4.6")}var Ao="https://api.x.ai/v1/chat/completions",je="grok-4.6",Ze="grok-4.7",Je="grok-4.5",B="grok-4.3",Bn="grok-4.20-0309-reasoning",Wn="grok-4.20-0309-non-reasoning",Ur="grok-4-1-fast-reasoning",Vr="grok-4-1-fast-non-reasoning",ga=[Ur,Vr],Fr=[je,Ze,Je,B,Bn,Wn];function Ye(o){return Fr.includes(o)}function $n(o){return Qe(o).length>0}function Qe(o){return o===je||o===Ze?["low","medium","high","xhigh"]:o===Je?["low","medium","high"]:o===B?["none","low","medium","high"]:[]}function Kr(o){return Qe(o).includes("none")}function zn(o){return o===Ze||o===je||o===Je?"low":Kr(o)?"none":void 0}function Po(o,e){return $n(o)?e===void 0?zn(o):Qe(o).includes(e)?e:e==="none"?"low":"high":void 0}var et="https://api.moonshot.ai/v1/chat/completions",xo="kimi-k3",Io="kimi-k2.7-code",yo="kimi-k2.7-code-highspeed",X="kimi-k2.6",Ui="kimi-k2.5",Do="kimi-k3.1-pro",bo="kimi-k3.1-pro-highspeed",Ea=[Ui],Oa={[Do]:["low","high","max"],[bo]:["low","high","max"],[xo]:["low","high","max"]},Hr=[xo,Io,yo,X,Ui,Do,bo],Br=[Io,yo];function tt(o){return Hr.includes(o)}function No(o){return Br.includes(o)}function le(o){return Oa[o]??[]}function ot(o){return pe(o)?"max":void 0}function pe(o){return le(o).length>0}var $r="https://api.deepseek.com",wo=`${$r}/chat/completions`,Xn="deepseek-flash",Ae="deepseek-v4-flash",qn="deepseek-v4-pro",nt="deepseek-v4-flash-vision-exp",Wr=["none","low","high","max"],Ma=["none","high","max"],zr="deepseek-chat",Xr="deepseek-reasoner",Fi=[Xn,Ae,qn,nt],qr=[Xn,nt],Sa=[zr,Xr];function ko(o){return o===Xn||o===Ae||o===nt?Wr:o===qn?Ma:[]}function Ki(o){return qr.includes(o)}function jr(o){return ko(o).length>0}function Vi(o){return jr(o)?"none":void 0}function Hi(o,e){let t=ko(o);if(t.length===0)return;let n=e??Vi(o);return n&&t.includes(n)?n:o===qn&&n==="low"?"high":Vi(o)}var Zr="https://api.mistral.ai/v1",Go=`${Zr}/chat/completions`,Bi="ministral-3b-2512",Wi="ministral-8b-2512",$i="ministral-14b-2512",q="mistral-small-latest",zi="mistral-small-2603",jn="mistral-medium-3-5",Jr="mistral-medium-2508",Xi="mistral-large-latest",qi="mistral-large-2512",Yr="zai-glm-5-3",ji=[q,Bi,Wi,$i,jn,Xi,qi,zi,Yr],va=[Jr],Qr=[q,jn],es=[q,Bi,Wi,$i,zi,jn,Xi,qi];function Uo(o){return Qr.includes(o)}function Zi(o){return o==="none"||o==="high"}function Ji(o){return es.includes(o)}var ts="https://api.sakana.ai/v1",Vo=`${ts}/chat/completions`,it="fugu",os="fugu-ultra",ns="fugu-ultra-v1.1",Pe="sakana-namazu",is="fugu-ultra-20260615",Yi=[it,ns,Pe],rs=[Pe];function Qi(o){return rs.includes(o)}var La=[os,is];var ss="https://api.platform.preferredai.jp/v1",Fo=`${ss}/chat/completions`,rt="plamo-3.0-prime",as="plamo-2.2-prime",er=[rt],Ca=[as];var C={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Zn={[C.VERY_SHORT]:40,[C.SHORT]:100,[C.MEDIUM]:200,[C.LONG]:300,[C.VERY_LONG]:1e3,[C.DEEP]:5e3},tr=5e3,or={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 I(o){return o?Zn[o]??tr:tr}var Ta="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",Ra=`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
|
|
11
|
-
`);i=l.pop()||"";for(let p of l){let c=p.trim();if(!c||c.startsWith(":")||!c.startsWith("data:"))continue;let h=c.slice(5).trim();if(h==="[DONE]"){r=!0;break}e(h)}}};async function X(o,e,t={}){let n="";return await Yr(o,i=>{let r=Jr(i,t.onJsonError);if(!r)return;t.throwOnApiError&&ji(r);let s=Bn(r.choices?.[0]?.delta?.content);s&&(e(s),n+=s)}),n}async function G(o,e,t={}){let n=[],i=new Map,r="",s="",a,l,p=t.appendTextBlock??M.append;await Yr(o,_=>{let f=Jr(_,t.onJsonError);if(!f)return;t.throwOnApiError&&ji(f);let v=f.choices?.[0];typeof v?.finish_reason=="string"&&(a=v.finish_reason),f.usage&&(l=f.usage);let d=v?.delta,E=Bn(d?.content);E&&(e(E),p(n,E),r+=E);let k=Bn(d?.reasoning_content);k&&(s+=k),d?.tool_calls&&d.tool_calls.forEach(g=>{let L=i.get(g.index)??{id:g.id,type:g.type,name:g.function?.name,args:""};g.id&&(L.id=g.id),g.type&&(L.type=g.type),g.function?.name&&(L.name=g.function.name),L.args+=g.function?.arguments||"",i.set(g.index,L)})});let c=Array.from(i.entries()).sort((_,f)=>_[0]-f[0]).map(([_,f])=>({type:"tool_use",id:f.id,name:f.name,input:Ae(f.args,t.onJsonError)})),h=[...n,...c],u=Array.from(i.entries()).sort((_,f)=>_[0]-f[0]).map(([_,f])=>({id:f.id,type:"function",function:{name:f.name,arguments:f.args}})),m={role:"assistant",content:r,...s?{reasoning_content:s}:{},...u.length>0?{tool_calls:u}:{}};return{blocks:h,stop_reason:c.length?"tool_use":"end",truncated:a==="length",finish_reason:a,usage:l,...t.preserveAssistantMessage?{assistant_message:m}:{}}}function V(o,e={}){e.throwOnApiError&&ji(o);let t=o?.choices?.[0],n=[],i=Bn(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:Ae(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 _a=[{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."}],P=class extends Error{constructor(e,t,n){super(t),this.name="OpenAICompatibleEndpointError",this.code=e,this.status=n}};function Qr(o){let e;try{e=new URL(o.trim())}catch{throw new P("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 P("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 P("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 es(o){let{modelsUrl:e}=Qr(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 P("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 P("aborted","The models request was aborted by the caller.");if(!l.ok)throw new P("http",`Model listing failed with HTTP ${l.status}.`,l.status);let p;try{p=await l.json()}catch{throw new P("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(c=>c&&typeof c=="object"&&"id"in c&&typeof c.id=="string"))throw new P("invalid-response","The models response must contain data with model IDs.");if(i)throw new P("aborted","The models request was aborted by the caller.");return[...new Set(p.data.map(c=>c.id))]}catch(a){throw i==="caller"?new P("aborted","The models request was aborted by the caller."):i==="timeout"?new P("timeout",`The models request timed out after ${t} ms.`):a instanceof P?a:new P("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 fa(o){let e=Date.now();try{let t=await es(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 P?t:new P("network","Could not reach the models endpoint. In a browser, this is usually a CORS restriction or the server is not running.")}}}var F=(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=M.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=M.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 ma="https://openrouter.ai/api/v1/models",ga=2,Ea=12e3,Oa=1,Ma=10;function Zi(o){return o instanceof Error?o.message:String(o)}function Wn(o,e){return typeof o!="number"||!Number.isFinite(o)?e:Math.max(1,Math.floor(o))}function Sa(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 ts(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 os(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 va(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 Sa(n)}async function La({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 ts(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 os(a)};try{await a.json()}catch(l){return{id:o,ok:!1,reason:`JSON parse failed: ${Zi(l)}`}}return{id:o,ok:!0}}catch(a){return{id:o,ok:!1,reason:Zi(a)}}}async function Ca(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 Ta(o){let e=o.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=o.modelsEndpoint||ma,n=o.endpoint||eo,i=Wn(o.timeoutMs,Ea),r=Wn(o.concurrency,ga),s=Wn(o.maxCandidates,Oa),a=Wn(o.maxWorking,Ma),l=await ts(t,{method:"GET"},i);if(!l.ok)throw new Error(await os(l));let p;try{p=await l.json()}catch(_){throw new Error(`JSON parse failed: ${Zi(_)}`)}let c=va(p).filter(_=>ve(_)).slice(0,s),h=await Ca(c,r,_=>La({modelId:_,apiKey:e,endpoint:n,timeoutMs:i,appName:o.appName,appUrl:o.appUrl})),u=h.filter(_=>_.ok).map(_=>_.id).slice(0,a),m=h.filter(_=>!_.ok).map(_=>({id:_.id,reason:_.reason||"Unknown error"}));return{working:u,failed:m,fetchedAt:Date.now()}}function ns(o){return o.map(e=>({role:bo(e.role),content:e.provider_content??e.content}))}function is(o){return o.map(e=>{if(e.provider_content)return{role:bo(e.role),content:e.provider_content};if(typeof e.content=="string")return{role:bo(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:Ra(n.image_url.url)}}}return n}).filter(n=>n);return{role:bo(e.role),content:t}}return{role:bo(e.role),content:[]}})}function bo(o){switch(o){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}function Ra(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 ut=class{constructor(e,t=U,n=U,i=[],r=[],s,a){this.provider="claude";if(this.apiKey=e,this.model=t||U,this.visionModel=n||U,this.tools=i,this.mcpServers=r,this.responseLength=s,this.reasoningEffort=a,!Qt.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(u=>u.role==="system")?.content??"",s=e.filter(u=>u.role!=="system"),a=s.some(u=>Array.isArray(u.content)&&u.content.some(m=>m.type==="image_url"||m.type==="image")),l={model:t,system:r,messages:a?is(s):ns(s),stream:n,max_tokens:i!==void 0?i:x(this.responseLength)},p=this.reasoningEffort??Bo(t);p!==void 0&&H(t).includes(p)&&(l.output_config={effort:p}),this.tools.length&&(l.tools=this.tools.map(u=>({name:u.name,description:u.description,input_schema:u.parameters})),l.tool_choice={type:"auto"}),this.mcpServers.length>0&&(l.mcp_servers=this.mcpServers);let c={"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"};return this.mcpServers.length>0&&(c["anthropic-beta"]="mcp-client-2025-04-04"),await O.post(ci,l,c)}async parseStream(e,t){let n=e.body.getReader(),i=new TextDecoder,r=[],s=new Map,a=new Map,l,p,c="";for(;;){let{done:u,value:m}=await n.read();if(u)break;c+=i.decode(m,{stream:!0});let _;for(;(_=c.indexOf(`
|
|
12
|
-
`))!==-1;){let f=c.slice(0,
|
|
13
|
-
`);h=k.pop()||"";for(let g=0;g<k.length;g++){let L=k[g].trim();if(L.startsWith("event:"))u=L.slice(6).trim();else if(L.startsWith("data:"))m=L.slice(5).trim();else if(L===""&&u&&m){let D;try{D=JSON.parse(m)}catch(y){t.onJsonError?.(m,y),console.warn("Failed to parse SSE data:",m),u="",m="";continue}as(D,u),Pa(u,D,e,r,s,a,y=>{y.responseStatus!==void 0&&(l=y.responseStatus),y.incompleteDetails!==void 0&&(p=y.incompleteDetails),y.usage!==void 0&&(c=y.usage)}),u="",m=""}}}let _=Array.from(s.values()).map(d=>({type:"tool_use",id:d.id,name:d.name,input:Ae(d.arguments,t.onJsonError)})),f=Array.from(a.values()),v=M.getFullText(r);return{blocks:[...r,..._],stop_reason:_.length?"tool_use":"end",truncated:l==="incomplete",response_status:l,incomplete_details:p,usage:c,...f.length>0?{assistant_message:{role:"assistant",content:v,provider_content:f}}:{}}}function Pa(o,e,t,n,i,r,s){switch(o){case"response.output_item.added":rs(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),M.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":rs(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),M.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),M.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(ss(e,"completed"));break;case"response.incomplete":s(ss(e,"incomplete"));break;default:break}}function rs(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 ss(o,e){let t=o?.response??o;return{responseStatus:t?.status??e,incompleteDetails:t?.incomplete_details??null,usage:t?.usage}}function ls(o,e={}){as(o);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:Ae(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 ps({tools:o,mcpServers:e,isResponsesAPI:t}){let n=[];return o.length>0&&n.push(...F(o,t?"responses":"chat-completions")),e.length>0&&t&&n.push(...Aa(e)),n}function Aa(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 xa={[C.VERY_SHORT]:800,[C.SHORT]:1200,[C.MEDIUM]:2e3,[C.LONG]:3e3,[C.VERY_LONG]:8e3,[C.DEEP]:25e3},Ia={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3,max:25e3},ya=new Set(["openai-compatible","deepseek","mistral","sakana","plamo"]);function Da(o){return o.type!=="json_schema"?o:{type:o.type,...o.json_schema}}function cs({provider:o,endpoint:e,messages:t,model:n,stream:i,tools:r,mcpServers:s,responseLength:a,verbosity:l,reasoning_effort:p,enableReasoningSummary:c,responseFormat:h,chatTemplateThinking:u,maxTokens:m}){(n===A||o==="openai"&&n===R)&&(!p||p==="none"||p==="minimal")&&(p="low");let _=e===w;if(o==="openai"&&n===R&&(r.length>0||s.length>0)&&!_)throw new Error("GPT-6.1 Sol tool calling requires the OpenAI Responses API endpoint: "+w+". Custom endpoints use Chat Completions and cannot be used with this model's tools.");Na(e,s);let f={model:n,stream:i},v=ba({provider:o,model:n,responseLength:a,reasoning_effort:p,maxTokens:m});_?v!==void 0&&(f.max_output_tokens=v):v!==void 0&&(us(o)?f.max_tokens=v:f.max_completion_tokens=v),_?f.input=wa(t):f.messages=o==="mistral"?ka(t):t,_e(n)&&(_?(p&&(f.reasoning={...f.reasoning,effort:p},c&&(f.reasoning.summary="auto")),l&&(f.text={...f.text,format:{type:"text"},verbosity:l})):(p&&(f.reasoning_effort=p),l&&(f.verbosity=l))),h&&(_?f.text={...f.text,format:Da(h)}:f.response_format=h),o==="mistral"&&xo(n)&&p&&Ui(p)&&(f.reasoning_effort=p),o==="plamo"&&p&&(f.reasoning_effort=p),o==="deepseek"&&p&&(f.thinking={type:p==="none"?"disabled":"enabled"},p!=="none"&&(f.reasoning_effort=p)),o==="sakana"&&u!==void 0&&(f.chat_template_kwargs={thinking:u});let d=ps({tools:r,mcpServers:s,isResponsesAPI:_});return d.length>0&&(f.tools=d,_||(f.tool_choice="auto")),f}function ba({provider:o,model:e,responseLength:t,reasoning_effort:n,maxTokens:i}){if(i!==void 0)return i;let r=us(o)?t!==void 0?x(t):void 0:x(t);if(o!=="openai"||!_e(e)||t===void 0)return r;let s=n??Ft(e);return Math.max(r??0,xa[t],Ia[s])}function Na(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 wa(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 ka(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 us(o){return ya.has(o)}var I=class{constructor(e,t=de,n=de,i,r=q,s=[],a,l,p,c=!1,h="openai",u=!0,m,_){this.provider=h,this.apiKey=e,this.model=t,this.tools=i||[];let f=h==="openai"&&(t===R||n===R)&&(this.tools.length>0||s.length>0);if(this.endpoint=(t===A||n===A||f)&&r===q?w:r,this.mcpServers=s,this.responseLength=a,this.verbosity=l,this.reasoning_effort=p,this.enableReasoningSummary=c,this.responseFormat=m,this.chatTemplateThinking=_,u&&!kt.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 $n(i,t);return M.getFullText(s.blocks)}return this.handleStream(i,t)}catch(s){throw console.error("[processChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse: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 $n(i,t);return M.getFullText(s.blocks)}return this.handleStream(i,t)}catch(s){throw console.error("[processVisionChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse: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?$n(e,n):ls(await e.json()):t?this.parseStream(e,n):this.parseOneShot(await e.json())}async callOpenAI(e,t,n=!1,i){let r=cs({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 O.post(this.endpoint,r,s)}async handleStream(e,t){return X(e,t,{throwOnApiError:!0})}async parseStream(e,t){return G(e,t,{appendTextBlock:M.addTextBlock,throwOnApiError:!0})}parseOneShot(e){return V(e,{throwOnApiError:!0})}};var dt=class extends I{constructor(e,t=Te,n=t,i,r=Ro,s,a){let l=Di(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 _t=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:at,supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"explicit"}),i=e.tools;return new dt(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"deepseek"}getSupportedModels(){return[...Ii]}getDefaultModel(){return Te}supportsVision(){return!0}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return yi(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 Ro}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var hs=(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"]}}),zn=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 O.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:[hs(e)],failures:[]}}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),{schemas:[hs(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 ds(o){switch(o){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}function _s(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=ds(s.role);if(s.tool_calls){r();let l=s.tool_calls.map(p=>gs(p,e));l.length>0&&t.push({role:"model",parts:l});continue}if(s.role==="tool"){r(),Os(t,Es(s,e));continue}a!==n&&r(),n=a,i.push({text:s.content})}return r(),t}async function fs(o,e={}){let t=e.imageFetcher??O.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=ds(l.role);if(l.tool_calls){a();let c=l.tool_calls.map(h=>gs(h,e));c.length>0&&i.push({role:"model",parts:c});continue}if(l.role==="tool"){a(),Os(i,Es(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 c of l.content)if(c.type==="text")s.push({text:c.text});else if(c.type==="image_url")try{let u=await(await t(c.image_url.url)).blob(),m=await n(u);s.push({inlineData:{mimeType:u.type||"image/jpeg",data:m.split(",")[1]}})}catch(h){throw console.error("Error processing image:",h),new Error(`Failed to process image: ${h.message}`)}}}return a(),i}function ms(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 gs(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 Es(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:Va(Ga(o.content))}}}function Os(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 Ga(o){try{return JSON.parse(o)}catch{return o}}function Va(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 Ua(o,e){return[...o,...e].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}function Ms(o,e){let t=Ua(o,e);if(t.length!==0)return{tools:[{functionDeclarations:t}],toolConfig:{functionCallingConfig:{mode:"AUTO"}}}}function Ss(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 ft=class{constructor(e,t=ee,n=ee,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,!Ut.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=Kt(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=zn.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=Ss(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 M.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 M.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(g=>Array.isArray(g.content)&&g.content.some(L=>L?.type==="image_url"||L?.inlineData))?await fs(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}):_s(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}),generationConfig:{maxOutputTokens:i!==void 0?i:x(this.responseLength)}},l=ms(e);l&&(a.systemInstruction=l);let p=this.resolveThinkingConfig(t);p&&(a.generationConfig.thinkingConfig=p);let c=[];if(this.mcpServers.length>0)try{await this.initializeMCPSchemas(),c=this.mcpToolSchemas}catch(g){console.warn("MCP initialization failed, skipping MCP tools:",g)}let h=Ms(this.tools,c);h&&Object.assign(a,h);let u=async(g,L)=>{let D=n?"streamGenerateContent":"generateContent",y=n?"?alt=sse":"",Ps=`${Qn}/${g}/models/${t}:${D}${y}${y?"&":"?"}key=${this.apiKey}`;return O.post(Ps,L)},m=/flash[-_]lite/.test(t),_=this.isGemma4Model(t),f=/gemini-2\.5/.test(t),v=/^gemini-3(?:\.[0-9]+)?-/.test(t),d=m||_||f||v,E=d?"v1beta":"v1",k=async()=>{try{let g=E==="v1"?a:this.adaptKeysForApi(a);return await u(E,g)}catch(g){let L=/Unknown name|Cannot find field|404/.test(g?.message||"")||g?.status===404;if(!d&&L)try{return await u("v1beta",this.adaptKeysForApi(a))}catch(D){throw D instanceof Error&&(D.cause=g),D}throw g}};try{return await k()}catch(g){throw g.body&&(console.error("Gemini API Error Details:",g.body),console.error("Request Body:",JSON.stringify(a,null,2))),g}}createFunctionCallBlock(e){let t=e.functionCall??e.function_call;if(!t)return;let 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=h=>{if(!h||h==="[DONE]")return;let u;try{u=JSON.parse(h)}catch{return}for(let m of u.candidates??[])for(let _ of m.content?.parts??[]){this.shouldExposeTextPart(_,n)&&(t(_.text),M.addTextBlock(s,_.text));let f=this.createFunctionCallBlock(_);f&&a.push(f);let v=this.createFunctionResponseBlock(_);v&&a.push(v)}};for(;;){let{done:h,value:u}=await i.read();if(h)break;l+=r.decode(u,{stream:!0});let m;for(;(m=l.indexOf(`
|
|
14
|
-
`))!==-1;){let
|
|
10
|
+
`;var xe="gemini-nano",nr=20;var ce=class extends Error{constructor(t,n,i){super(`HTTP ${t}: ${n}`);this.status=t;this.statusText=n;this.body=i;this.name="HttpError"}},Ko=class Ko{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},c=null;for(let h=0;h<=s;h++)try{let u=typeof AbortController<"u",m=u?new AbortController:void 0,d=u?setTimeout(()=>m.abort(),r):void 0,f=await Ko.fetchImpl(e,{method:"POST",headers:p,body:typeof t=="string"?t:JSON.stringify(t),...m?{signal:m.signal}:{}});if(d&&clearTimeout(d),!f.ok){let v=await f.text();throw new ce(f.status,f.statusText,v)}return f}catch(u){if(c=u,u instanceof ce&&u.status>=400&&u.status<500)throw u;if(u instanceof Error&&u.name==="AbortError")throw new Error(`Request timeout after ${r}ms`);h<s&&await new Promise(m=>setTimeout(m,a*(h+1)))}throw c||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new ce(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",c=p?new AbortController:void 0,h=p?setTimeout(()=>c.abort(),i):void 0,u=await Ko.fetchImpl(e,{method:"GET",headers:t,...c?{signal:c.signal}:{}});if(h&&clearTimeout(h),!u.ok){let m=await u.text();throw new ce(u.status,u.statusText,m)}return u}catch(p){if(a=p,p instanceof ce&&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(c=>setTimeout(c,s*(l+1)))}throw a||new Error("Request failed")}};Ko.fetchImpl=(e,t)=>fetch(e,t);var O=Ko;var M=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 Aa=["happy","sad","angry","surprised","neutral"],ls=/\[([a-z]+)\]/i,ir=/\[[a-z]+\]\s*/gi,st=class{static extractEmotion(e){let t=e.match(ls);if(t){let n=t[1].toLowerCase(),i=e.replace(ir,"").trim();return{emotion:n,cleanText:i}}return{cleanText:e}}static isValidEmotion(e){return Aa.includes(e)}static cleanEmotionTags(e){return e.replace(ir,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function ps(o){let{emotion:e,cleanText:t}=st.extractEmotion(o);return e?{emotion:e,text:t}:{text:t}}function Pa(o){return o.map(e=>ps(e))}function xa(o){return o.emotion?st.addEmotionTag(o.emotion,o.text):o.text}async function Ia(o,e){let{blocks:t}=await o.chatOnce(e,!1,()=>{});return M.getFullText(t)}var cs=(o,e,t)=>{try{return JSON.parse(o)}catch(n){return t?.(o,n),e}},Ie=(o,e)=>o?cs(o,{},e):{};var us=(o,e)=>{try{return JSON.parse(o)}catch(t){if(e){e(o,t);return}throw t}},Jn=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(""):"",rr=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}`)},hs=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 c=p.trim();if(!c||c.startsWith(":")||!c.startsWith("data:"))continue;let h=c.slice(5).trim();if(h==="[DONE]"){r=!0;break}e(h)}}};async function j(o,e,t={}){let n="";return await hs(o,i=>{let r=us(i,t.onJsonError);if(!r)return;t.throwOnApiError&&rr(r);let s=Jn(r.choices?.[0]?.delta?.content);s&&(e(s),n+=s)}),n}async function V(o,e,t={}){let n=[],i=new Map,r="",s="",a,l,p=t.appendTextBlock??M.append;await hs(o,d=>{let f=us(d,t.onJsonError);if(!f)return;t.throwOnApiError&&rr(f);let v=f.choices?.[0];typeof v?.finish_reason=="string"&&(a=v.finish_reason),f.usage&&(l=f.usage);let _=v?.delta,E=Jn(_?.content);E&&(e(E),p(n,E),r+=E);let G=Jn(_?.reasoning_content);G&&(s+=G),_?.tool_calls&&_.tool_calls.forEach(g=>{let L=i.get(g.index)??{id:g.id,type:g.type,name:g.function?.name,args:""};g.id&&(L.id=g.id),g.type&&(L.type=g.type),g.function?.name&&(L.name=g.function.name),L.args+=g.function?.arguments||"",i.set(g.index,L)})});let c=Array.from(i.entries()).sort((d,f)=>d[0]-f[0]).map(([d,f])=>({type:"tool_use",id:f.id,name:f.name,input:Ie(f.args,t.onJsonError)})),h=[...n,...c],u=Array.from(i.entries()).sort((d,f)=>d[0]-f[0]).map(([d,f])=>({id:f.id,type:"function",function:{name:f.name,arguments:f.args}})),m={role:"assistant",content:r,...s?{reasoning_content:s}:{},...u.length>0?{tool_calls:u}:{}};return{blocks:h,stop_reason:c.length?"tool_use":"end",truncated:a==="length",finish_reason:a,usage:l,...t.preserveAssistantMessage?{assistant_message:m}:{}}}function F(o,e={}){e.throwOnApiError&&rr(o);let t=o?.choices?.[0],n=[],i=Jn(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:Ie(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 ya=[{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."}],P=class extends Error{constructor(e,t,n){super(t),this.name="OpenAICompatibleEndpointError",this.code=e,this.status=n}};function _s(o){let e;try{e=new URL(o.trim())}catch{throw new P("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 P("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 P("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 ds(o){let{modelsUrl:e}=_s(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 P("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 P("aborted","The models request was aborted by the caller.");if(!l.ok)throw new P("http",`Model listing failed with HTTP ${l.status}.`,l.status);let p;try{p=await l.json()}catch{throw new P("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(c=>c&&typeof c=="object"&&"id"in c&&typeof c.id=="string"))throw new P("invalid-response","The models response must contain data with model IDs.");if(i)throw new P("aborted","The models request was aborted by the caller.");return[...new Set(p.data.map(c=>c.id))]}catch(a){throw i==="caller"?new P("aborted","The models request was aborted by the caller."):i==="timeout"?new P("timeout",`The models request timed out after ${t} ms.`):a instanceof P?a:new P("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 Da(o){let e=Date.now();try{let t=await ds(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 P?t:new P("network","Could not reach the models endpoint. In a browser, this is usually a CORS restriction or the server is not running.")}}}var K=(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=M.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=M.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 ba="https://openrouter.ai/api/v1/models",Na=2,wa=12e3,ka=1,Ga=10;function sr(o){return o instanceof Error?o.message:String(o)}function Yn(o,e){return typeof o!="number"||!Number.isFinite(o)?e:Math.max(1,Math.floor(o))}function Ua(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 fs(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 ms(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 Va(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 Ua(n)}async function Fa({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 fs(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 ms(a)};try{await a.json()}catch(l){return{id:o,ok:!1,reason:`JSON parse failed: ${sr(l)}`}}return{id:o,ok:!0}}catch(a){return{id:o,ok:!1,reason:sr(a)}}}async function Ka(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 Ha(o){let e=o.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=o.modelsEndpoint||ba,n=o.endpoint||eo,i=Yn(o.timeoutMs,wa),r=Yn(o.concurrency,Na),s=Yn(o.maxCandidates,ka),a=Yn(o.maxWorking,Ga),l=await fs(t,{method:"GET"},i);if(!l.ok)throw new Error(await ms(l));let p;try{p=await l.json()}catch(d){throw new Error(`JSON parse failed: ${sr(d)}`)}let c=Va(p).filter(d=>Te(d)).slice(0,s),h=await Ka(c,r,d=>Fa({modelId:d,apiKey:e,endpoint:n,timeoutMs:i,appName:o.appName,appUrl:o.appUrl})),u=h.filter(d=>d.ok).map(d=>d.id).slice(0,a),m=h.filter(d=>!d.ok).map(d=>({id:d.id,reason:d.reason||"Unknown error"}));return{working:u,failed:m,fetchedAt:Date.now()}}function gs(o){return o.map(e=>({role:Ho(e.role),content:e.provider_content??e.content}))}function Es(o){return o.map(e=>{if(e.provider_content)return{role:Ho(e.role),content:e.provider_content};if(typeof e.content=="string")return{role:Ho(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:Ba(n.image_url.url)}}}return n}).filter(n=>n);return{role:Ho(e.role),content:t}}return{role:Ho(e.role),content:[]}})}function Ho(o){switch(o){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}function Ba(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 at=class{constructor(e,t=H,n=H,i=[],r=[],s,a){this.provider="claude";if(this.apiKey=e,this.model=t||H,this.visionModel=n||H,this.tools=i,this.mcpServers=r,this.responseLength=s,this.reasoningEffort=a,!Qt.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(u=>u.role==="system")?.content??"",s=e.filter(u=>u.role!=="system"),a=s.some(u=>Array.isArray(u.content)&&u.content.some(m=>m.type==="image_url"||m.type==="image")),l={model:t,system:r,messages:a?Es(s):gs(s),stream:n,max_tokens:i!==void 0?i:I(this.responseLength)},p=this.reasoningEffort??Zo(t);p!==void 0&&$(t).includes(p)&&(l.output_config={effort:p}),this.tools.length&&(l.tools=this.tools.map(u=>({name:u.name,description:u.description,input_schema:u.parameters})),l.tool_choice={type:"auto"}),this.mcpServers.length>0&&(l.mcp_servers=this.mcpServers);let c={"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"};return this.mcpServers.length>0&&(c["anthropic-beta"]="mcp-client-2025-04-04"),await O.post(mi,l,c)}async parseStream(e,t){let n=e.body.getReader(),i=new TextDecoder,r=[],s=new Map,a=new Map,l,p,c="";for(;;){let{done:u,value:m}=await n.read();if(u)break;c+=i.decode(m,{stream:!0});let d;for(;(d=c.indexOf(`
|
|
12
|
+
`))!==-1;){let f=c.slice(0,d).trim();if(c=c.slice(d+1),!f.startsWith("data:"))continue;let v=f.slice(5).trim();if(v==="[DONE]")break;let _=JSON.parse(v);if(_.type==="message_delta"&&(typeof _.delta?.stop_reason=="string"&&(l=_.delta.stop_reason),(_.delta?.stop_details!==void 0||_.stop_details!==void 0)&&(p=_.delta?.stop_details??_.stop_details)),_.type==="content_block_start"&&_.content_block&&typeof _.index=="number"&&s.set(_.index,{..._.content_block}),_.type==="content_block_delta"&&_.delta?.type==="text_delta"){t(_.delta.text),r.push({type:"text",text:_.delta.text});let E=s.get(_.index);E?.type==="text"&&(E.text=`${E.text??""}${_.delta.text}`)}if(_.type==="content_block_delta"&&_.delta?.type==="thinking_delta"){let E=s.get(_.index);E?.type==="thinking"&&(E.thinking=`${E.thinking??""}${_.delta.thinking??""}`)}if(_.type==="content_block_delta"&&_.delta?.type==="signature_delta"){let E=s.get(_.index);E?.type==="thinking"&&(E.signature=`${E.signature??""}${_.delta.signature??""}`)}if(_.type==="content_block_start"&&_.content_block?.type==="tool_use"?a.set(_.index,{id:_.content_block.id,name:_.content_block.name,args:""}):_.type==="content_block_start"&&_.content_block?.type==="mcp_tool_use"?a.set(_.index,{id:_.content_block.id,name:_.content_block.name,args:"",server_name:_.content_block.server_name}):_.type==="content_block_start"&&_.content_block?.type==="tool_result"?r.push({type:"tool_result",tool_use_id:_.content_block.tool_use_id,content:_.content_block.content??""}):_.type==="content_block_start"&&_.content_block?.type==="mcp_tool_result"&&r.push({type:"mcp_tool_result",tool_use_id:_.content_block.tool_use_id,is_error:_.content_block.is_error??!1,content:_.content_block.content??[]}),_.type==="content_block_delta"&&_.delta?.type==="input_json_delta"){let E=a.get(_.index);E&&(E.args+=_.delta.partial_json||"")}if(_.type==="content_block_stop"&&a.has(_.index)){let{id:E,name:G,args:g,server_name:L}=a.get(_.index),b=JSON.parse(g||"{}"),D=s.get(_.index);D&&(D.input=b),L?r.push({type:"mcp_tool_use",id:E,name:G,server_name:L,input:b}):r.push({type:"tool_use",id:E,name:G,input:b}),a.delete(_.index)}}}let h=r.some(u=>u.type==="tool_use"||u.type==="mcp_tool_use");return{blocks:r,providerContent:[...s.entries()].sort(([u],[m])=>u-m).map(([,u])=>u),stop_reason:h?"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 lt=class{createChatService(e){let t=e.model||this.getDefaultModel(),n=$(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 at(e.apiKey,t,i,e.tools??[],e.mcpServers??[],e.responseLength,e.reasoning_effort)}getProviderName(){return"claude"}getSupportedModels(){return[H,Bt,Wt,$t,zt,Xt,Ht,qt,jt,Zt,jo,Jt,Yt]}getDefaultModel(){return H}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Qt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function Ss(o,e){let t=o?.response??o,n=t?.error;if(!n&&t?.status!=="failed"&&e!=="error"&&e!=="response.failed")return;let i=typeof n=="string"?n:n?.message??o?.message??"The provider response failed.";throw new Error(`Provider response error: ${i}`)}async function Qn(o,e,t={}){let n=o.body.getReader(),i=new TextDecoder,r=[],s=new Map,a=new Map,l,p,c,h="",u="",m="";for(;;){let{done:_,value:E}=await n.read();if(_)break;h+=i.decode(E,{stream:!0});let G=h.split(`
|
|
13
|
+
`);h=G.pop()||"";for(let g=0;g<G.length;g++){let L=G[g].trim();if(L.startsWith("event:"))u=L.slice(6).trim();else if(L.startsWith("data:"))m=L.slice(5).trim();else if(L===""&&u&&m){let b;try{b=JSON.parse(m)}catch(D){t.onJsonError?.(m,D),console.warn("Failed to parse SSE data:",m),u="",m="";continue}Ss(b,u),Wa(u,b,e,r,s,a,D=>{D.responseStatus!==void 0&&(l=D.responseStatus),D.incompleteDetails!==void 0&&(p=D.incompleteDetails),D.usage!==void 0&&(c=D.usage)}),u="",m=""}}}let d=Array.from(s.values()).map(_=>({type:"tool_use",id:_.id,name:_.name,input:Ie(_.arguments,t.onJsonError)})),f=Array.from(a.values()),v=M.getFullText(r);return{blocks:[...r,...d],stop_reason:d.length?"tool_use":"end",truncated:l==="incomplete",response_status:l,incomplete_details:p,usage:c,...f.length>0?{assistant_message:{role:"assistant",content:v,provider_content:f}}:{}}}function Wa(o,e,t,n,i,r,s){switch(o){case"response.output_item.added":Os(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),M.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":Os(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),M.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),M.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(Ms(e,"completed"));break;case"response.incomplete":s(Ms(e,"incomplete"));break;default:break}}function Os(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 Ms(o,e){let t=o?.response??o;return{responseStatus:t?.status??e,incompleteDetails:t?.incomplete_details??null,usage:t?.usage}}function vs(o,e={}){Ss(o);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:Ie(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 Ls({tools:o,mcpServers:e,isResponsesAPI:t}){let n=[];return o.length>0&&n.push(...K(o,t?"responses":"chat-completions")),e.length>0&&t&&n.push(...$a(e)),n}function $a(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 za={[C.VERY_SHORT]:800,[C.SHORT]:1200,[C.MEDIUM]:2e3,[C.LONG]:3e3,[C.VERY_LONG]:8e3,[C.DEEP]:25e3},Xa={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3,max:25e3},qa=new Set(["openai-compatible","deepseek","mistral","sakana","plamo"]);function ja(o){return o.type!=="json_schema"?o:{type:o.type,...o.json_schema}}function Cs({provider:o,endpoint:e,messages:t,model:n,stream:i,tools:r,mcpServers:s,responseLength:a,verbosity:l,reasoning_effort:p,enableReasoningSummary:c,responseFormat:h,chatTemplateThinking:u,maxTokens:m}){(n===x||o==="openai"&&n===A)&&(!p||p==="none"||p==="minimal")&&(p="low"),o==="openai"&&n===R&&(p=p==="minimal"?"none":p??"low");let d=e===k;if(o==="openai"&&(n===A||n===R)&&(r.length>0||s.length>0)&&!d)throw new Error(`${n===R?"GPT-6.1 Terra":"GPT-6.1 Sol"} tool calling requires the OpenAI Responses API endpoint: `+k+". Custom endpoints use Chat Completions and cannot be used with this model's tools.");Ja(e,s);let f={model:n,stream:i},v=Za({provider:o,model:n,responseLength:a,reasoning_effort:p,maxTokens:m});d?v!==void 0&&(f.max_output_tokens=v):v!==void 0&&(Ts(o)?f.max_tokens=v:f.max_completion_tokens=v),d?f.input=Ya(t):f.messages=o==="mistral"?Qa(t):t,fe(n)&&(d?(p&&(f.reasoning={...f.reasoning,effort:p},c&&(f.reasoning.summary="auto")),l&&(f.text={...f.text,format:{type:"text"},verbosity:l})):(p&&(f.reasoning_effort=p),l&&(f.verbosity=l))),h&&(d?f.text={...f.text,format:ja(h)}:f.response_format=h),o==="mistral"&&Uo(n)&&p&&Zi(p)&&(f.reasoning_effort=p),o==="plamo"&&p&&(f.reasoning_effort=p),o==="deepseek"&&p&&(f.thinking={type:p==="none"?"disabled":"enabled"},p!=="none"&&(f.reasoning_effort=p)),o==="sakana"&&u!==void 0&&(f.chat_template_kwargs={thinking:u});let _=Ls({tools:r,mcpServers:s,isResponsesAPI:d});return _.length>0&&(f.tools=_,d||(f.tool_choice="auto")),f}function Za({provider:o,model:e,responseLength:t,reasoning_effort:n,maxTokens:i}){if(i!==void 0)return i;let r=Ts(o)?t!==void 0?I(t):void 0:I(t);if(o!=="openai"||!fe(e)||t===void 0)return r;let s=n??Vt(e);return Math.max(r??0,za[t],Xa[s])}function Ja(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: ${k}. MCP tools are only available in the Responses API endpoint.`)}function Ya(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 Qa(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 Ts(o){return qa.has(o)}var y=class{constructor(e,t=de,n=de,i,r=Z,s=[],a,l,p,c=!1,h="openai",u=!0,m,d){this.provider=h,this.apiKey=e,this.model=t,this.tools=i||[];let f=h==="openai"&&(t===A||n===A||t===R||n===R)&&(this.tools.length>0||s.length>0);if(this.endpoint=(t===x||n===x||f)&&r===Z?k:r,this.mcpServers=s,this.responseLength=a,this.verbosity=l,this.reasoning_effort=p,this.enableReasoningSummary=c,this.responseFormat=m,this.chatTemplateThinking=d,u&&!kt.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===k;try{if(r){let s=await Qn(i,t);return M.getFullText(s.blocks)}return this.handleStream(i,t)}catch(s){throw console.error("[processChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse: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===k;try{if(r){let s=await Qn(i,t);return M.getFullText(s.blocks)}return this.handleStream(i,t)}catch(s){throw console.error("[processVisionChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse: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===k?t?Qn(e,n):vs(await e.json()):t?this.parseStream(e,n):this.parseOneShot(await e.json())}async callOpenAI(e,t,n=!1,i){let r=Cs({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 O.post(this.endpoint,r,s)}async handleStream(e,t){return j(e,t,{throwOnApiError:!0})}async parseStream(e,t){return V(e,t,{appendTextBlock:M.addTextBlock,throwOnApiError:!0})}parseOneShot(e){return F(e,{throwOnApiError:!0})}};var pt=class extends y{constructor(e,t=Ae,n=t,i,r=wo,s,a){let l=Hi(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 ct=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:nt,supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"explicit"}),i=e.tools;return new pt(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"deepseek"}getSupportedModels(){return[...Fi]}getDefaultModel(){return Ae}supportsVision(){return!0}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ki(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 wo}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Rs=(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"]}}),ei=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 O.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:[Rs(e)],failures:[]}}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),{schemas:[Rs(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 As(o){switch(o){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}function Ps(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=As(s.role);if(s.tool_calls){r();let l=s.tool_calls.map(p=>ys(p,e));l.length>0&&t.push({role:"model",parts:l});continue}if(s.role==="tool"){r(),bs(t,Ds(s,e));continue}a!==n&&r(),n=a,i.push({text:s.content})}return r(),t}async function xs(o,e={}){let t=e.imageFetcher??O.get,n=e.blobToBase64??ol,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=As(l.role);if(l.tool_calls){a();let c=l.tool_calls.map(h=>ys(h,e));c.length>0&&i.push({role:"model",parts:c});continue}if(l.role==="tool"){a(),bs(i,Ds(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 c of l.content)if(c.type==="text")s.push({text:c.text});else if(c.type==="image_url")try{let u=await(await t(c.image_url.url)).blob(),m=await n(u);s.push({inlineData:{mimeType:u.type||"image/jpeg",data:m.split(",")[1]}})}catch(h){throw console.error("Error processing image:",h),new Error(`Failed to process image: ${h.message}`)}}}return a(),i}function Is(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 ys(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 Ds(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:tl(el(o.content))}}}function bs(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 el(o){try{return JSON.parse(o)}catch{return o}}function tl(o){return o===null?{content:null}:typeof o=="object"?o:{content:o}}function ol(o){return new Promise((e,t)=>{let n=new FileReader;n.onloadend=()=>e(n.result),n.onerror=t,n.readAsDataURL(o)})}function nl(o,e){return[...o,...e].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}function Ns(o,e){let t=nl(o,e);if(t.length!==0)return{tools:[{functionDeclarations:t}],toolConfig:{functionCallingConfig:{mode:"AUTO"}}}}function ws(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 ut=class{constructor(e,t=te,n=te,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,!Ft.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=Kt(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=ei.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=ws(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 M.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 M.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(g=>Array.isArray(g.content)&&g.content.some(L=>L?.type==="image_url"||L?.inlineData))?await xs(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}):Ps(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}),generationConfig:{maxOutputTokens:i!==void 0?i:I(this.responseLength)}},l=Is(e);l&&(a.systemInstruction=l);let p=this.resolveThinkingConfig(t);p&&(a.generationConfig.thinkingConfig=p);let c=[];if(this.mcpServers.length>0)try{await this.initializeMCPSchemas(),c=this.mcpToolSchemas}catch(g){console.warn("MCP initialization failed, skipping MCP tools:",g)}let h=Ns(this.tools,c);h&&Object.assign(a,h);let u=async(g,L)=>{let b=n?"streamGenerateContent":"generateContent",D=n?"?alt=sse":"",Ks=`${ri}/${g}/models/${t}:${b}${D}${D?"&":"?"}key=${this.apiKey}`;return O.post(Ks,L)},m=/flash[-_]lite/.test(t),d=this.isGemma4Model(t),f=/gemini-2\.5/.test(t),v=/^gemini-3(?:\.[0-9]+)?-/.test(t),_=m||d||f||v,E=_?"v1beta":"v1",G=async()=>{try{let g=E==="v1"?a:this.adaptKeysForApi(a);return await u(E,g)}catch(g){let L=/Unknown name|Cannot find field|404/.test(g?.message||"")||g?.status===404;if(!_&&L)try{return await u("v1beta",this.adaptKeysForApi(a))}catch(b){throw b instanceof Error&&(b.cause=g),b}throw g}};try{return await G()}catch(g){throw g.body&&(console.error("Gemini API Error Details:",g.body),console.error("Request Body:",JSON.stringify(a,null,2))),g}}createFunctionCallBlock(e){let t=e.functionCall??e.function_call;if(!t)return;let 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=h=>{if(!h||h==="[DONE]")return;let u;try{u=JSON.parse(h)}catch{return}for(let m of u.candidates??[])for(let d of m.content?.parts??[]){this.shouldExposeTextPart(d,n)&&(t(d.text),M.addTextBlock(s,d.text));let f=this.createFunctionCallBlock(d);f&&a.push(f);let v=this.createFunctionResponseBlock(d);v&&a.push(v)}};for(;;){let{done:h,value:u}=await i.read();if(h)break;l+=r.decode(u,{stream:!0});let m;for(;(m=l.indexOf(`
|
|
14
|
+
`))!==-1;){let d=l.slice(0,m);if(l=l.slice(m+1),d.endsWith("\r")&&(d=d.slice(0,-1)),!d.trim()){p("");continue}d.startsWith("data:")&&(d=d.slice(5).trim()),d&&p(d)}}return l&&p(l),{blocks:[...s,...a],stop_reason:a.some(h=>h.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 ht=class{createChatService(e){let t=e.model||this.getDefaultModel();if(e.reasoning_effort!==void 0&&!fi(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 ut(e.apiKey,t,n,e.tools||[],e.mcpServers||[],e.responseLength,Kt(t,e.reasoning_effort))}getProviderName(){return"gemini"}getSupportedModels(){return[...qo]}getDefaultModel(){return te}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ft.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function il(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var _t=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 xe}getVisionModel(){return xe}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=il();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(m=>m.role==="system").map(m=>m.content).join(`
|
|
15
15
|
`),l=e.filter(m=>m.role==="user"||m.role==="assistant").slice(-20),p=this.findLastUserMessageIndex(l);if(p===-1)throw new Error("No user message found in the provided messages.");let c=l[p],h=l.slice(0,p);if(this.sessionMode==="persistent")return this.generatePersistentResponse(i,a,h,c.content,r,t,n);let u=await this.createSession(i,a,h,r);try{return await this.promptSession(u,c.content,t,n)}finally{try{u.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),c=p===this.liveSession&&this.isHistoryCompatible(n,this.consumedTranscript);this.persistentSessionKey=l;try{let h=await this.promptSession(p,i,s,a);return this.recordConsumedTranscript(n,i,h,c),h}catch(h){if(!this.isQuotaExceededError(h))throw this.destroyPersistentLiveSession(),h;this.destroyPersistentLiveSession(),p=await this.getPersistentLiveSession(e,t,[],r),this.persistentSessionKey=l;try{let u=await this.promptSession(p,i,s,a);return this.recordConsumedTranscript([],i,u,!1),u}catch(u){throw this.destroyPersistentLiveSession(),u}}}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:c}=await s.read();if(p)break;let h=String(c??"");l==="unknown"&&a!==""&&(l=h.startsWith(a)?"cumulative":"delta");let u=l==="cumulative",m=u?h.slice(a.length):h;a=u?h:a+h,m&&i(m)}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=Hn[this._responseLength];if(e)switch(this._responseLength){case C.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 C.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 C.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 C.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 C.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 C.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 Et=class{createChatService(e){return new gt({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,initialPrompts:e.initialPrompts,responseLength:e.responseLength,sessionMode:e.sessionMode})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[Pe]}getDefaultModel(){return Pe}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var Ot=class{constructor(e,t=$,n=$,i,r=nt,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 c=se(t);if(p!==void 0&&!c.includes(p))throw new Error(`Model ${t} does not support reasoning_effort: ${p}.`);this.reasoningEffort=p??st(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(!rt(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(!rt(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 O.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:x(this.responseLength);s!==void 0&&(Ce(t)?r.max_completion_tokens=s:r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),Ce(t)&&(r.reasoning_effort=this.reasoningEffort??st(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(nt)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveEffectiveThinking(e){if(Ce(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 F(this.tools,"chat-completions")}async parseStream(e,t){return G(e,t,{preserveAssistantMessage:!0,onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return V(e,{preserveAssistantMessage:!0})}};var Mt=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 Ot(e.apiKey,n,i,r,t,e.responseLength,e.responseFormat,s,a)}getProviderName(){return"kimi"}getSupportedModels(){return[it,Lo,Co,$,Vn]}getDefaultModel(){return $}getDefaultVisionModel(){return $}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return rt(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 nt}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveThinking(e,t,n){if(Ce(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=se(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??st(e)??n[0];if(!n.includes(i))throw new Error(`Model ${e} supports reasoning_effort values: ${n.join(", ")}.`);return i}};var St=class extends I{constructor(e,t=z,n=t,i,r=Ao,s,a){super(e,t,n,i,r,[],s,void 0,a,!1,"mistral",!1)}};var vt=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=xo(t)?e.reasoning_effort:void 0;return new St(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"mistral"}getSupportedModels(){return[...Fi]}getDefaultModel(){return z}getDefaultVisionModel(){return z}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ki(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 Ao}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Lt=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 I(...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 Ct=class{createChatService(e){let t=this.optimizeGPT5Options(e),n=T({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:c=>this.supportsVisionForModel(c),validate:"resolved"}),i=t.tools,r=t.mcpServers??[],s=t.model||this.getDefaultModel(),a=!1;if(r.length>0||s===A||n===A)a=!0;else if(s===b||n===b||s===N||n===N)a=(t.gpt5EndpointPreference||"responses")!=="chat"||t.reasoning_effort!=="none";else if(Jn(s))a=!0;else if(s===R||n===R){let c=t.gpt5EndpointPreference||"responses";a=(i?.length??0)>0||c!=="chat"}else _e(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 I(...p)}getProviderName(){return"openai"}getSupportedModels(){return[le,xe,Ie,ye,pe,ce,j,R,A,b,N,Z,J,Y,ue,he,Q,No,wo,ko,de,Go,qn,jn,"o1"]}getDefaultModel(){return le}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return kt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!_e(t))return e;let n={...e};if(e.gpt5Preset){let i=zi[e.gpt5Preset];n.reasoning_effort=i.reasoning_effort,n.verbosity=i.verbosity}else e.reasoning_effort||(n.reasoning_effort=Ft(t));return n.reasoning_effort=this.normalizeReasoningEffort(t,n.reasoning_effort),n}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!Gt(e)||t==="minimal"&&!Vt(e)?t==="minimal"&&Gt(e)?"none":t==="none"&&Vt(e)?"minimal":Fo(e)?"low":"medium":t==="low"&&!Fo(e)?"medium":t==="xhigh"&&!Vo(e)?"high":t==="max"&&!Yn(e)?Vo(e)?"xhigh":"high":t}};var Ls=o=>[_o,He].includes(o.trim()),Ha=o=>[B,ne,W,We].includes(o.trim()),Ji=(o,e)=>{if(Ls(o)&&!e)throw new Error("OpenRouter Auto Router returned no visible content. Please retry.")},vs=o=>o.blocks.some(e=>e.type!=="text"||e.text.trim().length>0),Tt=class{constructor(e,t=B,n=B,i,r=eo,s,a,l,p,c,h){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.appName=a,this.appUrl=l,this.reasoning_effort=p,this.includeReasoning=c,this.reasoningMaxTokens=h,this.visionModel=n}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!ve(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=Oi){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(!qe(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(!qe(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 O.post(this.endpoint,r,s)}buildRequestBody(e,t,n,i){let r={model:t,messages:e,stream:n},s=i!==void 0?i:x(this.responseLength),a=Ha(t)||Ls(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=hi.includes(t.trim())?void 0:this.reasoningMaxTokens;if(t.trim()!==oe){let p=An(t),c=Mi(t,this.reasoning_effort);if(c!==void 0||this.includeReasoning!==void 0||l||p){if(r.reasoning={},c){let h=c==="minimal"&&t!==Ee&&t!==Oe&&t!==fe&&t!==me?"low":c;r.reasoning.effort=h}else p&&(r.reasoning.effort=p);(c==="none"||this.includeReasoning!==!0)&&(r.reasoning.exclude=!0),l&&(r.reasoning.max_tokens=l)}else r.reasoning={exclude:!0}}return this.tools.length>0&&(r.tools=F(this.tools,"chat-completions"),t!==ge&&(r.tool_choice="auto")),r}async handleStream(e,t,n){let i=await X(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:!0});return Ji(n,i.trim().length>0),i}async parseStream(e,t,n){let i=await G(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:!0});return Ji(n,vs(i)),i}parseOneShot(e,t){let n=V(e,{throwOnApiError:!0});return Ji(t,vs(n)),n}};var Rt=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 Tt(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[to,fe,me,we,ke,oo,no,io,ro,so,ao,lo,po,ge,co,uo,Ge,Wo,Ve,Fe,Ee,Oe,ho,Ue,Ke,_o,He,di,B,jo,Zo,Jo,Yo,Qo,en,tn,on,nn,rn,sn,an,ln,pn,cn,un,Be,hn,mo,dn,_n,fn,mn,gn,En,On,Mn,Sn,vn,Ln,ne,W,Me,We,_i,fi,Cn,Tn,Rn,ze,$e,Xe,Se,go,qo,$o,zo,fo,Xo,mi,gi,oe,Ne]}getDefaultModel(){return B}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return qe(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return Ei}isModelFree(e){return ve(e)}};var Pt=class extends I{constructor(e,t=pt,n=t,i,r=yo,s,a){super(e,t,n,i,r,[],s,void 0,a,!1,"plamo",!1)}};var At=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=e.tools;return new Pt(e.apiKey,t,e.visionModel??t,n,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"plamo"}getSupportedModels(){return[...Wi]}getDefaultModel(){return pt}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 yo}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var xt=class extends I{constructor(e,t=lt,n=t,i,r=Io,s,a){super(e,t,n,i,r,[],s,void 0,void 0,!1,"sakana",!1,void 0,a?.type==="enabled")}};var It=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:Re,supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools;if(e.thinking!==void 0&&t!==Re)throw new Error("Sakana thinking control is only supported for sakana-namazu.");let r=t===Re?e.thinking??{type:"disabled"}:void 0;return new xt(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"sakana"}getSupportedModels(){return[...Hi]}getDefaultModel(){return lt}supportsVision(){return!0}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Bi(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 Io}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var yt=class{constructor(e,t=K,n=K,i,r=So,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(!tt(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(!tt(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 O.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:x(this.responseLength);s!==void 0&&(r.max_tokens=s),this.reasoningEffort&&kn(t)&&(r.reasoning_effort=vo(t,this.reasoningEffort));let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto"),r}buildToolsDefinition(){return F(this.tools,"chat-completions")}async handleStream(e,t){return X(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}async parseStream(e,t){return G(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return V(e)}};var Dt=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 yt(e.apiKey,t,n,i,e.endpoint||So,e.responseLength,vo(t,e.reasoning_effort??Gn(t)))}getProviderName(){return"xai"}getSupportedModels(){return[Ye,Qe,et,K,Nn,wn]}getDefaultModel(){return K}getDefaultVisionModel(){return K}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return tt(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var bt=class{constructor(e,t=re,n=Le,i,r=Eo,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(!Je(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(!Je(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 O.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:x(this.responseLength);s!==void 0&&(r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),t===ie?(r.thinking={type:"enabled",clear_thinking:this.thinking?.clear_thinking??!0},r.reasoning_effort=Mo(t,this.reasoningEffort)):this.thinking&&(r.thinking=this.thinking),t!==ie&&bn(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 F(this.tools,"chat-completions")}async handleStream(e,t){return X(e,t,{throwOnApiError:!0,onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}async parseStream(e,t){return G(e,t,{throwOnApiError:!0,onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return V(e,{throwOnApiError:!0})}};var Nt=class{createChatService(e){let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:h=>this.supportsVisionForModel(h),validate:"explicit"}),i=e.tools,r=Ze(t);if(e.reasoning_effort!==void 0&&!r.includes(e.reasoning_effort)){let h=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}. ${h}`)}let s=Mo(t,e.reasoning_effort),a=je(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},c=a||p?.type==="enabled"&&e.reasoning_effort!==void 0?s:void 0;return new bt(e.apiKey,t,n,i,e.endpoint||Eo,e.responseLength,e.responseFormat,p,c)}getProviderName(){return"zai"}getSupportedModels(){return[xn,Oo,ie,re,Si,vi,Li,In,Ci,Ti,Ri,Pi,yn,Dn,Le]}getDefaultModel(){return re}getDefaultVisionModel(){return Le}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Je(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Cs=[new Ct,new Lt,new mt,new Et,new ht,new Rt,new Nt,new Dt,new Mt,new _t,new vt,new It,new At];var Ba=new Set(["claude","claude-agent-sdk","codex-sdk","copilot-sdk","cursor-sdk","deepseek","gemini","gemini-nano","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),Wa=new Set(["claude","deepseek","gemini","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),$a=new Set(["codex-sdk"]);function Yi(o){if(Ba.has(o))return{text:!0,streaming:!$a.has(o),tools:Wa.has(o)}}function za(o){let e=o.provider==="claude",t=o.messages.filter(r=>!Ts(e,r)),n=o.completion.blocks.filter(r=>r.type==="tool_use"),i=o.completion.assistant_message??Xa(e,n);return Ts(e,i)||t.push({...i}),t.push(...qa(e,o.toolResults)),t}function Ts(o,e){if(!o||e.role!=="assistant")return!1;let t=e.content;return Array.isArray(t)&&t.length===0}function Xa(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 qa(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 ja=new Set(["openai","gemini","claude"]),Za=new Set(["openai","openai-compatible","zai","kimi"]),Ja={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"]},wt=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:ja.has(e),jsonMode:Za.has(e),responseLength:!0,reasoningEffort:e==="openai"&&(t===R||t===A)?["low","medium","high","xhigh","max"]:e==="openai"&&t===b?["none","low","medium","high","xhigh","max"]:e==="openai"&&t===N?["none","low","medium","high","xhigh","max"]:e==="claude"&&t?[...H(t)]:e==="gemini"&&t?[...De(t)]:e==="kimi"&&t?[...se(t)]:e==="deepseek"&&t?[...Po(t)]:e==="openrouter"&&t?[...Pn(t)]:e==="xai"&&t?[...ot(t)]:e==="zai"&&t?[...Ze(t)]:Ja[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"}};wt.providers=new Map;Cs.forEach(o=>wt.registerProvider(o));function Rs(){O.setFetch(async(o,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),n=e.headers,i={};if(Array.isArray(n))for(let[h,u]of n)i[h]=String(u);else if(n&&typeof n=="object")for(let[h,u]of Object.entries(n))i[h]=String(u);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 bs(Ya);})();
|
|
19
|
+
`)}getResponseLengthInstruction(){if(!this._responseLength)return;let e=Zn[this._responseLength];if(e)switch(this._responseLength){case C.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 C.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 C.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 C.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 C.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 C.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 dt=class{createChatService(e){return new _t({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,initialPrompts:e.initialPrompts,responseLength:e.responseLength,sessionMode:e.sessionMode})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[xe]}getDefaultModel(){return xe}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var ft=class{constructor(e,t=X,n=X,i,r=et,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 c=le(t);if(p!==void 0&&!c.includes(p))throw new Error(`Model ${t} does not support reasoning_effort: ${p}.`);this.reasoningEffort=p??ot(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(!tt(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(!tt(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 O.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:I(this.responseLength);s!==void 0&&(pe(t)?r.max_completion_tokens=s:r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),pe(t)&&(r.reasoning_effort=this.reasoningEffort??ot(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(et)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveEffectiveThinking(e){if(pe(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 K(this.tools,"chat-completions")}async parseStream(e,t){return V(e,t,{preserveAssistantMessage:!0,onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return F(e,{preserveAssistantMessage:!0})}};var mt=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 ft(e.apiKey,n,i,r,t,e.responseLength,e.responseFormat,s,a)}getProviderName(){return"kimi"}getSupportedModels(){return[xo,Io,yo,X,Do,bo]}getDefaultModel(){return X}getDefaultVisionModel(){return X}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return tt(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 et}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveThinking(e,t,n){if(pe(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=le(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??ot(e)??n[0];if(!n.includes(i))throw new Error(`Model ${e} supports reasoning_effort values: ${n.join(", ")}.`);return i}};var gt=class extends y{constructor(e,t=q,n=t,i,r=Go,s,a){super(e,t,n,i,r,[],s,void 0,a,!1,"mistral",!1)}};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:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=Uo(t)?e.reasoning_effort:void 0;return new gt(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"mistral"}getSupportedModels(){return[...ji]}getDefaultModel(){return q}getDefaultVisionModel(){return q}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ji(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 Go}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Ot=class{createChatService(e){this.validateRequiredOptions(e);let t=[e.apiKey?.trim()??"",e.model,e.visionModel??e.model,e.tools,e.endpoint,[],e.responseLength,e.verbosity,e.reasoning_effort,e.enableReasoningSummary,this.getProviderName(),!1];return e.responseFormat!==void 0&&t.push(e.responseFormat),new y(...t)}getProviderName(){return"openai-compatible"}getSupportedModels(){return[]}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"unknown"}supportsVisionForModel(e){return!0}getVisionSupportLevelForModel(e){return"unknown"}getDefaultModel(){return"local-model"}validateRequiredOptions(e){if(e.mcpServers!==void 0)throw new Error("openai-compatible provider does not support mcpServers.");let t=e.endpoint?.trim();if(!t)throw new Error("openai-compatible provider requires endpoint (full URL).");let 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 Mt=class{createChatService(e){let t=this.optimizeGPT5Options(e),n=T({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:c=>this.supportsVisionForModel(c),validate:"resolved"}),i=t.tools,r=t.mcpServers??[],s=t.model||this.getDefaultModel(),a=!1;if(r.length>0||s===x||n===x)a=!0;else if(s===N||n===N||s===w||n===w)a=(t.gpt5EndpointPreference||"responses")!=="chat"||t.reasoning_effort!=="none";else if(ni(s))a=!0;else if(s===A||n===A||s===R||n===R){let c=t.gpt5EndpointPreference||"responses";a=(i?.length??0)>0||c!=="chat"}else fe(s)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let l=t.endpoint||(a?k: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 y(...p)}getProviderName(){return"openai"}getSupportedModels(){return[ue,he,J,A,x,N,w,Y,Q,W,_e,ee,Bo,Wo,de,$o,R]}getDefaultModel(){return W}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return kt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!fe(t))return e;let n={...e};if(e.gpt5Preset){let i=or[e.gpt5Preset];n.reasoning_effort=i.reasoning_effort,n.verbosity=i.verbosity}else e.reasoning_effort||(n.reasoning_effort=Vt(t));return n.reasoning_effort=this.normalizeReasoningEffort(t,n.reasoning_effort),n}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!Gt(e)||t==="minimal"&&!Ut(e)?t==="minimal"&&Gt(e)?"none":t==="none"&&Ut(e)?"minimal":Xo(e)?"low":"medium":t==="low"&&!Xo(e)?"medium":t==="xhigh"&&!zo(e)?"high":t==="max"&&!ii(e)?zo(e)?"xhigh":"high":t}};var Gs=o=>[Mo,Ve].includes(o.trim()),rl=o=>[nn,re,z,Ke].includes(o.trim()),ar=(o,e)=>{if(Gs(o)&&!e)throw new Error("OpenRouter Auto Router returned no visible content. Please retry.")},ks=o=>o.blocks.some(e=>e.type!=="text"||e.text.trim().length>0),St=class{constructor(e,t=U,n=U,i,r=eo,s,a,l,p,c,h){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.appName=a,this.appUrl=l,this.reasoning_effort=p,this.includeReasoning=c,this.reasoningMaxTokens=h,this.visionModel=n}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!Te(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=Pi){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(!$e(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(!$e(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let r=await this.callOpenRouter(e,this.visionModel,t,i);return t?this.parseStream(r,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 O.post(this.endpoint,r,s)}buildRequestBody(e,t,n,i){let r={model:t,messages:e,stream:n},s=i!==void 0?i:I(this.responseLength),a=rl(t)||Gs(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=Oi.includes(t.trim())?void 0:this.reasoningMaxTokens;if(![me,ne,ie].includes(t.trim())){let p=Gn(t),c=xi(t,this.reasoning_effort);if(c!==void 0||this.includeReasoning!==void 0||l||p){if(r.reasoning={},c){let h=c==="minimal"&&t!==Me&&t!==Se&&t!==ge&&t!==Ee?"low":c;r.reasoning.effort=h}else p&&(r.reasoning.effort=p);(c==="none"||this.includeReasoning!==!0)&&(r.reasoning.exclude=!0),l&&(r.reasoning.max_tokens=l)}else r.reasoning={exclude:!0}}return this.tools.length>0&&(r.tools=K(this.tools,"chat-completions"),t!==Oe&&(r.tool_choice="auto")),r}async handleStream(e,t,n){let i=await j(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:!0});return ar(n,i.trim().length>0),i}async parseStream(e,t,n){let i=await V(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:!0});return ar(n,ks(i)),i}parseOneShot(e,t){let n=F(e,{throwOnApiError:!0});return ar(t,ks(n)),n}};var vt=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 St(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[to,ge,Ee,we,no,io,ro,so,ao,lo,po,co,Oe,uo,ho,Qo,Me,Se,_o,ke,Ge,Mo,Ve,Mi,pn,cn,un,hn,_n,dn,fn,mn,gn,En,On,Mn,Sn,vn,Ln,Fe,Cn,vo,Tn,Rn,An,Pn,xn,In,yn,Dn,re,z,Le,Ke,Ti,Ri,bn,Nn,wn,Be,He,We,Ce,Lo,ln,rn,sn,So,an,Ne,ne,U,ve,fo,on,mo,go,Eo,ie,Ue,Oo,oo]}getDefaultModel(){return U}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return $e(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return Ai}isModelFree(e){return Te(e)}};var Lt=class extends y{constructor(e,t=rt,n=t,i,r=Fo,s,a){super(e,t,n,i,r,[],s,void 0,a,!1,"plamo",!1)}};var Ct=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=e.tools;return new Lt(e.apiKey,t,e.visionModel??t,n,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"plamo"}getSupportedModels(){return[...er]}getDefaultModel(){return rt}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 Fo}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Tt=class extends y{constructor(e,t=it,n=t,i,r=Vo,s,a){super(e,t,n,i,r,[],s,void 0,void 0,!1,"sakana",!1,void 0,a?.type==="enabled")}};var Rt=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:Pe,supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools;if(e.thinking!==void 0&&t!==Pe)throw new Error("Sakana thinking control is only supported for sakana-namazu.");let r=t===Pe?e.thinking??{type:"disabled"}:void 0;return new Tt(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"sakana"}getSupportedModels(){return[...Yi]}getDefaultModel(){return it}supportsVision(){return!0}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Qi(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 Vo}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var At=class{constructor(e,t=B,n=B,i,r=Ao,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(!Ye(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(!Ye(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 O.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:I(this.responseLength);s!==void 0&&(r.max_tokens=s),this.reasoningEffort&&$n(t)&&(r.reasoning_effort=Po(t,this.reasoningEffort));let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto"),r}buildToolsDefinition(){return K(this.tools,"chat-completions")}async handleStream(e,t){return j(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}async parseStream(e,t){return V(e,t,{onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return F(e)}};var Pt=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 At(e.apiKey,t,n,i,e.endpoint||Ao,e.responseLength,Po(t,e.reasoning_effort??zn(t)))}getProviderName(){return"xai"}getSupportedModels(){return[je,Ze,Je,B,Bn,Wn]}getDefaultModel(){return B}getDefaultVisionModel(){return B}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ye(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var xt=class{constructor(e,t=ae,n=Re,i,r=Co,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(!qe(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(!qe(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 O.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:I(this.responseLength);s!==void 0&&(r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),t===se?(r.thinking={type:"enabled",clear_thinking:this.thinking?.clear_thinking??!0},r.reasoning_effort=Ro(t,this.reasoningEffort)):this.thinking&&(r.thinking=this.thinking),t!==se&&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&&Gi(t)&&(r.tool_stream=!0)),r}buildToolsDefinition(){return K(this.tools,"chat-completions")}async handleStream(e,t){return j(e,t,{throwOnApiError:!0,onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}async parseStream(e,t){return V(e,t,{throwOnApiError:!0,onJsonError:n=>console.debug("Failed to parse SSE data:",n)})}parseOneShot(e){return F(e,{throwOnApiError:!0})}};var It=class{createChatService(e){let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:h=>this.supportsVisionForModel(h),validate:"explicit"}),i=e.tools,r=Xe(t);if(e.reasoning_effort!==void 0&&!r.includes(e.reasoning_effort)){let h=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}. ${h}`)}let s=Ro(t,e.reasoning_effort),a=ze(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},c=a||p?.type==="enabled"&&e.reasoning_effort!==void 0?s:void 0;return new xt(e.apiKey,t,n,i,e.endpoint||Co,e.responseLength,e.responseFormat,p,c)}getProviderName(){return"zai"}getSupportedModels(){return[Un,To,se,ae,Ii,yi,Di,Vn,bi,Ni,wi,ki,Fn,Kn,Re]}getDefaultModel(){return ae}getDefaultVisionModel(){return Re}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return qe(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Us=[new Mt,new Ot,new ht,new dt,new lt,new vt,new It,new Pt,new mt,new ct,new Et,new Rt,new Ct];var sl=new Set(["claude","claude-agent-sdk","codex-sdk","copilot-sdk","cursor-sdk","deepseek","gemini","gemini-nano","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),al=new Set(["claude","deepseek","gemini","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),ll=new Set(["codex-sdk"]);function lr(o){if(sl.has(o))return{text:!0,streaming:!ll.has(o),tools:al.has(o)}}function pl(o){let e=o.provider==="claude",t=o.messages.filter(r=>!Vs(e,r)),n=o.completion.blocks.filter(r=>r.type==="tool_use"),i=o.completion.assistant_message??cl(e,n);return Vs(e,i)||t.push({...i}),t.push(...ul(e,o.toolResults)),t}function Vs(o,e){if(!o||e.role!=="assistant")return!1;let t=e.content;return Array.isArray(t)&&t.length===0}function cl(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 ul(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 hl=new Set(["openai","gemini","claude"]),_l=new Set(["openai","openai-compatible","zai","kimi"]),dl={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"]},yt=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=lr(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:hl.has(e),jsonMode:_l.has(e),responseLength:!0,reasoningEffort:e==="openai"&&(t===A||t===x)?["low","medium","high","xhigh","max"]:e==="openai"&&t===N?["none","low","medium","high","xhigh","max"]:e==="openai"&&(t===w||t===R)?["none","low","medium","high","xhigh","max"]:e==="claude"&&t?[...$(t)]:e==="gemini"&&t?[...De(t)]:e==="kimi"&&t?[...le(t)]:e==="deepseek"&&t?[...ko(t)]:e==="openrouter"&&t?[...kn(t)]:e==="xai"&&t?[...Qe(t)]:e==="zai"&&t?[...Xe(t)]:dl[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"}};yt.providers=new Map;Us.forEach(o=>yt.registerProvider(o));function Fs(){O.setFetch(async(o,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),n=e.headers,i={};if(Array.isArray(n))for(let[h,u]of n)i[h]=String(u);else if(n&&typeof n=="object")for(let[h,u]of Object.entries(n))i[h]=String(u);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 Xs(fl);})();
|