@aituber-onair/chat 0.60.0 → 0.61.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 +10 -4
- package/README.md +10 -4
- package/dist/cjs/constants/mistral.d.ts +1 -0
- package/dist/cjs/constants/mistral.d.ts.map +1 -1
- package/dist/cjs/constants/mistral.js +4 -1
- package/dist/cjs/constants/mistral.js.map +1 -1
- package/dist/cjs/constants/openrouter.d.ts +4 -0
- package/dist/cjs/constants/openrouter.d.ts.map +1 -1
- package/dist/cjs/constants/openrouter.js +19 -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 +6 -3
- package/dist/cjs/services/providers/openrouter/OpenRouterChatService.js.map +1 -1
- package/dist/cjs/services/providers/openrouter/OpenRouterChatServiceProvider.d.ts.map +1 -1
- package/dist/cjs/services/providers/openrouter/OpenRouterChatServiceProvider.js +3 -0
- package/dist/cjs/services/providers/openrouter/OpenRouterChatServiceProvider.js.map +1 -1
- package/dist/esm/constants/mistral.d.ts +1 -0
- package/dist/esm/constants/mistral.d.ts.map +1 -1
- package/dist/esm/constants/mistral.js +3 -0
- package/dist/esm/constants/mistral.js.map +1 -1
- package/dist/esm/constants/openrouter.d.ts +4 -0
- package/dist/esm/constants/openrouter.d.ts.map +1 -1
- package/dist/esm/constants/openrouter.js +17 -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 +7 -4
- package/dist/esm/services/providers/openrouter/OpenRouterChatService.js.map +1 -1
- package/dist/esm/services/providers/openrouter/OpenRouterChatServiceProvider.d.ts.map +1 -1
- package/dist/esm/services/providers/openrouter/OpenRouterChatServiceProvider.js +4 -1
- package/dist/esm/services/providers/openrouter/OpenRouterChatServiceProvider.js.map +1 -1
- package/dist/umd/aituber-onair-chat.js +31 -4
- package/dist/umd/aituber-onair-chat.min.js +7 -7
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var AITuberOnAirChat=(()=>{var wn=Object.defineProperty;var fs=Object.getOwnPropertyDescriptor;var ms=Object.getOwnPropertyNames;var gs=Object.prototype.hasOwnProperty;var Es=(o,e)=>{for(var t in e)wn(o,t,{get:e[t],enumerable:!0})},Os=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ms(e))!gs.call(o,i)&&i!==t&&wn(o,i,{get:()=>e[i],enumerable:!(n=fs(e,i))||n.enumerable});return o};var Ms=o=>Os(wn({},"__esModule",{value:!0}),o);var Fa={};Es(Fa,{CHAT_RESPONSE_LENGTH:()=>C,CLAUDE_DEPRECATED_MODELS:()=>Ps,CLAUDE_VISION_SUPPORTED_MODELS:()=>Wt,ChatServiceFactory:()=>Rt,ChatServiceHttpClient:()=>O,ClaudeChatService:()=>nt,ClaudeChatServiceProvider:()=>it,DEEPSEEK_API_BASE_URL:()=>Or,DEEPSEEK_DEPRECATED_MODELS:()=>$s,DEEPSEEK_SUPPORTED_MODELS:()=>gi,DEEPSEEK_VISION_SUPPORTED_MODELS:()=>vr,DEFAULT_MAX_TOKENS:()=>Di,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>Zs,DEFAULT_VISION_PROMPT:()=>js,DeepSeekChatService:()=>rt,DeepSeekChatServiceProvider:()=>st,EMOTION_TAG_CLEANUP_REGEX:()=>wi,EMOTION_TAG_REGEX:()=>wr,ENDPOINT_CLAUDE_API:()=>Yn,ENDPOINT_DEEPSEEK_CHAT_COMPLETIONS_API:()=>fo,ENDPOINT_GEMINI_API:()=>Kn,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>je,ENDPOINT_MISTRAL_CHAT_COMPLETIONS_API:()=>go,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>q,ENDPOINT_OPENAI_RESPONSES_API:()=>w,ENDPOINT_OPENROUTER_API:()=>$t,ENDPOINT_PLAMO_CHAT_COMPLETIONS_API:()=>Mo,ENDPOINT_SAKANA_CHAT_COMPLETIONS_API:()=>Oo,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>po,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>so,EmotionParser:()=>ot,GEMINI_DEPRECATED_MODELS:()=>ji,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>Ni,GEMINI_RECOMMENDED_MODELS:()=>xo,GEMINI_VISION_SUPPORTED_MODELS:()=>Dt,GPT5_PRESETS:()=>bi,GPT_5_MODELS:()=>Ui,GeminiChatService:()=>at,GeminiChatServiceProvider:()=>lt,GeminiNanoChatService:()=>pt,GeminiNanoChatServiceProvider:()=>ct,HttpError:()=>re,KIMI_THINKING_REQUIRED_MODELS:()=>gr,KIMI_VISION_SUPPORTED_MODELS:()=>mr,KimiChatService:()=>ut,KimiChatServiceProvider:()=>ht,MAX_TOKENS_BY_LENGTH:()=>An,MISTRAL_API_BASE_URL:()=>Cr,MISTRAL_DEPRECATED_MODELS:()=>zs,MISTRAL_REASONING_EFFORT_SUPPORTED_MODELS:()=>Pr,MISTRAL_SUPPORTED_MODELS:()=>Pi,MISTRAL_VISION_SUPPORTED_MODELS:()=>Rr,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>ar,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>sr,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>on,MODEL_ANTHROPIC_CLAUDE_FABLE_5:()=>Yo,MODEL_ANTHROPIC_CLAUDE_FABLE_5_1:()=>_e,MODEL_ANTHROPIC_CLAUDE_HAIKU_LATEST:()=>Jo,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>en,MODEL_ANTHROPIC_CLAUDE_OPUS_4_8:()=>io,MODEL_ANTHROPIC_CLAUDE_OPUS_5:()=>Qo,MODEL_ANTHROPIC_CLAUDE_OPUS_5_5:()=>Zt,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>tn,MODEL_ANTHROPIC_CLAUDE_SONNET_5:()=>we,MODEL_ANTHROPIC_CLAUDE_SONNET_5_5:()=>jt,MODEL_ANTHROPIC_CLAUDE_SONNET_LATEST:()=>Zo,MODEL_CLAUDE_3_5_HAIKU:()=>Yi,MODEL_CLAUDE_3_5_SONNET:()=>Qi,MODEL_CLAUDE_3_7_SONNET:()=>er,MODEL_CLAUDE_3_HAIKU:()=>Ji,MODEL_CLAUDE_4_5_HAIKU:()=>U,MODEL_CLAUDE_4_5_OPUS:()=>wt,MODEL_CLAUDE_4_5_SONNET:()=>Ao,MODEL_CLAUDE_4_6_OPUS:()=>Gt,MODEL_CLAUDE_4_6_SONNET:()=>kt,MODEL_CLAUDE_4_7_OPUS:()=>Vt,MODEL_CLAUDE_4_8_OPUS:()=>Ft,MODEL_CLAUDE_4_OPUS:()=>or,MODEL_CLAUDE_4_SONNET:()=>tr,MODEL_CLAUDE_5_1_FABLE:()=>Nt,MODEL_CLAUDE_5_5_OPUS:()=>Io,MODEL_CLAUDE_5_5_SONNET:()=>Bt,MODEL_CLAUDE_5_FABLE:()=>Ut,MODEL_CLAUDE_5_OPUS:()=>Ht,MODEL_CLAUDE_5_SONNET:()=>Kt,MODEL_DEEPSEEK_CHAT:()=>Mr,MODEL_DEEPSEEK_FLASH:()=>Rn,MODEL_DEEPSEEK_REASONER:()=>Sr,MODEL_DEEPSEEK_V4_FLASH:()=>ve,MODEL_DEEPSEEK_V4_FLASH_VISION_EXP:()=>Qe,MODEL_DEEPSEEK_V4_PRO:()=>yn,MODEL_FUGU:()=>et,MODEL_FUGU_ULTRA:()=>xr,MODEL_FUGU_ULTRA_20260615:()=>Ir,MODEL_FUGU_ULTRA_V1_1:()=>Ar,MODEL_GEMINI_2_5_FLASH:()=>zi,MODEL_GEMINI_2_5_FLASH_LITE:()=>Xi,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>qi,MODEL_GEMINI_2_5_PRO:()=>$i,MODEL_GEMINI_3_1_FLASH_LITE:()=>ee,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>qn,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>Xn,MODEL_GEMINI_3_5_FLASH:()=>$n,MODEL_GEMINI_3_5_FLASH_LITE:()=>zn,MODEL_GEMINI_3_6_FLASH:()=>Wn,MODEL_GEMINI_3_7_FLASH:()=>Bn,MODEL_GEMINI_3_8_FLASH:()=>Hn,MODEL_GEMINI_3_FLASH_PREVIEW:()=>Zn,MODEL_GEMINI_3_PRO_PREVIEW:()=>jn,MODEL_GEMINI_NANO:()=>Ce,MODEL_GEMMA_4_26B_A4B_IT:()=>Wi,MODEL_GEMMA_4_31B_IT:()=>Bi,MODEL_GLM_4_6:()=>_i,MODEL_GLM_4_6V:()=>On,MODEL_GLM_4_6V_FLASH:()=>Me,MODEL_GLM_4_6V_FLASHX:()=>Mn,MODEL_GLM_4_7:()=>ui,MODEL_GLM_4_7_FLASH:()=>di,MODEL_GLM_4_7_FLASHX:()=>hi,MODEL_GLM_5:()=>pi,MODEL_GLM_5V_TURBO:()=>En,MODEL_GLM_5_1:()=>li,MODEL_GLM_5_2:()=>ne,MODEL_GLM_5_3:()=>gn,MODEL_GLM_5_3_FLASH:()=>ao,MODEL_GLM_5_3_FLASHX:()=>oe,MODEL_GLM_5_TURBO:()=>ci,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>cn,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>un,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>pn,MODEL_GOOGLE_GEMINI_3_5_FLASH_LITE:()=>ln,MODEL_GOOGLE_GEMINI_3_6_FLASH:()=>an,MODEL_GOOGLE_GEMINI_3_7_FLASH:()=>sn,MODEL_GOOGLE_GEMINI_3_8_FLASH:()=>to,MODEL_GOOGLE_GEMINI_FLASH_LATEST:()=>rn,MODEL_GOOGLE_GEMINI_PRO_LATEST:()=>nn,MODEL_GPT_4O:()=>Po,MODEL_GPT_4O_MINI:()=>ue,MODEL_GPT_4_1:()=>Lo,MODEL_GPT_4_1_MINI:()=>Co,MODEL_GPT_4_1_NANO:()=>To,MODEL_GPT_5:()=>Re,MODEL_GPT_5_1:()=>ye,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:()=>Pe,MODEL_GPT_5_NANO:()=>se,MODEL_GPT_6_1_SOL:()=>P,MODEL_GPT_6_ASTRA:()=>y,MODEL_GPT_6_LUNA:()=>N,MODEL_GPT_6_SOL:()=>b,MODEL_GPT_OSS_20B_FREE:()=>B,MODEL_GROK_4_1_FAST_NON_REASONING:()=>dr,MODEL_GROK_4_1_FAST_REASONING:()=>hr,MODEL_GROK_4_20_NON_REASONING:()=>Ln,MODEL_GROK_4_20_REASONING:()=>vn,MODEL_GROK_4_3:()=>K,MODEL_GROK_4_5:()=>ze,MODEL_GROK_4_6:()=>We,MODEL_GROK_4_7:()=>$e,MODEL_INCEPTION_MERCURY_2_5:()=>Do,MODEL_INCLUSIONAI_LING_3_0_FLASH_VL_FREE:()=>Ie,MODEL_KIMI_K2_5:()=>Pn,MODEL_KIMI_K2_6:()=>$,MODEL_KIMI_K2_7_CODE:()=>uo,MODEL_KIMI_K2_7_CODE_HIGHSPEED:()=>ho,MODEL_KIMI_K3:()=>Ze,MODEL_KWAIPILOT_KAT_CODER_AIR_V2_5:()=>ni,MODEL_KWAIPILOT_KAT_CODER_PRO_V2_5:()=>ii,MODEL_META_MUSE_SPARK_1_3:()=>me,MODEL_MINISTRAL_14B_2512:()=>vi,MODEL_MINISTRAL_3B_2512:()=>Mi,MODEL_MINISTRAL_8B_2512:()=>Si,MODEL_MISTRAL_LARGE_2512:()=>Ti,MODEL_MISTRAL_LARGE_LATEST:()=>Ci,MODEL_MISTRAL_MEDIUM_2508:()=>Tr,MODEL_MISTRAL_MEDIUM_3_5:()=>xn,MODEL_MISTRAL_SMALL_2603:()=>Li,MODEL_MISTRAL_SMALL_LATEST:()=>z,MODEL_MOONSHOTAI_KIMI_K2_5:()=>wo,MODEL_MOONSHOTAI_KIMI_K2_6:()=>no,MODEL_MOONSHOTAI_KIMI_K2_7_CODE:()=>No,MODEL_MOONSHOTAI_KIMI_K3:()=>bo,MODEL_MOONSHOTAI_KIMI_LATEST:()=>ko,MODEL_NEX_AGI_NEX_N2_5_MINI_FREE:()=>De,MODEL_NEX_AGI_NEX_N2_5_PRO_FREE:()=>be,MODEL_O1:()=>Vn,MODEL_O1_MINI:()=>Gn,MODEL_O3_MINI:()=>kn,MODEL_OPENAI_GPT_4O:()=>Xo,MODEL_OPENAI_GPT_4_1_MINI:()=>qo,MODEL_OPENAI_GPT_4_1_NANO:()=>jo,MODEL_OPENAI_GPT_5_1_CHAT:()=>rr,MODEL_OPENAI_GPT_5_1_CODEX:()=>Wo,MODEL_OPENAI_GPT_5_5:()=>Bo,MODEL_OPENAI_GPT_5_5_PRO:()=>Ho,MODEL_OPENAI_GPT_5_6_LUNA:()=>Ko,MODEL_OPENAI_GPT_5_6_SOL:()=>Fo,MODEL_OPENAI_GPT_5_6_TERRA:()=>Uo,MODEL_OPENAI_GPT_5_MINI:()=>$o,MODEL_OPENAI_GPT_5_NANO:()=>zo,MODEL_OPENAI_GPT_6_1_SOL:()=>zt,MODEL_OPENAI_GPT_6_ASTRA:()=>Yt,MODEL_OPENAI_GPT_6_ASTRA_PRO:()=>Qt,MODEL_OPENAI_GPT_6_LUNA:()=>qt,MODEL_OPENAI_GPT_6_SOL:()=>Xt,MODEL_OPENAI_GPT_LATEST:()=>Go,MODEL_OPENAI_GPT_MINI_LATEST:()=>Vo,MODEL_OPENROUTER_AUTO:()=>oo,MODEL_OPENROUTER_AUTO_BETA:()=>Ne,MODEL_OPENROUTER_DEEPSEEK_V4_1_FLASH:()=>eo,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH:()=>Ge,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_0731:()=>Ve,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_VISION_EXP:()=>Ee,MODEL_OPENROUTER_DEEPSEEK_V4_PRO_0813:()=>Fe,MODEL_OPENROUTER_FUSION:()=>ei,MODEL_PLAMO_2_2_PRIME:()=>Nr,MODEL_PLAMO_3_0_PRIME:()=>tt,MODEL_QWEN_QWEN_3_8_FLASH:()=>ro,MODEL_QWEN_QWEN_3_8_MAX_0902:()=>fe,MODEL_SAKANA_NAMAZU:()=>Le,MODEL_XAI_GROK_4_5:()=>_n,MODEL_XAI_GROK_4_6:()=>dn,MODEL_XAI_GROK_4_7:()=>Jt,MODEL_XAI_GROK_LATEST:()=>hn,MODEL_ZAI_GLM_4_5_AIR:()=>oi,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>lr,MODEL_ZAI_GLM_4_7_FLASH:()=>ti,MODEL_ZAI_GLM_5_2:()=>ke,MODEL_ZAI_GLM_5_3:()=>te,MODEL_ZAI_GLM_5_3_FLASH:()=>W,MODEL_ZAI_GLM_5_3_FLASHX:()=>ge,MistralChatService:()=>dt,MistralChatServiceProvider:()=>_t,OPENAI_COMPATIBLE_LOCAL_PRESETS:()=>ta,OPENROUTER_CREDITS_THRESHOLD:()=>Fs,OPENROUTER_DEPRECATED_MODELS:()=>xs,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>Vs,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>Gs,OPENROUTER_FREE_MODELS:()=>ri,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>si,OPENROUTER_VISION_SUPPORTED_MODELS:()=>pr,OpenAIChatService:()=>A,OpenAIChatServiceProvider:()=>mt,OpenAICompatibleChatServiceProvider:()=>ft,OpenAICompatibleEndpointError:()=>R,OpenRouterChatService:()=>gt,OpenRouterChatServiceProvider:()=>Et,PLAMO_API_BASE_URL:()=>br,PLAMO_DEPRECATED_MODELS:()=>qs,PLAMO_SUPPORTED_MODELS:()=>Ii,PlamoChatService:()=>Ot,PlamoChatServiceProvider:()=>Mt,SAKANA_API_BASE_URL:()=>yr,SAKANA_COMPATIBILITY_MODELS:()=>Xs,SAKANA_SUPPORTED_MODELS:()=>xi,SAKANA_VISION_SUPPORTED_MODELS:()=>Dr,SakanaChatService:()=>St,SakanaChatServiceProvider:()=>vt,StreamTextAccumulator:()=>M,VISION_SUPPORTED_MODELS:()=>yt,XAIChatService:()=>Lt,XAIChatServiceProvider:()=>Ct,XAI_DEPRECATED_MODELS:()=>Hs,XAI_VISION_SUPPORTED_MODELS:()=>_r,ZAIChatService:()=>Tt,ZAIChatServiceProvider:()=>Pt,ZAI_VISION_SUPPORTED_MODELS:()=>ur,allowsReasoningLow:()=>yo,allowsReasoningMax:()=>Un,allowsReasoningMinimal:()=>At,allowsReasoningNone:()=>xt,allowsReasoningXHigh:()=>Ro,buildOpenAICompatibleTools:()=>F,buildToolContinuationMessages:()=>ba,getChatBackendProviderCapabilities:()=>Fi,getClaudeSupportedReasoningEfforts:()=>H,getDeepSeekSupportedReasoningEfforts:()=>mo,getDefaultClaudeReasoningEffort:()=>ir,getDefaultDeepSeekReasoningEffort:()=>mi,getDefaultGeminiReasoningEffort:()=>Ts,getDefaultKimiReasoningEffort:()=>Ye,getDefaultOpenRouterReasoningEffort:()=>mn,getDefaultReasoningEffortForGPT5Model:()=>Hi,getDefaultReasoningEffortForOpenAIModel:()=>It,getDefaultXaiReasoningEffort:()=>Tn,getDefaultZaiReasoningEffort:()=>cr,getGeminiSupportedReasoningEfforts:()=>xe,getKimiSupportedReasoningEfforts:()=>ie,getMaxTokensForResponseLength:()=>x,getOpenRouterSupportedReasoningEfforts:()=>fn,getXaiSupportedReasoningEfforts:()=>qe,getZaiSupportedReasoningEfforts:()=>He,installGASFetch:()=>ds,isClaudeReasoningEffortModel:()=>nr,isDeepSeekReasoningEffortModel:()=>Lr,isDeepSeekVisionModel:()=>Ei,isGPT5Model:()=>Ki,isGeminiReasoningEffortModel:()=>Jn,isKimiReasoningEffortModel:()=>Se,isKimiThinkingRequiredModel:()=>_o,isKimiVisionModel:()=>Je,isMistralReasoningEffort:()=>Ri,isMistralReasoningEffortModel:()=>Eo,isMistralVisionModel:()=>yi,isOpenAIReasoningModel:()=>he,isOpenRouterFreeModel:()=>Oe,isOpenRouterVisionModel:()=>Ue,isResponsesOnlyGPT5Model:()=>Fn,isSakanaVisionModel:()=>Ai,isXaiReasoningEffortModel:()=>Cn,isXaiReasoningEffortNoneModel:()=>fr,isXaiVisionModel:()=>Xe,isZaiAlwaysThinkingModel:()=>Ke,isZaiReasoningEffortModel:()=>Sn,isZaiToolStreamModel:()=>fi,isZaiVisionModel:()=>Be,listOpenAICompatibleModels:()=>Kr,normalizeClaudeReasoningEffort:()=>ys,normalizeDeepSeekReasoningEffort:()=>Oi,normalizeGeminiReasoningEffort:()=>bt,normalizeOpenRouterReasoningEffort:()=>ai,normalizeXaiReasoningEffort:()=>co,normalizeZaiReasoningEffort:()=>lo,parseOpenAICompatibleOneShot:()=>V,parseOpenAICompatibleTextStream:()=>X,parseOpenAICompatibleToolStream:()=>G,processChatWithOptionalTools:()=>S,refreshOpenRouterFreeModels:()=>ha,resolveOpenAICompatibleEndpoint:()=>Ur,resolveVisionModel:()=>T,runOnceText:()=>ea,safeJsonParse:()=>Gr,safeParseToolCallInput:()=>Te,screenplayToText:()=>Qs,testOpenAICompatibleConnection:()=>oa,textToScreenplay:()=>kr,textsToScreenplay:()=>Ys});var q="https://api.openai.com/v1/chat/completions",w="https://api.openai.com/v1/responses",P="gpt-6.1-sol",y="gpt-6-astra",b="gpt-6-sol",N="gpt-6-luna",se="gpt-5-nano",Pe="gpt-5-mini",Re="gpt-5",ye="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",Lo="gpt-4.1",Co="gpt-4.1-mini",To="gpt-4.1-nano",ue="gpt-4o-mini",Po="gpt-4o",kn="o3-mini",Gn="o1-mini",Vn="o1",yt=[P,y,b,N,se,Pe,Re,ye,ae,le,j,Z,J,Y,pe,ce,Q,Lo,Co,To,ue,Po,"o1"],Ui=[se,Pe,Re,ye,ae,le,j,Z,J,Y,pe,ce,Q];function Ki(o){return Ui.includes(o)}function he(o){return o===P||o===y||o===b||o===N||Ki(o)}function Fn(o){return o===Q}function Ro(o){return o===P||o===y||o===b||o===N||o===j||o===Z||o===J||o===Y||o===le||o===ae||o===pe||o===ce||o===Q}function Un(o){return o===P||o===y||o===b||o===N||o===j||o===Z||o===J||o===Y}function xt(o){return o===b||o===N||o===j||o===Z||o===J||o===Y||o===ye||o===ae||o===le||o===pe||o===ce}function At(o){return o===se||o===Pe||o===Re}function yo(o){return o!==Q}function Hi(o){return xt(o)?"none":At(o)?"minimal":"medium"}function It(o){return o===P||o===y?"low":o===b?"medium":o===N?"low":Hi(o)}var Kn="https://generativelanguage.googleapis.com",Bi="gemma-4-31b-it",Wi="gemma-4-26b-a4b-it",Hn="gemini-3.8-flash",Bn="gemini-3.7-flash",Wn="gemini-3.6-flash",$n="gemini-3.5-flash",zn="gemini-3.5-flash-lite",Xn="gemini-3.1-pro-preview",ee="gemini-3.1-flash-lite",qn="gemini-3.1-flash-lite-preview",jn="gemini-3-pro-preview",Zn="gemini-3-flash-preview",$i="gemini-2.5-pro",zi="gemini-2.5-flash",Xi="gemini-2.5-flash-lite",qi="gemini-2.5-flash-lite-preview-06-17",xo=[Hn,Bn,Wn,$n,zn,ee,Xn,Zn,$i,zi,Xi,Bi,Wi],ji=[qn,jn,qi],Dt=[...xo,...ji],Ss=["minimal","low","medium","high"],vs=["low","medium","high"],Ls=[Wn,$n,zn,ee,qn,Zn],Cs=[Hn,Bn,Xn,jn];function xe(o){return Ls.includes(o)?Ss:Cs.includes(o)?vs:[]}function Jn(o){return xe(o).length>0}function Ts(o){return xe(o)[0]}function bt(o,e){let t=xe(o);if(t.length!==0)return e&&t.includes(e)?e:t[0]}var Yn="https://api.anthropic.com/v1/messages",Nt="claude-fable-5-1",Ji="claude-3-haiku-20240307",Yi="claude-3-5-haiku-20241022",Qi="claude-3-5-sonnet-20241022",er="claude-3-7-sonnet-20250219",tr="claude-sonnet-4-20250514",or="claude-opus-4-20250514",Ao="claude-sonnet-4-5-20250929",U="claude-haiku-4-5-20251001",wt="claude-opus-4-5-20251101",kt="claude-sonnet-4-6",Gt="claude-opus-4-6",Vt="claude-opus-4-7",Ft="claude-opus-4-8",Ut="claude-fable-5",Kt="claude-sonnet-5",Ht="claude-opus-5",Io="claude-opus-5-5",Bt="claude-sonnet-5-5",Ps=[Ji,Yi,Qi,er,tr,or],Qn=["low","medium","high"],Zi=[...Qn,"max"],de=[...Qn,"xhigh","max"],Rs={[wt]:Qn,[kt]:Zi,[Gt]:Zi,[Vt]:de,[Ft]:de,[Nt]:de,[Ut]:de,[Kt]:de,[Ht]:de,[Bt]:de},Wt=[Nt,Ao,U,wt,kt,Gt,Vt,Ft,Ut,Kt,Ht,Io,Bt];function H(o){return Rs[o]??[]}function nr(o){return H(o).length>0}function ir(o){return nr(o)?"high":void 0}function ys(o,e){let t=H(o);if(t.length!==0)return e?t.includes(e)?e:"high":ir(o)}var $t="https://openrouter.ai/api/v1/chat/completions",zt="openai/gpt-6.1-sol",Xt="openai/gpt-6-sol",qt="openai/gpt-6-luna",jt="anthropic/claude-sonnet-5.5",Zt="anthropic/claude-opus-5.5",Jt="x-ai/grok-4.7",Yt="openai/gpt-6-astra",Qt="openai/gpt-6-astra-pro",_e="anthropic/claude-fable-5.1",eo="deepseek/deepseek-v4.1-flash",to="google/gemini-3.8-flash",Ie="inclusionai/ling-3.0-flash-vl:free",Do="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",oo="openrouter/auto",Ne="openrouter/auto-beta",ei="openrouter/fusion",B="openai/gpt-oss-20b:free",bo="moonshotai/kimi-k3",No="moonshotai/kimi-k2.7-code",no="moonshotai/kimi-k2.6",wo="moonshotai/kimi-k2.5",ko="~moonshotai/kimi-latest",Go="~openai/gpt-latest",Vo="~openai/gpt-mini-latest",Fo="openai/gpt-5.6-sol",Uo="openai/gpt-5.6-terra",Ko="openai/gpt-5.6-luna",Ho="openai/gpt-5.5-pro",Bo="openai/gpt-5.5",rr="openai/gpt-5.1-chat",Wo="openai/gpt-5.1-codex",$o="openai/gpt-5-mini",zo="openai/gpt-5-nano",Xo="openai/gpt-4o",qo="openai/gpt-4.1-mini",jo="openai/gpt-4.1-nano",Zo="~anthropic/claude-sonnet-latest",Jo="~anthropic/claude-haiku-latest",Yo="anthropic/claude-fable-5",we="anthropic/claude-sonnet-5",Qo="anthropic/claude-opus-5",io="anthropic/claude-opus-4.8",en="anthropic/claude-opus-4",tn="anthropic/claude-sonnet-4",sr="anthropic/claude-3.7-sonnet",ar="anthropic/claude-3.5-sonnet",on="anthropic/claude-haiku-4.5",nn="~google/gemini-pro-latest",rn="~google/gemini-flash-latest",sn="google/gemini-3.7-flash",an="google/gemini-3.6-flash",ln="google/gemini-3.5-flash-lite",pn="google/gemini-2.5-pro",cn="google/gemini-2.5-flash",un="google/gemini-2.5-flash-lite-preview-09-2025",ke="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",ti="z-ai/glm-4.7-flash",oi="z-ai/glm-4.5-air",lr="z-ai/glm-4.5-air:free",ni="kwaipilot/kat-coder-air-v2.5",ii="kwaipilot/kat-coder-pro-v2.5",hn="~x-ai/grok-latest",dn="x-ai/grok-4.6",_n="x-ai/grok-4.5",Ge="deepseek/deepseek-v4-flash",Ve="deepseek/deepseek-v4-flash-0731",Fe="deepseek/deepseek-v4-pro-0813",Ee="deepseek/deepseek-v4-flash-vision-exp",ro="qwen/qwen3.8-flash",xs=[rr,sr,ar,lr],As=["none","minimal","low","medium","high"],Is=["none","high","xhigh"],Ds=["none","low","high","max"],bs=["none","high","xhigh"],Ns=["low","high","max"],ws=["none","low","high","max"],ks=["none","low","medium","high","xhigh","max"],Ae={[zt]:{efforts:["low","medium","high","xhigh","max"],defaultEffort:"low"},[Xt]:{efforts:["none","low","medium","high","xhigh","max"],defaultEffort:"none"},[qt]:{efforts:["none","low","medium","high","xhigh","max"],defaultEffort:"none"},[jt]:{efforts:["low","medium","high","xhigh","max"],defaultEffort:"low"},[Zt]:{efforts:["low","medium","high","xhigh","max"],defaultEffort:"low"},[Jt]:{efforts:["low","medium","high","xhigh"],defaultEffort:"low"},[Yt]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"medium"},[Qt]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"medium"},[_e]:{efforts:["max","xhigh","high","medium","low"],defaultEffort:"high"},[eo]:{efforts:["max","high","low","none"],defaultEffort:"none"},[to]:{efforts:["high","medium","low"],defaultEffort:"medium"},[Ie]:{efforts:[],defaultEffort:void 0},[Do]:{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"}},ri=[B,Ie,De,be],pr=[zt,Xt,qt,jt,Zt,Jt,Yt,Qt,_e,eo,to,Ie,De,be,fe,me,Ne,bo,no,ko,Go,Vo,Fo,Uo,Ko,Ho,Bo,Wo,$o,zo,Xo,qo,jo,Zo,Jo,Yo,we,Qo,io,en,tn,on,nn,rn,sn,an,ln,pn,cn,un,W,ge,Ee,ro,No,wo,hn,dn,_n],si=20,Gs=50,Vs=1e3,Fs=10;function Oe(o){return o.trim().endsWith(":free")}function Ue(o){return pr.some(e=>o.includes(e))}function fn(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?Ns:e===Ee?ws:e===we||e===io?ks:e===Ge?Is:e===Ve?Ds:e===Fe?bs:As}function mn(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===ke||e===ro||e===no||e===we||e===Ee||e===Ge||e===Ve||e===Fe?"none":void 0}function ai(o,e){let t=o.trim(),n=Object.prototype.hasOwnProperty.call(Ae,t)?Ae[t]:void 0,i=e??mn(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(fn(o).includes(i))return i;if(t===Ge)return i==="max"?"xhigh":"none";if(t===Ve){if(i==="minimal"||i==="medium")return"low";if(i==="xhigh")return"high"}if(t===Fe){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 so="https://api.z.ai/api/paas/v4/chat/completions",gn="glm-5.3",ao="glm-5.3-flash",oe="glm-5.3-flashx",ne="glm-5.2",li="glm-5.1",pi="glm-5",ci="glm-5-turbo",En="glm-5v-turbo",ui="glm-4.7",hi="glm-4.7-FlashX",di="glm-4.7-Flash",_i="glm-4.6",On="glm-4.6V",Mn="glm-4.6V-FlashX",Me="glm-4.6V-Flash",Us=["none","minimal","low","medium","high","xhigh","max"],Ks=["low","high","max"];function Ke(o){return o===gn||o===ao||o===oe}function He(o){return Ke(o)?Ks:o===ne?Us:[]}function Sn(o){return He(o).length>0}function cr(o){return Ke(o)?"low":o===ne?"none":void 0}function lo(o,e){if(!Sn(o))return;let t=e??cr(o);return Ke(o)?t==="high"?"high":t==="max"||t==="xhigh"?"max":"low":t==="none"||t==="minimal"?"none":t==="low"||t==="medium"||t==="high"?"high":"max"}var ur=[oe,ao,En,On,Mn,Me];function Be(o){return ur.includes(o)}function fi(o){let e=o.toLowerCase();return e.startsWith("glm-5.3")||e.startsWith("glm-4.6")}var po="https://api.x.ai/v1/chat/completions",We="grok-4.6",$e="grok-4.7",ze="grok-4.5",K="grok-4.3",vn="grok-4.20-0309-reasoning",Ln="grok-4.20-0309-non-reasoning",hr="grok-4-1-fast-reasoning",dr="grok-4-1-fast-non-reasoning",Hs=[hr,dr],_r=[We,$e,ze,K,vn,Ln];function Xe(o){return _r.includes(o)}function Cn(o){return qe(o).length>0}function qe(o){return o===We||o===$e?["low","medium","high","xhigh"]:o===ze?["low","medium","high"]:o===K?["none","low","medium","high"]:[]}function fr(o){return qe(o).includes("none")}function Tn(o){return o===$e||o===We||o===ze?"low":fr(o)?"none":void 0}function co(o,e){return Cn(o)?e===void 0?Tn(o):qe(o).includes(e)?e:e==="none"?"low":"high":void 0}var je="https://api.moonshot.ai/v1/chat/completions",Ze="kimi-k3",uo="kimi-k2.7-code",ho="kimi-k2.7-code-highspeed",$="kimi-k2.6",Pn="kimi-k2.5",Bs={[Ze]:["low","high","max"]},mr=[Ze,uo,ho,$,Pn],gr=[uo,ho];function Je(o){return mr.includes(o)}function _o(o){return gr.includes(o)}function ie(o){return Bs[o]??[]}function Ye(o){return o===Ze?"max":void 0}function Se(o){return ie(o).length>0}var Or="https://api.deepseek.com",fo=`${Or}/chat/completions`,Rn="deepseek-flash",ve="deepseek-v4-flash",yn="deepseek-v4-pro",Qe="deepseek-v4-flash-vision-exp",Er=["none","low","high","max"],Ws=["none","high","max"],Mr="deepseek-chat",Sr="deepseek-reasoner",gi=[Rn,ve,yn,Qe],vr=[Rn,Qe],$s=[Mr,Sr];function mo(o){return o===Rn||o===ve||o===Qe?Er:o===yn?Ws:[]}function Ei(o){return vr.includes(o)}function Lr(o){return mo(o).length>0}function mi(o){return Lr(o)?"none":void 0}function Oi(o,e){let t=mo(o);if(t.length===0)return;let n=e??mi(o);return n&&t.includes(n)?n:o===yn&&n==="low"?"high":mi(o)}var Cr="https://api.mistral.ai/v1",go=`${Cr}/chat/completions`,Mi="ministral-3b-2512",Si="ministral-8b-2512",vi="ministral-14b-2512",z="mistral-small-latest",Li="mistral-small-2603",xn="mistral-medium-3-5",Tr="mistral-medium-2508",Ci="mistral-large-latest",Ti="mistral-large-2512",Pi=[z,Mi,Si,vi,xn,Ci,Ti,Li],zs=[Tr],Pr=[z,xn],Rr=[z,Mi,Si,vi,Li,xn,Ci,Ti];function Eo(o){return Pr.includes(o)}function Ri(o){return o==="none"||o==="high"}function yi(o){return Rr.includes(o)}var yr="https://api.sakana.ai/v1",Oo=`${yr}/chat/completions`,et="fugu",xr="fugu-ultra",Ar="fugu-ultra-v1.1",Le="sakana-namazu",Ir="fugu-ultra-20260615",xi=[et,Ar,Le],Dr=[Le];function Ai(o){return Dr.includes(o)}var Xs=[xr,Ir];var br="https://api.platform.preferredai.jp/v1",Mo=`${br}/chat/completions`,tt="plamo-3.0-prime",Nr="plamo-2.2-prime",Ii=[tt],qs=[Nr];var C={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},An={[C.VERY_SHORT]:40,[C.SHORT]:100,[C.MEDIUM]:200,[C.LONG]:300,[C.VERY_LONG]:1e3,[C.DEEP]:5e3},Di=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?An[o]??Di:Di}var js="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",Zs=`You are a skilled summarizing assistant.
|
|
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.
|
|
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 Ce="gemini-nano",
|
|
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 Fr(o,i=>{let r=Vr(i,t.onJsonError);if(!r)return;t.throwOnApiError&&ki(r);let s=In(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 Fr(o,_=>{let f=Vr(_,t.onJsonError);if(!f)return;t.throwOnApiError&&ki(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=In(h?.content);E&&(e(E),p(n,E),r+=E);let k=In(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&&ki(o);let t=o?.choices?.[0],n=[],i=In(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 ta=[{id:"ollama",label:"Ollama",baseUrl:"http://localhost:11434/v1",docsUrl:"https://docs.ollama.com/api/openai-compatibility",corsHint:"Set OLLAMA_ORIGINS to allow additional browser origins."},{id:"lmStudio",label:"LM Studio",baseUrl:"http://localhost:1234/v1",docsUrl:"https://lmstudio.ai/docs/developer/openai-compat",corsHint:"Start the server with lms server start --cors for browser access."},{id:"llamaCpp",label:"llama.cpp",baseUrl:"http://127.0.0.1:8080/v1",docsUrl:"https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md",corsHint:"All origins are allowed by default; use --cors-origins to restrict them."},{id:"vllm",label:"vLLM",baseUrl:"http://localhost:8000/v1",docsUrl:"https://docs.vllm.ai/en/latest/serving/online_serving/openai_compatible_server/",corsHint:"All origins are allowed by default; use --allowed-origins to restrict them."}],R=class extends Error{constructor(e,t,n){super(t),this.name="OpenAICompatibleEndpointError",this.code=e,this.status=n}};function Ur(o){let e;try{e=new URL(o.trim())}catch{throw new R("invalid-url","Enter a valid HTTP or HTTPS endpoint URL.")}if(e.protocol!=="http:"&&e.protocol!=="https:"||e.search||e.hash||e.username||e.password)throw new R("invalid-url","Use an HTTP or HTTPS endpoint URL without credentials, a query, or a fragment.");let t=e.pathname.replace(/\/+$/,"");if(t.endsWith("/api/chat")||t.endsWith("/api/generate"))throw new R("invalid-url","This looks like Ollama's native API URL. Use the OpenAI-compatible base URL instead, e.g. http://localhost:11434/v1.");let n=!t||t==="/"?"/v1":t.endsWith("/chat/completions")?t.slice(0,-17):t,i=`${e.origin}${n}`;return{baseUrl:i,chatCompletionsUrl:`${i}/chat/completions`,modelsUrl:`${i}/models`}}async function Kr(o){let{modelsUrl:e}=Ur(o.endpoint),t=o.timeoutMs??8e3;if(!Number.isFinite(t)||t<=0)throw new RangeError("timeoutMs must be a positive finite number.");if(o.signal?.aborted)throw new R("aborted","The models request was aborted by the caller.");let n=new AbortController,i,r=()=>{i||(i="caller"),n.abort()};o.signal?.addEventListener("abort",r,{once:!0}),o.signal?.aborted&&r();let s=setTimeout(()=>{i||(i="timeout"),n.abort()},t);try{let a={};o.apiKey?.trim()&&(a.Authorization=`Bearer ${o.apiKey.trim()}`);let l=await(o.fetch??fetch)(e,{method:"GET",headers:a,signal:n.signal});if(i)throw new R("aborted","The models request was aborted by the caller.");if(!l.ok)throw new R("http",`Model listing failed with HTTP ${l.status}.`,l.status);let p;try{p=await l.json()}catch{throw new R("invalid-response","The models endpoint did not return valid JSON.")}if(!p||typeof p!="object"||!("data"in p)||!Array.isArray(p.data)||!p.data.every(u=>u&&typeof u=="object"&&"id"in u&&typeof u.id=="string"))throw new R("invalid-response","The models response must contain data with model IDs.");if(i)throw new R("aborted","The models request was aborted by the caller.");return[...new Set(p.data.map(u=>u.id))]}catch(a){throw i==="caller"?new R("aborted","The models request was aborted by the caller."):i==="timeout"?new R("timeout",`The models request timed out after ${t} ms.`):a instanceof R?a:new R("network","Could not reach the models endpoint. In a browser, this is usually a CORS restriction or the server is not running.")}finally{clearTimeout(s),o.signal?.removeEventListener("abort",r)}}async function oa(o){let e=Date.now();try{let t=await Kr(o);return{ok:!0,latencyMs:Date.now()-e,models:t,...o.model!==void 0?{modelFound:t.includes(o.model)}:{}}}catch(t){if(t instanceof RangeError)throw t;return{ok:!1,error:t instanceof R?t:new R("network","Could not reach the models endpoint. In a browser, this is usually a CORS restriction or the server is not running.")}}}var 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 na="https://openrouter.ai/api/v1/models",ia=2,ra=12e3,sa=1,aa=10;function Gi(o){return o instanceof Error?o.message:String(o)}function Dn(o,e){return typeof o!="number"||!Number.isFinite(o)?e:Math.max(1,Math.floor(o))}function la(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 Hr(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 Br(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 pa(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 la(n)}async function ca({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 Hr(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 Br(a)};try{await a.json()}catch(l){return{id:o,ok:!1,reason:`JSON parse failed: ${Gi(l)}`}}return{id:o,ok:!0}}catch(a){return{id:o,ok:!1,reason:Gi(a)}}}async function ua(o,e,t){if(o.length===0)return[];let n=new Array(o.length),i=0,r=Math.min(e,o.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<o.length;){let s=i;i+=1,n[s]=await t(o[s])}})),n}async function ha(o){let e=o.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=o.modelsEndpoint||na,n=o.endpoint||$t,i=Dn(o.timeoutMs,ra),r=Dn(o.concurrency,ia),s=Dn(o.maxCandidates,sa),a=Dn(o.maxWorking,aa),l=await Hr(t,{method:"GET"},i);if(!l.ok)throw new Error(await Br(l));let p;try{p=await l.json()}catch(_){throw new Error(`JSON parse failed: ${Gi(_)}`)}let u=pa(p).filter(_=>Oe(_)).slice(0,s),c=await ua(u,r,_=>ca({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 Wr(o){return o.map(e=>({role:vo(e.role),content:e.provider_content??e.content}))}function $r(o){return o.map(e=>{if(e.provider_content)return{role:vo(e.role),content:e.provider_content};if(typeof e.content=="string")return{role:vo(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:da(n.image_url.url)}}}return n}).filter(n=>n);return{role:vo(e.role),content:t}}return{role:vo(e.role),content:[]}})}function vo(o){switch(o){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}function da(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 nt=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,!Wt.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?$r(s):Wr(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(Yn,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||"{}"),I=s.get(h.index);I&&(I.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
|
|
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),_a(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 _a(o,e,t,n,i,r,s){switch(o){case"response.output_item.added":zr(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":zr(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(Xr(e,"completed"));break;case"response.incomplete":s(Xr(e,"incomplete"));break;default:break}}function zr(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 Xr(o,e){let t=o?.response??o;return{responseStatus:t?.status??e,incompleteDetails:t?.incomplete_details??null,usage:t?.usage}}function jr(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 Zr({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(...fa(e)),n}function fa(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 ma={[C.VERY_SHORT]:800,[C.SHORT]:1200,[C.MEDIUM]:2e3,[C.LONG]:3e3,[C.VERY_LONG]:8e3,[C.DEEP]:25e3},ga={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3,max:25e3},Ea=new Set(["openai-compatible","deepseek","mistral","sakana","plamo"]);function Oa(o){return o.type!=="json_schema"?o:{type:o.type,...o.json_schema}}function Jr({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===y||o==="openai"&&n===P)&&(!p||p==="none"||p==="minimal")&&(p="low");let _=e===w;if(o==="openai"&&n===P&&(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.");Sa(e,s);let f={model:n,stream:i},v=Ma({provider:o,model:n,responseLength:a,reasoning_effort:p,maxTokens:m});_?v!==void 0&&(f.max_output_tokens=v):v!==void 0&&(Yr(o)?f.max_tokens=v:f.max_completion_tokens=v),_?f.input=va(t):f.messages=o==="mistral"?La(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:Oa(c)}:f.response_format=c),o==="mistral"&&Eo(n)&&p&&Ri(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=Zr({tools:r,mcpServers:s,isResponsesAPI:_});return h.length>0&&(f.tools=h,_||(f.tool_choice="auto")),f}function Ma({provider:o,model:e,responseLength:t,reasoning_effort:n,maxTokens:i}){if(i!==void 0)return i;let r=Yr(o)?t!==void 0?x(t):void 0:x(t);if(o!=="openai"||!he(e)||t===void 0)return r;let s=n??It(e);return Math.max(r??0,ma[t],ga[s])}function Sa(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 va(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 La(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 Yr(o){return Ea.has(o)}var A=class{constructor(e,t=ue,n=ue,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===P||n===P)&&(this.tools.length>0||s.length>0);if(this.endpoint=(t===y||n===y||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&&!yt.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 bn(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 bn(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?bn(e,n):jr(await e.json()):t?this.parseStream(e,n):this.parseOneShot(await e.json())}async callOpenAI(e,t,n=!1,i){let r=Jr({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 rt=class extends A{constructor(e,t=ve,n=t,i,r=fo,s,a){let l=Oi(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 st=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:Qe,supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"explicit"}),i=e.tools;return new rt(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"deepseek"}getSupportedModels(){return[...gi]}getDefaultModel(){return ve}supportsVision(){return!0}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ei(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("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 fo}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Qr=(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"]}}),Nn=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:[Qr(e)],failures:[]}}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),{schemas:[Qr(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 es(o){switch(o){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}function ts(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=es(s.role);if(s.tool_calls){r();let l=s.tool_calls.map(p=>is(p,e));l.length>0&&t.push({role:"model",parts:l});continue}if(s.role==="tool"){r(),ss(t,rs(s,e));continue}a!==n&&r(),n=a,i.push({text:s.content})}return r(),t}async function os(o,e={}){let t=e.imageFetcher??O.get,n=e.blobToBase64??Pa,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=es(l.role);if(l.tool_calls){a();let u=l.tool_calls.map(c=>is(c,e));u.length>0&&i.push({role:"model",parts:u});continue}if(l.role==="tool"){a(),ss(i,rs(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 ns(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 is(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 rs(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:Ta(Ca(o.content))}}}function ss(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 Ca(o){try{return JSON.parse(o)}catch{return o}}function Ta(o){return o===null?{content:null}:typeof o=="object"?o:{content:o}}function Pa(o){return new Promise((e,t)=>{let n=new FileReader;n.onloadend=()=>e(n.result),n.onerror=t,n.readAsDataURL(o)})}function Ra(o,e){return[...o,...e].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}function as(o,e){let t=Ra(o,e);if(t.length!==0)return{tools:[{functionDeclarations:t}],toolConfig:{functionCallingConfig:{mode:"AUTO"}}}}function ls(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 at=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,!Dt.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=bt(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=Nn.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=ls(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 os(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}):ts(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}),generationConfig:{maxOutputTokens:i!==void 0?i:x(this.responseLength)}},l=ns(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=as(this.tools,u);c&&Object.assign(a,c);let d=async(g,L)=>{let D=n?"streamGenerateContent":"generateContent",I=n?"?alt=sse":"",_s=`${Kn}/${g}/models/${t}:${D}${I}${I?"&":"?"}key=${this.apiKey}`;return O.post(_s,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 Ce="gemini-nano",Vi=20;var re=class extends Error{constructor(t,n,i){super(`HTTP ${t}: ${n}`);this.status=t;this.statusText=n;this.body=i;this.name="HttpError"}},Co=class Co{static setFetch(e){this.fetchImpl=e}static async post(e,t,n={},i={}){let{timeout:r=3e4,retries:s=0,retryDelay:a=1e3}=i,p={...{"Content-Type":"application/json"},...n},u=null;for(let c=0;c<=s;c++)try{let d=typeof AbortController<"u",m=d?new AbortController:void 0,_=d?setTimeout(()=>m.abort(),r):void 0,f=await Co.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 re(f.status,f.statusText,v)}return f}catch(d){if(u=d,d instanceof re&&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 re(e.status,e.statusText,t)}static async get(e,t={},n={}){let{timeout:i=3e4,retries:r=0,retryDelay:s=1e3}=n,a=null;for(let l=0;l<=r;l++)try{let p=typeof AbortController<"u",u=p?new AbortController:void 0,c=p?setTimeout(()=>u.abort(),i):void 0,d=await Co.fetchImpl(e,{method:"GET",headers:t,...u?{signal:u.signal}:{}});if(c&&clearTimeout(c),!d.ok){let m=await d.text();throw new re(d.status,d.statusText,m)}return d}catch(p){if(a=p,p instanceof re&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError")throw new Error(`Request timeout after ${i}ms`);l<r&&await new Promise(u=>setTimeout(u,s*(l+1)))}throw a||new Error("Request failed")}};Co.fetchImpl=(e,t)=>fetch(e,t);var O=Co;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 oa=["happy","sad","angry","surprised","neutral"],Ur=/\[([a-z]+)\]/i,Fi=/\[[a-z]+\]\s*/gi,it=class{static extractEmotion(e){let t=e.match(Ur);if(t){let n=t[1].toLowerCase(),i=e.replace(Fi,"").trim();return{emotion:n,cleanText:i}}return{cleanText:e}}static isValidEmotion(e){return oa.includes(e)}static cleanEmotionTags(e){return e.replace(Fi,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function Kr(o){let{emotion:e,cleanText:t}=it.extractEmotion(o);return e?{emotion:e,text:t}:{text:t}}function na(o){return o.map(e=>Kr(e))}function ia(o){return o.emotion?it.addEmotionTag(o.emotion,o.text):o.text}async function ra(o,e){let{blocks:t}=await o.chatOnce(e,!1,()=>{});return M.getFullText(t)}var Hr=(o,e,t)=>{try{return JSON.parse(o)}catch(n){return t?.(o,n),e}},Te=(o,e)=>o?Hr(o,{},e):{};var Br=(o,e)=>{try{return JSON.parse(o)}catch(t){if(e){e(o,t);return}throw t}},Nn=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(""):"",Ui=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}`)},Wr=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 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||"{}"),I=s.get(h.index);I&&(I.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 st=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 rt(e.apiKey,t,i,e.tools??[],e.mcpServers??[],e.responseLength,e.reasoning_effort)}getProviderName(){return"claude"}getSupportedModels(){return[bo,U,Gt,Vt,Ft,Ut,Kt,kt,Ht,Bt,Wt,No,$t]}getDefaultModel(){return U}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return zt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function Qr(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 kn(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(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 ct=class{createChatService(e){let t=e.model||this.getDefaultModel();if(e.reasoning_effort!==void 0&&!ei(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 pt(e.apiKey,t,n,e.tools||[],e.mcpServers||[],e.responseLength,wt(t,e.reasoning_effort))}getProviderName(){return"gemini"}getSupportedModels(){return[...Do]}getDefaultModel(){return ee}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Nt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function ba(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var ut=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 Ce}getVisionModel(){return Ce}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=ba();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=An[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 ct=class{createChatService(e){return new pt({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 ut=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??Ye(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(!Je(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(!Je(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&&(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??Ye(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(_o(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 ht=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 ut(e.apiKey,n,i,r,t,e.responseLength,e.responseFormat,s,a)}getProviderName(){return"kimi"}getSupportedModels(){return[Ze,uo,ho,$,Pn]}getDefaultModel(){return $}getDefaultVisionModel(){return $}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Je(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(_o(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??Ye(e)??n[0];if(!n.includes(i))throw new Error(`Model ${e} supports reasoning_effort values: ${n.join(", ")}.`);return i}};var dt=class extends A{constructor(e,t=z,n=t,i,r=go,s,a){super(e,t,n,i,r,[],s,void 0,a,!1,"mistral",!1)}};var _t=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=Eo(t)?e.reasoning_effort:void 0;return new dt(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"mistral"}getSupportedModels(){return[...Pi]}getDefaultModel(){return z}getDefaultVisionModel(){return z}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return yi(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("mistral provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return go}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var ft=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 mt=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===y||n===y)a=!0;else if(s===b||n===b||s===N||n===N)a=(t.gpt5EndpointPreference||"responses")!=="chat"||t.reasoning_effort!=="none";else if(Fn(s))a=!0;else if(s===P||n===P){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: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 A(...p)}getProviderName(){return"openai"}getSupportedModels(){return[se,Pe,Re,ye,ae,le,j,P,y,b,N,Z,J,Y,pe,ce,Q,Lo,Co,To,ue,Po,kn,Gn,"o1"]}getDefaultModel(){return se}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return yt.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=bi[e.gpt5Preset];n.reasoning_effort=i.reasoning_effort,n.verbosity=i.verbosity}else e.reasoning_effort||(n.reasoning_effort=It(t));return n.reasoning_effort=this.normalizeReasoningEffort(t,n.reasoning_effort),n}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!xt(e)||t==="minimal"&&!At(e)?t==="minimal"&&xt(e)?"none":t==="none"&&At(e)?"minimal":yo(e)?"low":"medium":t==="low"&&!yo(e)?"medium":t==="xhigh"&&!Ro(e)?"high":t==="max"&&!Un(e)?Ro(e)?"xhigh":"high":t}};var cs=o=>[oo,Ne].includes(o.trim()),xa=o=>[B,te,W,ke].includes(o.trim()),Vi=(o,e)=>{if(cs(o)&&!e)throw new Error("OpenRouter Auto Router returned no visible content. Please retry.")},ps=o=>o.blocks.some(e=>e.type!=="text"||e.text.trim().length>0),gt=class{constructor(e,t=B,n=B,i,r=$t,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>=si){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(!Ue(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(!Ue(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=xa(t)||cs(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=mn(t),p=ai(t,this.reasoning_effort);if(p!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens||l){if(r.reasoning={},p){let u=p==="minimal"&&t!==fe&&t!==me?"low":p;r.reasoning.effort=u}else l&&(r.reasoning.effort=l);(p==="none"||this.includeReasoning!==!0)&&(r.reasoning.exclude=!0),this.reasoningMaxTokens&&(r.reasoning.max_tokens=this.reasoningMaxTokens)}else r.reasoning={exclude:!0};return this.tools.length>0&&(r.tools=F(this.tools,"chat-completions"),t!==_e&&(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 Vi(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 Vi(n,ps(i)),i}parseOneShot(e,t){let n=V(e,{throwOnApiError:!0});return Vi(t,ps(n)),n}};var Et=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 gt(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[zt,Xt,qt,jt,Zt,Jt,Yt,Qt,_e,eo,to,Ie,Do,De,be,fe,me,oo,Ne,ei,B,Go,Vo,Fo,Uo,Ko,Ho,Bo,Wo,$o,zo,Xo,qo,jo,Zo,Jo,Yo,we,Qo,io,en,tn,on,nn,rn,sn,an,ln,pn,cn,un,te,W,ge,ke,ti,oi,hn,dn,_n,Ve,Ge,Fe,Ee,ro,ko,bo,No,no,wo,ni,ii]}getDefaultModel(){return B}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return Ue(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return ri}isModelFree(e){return Oe(e)}};var Ot=class extends A{constructor(e,t=tt,n=t,i,r=Mo,s,a){super(e,t,n,i,r,[],s,void 0,a,!1,"plamo",!1)}};var Mt=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=e.tools;return new Ot(e.apiKey,t,e.visionModel??t,n,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"plamo"}getSupportedModels(){return[...Ii]}getDefaultModel(){return tt}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 Mo}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var St=class extends A{constructor(e,t=et,n=t,i,r=Oo,s,a){super(e,t,n,i,r,[],s,void 0,void 0,!1,"sakana",!1,void 0,a?.type==="enabled")}};var vt=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),n=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel: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 St(e.apiKey,t,n,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"sakana"}getSupportedModels(){return[...xi]}getDefaultModel(){return et}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("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 Oo}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Lt=class{constructor(e,t=K,n=K,i,r=po,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(!Xe(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(!Xe(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&&Cn(t)&&(r.reasoning_effort=co(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 Ct=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 Lt(e.apiKey,t,n,i,e.endpoint||po,e.responseLength,co(t,e.reasoning_effort??Tn(t)))}getProviderName(){return"xai"}getSupportedModels(){return[We,$e,ze,K,vn,Ln]}getDefaultModel(){return K}getDefaultVisionModel(){return K}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Xe(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Tt=class{constructor(e,t=ne,n=Me,i,r=so,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(!Be(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await S({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.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(!Be(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===oe?(r.thinking={type:"enabled",clear_thinking:this.thinking?.clear_thinking??!0},r.reasoning_effort=lo(t,this.reasoningEffort)):this.thinking&&(r.thinking=this.thinking),t!==oe&&Sn(t)&&this.reasoningEffort&&(r.reasoning_effort=this.reasoningEffort);let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto",n&&fi(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 Pt=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=He(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=lo(t,e.reasoning_effort),a=Ke(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 Tt(e.apiKey,t,n,i,e.endpoint||so,e.responseLength,e.responseFormat,p,u)}getProviderName(){return"zai"}getSupportedModels(){return[gn,ao,oe,ne,li,pi,ci,En,ui,hi,di,_i,On,Mn,Me]}getDefaultModel(){return ne}getDefaultVisionModel(){return Me}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Be(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var us=[new mt,new ft,new lt,new ct,new it,new Et,new Pt,new Ct,new ht,new st,new _t,new vt,new Mt];var Aa=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"]),Ia=new Set(["claude","deepseek","gemini","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),Da=new Set(["codex-sdk"]);function Fi(o){if(Aa.has(o))return{text:!0,streaming:!Da.has(o),tools:Ia.has(o)}}function ba(o){let e=o.provider==="claude",t=o.messages.filter(r=>!hs(e,r)),n=o.completion.blocks.filter(r=>r.type==="tool_use"),i=o.completion.assistant_message??Na(e,n);return hs(e,i)||t.push({...i}),t.push(...wa(e,o.toolResults)),t}function hs(o,e){if(!o||e.role!=="assistant")return!1;let t=e.content;return Array.isArray(t)&&t.length===0}function Na(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 wa(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"]),Ga=new Set(["openai","openai-compatible","zai","kimi"]),Va={openai:["none","minimal","low","medium","high","xhigh","max"],claude:["low","medium","high","xhigh","max"],gemini:["minimal","low","medium","high"],openrouter:["none","minimal","low","medium","high","xhigh","max"],kimi:["low","high","max"],mistral:["low","medium","high"],plamo:["none","medium"],xai:["none","low","medium","high","xhigh"],deepseek:["none","low","high","max"],zai:["none","minimal","low","medium","high","xhigh","max"]},Rt=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=Fi(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:Ga.has(e),responseLength:!0,reasoningEffort:e==="openai"&&(t===P||t===y)?["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?[...xe(t)]:e==="kimi"&&t?[...ie(t)]:e==="deepseek"&&t?[...mo(t)]:e==="openrouter"&&t?[...fn(t)]:e==="xai"&&t?[...qe(t)]:e==="zai"&&t?[...He(t)]:Va[e]??[]}}static getAllProviderCapabilities(){return this.getAvailableProviders().map(e=>this.getProviderCapabilities(e)).filter(e=>e!==void 0)}static getVisionSupportLevel(e){let t=this.providers.get(e);return t?t.getVisionSupportLevel():"unsupported"}static getVisionSupportLevelForModel(e,t){let n=this.providers.get(e);return n?n.getVisionSupportLevelForModel?n.getVisionSupportLevelForModel(t):n.supportsVisionForModel?n.supportsVisionForModel(t)?"supported":"unsupported":n.getVisionSupportLevel():"unsupported"}};Rt.providers=new Map;us.forEach(o=>Rt.registerProvider(o));function ds(){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 Ms(Fa);})();
|
|
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);})();
|