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