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