@aituber-onair/chat 0.38.0 → 0.40.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 +19 -9
- package/README.md +18 -9
- package/dist/cjs/constants/kimi.d.ts +7 -0
- package/dist/cjs/constants/kimi.d.ts.map +1 -1
- package/dist/cjs/constants/kimi.js +21 -2
- package/dist/cjs/constants/kimi.js.map +1 -1
- package/dist/cjs/constants/openai.d.ts +3 -2
- package/dist/cjs/constants/openai.d.ts.map +1 -1
- package/dist/cjs/constants/openai.js +5 -1
- package/dist/cjs/constants/openai.js.map +1 -1
- package/dist/cjs/constants/openrouter.d.ts +3 -0
- package/dist/cjs/constants/openrouter.d.ts.map +1 -1
- package/dist/cjs/constants/openrouter.js +5 -1
- package/dist/cjs/constants/openrouter.js.map +1 -1
- package/dist/cjs/constants/zai.d.ts +1 -0
- package/dist/cjs/constants/zai.d.ts.map +1 -1
- package/dist/cjs/constants/zai.js +2 -1
- package/dist/cjs/constants/zai.js.map +1 -1
- package/dist/cjs/services/providers/kimi/KimiChatService.d.ts +1 -0
- package/dist/cjs/services/providers/kimi/KimiChatService.d.ts.map +1 -1
- package/dist/cjs/services/providers/kimi/KimiChatService.js +13 -1
- package/dist/cjs/services/providers/kimi/KimiChatService.js.map +1 -1
- package/dist/cjs/services/providers/kimi/KimiChatServiceProvider.d.ts +2 -0
- package/dist/cjs/services/providers/kimi/KimiChatServiceProvider.d.ts.map +1 -1
- package/dist/cjs/services/providers/kimi/KimiChatServiceProvider.js +22 -5
- package/dist/cjs/services/providers/kimi/KimiChatServiceProvider.js.map +1 -1
- package/dist/cjs/services/providers/openrouter/OpenRouterChatService.d.ts.map +1 -1
- package/dist/cjs/services/providers/openrouter/OpenRouterChatService.js +12 -4
- 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/cjs/services/providers/zai/ZAIChatService.js +1 -1
- package/dist/cjs/services/providers/zai/ZAIChatServiceProvider.d.ts.map +1 -1
- package/dist/cjs/services/providers/zai/ZAIChatServiceProvider.js +2 -1
- package/dist/cjs/services/providers/zai/ZAIChatServiceProvider.js.map +1 -1
- package/dist/esm/constants/kimi.d.ts +7 -0
- package/dist/esm/constants/kimi.d.ts.map +1 -1
- package/dist/esm/constants/kimi.js +19 -1
- package/dist/esm/constants/kimi.js.map +1 -1
- package/dist/esm/constants/openai.d.ts +3 -2
- package/dist/esm/constants/openai.d.ts.map +1 -1
- package/dist/esm/constants/openai.js +5 -1
- package/dist/esm/constants/openai.js.map +1 -1
- package/dist/esm/constants/openrouter.d.ts +3 -0
- package/dist/esm/constants/openrouter.d.ts.map +1 -1
- package/dist/esm/constants/openrouter.js +4 -0
- package/dist/esm/constants/openrouter.js.map +1 -1
- package/dist/esm/constants/zai.d.ts +1 -0
- package/dist/esm/constants/zai.d.ts.map +1 -1
- package/dist/esm/constants/zai.js +1 -0
- package/dist/esm/constants/zai.js.map +1 -1
- package/dist/esm/services/providers/kimi/KimiChatService.d.ts +1 -0
- package/dist/esm/services/providers/kimi/KimiChatService.d.ts.map +1 -1
- package/dist/esm/services/providers/kimi/KimiChatService.js +14 -2
- package/dist/esm/services/providers/kimi/KimiChatService.js.map +1 -1
- package/dist/esm/services/providers/kimi/KimiChatServiceProvider.d.ts +2 -0
- package/dist/esm/services/providers/kimi/KimiChatServiceProvider.d.ts.map +1 -1
- package/dist/esm/services/providers/kimi/KimiChatServiceProvider.js +23 -6
- package/dist/esm/services/providers/kimi/KimiChatServiceProvider.js.map +1 -1
- package/dist/esm/services/providers/openrouter/OpenRouterChatService.d.ts.map +1 -1
- package/dist/esm/services/providers/openrouter/OpenRouterChatService.js +13 -5
- 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/esm/services/providers/zai/ZAIChatService.js +2 -2
- package/dist/esm/services/providers/zai/ZAIChatServiceProvider.d.ts.map +1 -1
- package/dist/esm/services/providers/zai/ZAIChatServiceProvider.js +3 -2
- package/dist/esm/services/providers/zai/ZAIChatServiceProvider.js.map +1 -1
- package/dist/umd/aituber-onair-chat.js +83 -10
- 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 Bt=Object.defineProperty;var Er=Object.getOwnPropertyDescriptor;var Or=Object.getOwnPropertyNames;var Sr=Object.prototype.hasOwnProperty;var Cr=(i,e)=>{for(var t in e)Bt(i,t,{get:e[t],enumerable:!0})},Tr=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Or(e))!Sr.call(i,r)&&r!==t&&Bt(i,r,{get:()=>e[r],enumerable:!(o=Er(e,r))||o.enumerable});return i};var yr=i=>Tr(Bt({},"__esModule",{value:!0}),i);var pi={};Cr(pi,{CHAT_RESPONSE_LENGTH:()=>C,CLAUDE_VISION_SUPPORTED_MODELS:()=>we,ChatServiceFactory:()=>Ae,ChatServiceHttpClient:()=>f,ClaudeChatService:()=>ce,ClaudeChatServiceProvider:()=>ue,DEEPSEEK_API_BASE_URL:()=>Ko,DEEPSEEK_DEPRECATED_MODELS:()=>Rr,DEEPSEEK_SUPPORTED_MODELS:()=>co,DEFAULT_MAX_TOKENS:()=>vo,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>Nr,DEFAULT_VISION_PROMPT:()=>br,DeepSeekChatService:()=>he,DeepSeekChatServiceProvider:()=>me,EMOTION_TAG_CLEANUP_REGEX:()=>So,EMOTION_TAG_REGEX:()=>Jo,ENDPOINT_CLAUDE_API:()=>Zt,ENDPOINT_DEEPSEEK_CHAT_COMPLETIONS_API:()=>Fe,ENDPOINT_GEMINI_API:()=>Xt,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>se,ENDPOINT_MISTRAL_CHAT_COMPLETIONS_API:()=>Ue,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>U,ENDPOINT_OPENAI_RESPONSES_API:()=>D,ENDPOINT_OPENROUTER_API:()=>Ve,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>Ge,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>ke,EmotionParser:()=>pe,GEMINI_DEPRECATED_MODELS:()=>ko,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>Oo,GEMINI_RECOMMENDED_MODELS:()=>Xe,GEMINI_VISION_SUPPORTED_MODELS:()=>Ne,GPT5_PRESETS:()=>Eo,GPT_5_MODELS:()=>Lo,GeminiChatService:()=>de,GeminiChatServiceProvider:()=>ge,GeminiNanoChatService:()=>_e,GeminiNanoChatServiceProvider:()=>fe,HttpError:()=>F,KIMI_VISION_SUPPORTED_MODELS:()=>Ho,KimiChatService:()=>Me,KimiChatServiceProvider:()=>ve,MAX_TOKENS_BY_LENGTH:()=>Ft,MISTRAL_API_BASE_URL:()=>zo,MISTRAL_REASONING_EFFORT_SUPPORTED_MODELS:()=>jo,MISTRAL_SUPPORTED_MODELS:()=>_o,MISTRAL_VISION_SUPPORTED_MODELS:()=>qo,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>Qt,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>Ct,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>Tt,MODEL_ANTHROPIC_CLAUDE_HAIKU_LATEST:()=>Et,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>Ot,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>St,MODEL_ANTHROPIC_CLAUDE_SONNET_LATEST:()=>vt,MODEL_CLAUDE_3_5_HAIKU:()=>Lr,MODEL_CLAUDE_3_5_SONNET:()=>Pr,MODEL_CLAUDE_3_7_SONNET:()=>Ir,MODEL_CLAUDE_3_HAIKU:()=>Ze,MODEL_CLAUDE_4_5_HAIKU:()=>R,MODEL_CLAUDE_4_5_OPUS:()=>tt,MODEL_CLAUDE_4_5_SONNET:()=>et,MODEL_CLAUDE_4_6_OPUS:()=>rt,MODEL_CLAUDE_4_6_SONNET:()=>ot,MODEL_CLAUDE_4_7_OPUS:()=>it,MODEL_CLAUDE_4_8_OPUS:()=>nt,MODEL_CLAUDE_4_OPUS:()=>Qe,MODEL_CLAUDE_4_SONNET:()=>Ye,MODEL_DEEPSEEK_CHAT:()=>Bo,MODEL_DEEPSEEK_REASONER:()=>$o,MODEL_DEEPSEEK_V4_FLASH:()=>le,MODEL_DEEPSEEK_V4_PRO:()=>Wo,MODEL_GEMINI_2_5_FLASH:()=>No,MODEL_GEMINI_2_5_FLASH_LITE:()=>wo,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>Vo,MODEL_GEMINI_2_5_PRO:()=>bo,MODEL_GEMINI_3_1_FLASH_LITE:()=>q,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>Ao,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>xo,MODEL_GEMINI_3_5_FLASH:()=>Je,MODEL_GEMINI_3_FLASH_PREVIEW:()=>Ro,MODEL_GEMINI_3_PRO_PREVIEW:()=>Do,MODEL_GEMINI_NANO:()=>Z,MODEL_GEMMA_4_26B_A4B_IT:()=>Io,MODEL_GEMMA_4_31B_IT:()=>Po,MODEL_GLM_4_6:()=>lo,MODEL_GLM_4_6V:()=>Dt,MODEL_GLM_4_6V_FLASH:()=>X,MODEL_GLM_4_6V_FLASHX:()=>Rt,MODEL_GLM_4_7:()=>re,MODEL_GLM_4_7_FLASH:()=>ao,MODEL_GLM_4_7_FLASHX:()=>so,MODEL_GLM_5:()=>io,MODEL_GLM_5_TURBO:()=>no,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>It,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>xt,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>Pt,MODEL_GOOGLE_GEMINI_FLASH_LATEST:()=>Lt,MODEL_GOOGLE_GEMINI_PRO_LATEST:()=>yt,MODEL_GPT_4O:()=>ze,MODEL_GPT_4O_MINI:()=>z,MODEL_GPT_4_1:()=>We,MODEL_GPT_4_1_MINI:()=>Be,MODEL_GPT_4_1_NANO:()=>$e,MODEL_GPT_5:()=>ee,MODEL_GPT_5_1:()=>te,MODEL_GPT_5_4:()=>K,MODEL_GPT_5_4_MINI:()=>B,MODEL_GPT_5_4_NANO:()=>$,MODEL_GPT_5_4_PRO:()=>G,MODEL_GPT_5_5:()=>W,MODEL_GPT_5_MINI:()=>Q,MODEL_GPT_5_NANO:()=>H,MODEL_GPT_OSS_20B_FREE:()=>b,MODEL_GROK_4_1_FAST_NON_REASONING:()=>N,MODEL_GROK_4_1_FAST_REASONING:()=>Vt,MODEL_GROK_4_20_NON_REASONING:()=>wt,MODEL_GROK_4_20_REASONING:()=>Nt,MODEL_GROK_4_3:()=>bt,MODEL_KIMI_K2_5:()=>kt,MODEL_KIMI_K2_6:()=>w,MODEL_MISTRAL_LARGE_2512:()=>go,MODEL_MISTRAL_LARGE_LATEST:()=>mo,MODEL_MISTRAL_MEDIUM_2508:()=>ho,MODEL_MISTRAL_MEDIUM_3_5:()=>Gt,MODEL_MISTRAL_SMALL_2603:()=>uo,MODEL_MISTRAL_SMALL_LATEST:()=>V,MODEL_MOONSHOTAI_KIMI_K2_5:()=>st,MODEL_MOONSHOTAI_KIMI_LATEST:()=>at,MODEL_O1:()=>jt,MODEL_O1_MINI:()=>zt,MODEL_O3_MINI:()=>$t,MODEL_OPENAI_GPT_4O:()=>_t,MODEL_OPENAI_GPT_4_1_MINI:()=>ft,MODEL_OPENAI_GPT_4_1_NANO:()=>Mt,MODEL_OPENAI_GPT_5_1_CHAT:()=>ht,MODEL_OPENAI_GPT_5_1_CODEX:()=>mt,MODEL_OPENAI_GPT_5_5:()=>ut,MODEL_OPENAI_GPT_5_5_PRO:()=>ct,MODEL_OPENAI_GPT_5_MINI:()=>dt,MODEL_OPENAI_GPT_5_NANO:()=>gt,MODEL_OPENAI_GPT_LATEST:()=>lt,MODEL_OPENAI_GPT_MINI_LATEST:()=>pt,MODEL_OPENROUTER_AUTO:()=>Yt,MODEL_ZAI_GLM_4_5_AIR:()=>to,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>At,MODEL_ZAI_GLM_4_7_FLASH:()=>eo,MistralChatService:()=>Ee,MistralChatServiceProvider:()=>Oe,OPENROUTER_CREDITS_THRESHOLD:()=>Dr,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>Ar,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>xr,OPENROUTER_FREE_MODELS:()=>oo,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>ro,OPENROUTER_VISION_SUPPORTED_MODELS:()=>Go,OpenAIChatService:()=>y,OpenAIChatServiceProvider:()=>Ce,OpenAICompatibleChatServiceProvider:()=>Se,OpenRouterChatService:()=>Te,OpenRouterChatServiceProvider:()=>ye,StreamTextAccumulator:()=>v,VISION_SUPPORTED_MODELS:()=>De,XAIChatService:()=>Le,XAIChatServiceProvider:()=>Pe,XAI_VISION_SUPPORTED_MODELS:()=>Uo,ZAIChatService:()=>Ie,ZAIChatServiceProvider:()=>xe,ZAI_VISION_SUPPORTED_MODELS:()=>Fo,allowsReasoningLow:()=>qe,allowsReasoningMinimal:()=>je,allowsReasoningNone:()=>Re,allowsReasoningXHigh:()=>Jt,buildOpenAICompatibleTools:()=>x,getDefaultReasoningEffortForGPT5Model:()=>be,getMaxTokensForResponseLength:()=>O,installGASFetch:()=>Mr,isGPT5Model:()=>j,isKimiVisionModel:()=>ae,isMistralReasoningEffort:()=>fo,isMistralReasoningEffortModel:()=>He,isMistralVisionModel:()=>Mo,isOpenRouterFreeModel:()=>J,isOpenRouterVisionModel:()=>oe,isResponsesOnlyGPT5Model:()=>qt,isXaiVisionModel:()=>ne,isZaiToolStreamModel:()=>po,isZaiVisionModel:()=>ie,parseOpenAICompatibleOneShot:()=>I,parseOpenAICompatibleTextStream:()=>L,parseOpenAICompatibleToolStream:()=>P,processChatWithOptionalTools:()=>M,refreshOpenRouterFreeModels:()=>qr,resolveVisionModel:()=>E,runOnceText:()=>Gr,safeJsonParse:()=>Zo,safeParseToolCallInput:()=>Y,screenplayToText:()=>kr,textToScreenplay:()=>Xo,textsToScreenplay:()=>Vr});var U="https://api.openai.com/v1/chat/completions",D="https://api.openai.com/v1/responses",H="gpt-5-nano",Q="gpt-5-mini",ee="gpt-5",te="gpt-5.1",K="gpt-5.4",W="gpt-5.5",B="gpt-5.4-mini",$="gpt-5.4-nano",G="gpt-5.4-pro",We="gpt-4.1",Be="gpt-4.1-mini",$e="gpt-4.1-nano",z="gpt-4o-mini",ze="gpt-4o",$t="o3-mini",zt="o1-mini",jt="o1",De=[H,Q,ee,te,K,W,B,$,G,We,Be,$e,z,ze,"o1"],Lo=[H,Q,ee,te,K,W,B,$,G];function j(i){return Lo.includes(i)}function qt(i){return i===G}function Jt(i){return i===W||i===K||i===B||i===$||i===G}function Re(i){return i===te||i===K||i===W||i===B||i===$}function je(i){return i===H||i===Q||i===ee}function qe(i){return i!==G}function be(i){return Re(i)?"none":"medium"}var Xt="https://generativelanguage.googleapis.com",Po="gemma-4-31b-it",Io="gemma-4-26b-a4b-it",Je="gemini-3.5-flash",xo="gemini-3.1-pro-preview",q="gemini-3.1-flash-lite",Ao="gemini-3.1-flash-lite-preview",Do="gemini-3-pro-preview",Ro="gemini-3-flash-preview",bo="gemini-2.5-pro",No="gemini-2.5-flash",wo="gemini-2.5-flash-lite",Vo="gemini-2.5-flash-lite-preview-06-17",Xe=[Je,q,xo,Ro,bo,No,wo,Po,Io],ko=[Ao,Do,Vo],Ne=[...Xe,...ko];var Zt="https://api.anthropic.com/v1/messages",Ze="claude-3-haiku-20240307",Lr="claude-3-5-haiku-20241022",Pr="claude-3-5-sonnet-20241022",Ir="claude-3-7-sonnet-20250219",Ye="claude-sonnet-4-20250514",Qe="claude-opus-4-20250514",et="claude-sonnet-4-5-20250929",R="claude-haiku-4-5-20251001",tt="claude-opus-4-5-20251101",ot="claude-sonnet-4-6",rt="claude-opus-4-6",it="claude-opus-4-7",nt="claude-opus-4-8",we=[Ze,Ye,Qe,et,R,tt,ot,rt,it,nt];var Ve="https://openrouter.ai/api/v1/chat/completions",Yt="openrouter/auto",b="openai/gpt-oss-20b:free",st="moonshotai/kimi-k2.5",at="~moonshotai/kimi-latest",lt="~openai/gpt-latest",pt="~openai/gpt-mini-latest",ct="openai/gpt-5.5-pro",ut="openai/gpt-5.5",ht="openai/gpt-5.1-chat",mt="openai/gpt-5.1-codex",dt="openai/gpt-5-mini",gt="openai/gpt-5-nano",_t="openai/gpt-4o",ft="openai/gpt-4.1-mini",Mt="openai/gpt-4.1-nano",vt="~anthropic/claude-sonnet-latest",Et="~anthropic/claude-haiku-latest",Ot="anthropic/claude-opus-4",St="anthropic/claude-sonnet-4",Ct="anthropic/claude-3.7-sonnet",Qt="anthropic/claude-3.5-sonnet",Tt="anthropic/claude-haiku-4.5",yt="~google/gemini-pro-latest",Lt="~google/gemini-flash-latest",Pt="google/gemini-2.5-pro",It="google/gemini-2.5-flash",xt="google/gemini-2.5-flash-lite-preview-09-2025",eo="z-ai/glm-4.7-flash",to="z-ai/glm-4.5-air",At="z-ai/glm-4.5-air:free",oo=[b,At],Go=[at,lt,pt,ct,ut,ht,mt,dt,gt,_t,ft,Mt,vt,Et,Ot,St,Ct,Tt,yt,Lt,Pt,It,xt,st],ro=20,xr=50,Ar=1e3,Dr=10;function J(i){return i.trim().endsWith(":free")}function oe(i){return Go.some(e=>i.includes(e))}var ke="https://api.z.ai/api/paas/v4/chat/completions",io="glm-5",no="glm-5-turbo",re="glm-4.7",so="glm-4.7-FlashX",ao="glm-4.7-Flash",lo="glm-4.6",Dt="glm-4.6V",Rt="glm-4.6V-FlashX",X="glm-4.6V-Flash",Fo=[Dt,Rt,X];function ie(i){return Fo.includes(i)}function po(i){return i.toLowerCase().startsWith("glm-4.6")}var Ge="https://api.x.ai/v1/chat/completions",bt="grok-4.3",Nt="grok-4.20-0309-reasoning",wt="grok-4.20-0309-non-reasoning",Vt="grok-4-1-fast-reasoning",N="grok-4-1-fast-non-reasoning",Uo=[bt,Nt,wt,Vt,N];function ne(i){return Uo.includes(i)}var se="https://api.moonshot.ai/v1/chat/completions",w="kimi-k2.6",kt="kimi-k2.5",Ho=[w,kt];function ae(i){return Ho.includes(i)}var Ko="https://api.deepseek.com",Fe=`${Ko}/chat/completions`,le="deepseek-v4-flash",Wo="deepseek-v4-pro",Bo="deepseek-chat",$o="deepseek-reasoner",co=[le,Wo],Rr=[Bo,$o];var zo="https://api.mistral.ai/v1",Ue=`${zo}/chat/completions`,V="mistral-small-latest",uo="mistral-small-2603",Gt="mistral-medium-3-5",ho="mistral-medium-2508",mo="mistral-large-latest",go="mistral-large-2512",_o=[V,Gt,mo,go,uo,ho],jo=[V,Gt],qo=[V,uo,Gt,ho,mo,go];function He(i){return jo.includes(i)}function fo(i){return i==="none"||i==="high"}function Mo(i){return qo.includes(i)}var C={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Ft={[C.VERY_SHORT]:40,[C.SHORT]:100,[C.MEDIUM]:200,[C.LONG]:300,[C.VERY_LONG]:1e3,[C.DEEP]:5e3},vo=5e3,Eo={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 O(i){return i?Ft[i]??vo:vo}var br="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",Nr=`You are a skilled summarizing assistant.
|
|
1
|
+
"use strict";var AITuberOnAirChat=(()=>{var Jt=Object.defineProperty;var Ii=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var Di=Object.prototype.hasOwnProperty;var Ai=(i,e)=>{for(var t in e)Jt(i,t,{get:e[t],enumerable:!0})},Ri=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xi(e))!Di.call(i,r)&&r!==t&&Jt(i,r,{get:()=>e[r],enumerable:!(o=Ii(e,r))||o.enumerable});return i};var bi=i=>Ri(Jt({},"__esModule",{value:!0}),i);var Mr={};Ai(Mr,{CHAT_RESPONSE_LENGTH:()=>C,CLAUDE_VISION_SUPPORTED_MODELS:()=>ke,ChatServiceFactory:()=>Ae,ChatServiceHttpClient:()=>f,ClaudeChatService:()=>ue,ClaudeChatServiceProvider:()=>he,DEEPSEEK_API_BASE_URL:()=>Xo,DEEPSEEK_DEPRECATED_MODELS:()=>Ui,DEEPSEEK_SUPPORTED_MODELS:()=>Mo,DEFAULT_MAX_TOKENS:()=>Lo,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>Ki,DEFAULT_VISION_PROMPT:()=>Hi,DeepSeekChatService:()=>me,DeepSeekChatServiceProvider:()=>de,EMOTION_TAG_CLEANUP_REGEX:()=>xo,EMOTION_TAG_REGEX:()=>ii,ENDPOINT_CLAUDE_API:()=>oo,ENDPOINT_DEEPSEEK_CHAT_COMPLETIONS_API:()=>Be,ENDPOINT_GEMINI_API:()=>to,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>ae,ENDPOINT_MISTRAL_CHAT_COMPLETIONS_API:()=>$e,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>U,ENDPOINT_OPENAI_RESPONSES_API:()=>A,ENDPOINT_OPENROUTER_API:()=>Ge,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>Ue,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>Fe,EmotionParser:()=>ce,GEMINI_DEPRECATED_MODELS:()=>Bo,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>Io,GEMINI_RECOMMENDED_MODELS:()=>et,GEMINI_VISION_SUPPORTED_MODELS:()=>Ve,GPT5_PRESETS:()=>Po,GPT_5_MODELS:()=>bo,GeminiChatService:()=>ge,GeminiChatServiceProvider:()=>_e,GeminiNanoChatService:()=>fe,GeminiNanoChatServiceProvider:()=>Me,HttpError:()=>F,KIMI_THINKING_REQUIRED_MODELS:()=>Jo,KIMI_VISION_SUPPORTED_MODELS:()=>qo,KimiChatService:()=>ve,KimiChatServiceProvider:()=>Ee,MAX_TOKENS_BY_LENGTH:()=>Bt,MISTRAL_API_BASE_URL:()=>ei,MISTRAL_REASONING_EFFORT_SUPPORTED_MODELS:()=>ti,MISTRAL_SUPPORTED_MODELS:()=>Co,MISTRAL_VISION_SUPPORTED_MODELS:()=>oi,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>no,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>It,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>xt,MODEL_ANTHROPIC_CLAUDE_HAIKU_LATEST:()=>yt,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>Lt,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>Pt,MODEL_ANTHROPIC_CLAUDE_SONNET_LATEST:()=>Tt,MODEL_CLAUDE_3_5_HAIKU:()=>Ni,MODEL_CLAUDE_3_5_SONNET:()=>wi,MODEL_CLAUDE_3_7_SONNET:()=>Vi,MODEL_CLAUDE_3_HAIKU:()=>tt,MODEL_CLAUDE_4_5_HAIKU:()=>R,MODEL_CLAUDE_4_5_OPUS:()=>nt,MODEL_CLAUDE_4_5_SONNET:()=>rt,MODEL_CLAUDE_4_6_OPUS:()=>at,MODEL_CLAUDE_4_6_SONNET:()=>st,MODEL_CLAUDE_4_7_OPUS:()=>lt,MODEL_CLAUDE_4_8_OPUS:()=>pt,MODEL_CLAUDE_4_OPUS:()=>it,MODEL_CLAUDE_4_SONNET:()=>ot,MODEL_DEEPSEEK_CHAT:()=>Yo,MODEL_DEEPSEEK_REASONER:()=>Qo,MODEL_DEEPSEEK_V4_FLASH:()=>pe,MODEL_DEEPSEEK_V4_PRO:()=>Zo,MODEL_GEMINI_2_5_FLASH:()=>Ho,MODEL_GEMINI_2_5_FLASH_LITE:()=>Ko,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>Wo,MODEL_GEMINI_2_5_PRO:()=>Uo,MODEL_GEMINI_3_1_FLASH_LITE:()=>q,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>ko,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>Vo,MODEL_GEMINI_3_5_FLASH:()=>Qe,MODEL_GEMINI_3_FLASH_PREVIEW:()=>Fo,MODEL_GEMINI_3_PRO_PREVIEW:()=>Go,MODEL_GEMINI_NANO:()=>Z,MODEL_GEMMA_4_26B_A4B_IT:()=>wo,MODEL_GEMMA_4_31B_IT:()=>No,MODEL_GLM_4_6:()=>_o,MODEL_GLM_4_6V:()=>Vt,MODEL_GLM_4_6V_FLASH:()=>X,MODEL_GLM_4_6V_FLASHX:()=>kt,MODEL_GLM_4_7:()=>ho,MODEL_GLM_4_7_FLASH:()=>go,MODEL_GLM_4_7_FLASHX:()=>mo,MODEL_GLM_5:()=>co,MODEL_GLM_5_2:()=>re,MODEL_GLM_5_TURBO:()=>uo,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>bt,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>Nt,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>Rt,MODEL_GOOGLE_GEMINI_FLASH_LATEST:()=>At,MODEL_GOOGLE_GEMINI_PRO_LATEST:()=>Dt,MODEL_GPT_4O:()=>Ze,MODEL_GPT_4O_MINI:()=>z,MODEL_GPT_4_1:()=>qe,MODEL_GPT_4_1_MINI:()=>Je,MODEL_GPT_4_1_NANO:()=>Xe,MODEL_GPT_5:()=>ee,MODEL_GPT_5_1:()=>te,MODEL_GPT_5_4:()=>K,MODEL_GPT_5_4_MINI:()=>B,MODEL_GPT_5_4_NANO:()=>$,MODEL_GPT_5_4_PRO:()=>G,MODEL_GPT_5_5:()=>W,MODEL_GPT_5_MINI:()=>Q,MODEL_GPT_5_NANO:()=>H,MODEL_GPT_OSS_20B_FREE:()=>b,MODEL_GROK_4_1_FAST_NON_REASONING:()=>N,MODEL_GROK_4_1_FAST_REASONING:()=>Ht,MODEL_GROK_4_20_NON_REASONING:()=>Ut,MODEL_GROK_4_20_REASONING:()=>Ft,MODEL_GROK_4_3:()=>Gt,MODEL_KIMI_K2_5:()=>Kt,MODEL_KIMI_K2_6:()=>w,MODEL_KIMI_K2_7_CODE:()=>He,MODEL_KIMI_K2_7_CODE_HIGHSPEED:()=>Ke,MODEL_MISTRAL_LARGE_2512:()=>So,MODEL_MISTRAL_LARGE_LATEST:()=>Oo,MODEL_MISTRAL_MEDIUM_2508:()=>Eo,MODEL_MISTRAL_MEDIUM_3_5:()=>Wt,MODEL_MISTRAL_SMALL_2603:()=>vo,MODEL_MISTRAL_SMALL_LATEST:()=>V,MODEL_MOONSHOTAI_KIMI_K2_5:()=>ut,MODEL_MOONSHOTAI_KIMI_K2_7_CODE:()=>ct,MODEL_MOONSHOTAI_KIMI_LATEST:()=>ht,MODEL_O1:()=>Yt,MODEL_O1_MINI:()=>Zt,MODEL_O3_MINI:()=>Xt,MODEL_OPENAI_GPT_4O:()=>Ot,MODEL_OPENAI_GPT_4_1_MINI:()=>St,MODEL_OPENAI_GPT_4_1_NANO:()=>Ct,MODEL_OPENAI_GPT_5_1_CHAT:()=>ft,MODEL_OPENAI_GPT_5_1_CODEX:()=>Mt,MODEL_OPENAI_GPT_5_5:()=>_t,MODEL_OPENAI_GPT_5_5_PRO:()=>gt,MODEL_OPENAI_GPT_5_MINI:()=>vt,MODEL_OPENAI_GPT_5_NANO:()=>Et,MODEL_OPENAI_GPT_LATEST:()=>mt,MODEL_OPENAI_GPT_MINI_LATEST:()=>dt,MODEL_OPENROUTER_AUTO:()=>io,MODEL_OPENROUTER_FUSION:()=>ro,MODEL_ZAI_GLM_4_5_AIR:()=>ao,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>wt,MODEL_ZAI_GLM_4_7_FLASH:()=>so,MODEL_ZAI_GLM_5_2:()=>oe,MistralChatService:()=>Oe,MistralChatServiceProvider:()=>Se,OPENROUTER_CREDITS_THRESHOLD:()=>Fi,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>Gi,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>ki,OPENROUTER_FREE_MODELS:()=>lo,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>po,OPENROUTER_VISION_SUPPORTED_MODELS:()=>$o,OpenAIChatService:()=>y,OpenAIChatServiceProvider:()=>Te,OpenAICompatibleChatServiceProvider:()=>Ce,OpenRouterChatService:()=>ye,OpenRouterChatServiceProvider:()=>Le,StreamTextAccumulator:()=>v,VISION_SUPPORTED_MODELS:()=>Re,XAIChatService:()=>Pe,XAIChatServiceProvider:()=>Ie,XAI_VISION_SUPPORTED_MODELS:()=>jo,ZAIChatService:()=>xe,ZAIChatServiceProvider:()=>De,ZAI_VISION_SUPPORTED_MODELS:()=>zo,allowsReasoningLow:()=>Ye,allowsReasoningMinimal:()=>Ne,allowsReasoningNone:()=>be,allowsReasoningXHigh:()=>eo,buildOpenAICompatibleTools:()=>x,getDefaultReasoningEffortForGPT5Model:()=>we,getMaxTokensForResponseLength:()=>O,installGASFetch:()=>Li,isGPT5Model:()=>j,isKimiThinkingRequiredModel:()=>We,isKimiVisionModel:()=>le,isMistralReasoningEffort:()=>To,isMistralReasoningEffortModel:()=>ze,isMistralVisionModel:()=>yo,isOpenRouterFreeModel:()=>J,isOpenRouterVisionModel:()=>ie,isResponsesOnlyGPT5Model:()=>Qt,isXaiVisionModel:()=>se,isZaiToolStreamModel:()=>fo,isZaiVisionModel:()=>ne,parseOpenAICompatibleOneShot:()=>I,parseOpenAICompatibleTextStream:()=>L,parseOpenAICompatibleToolStream:()=>P,processChatWithOptionalTools:()=>M,refreshOpenRouterFreeModels:()=>or,resolveVisionModel:()=>E,runOnceText:()=>zi,safeJsonParse:()=>ni,safeParseToolCallInput:()=>Y,screenplayToText:()=>$i,textToScreenplay:()=>ri,textsToScreenplay:()=>Bi});var U="https://api.openai.com/v1/chat/completions",A="https://api.openai.com/v1/responses",H="gpt-5-nano",Q="gpt-5-mini",ee="gpt-5",te="gpt-5.1",K="gpt-5.4",W="gpt-5.5",B="gpt-5.4-mini",$="gpt-5.4-nano",G="gpt-5.4-pro",qe="gpt-4.1",Je="gpt-4.1-mini",Xe="gpt-4.1-nano",z="gpt-4o-mini",Ze="gpt-4o",Xt="o3-mini",Zt="o1-mini",Yt="o1",Re=[H,Q,ee,te,K,W,B,$,G,qe,Je,Xe,z,Ze,"o1"],bo=[H,Q,ee,te,K,W,B,$,G];function j(i){return bo.includes(i)}function Qt(i){return i===G}function eo(i){return i===W||i===K||i===B||i===$||i===G}function be(i){return i===te||i===K||i===W||i===B||i===$}function Ne(i){return i===H||i===Q||i===ee}function Ye(i){return i!==G}function we(i){return be(i)?"none":Ne(i)?"minimal":"medium"}var to="https://generativelanguage.googleapis.com",No="gemma-4-31b-it",wo="gemma-4-26b-a4b-it",Qe="gemini-3.5-flash",Vo="gemini-3.1-pro-preview",q="gemini-3.1-flash-lite",ko="gemini-3.1-flash-lite-preview",Go="gemini-3-pro-preview",Fo="gemini-3-flash-preview",Uo="gemini-2.5-pro",Ho="gemini-2.5-flash",Ko="gemini-2.5-flash-lite",Wo="gemini-2.5-flash-lite-preview-06-17",et=[Qe,q,Vo,Fo,Uo,Ho,Ko,No,wo],Bo=[ko,Go,Wo],Ve=[...et,...Bo];var oo="https://api.anthropic.com/v1/messages",tt="claude-3-haiku-20240307",Ni="claude-3-5-haiku-20241022",wi="claude-3-5-sonnet-20241022",Vi="claude-3-7-sonnet-20250219",ot="claude-sonnet-4-20250514",it="claude-opus-4-20250514",rt="claude-sonnet-4-5-20250929",R="claude-haiku-4-5-20251001",nt="claude-opus-4-5-20251101",st="claude-sonnet-4-6",at="claude-opus-4-6",lt="claude-opus-4-7",pt="claude-opus-4-8",ke=[tt,ot,it,rt,R,nt,st,at,lt,pt];var Ge="https://openrouter.ai/api/v1/chat/completions",io="openrouter/auto",ro="openrouter/fusion",b="openai/gpt-oss-20b:free",ct="moonshotai/kimi-k2.7-code",ut="moonshotai/kimi-k2.5",ht="~moonshotai/kimi-latest",mt="~openai/gpt-latest",dt="~openai/gpt-mini-latest",gt="openai/gpt-5.5-pro",_t="openai/gpt-5.5",ft="openai/gpt-5.1-chat",Mt="openai/gpt-5.1-codex",vt="openai/gpt-5-mini",Et="openai/gpt-5-nano",Ot="openai/gpt-4o",St="openai/gpt-4.1-mini",Ct="openai/gpt-4.1-nano",Tt="~anthropic/claude-sonnet-latest",yt="~anthropic/claude-haiku-latest",Lt="anthropic/claude-opus-4",Pt="anthropic/claude-sonnet-4",It="anthropic/claude-3.7-sonnet",no="anthropic/claude-3.5-sonnet",xt="anthropic/claude-haiku-4.5",Dt="~google/gemini-pro-latest",At="~google/gemini-flash-latest",Rt="google/gemini-2.5-pro",bt="google/gemini-2.5-flash",Nt="google/gemini-2.5-flash-lite-preview-09-2025",oe="z-ai/glm-5.2",so="z-ai/glm-4.7-flash",ao="z-ai/glm-4.5-air",wt="z-ai/glm-4.5-air:free",lo=[b,wt],$o=[ht,mt,dt,gt,_t,ft,Mt,vt,Et,Ot,St,Ct,Tt,yt,Lt,Pt,It,xt,Dt,At,Rt,bt,Nt,ct,ut],po=20,ki=50,Gi=1e3,Fi=10;function J(i){return i.trim().endsWith(":free")}function ie(i){return $o.some(e=>i.includes(e))}var Fe="https://api.z.ai/api/paas/v4/chat/completions",re="glm-5.2",co="glm-5",uo="glm-5-turbo",ho="glm-4.7",mo="glm-4.7-FlashX",go="glm-4.7-Flash",_o="glm-4.6",Vt="glm-4.6V",kt="glm-4.6V-FlashX",X="glm-4.6V-Flash",zo=[Vt,kt,X];function ne(i){return zo.includes(i)}function fo(i){return i.toLowerCase().startsWith("glm-4.6")}var Ue="https://api.x.ai/v1/chat/completions",Gt="grok-4.3",Ft="grok-4.20-0309-reasoning",Ut="grok-4.20-0309-non-reasoning",Ht="grok-4-1-fast-reasoning",N="grok-4-1-fast-non-reasoning",jo=[Gt,Ft,Ut,Ht,N];function se(i){return jo.includes(i)}var ae="https://api.moonshot.ai/v1/chat/completions",He="kimi-k2.7-code",Ke="kimi-k2.7-code-highspeed",w="kimi-k2.6",Kt="kimi-k2.5",qo=[He,Ke,w,Kt],Jo=[He,Ke];function le(i){return qo.includes(i)}function We(i){return Jo.includes(i)}var Xo="https://api.deepseek.com",Be=`${Xo}/chat/completions`,pe="deepseek-v4-flash",Zo="deepseek-v4-pro",Yo="deepseek-chat",Qo="deepseek-reasoner",Mo=[pe,Zo],Ui=[Yo,Qo];var ei="https://api.mistral.ai/v1",$e=`${ei}/chat/completions`,V="mistral-small-latest",vo="mistral-small-2603",Wt="mistral-medium-3-5",Eo="mistral-medium-2508",Oo="mistral-large-latest",So="mistral-large-2512",Co=[V,Wt,Oo,So,vo,Eo],ti=[V,Wt],oi=[V,vo,Wt,Eo,Oo,So];function ze(i){return ti.includes(i)}function To(i){return i==="none"||i==="high"}function yo(i){return oi.includes(i)}var C={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Bt={[C.VERY_SHORT]:40,[C.SHORT]:100,[C.MEDIUM]:200,[C.LONG]:300,[C.VERY_LONG]:1e3,[C.DEEP]:5e3},Lo=5e3,Po={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 O(i){return i?Bt[i]??Lo:Lo}var Hi="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",Ki=`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,15 +7,15 @@ 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 Z="gemini-nano",
|
|
11
|
-
`);r=l.pop()||"";for(let c of l){let d=c.trim();if(!d||d.startsWith(":")||!d.startsWith("data:"))continue;let u=d.slice(5).trim();if(u==="[DONE]"){n=!0;break}e(u)}}};async function L(i,e,t={}){let o="";return await
|
|
12
|
-
`))!==-1;){let u=a.slice(0,d).trim();if(a=a.slice(d+1),!u.startsWith("data:"))continue;let m=u.slice(5).trim();if(m==="[DONE]")break;let p=JSON.parse(m);if(p.type==="content_block_delta"&&p.delta?.text&&(t(p.delta.text),n.push({type:"text",text:p.delta.text})),p.type==="content_block_start"&&p.content_block?.type==="tool_use"?s.set(p.index,{id:p.content_block.id,name:p.content_block.name,args:""}):p.type==="content_block_start"&&p.content_block?.type==="mcp_tool_use"?s.set(p.index,{id:p.content_block.id,name:p.content_block.name,args:"",server_name:p.content_block.server_name}):p.type==="content_block_start"&&p.content_block?.type==="tool_result"?n.push({type:"tool_result",tool_use_id:p.content_block.tool_use_id,content:p.content_block.content??""}):p.type==="content_block_start"&&p.content_block?.type==="mcp_tool_result"&&n.push({type:"mcp_tool_result",tool_use_id:p.content_block.tool_use_id,is_error:p.content_block.is_error??!1,content:p.content_block.content??[]}),p.type==="content_block_delta"&&p.delta?.type==="input_json_delta"){let h=s.get(p.index);h&&(h.args+=p.delta.partial_json||"")}if(p.type==="content_block_stop"&&s.has(p.index)){let{id:h,name:g,args:S,server_name:k}=s.get(p.index);k?n.push({type:"mcp_tool_use",id:h,name:g,server_name:k,input:JSON.parse(S||"{}")}):n.push({type:"tool_use",id:h,name:g,input:JSON.parse(S||"{}")}),s.delete(p.index)}}}return{blocks:n,stop_reason:n.some(l=>l.type==="tool_use"||l.type==="mcp_tool_use")?"tool_use":"end"}}async parsePureStream(e,t){let{blocks:o}=await this.parseStream(e,t);return o.filter(r=>r.type==="text").map(r=>r.text).join("")}parseOneShot(e){let t=[];return(e.content??[]).forEach(o=>{o.type==="text"?t.push({type:"text",text:o.text}):o.type==="tool_use"?t.push({type:"tool_use",id:o.id,name:o.name,input:o.input??{}}):o.type==="mcp_tool_use"?t.push({type:"mcp_tool_use",id:o.id,name:o.name,server_name:o.server_name,input:o.input??{}}):o.type==="tool_result"?t.push({type:"tool_result",tool_use_id:o.tool_use_id,content:o.content??""}):o.type==="mcp_tool_result"&&t.push({type:"mcp_tool_result",tool_use_id:o.tool_use_id,is_error:o.is_error??!1,content:o.content??[]})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use"||o.type==="mcp_tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callClaude(e,this.model,t,r),s=t?await this.parseStream(n,o):this.parseOneShot(await n.json());return this.convertToStandardCompletion(s)}async visionChatOnce(e,t=!1,o=()=>{},r){let n=await this.callClaude(e,this.visionModel,t,r),s=t?await this.parseStream(n,o):this.parseOneShot(await n.json());return this.convertToStandardCompletion(s)}convertToStandardCompletion(e){return{blocks:e.blocks.filter(o=>o.type==="text"||o.type==="tool_use"||o.type==="tool_result"),stop_reason:e.stop_reason}}};var
|
|
13
|
-
`);d=S.pop()||"";for(let k=0;k<S.length;k++){let _=S[k].trim();if(_.startsWith("event:"))h=_.slice(6).trim();else if(_.startsWith("data:"))g=_.slice(5).trim();else if(_===""&&h&&g){try{let A=JSON.parse(g);Xr(h,A,e,n,s,t,T=>{T.responseStatus!==void 0&&(a=T.responseStatus),T.incompleteDetails!==void 0&&(l=T.incompleteDetails),T.usage!==void 0&&(c=T.usage)})}catch(A){t.onJsonError?.(g,A),console.warn("Failed to parse SSE data:",g)}h="",g=""}}}let u=Array.from(s.values()).map(m=>({type:"tool_use",id:m.id,name:m.name,input:m.input||{}}));return{blocks:[...n,...u],stop_reason:u.length?"tool_use":"end",truncated:a==="incomplete",response_status:a,incomplete_details:l,usage:c}}function Xr(i,e,t,o,r,n,s){switch(i){case"response.output_item.added":e.item?.type==="message"&&Array.isArray(e.item.content)?e.item.content.forEach(a=>{a.type==="output_text"&&a.text&&(t(a.text),v.append(o,a.text))}):e.item?.type==="function_call"&&r.set(e.item.id,{id:e.item.id,name:e.item.name,input:Y(e.item.arguments,n.onJsonError)});break;case"response.content_part.added":e.part?.type==="output_text"&&typeof e.part.text=="string"&&(t(e.part.text),v.append(o,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),v.append(o,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(ir(e,"completed"));break;case"response.incomplete":s(ir(e,"incomplete"));break;default:break}}function ir(i,e){let t=i?.response??i;return{responseStatus:t?.status??e,incompleteDetails:t?.incomplete_details??null,usage:t?.usage}}function nr(i,e={}){let t=[];return i.output&&Array.isArray(i.output)&&i.output.forEach(o=>{o.type==="message"&&o.content&&o.content.forEach(r=>{r.type==="output_text"&&r.text&&t.push({type:"text",text:r.text})}),o.type==="function_call"&&t.push({type:"tool_use",id:o.id,name:o.name,input:Y(o.arguments,e.onJsonError)})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use")?"tool_use":"end",truncated:i?.status==="incomplete",response_status:i?.status,incomplete_details:i?.incomplete_details??null,usage:i?.usage}}function sr({tools:i,mcpServers:e,isResponsesAPI:t}){let o=[];return i.length>0&&o.push(...x(i,t?"responses":"chat-completions")),e.length>0&&t&&o.push(...Zr(e)),o}function Zr(i){return i.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 Yr={[C.VERY_SHORT]:800,[C.SHORT]:1200,[C.MEDIUM]:2e3,[C.LONG]:3e3,[C.VERY_LONG]:8e3,[C.DEEP]:25e3},Qr={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3},ei=new Set(["openai-compatible","deepseek","mistral"]);function ar({provider:i,endpoint:e,messages:t,model:o,stream:r,tools:n,mcpServers:s,responseLength:a,verbosity:l,reasoning_effort:c,enableReasoningSummary:d,maxTokens:u}){let m=e===D;oi(e,s);let p={model:o,stream:r},h=ti({provider:i,model:o,responseLength:a,reasoning_effort:c,maxTokens:u});m?h!==void 0&&(p.max_output_tokens=h):h!==void 0&&(lr(i)?p.max_tokens=h:p.max_completion_tokens=h),m?p.input=ri(t):p.messages=i==="mistral"?ii(t):t,j(o)&&(m?(c&&(p.reasoning={...p.reasoning,effort:c},d&&(p.reasoning.summary="auto")),l&&(p.text={...p.text,format:{type:"text"},verbosity:l})):(c&&(p.reasoning_effort=c),l&&(p.verbosity=l))),i==="mistral"&&He(o)&&c&&fo(c)&&(p.reasoning_effort=c);let g=sr({tools:n,mcpServers:s,isResponsesAPI:m});return g.length>0&&(p.tools=g,m||(p.tool_choice="auto")),p}function ti({provider:i,model:e,responseLength:t,reasoning_effort:o,maxTokens:r}){if(r!==void 0)return r;let n=lr(i)?t!==void 0?O(t):void 0:O(t);if(i!=="openai"||!j(e)||t===void 0)return n;let s=o??be(e);return Math.max(n??0,Yr[t],Qr[s])}function oi(i,e){if(e.length>0&&i===U)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${i}. Please use OpenAI Responses API endpoint: ${D}. MCP tools are only available in the Responses API endpoint.`)}function ri(i){return i.map(e=>{let o={role:e.role==="tool"?"user":e.role};return typeof e.content=="string"?o.content=e.content:Array.isArray(e.content)?o.content=e.content.map(r=>r.type==="text"?{type:"input_text",text:r.text}:r.type==="image_url"?{type:"input_image",image_url:r.image_url.url}:r):o.content=e.content,o})}function ii(i){return i.map(e=>{let t={role:e.role};return Array.isArray(e.content)?(t.content=e.content.map(o=>o.type==="image_url"&&typeof o.image_url=="object"&&typeof o.image_url?.url=="string"?{type:"image_url",image_url:o.image_url.url}:o),t):(t.content=e.content,t)})}function lr(i){return ei.has(i)}var y=class{constructor(e,t=z,o=z,r,n=U,s=[],a,l,c,d=!1,u="openai",m=!0){if(this.provider=u,this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=n,this.mcpServers=s,this.responseLength=a,this.verbosity=l,this.reasoning_effort=c,this.enableReasoningSummary=d,m&&!De.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenAI(e,this.model,!0),n=this.endpoint===D;try{if(n){let s=await Kt(r,t);return v.getFullText(s.blocks)}return this.handleStream(r,t)}catch(s){throw console.error("[processChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){try{await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenAI(e,this.visionModel,!0),n=this.endpoint===D;try{if(n){let s=await Kt(r,t);return v.getFullText(s.blocks)}return this.handleStream(r,t)}catch(s){throw console.error("[processVisionChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processVisionChat:",r),r}}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callOpenAI(e,this.model,t,r);return this.parseResponse(n,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){let n=await this.callOpenAI(e,this.visionModel,t,r);return this.parseResponse(n,t,o)}async parseResponse(e,t,o){return this.endpoint===D?t?Kt(e,o):nr(await e.json()):t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callOpenAI(e,t,o=!1,r){let n=ar({provider:this.provider,endpoint:this.endpoint,messages:e,model:t,stream:o,tools:this.tools,mcpServers:this.mcpServers,responseLength:this.responseLength,verbosity:this.verbosity,reasoning_effort:this.reasoning_effort,enableReasoningSummary:this.enableReasoningSummary,maxTokens:r}),s={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(s.Authorization=`Bearer ${this.apiKey}`),await f.post(this.endpoint,n,s)}async handleStream(e,t){return L(e,t)}async parseStream(e,t){return P(e,t,{appendTextBlock:v.addTextBlock})}parseOneShot(e){return I(e)}};var he=class extends y{constructor(e,t=le,o=t,r,n=Fe,s){super(e,t,o,r,n,[],s,void 0,void 0,!1,"deepseek",!1)}};var me=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new he(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength)}getProviderName(){return"deepseek"}getSupportedModels(){return[...co]}getDefaultModel(){return le}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("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 Fe}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var pr=(i,e)=>({name:`mcp_${i.name}_search`,description:e==="schema-fetch-failed"?`Search using ${i.name} MCP server (schema fetch failed)`:`Search using ${i.name} MCP server`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}),Wt=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 r=await(await f.post(`${e.url}/tools`,{},t)).json();return Array.isArray(r.tools)?{schemas:r.tools.map(n=>({name:`mcp_${e.name}_${n.name}`,description:n.description||`Tool from ${e.name} MCP server`,parameters:n.inputSchema||{type:"object",properties:{},required:[]}})),failures:[]}:{schemas:[pr(e)],failures:[]}}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),{schemas:[pr(e,"schema-fetch-failed")],failures:[{server:e,error:t}]}}}static async fetchAllToolSchemas(e){return(await this.fetchAllToolSchemasWithStatus(e)).schemas}static async fetchAllToolSchemasWithStatus(e){let t=[],o=[];for(let r of e)try{let n=await this.fetchToolSchemasWithStatus(r);t.push(...n.schemas),o.push(...n.failures)}catch(n){console.error(`Failed to fetch schemas from ${r.name}:`,n),o.push({server:r,error:n})}return{schemas:t,failures:o}}};function cr(i){switch(i){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}function ur(i,e={}){let t=[],o=null,r=[],n=()=>{o&&r.length&&(t.push({role:o,parts:[...r]}),r=[])};for(let s of i){let a=cr(s.role);if(s.tool_calls){n();for(let l of s.tool_calls)e.callIdMap?.set(l.id,l.function.name),t.push({role:"model",parts:[{functionCall:{name:l.function.name,args:JSON.parse(l.function.arguments||"{}")}}]});continue}if(s.role==="tool"){n();let l=s.name??e.callIdMap?.get(s.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:l,response:dr(mr(s.content))}}]});continue}a!==o&&n(),o=a,r.push({text:s.content})}return n(),t}async function hr(i,e={}){let t=e.imageFetcher??f.get,o=e.blobToBase64??ni,r=[],n=null,s=[];for(let a of i){let l=cr(a.role);if(a.tool_calls){for(let c of a.tool_calls)r.push({role:"model",parts:[{functionCall:{name:c.function.name,args:JSON.parse(c.function.arguments||"{}")}}]});continue}if(a.role==="tool"){let c=a.name??e.callIdMap?.get(a.tool_call_id)??"result";r.push({role:"user",parts:[{functionResponse:{name:c,response:dr(mr(a.content))}}]});continue}if(l!==n&&s.length>0&&(r.push({role:n,parts:[...s]}),s=[]),n=l,typeof a.content=="string")s.push({text:a.content});else if(Array.isArray(a.content)){for(let c of a.content)if(c.type==="text")s.push({text:c.text});else if(c.type==="image_url")try{let u=await(await t(c.image_url.url)).blob(),m=await o(u);s.push({inlineData:{mimeType:u.type||"image/jpeg",data:m.split(",")[1]}})}catch(d){throw console.error("Error processing image:",d),new Error(`Failed to process image: ${d.message}`)}}}return n&&s.length>0&&r.push({role:n,parts:[...s]}),r}function mr(i){try{return JSON.parse(i)}catch{return i}}function dr(i){return i===null?{content:null}:typeof i=="object"?i:{content:i}}function ni(i){return new Promise((e,t)=>{let o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=t,o.readAsDataURL(i)})}function si(i,e){return[...i,...e].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}function gr(i,e){let t=si(i,e);if(t.length!==0)return{tools:[{functionDeclarations:t}],toolConfig:{functionCallingConfig:{mode:"AUTO"}}}}function _r(i){return i.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 de=class{constructor(e,t=q,o=q,r=[],n=[],s){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=s,!Ne.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=r,this.mcpServers=n}isGemma4Model(e){return/^gemma-4-/.test(e)}shouldMinimizeThinking(e){return e===Je||this.isGemma4Model(e)}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"};return Array.isArray(e)?e.map(o=>this.adaptKeysForApi(o)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([o,r])=>[t[o]??o,this.adaptKeysForApi(r)])):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((r,n)=>setTimeout(()=>n(new Error("MCP schema fetch timeout")),5e3)),t=Wt.fetchAllToolSchemasWithStatus(this.mcpServers),o=await Promise.race([t,e]);this.mcpToolSchemas=o.schemas,this.mcpSchemasInitialized=!0,this.mcpSchemaInitializationError=o.failures[0]?.error}catch(e){console.warn("Failed to initialize MCP schemas, using fallback:",e),this.mcpSchemaInitializationError=e,this.mcpToolSchemas=_r(this.mcpServers),this.mcpSchemasInitialized=!0}}async processChat(e,t,o){try{await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callGemini(e,this.model,!0),{blocks:n}=await this.parseStream(r,t,this.model);return v.getFullText(n)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use chatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processChat:",r),r}}async processVisionChat(e,t,o){try{await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callGemini(e,this.visionModel,!0),{blocks:n}=await this.parseStream(r,t,this.visionModel);return v.getFullText(n)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:r=>{r.filter(n=>n.type==="text").forEach(n=>t(n.text))},onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use visionChatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processVisionChat:",r),r}}async callGemini(e,t,o=!1,r){let a={contents:e.some(_=>Array.isArray(_.content)&&_.content.some(A=>A?.type==="image_url"||A?.inlineData))?await hr(e,{callIdMap:this.callIdMap}):ur(e,{callIdMap:this.callIdMap}),generationConfig:{maxOutputTokens:r!==void 0?r:O(this.responseLength)}};this.shouldMinimizeThinking(t)&&(a.generationConfig.thinkingConfig={includeThoughts:!1,thinkingLevel:"MINIMAL"});let l=[];if(this.mcpServers.length>0)try{await this.initializeMCPSchemas(),l=this.mcpToolSchemas}catch(_){console.warn("MCP initialization failed, skipping MCP tools:",_)}let c=gr(this.tools,l);c&&Object.assign(a,c);let d=async(_,A)=>{let T=o?"streamGenerateContent":"generateContent",yo=o?"?alt=sse":"",vr=`${Xt}/${_}/models/${t}:${T}${yo}${yo?"&":"?"}key=${this.apiKey}`;return f.post(vr,A)},u=/flash[-_]lite/.test(t),m=this.isGemma4Model(t),p=/gemini-2\.5/.test(t),h=/^gemini-3(?:\.[0-9]+)?-/.test(t),g=u||m||p||h,S=g?"v1beta":"v1",k=async()=>{try{let _=S==="v1"?a:this.adaptKeysForApi(a);return await d(S,_)}catch(_){let A=/Unknown name|Cannot find field|404/.test(_?.message||"")||_?.status===404;if(!g&&A)try{return await d("v1beta",this.adaptKeysForApi(a))}catch(T){throw T instanceof Error&&(T.cause=_),T}throw _}};try{return await k()}catch(_){throw _.body&&(console.error("Gemini API Error Details:",_.body),console.error("Request Body:",JSON.stringify(a,null,2))),_}}async parseStream(e,t,o){let r=e.body.getReader(),n=new TextDecoder,s=[],a=[],l="",c=u=>{if(!u||u==="[DONE]")return;let m;try{m=JSON.parse(u)}catch{return}for(let p of m.candidates??[])for(let h of p.content?.parts??[])this.shouldExposeTextPart(h,o)&&(t(h.text),v.addTextBlock(s,h.text)),h.functionCall&&a.push({type:"tool_use",id:this.genUUID(),name:h.functionCall.name,input:h.functionCall.args??{}}),h.functionResponse&&a.push({type:"tool_result",tool_use_id:h.functionResponse.name,content:JSON.stringify(h.functionResponse.response)})};for(;;){let{done:u,value:m}=await r.read();if(u)break;l+=n.decode(m,{stream:!0});let p;for(;(p=l.indexOf(`
|
|
14
|
-
`))!==-1;){let h=l.slice(0,p);if(l=l.slice(p+1),h.endsWith("\r")&&(h=h.slice(0,-1)),!h.trim()){c("");continue}h.startsWith("data:")&&(h=h.slice(5).trim()),h&&c(h)}}return l&&c(l),{blocks:[...s,...a],stop_reason:a.some(u=>u.type==="tool_use")?"tool_use":"end"}}parseOneShot(e,t){let o=[],r=[];for(let s of e.candidates??[])for(let a of s.content?.parts??[])this.shouldExposeTextPart(a,t)&&o.push({type:"text",text:a.text}),a.functionCall&&r.push({type:"tool_use",id:this.genUUID(),name:a.functionCall.name,input:a.functionCall.args??{}}),a.functionResponse&&r.push({type:"tool_result",tool_use_id:a.functionResponse.name,content:JSON.stringify(a.functionResponse.response)});return{blocks:[...o,...r],stop_reason:r.some(s=>s.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callGemini(e,this.model,t,r);return t?this.parseStream(n,o,this.model):this.parseOneShot(await n.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},r){let n=await this.callGemini(e,this.visionModel,t,r);return t?this.parseStream(n,o,this.visionModel):this.parseOneShot(await n.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 Z="gemini-nano",Io=20;var F=class extends Error{constructor(t,o,r){super(`HTTP ${t}: ${o}`);this.status=t;this.statusText=o;this.body=r;this.name="HttpError"}},je=class je{static setFetch(e){this.fetchImpl=e}static async post(e,t,o={},r={}){let{timeout:n=3e4,retries:s=0,retryDelay:a=1e3}=r,c={...{"Content-Type":"application/json"},...o},d=null;for(let u=0;u<=s;u++)try{let m=typeof AbortController<"u",p=m?new AbortController:void 0,h=m?setTimeout(()=>p.abort(),n):void 0,g=await je.fetchImpl(e,{method:"POST",headers:c,body:typeof t=="string"?t:JSON.stringify(t),...p?{signal:p.signal}:{}});if(h&&clearTimeout(h),!g.ok){let S=await g.text();throw new F(g.status,g.statusText,S)}return g}catch(m){if(d=m,m instanceof F&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError")throw new Error(`Request timeout after ${n}ms`);u<s&&await new Promise(p=>setTimeout(p,a*(u+1)))}throw d||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new F(e.status,e.statusText,t)}static async get(e,t={},o={}){let{timeout:r=3e4,retries:n=0,retryDelay:s=1e3}=o,a=null;for(let l=0;l<=n;l++)try{let c=typeof AbortController<"u",d=c?new AbortController:void 0,u=c?setTimeout(()=>d.abort(),r):void 0,m=await je.fetchImpl(e,{method:"GET",headers:t,...d?{signal:d.signal}:{}});if(u&&clearTimeout(u),!m.ok){let p=await m.text();throw new F(m.status,m.statusText,p)}return m}catch(c){if(a=c,c instanceof F&&c.status>=400&&c.status<500)throw c;if(c instanceof Error&&c.name==="AbortError")throw new Error(`Request timeout after ${r}ms`);l<n&&await new Promise(d=>setTimeout(d,s*(l+1)))}throw a||new Error("Request failed")}};je.fetchImpl=(e,t)=>fetch(e,t);var f=je;var v=class{static append(e,t){if(!t)return;let o=e[e.length-1];o&&o.type==="text"?o.text+=t:e.push({type:"text",text:t})}static getFullText(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}static addTextBlock(e,t){t&&e.push({type:"text",text:t})}};var Wi=["happy","sad","angry","surprised","neutral"],ii=/\[([a-z]+)\]/i,xo=/\[[a-z]+\]\s*/gi,ce=class{static extractEmotion(e){let t=e.match(ii);if(t){let o=t[1].toLowerCase(),r=e.replace(xo,"").trim();return{emotion:o,cleanText:r}}return{cleanText:e}}static isValidEmotion(e){return Wi.includes(e)}static cleanEmotionTags(e){return e.replace(xo,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function ri(i){let{emotion:e,cleanText:t}=ce.extractEmotion(i);return e?{emotion:e,text:t}:{text:t}}function Bi(i){return i.map(e=>ri(e))}function $i(i){return i.emotion?ce.addEmotionTag(i.emotion,i.text):i.text}async function zi(i,e){let{blocks:t}=await i.chatOnce(e,!1,()=>{});return v.getFullText(t)}var ni=(i,e,t)=>{try{return JSON.parse(i)}catch(o){return t?.(i,o),e}},Y=(i,e)=>i?ni(i,{},e):{};var si=(i,e)=>{try{return JSON.parse(i)}catch(t){if(e){e(i,t);return}throw t}},Do=i=>typeof i=="string"?i:Array.isArray(i)?i.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&e.type==="text"&&typeof e.text=="string"?e.text:"").join(""):"",ai=async(i,e)=>{let t=i.body?.getReader();if(!t)throw new Error("Response body is null.");let o=new TextDecoder,r="",n=!1;for(;!n;){let{done:s,value:a}=await t.read();if(s)break;r+=o.decode(a,{stream:!0});let l=r.split(`
|
|
11
|
+
`);r=l.pop()||"";for(let c of l){let d=c.trim();if(!d||d.startsWith(":")||!d.startsWith("data:"))continue;let u=d.slice(5).trim();if(u==="[DONE]"){n=!0;break}e(u)}}};async function L(i,e,t={}){let o="";return await ai(i,r=>{let n=si(r,t.onJsonError);if(!n)return;let s=Do(n.choices?.[0]?.delta?.content);s&&(e(s),o+=s)}),o}async function P(i,e,t={}){let o=[],r=new Map,n,s,a=t.appendTextBlock??v.append;await ai(i,d=>{let u=si(d,t.onJsonError);if(!u)return;let m=u.choices?.[0];typeof m?.finish_reason=="string"&&(n=m.finish_reason),u.usage&&(s=u.usage);let p=m?.delta,h=Do(p?.content);h&&(e(h),a(o,h)),p?.tool_calls&&p.tool_calls.forEach(g=>{let S=r.get(g.index)??{id:g.id,name:g.function?.name,args:""};S.args+=g.function?.arguments||"",r.set(g.index,S)})});let l=Array.from(r.entries()).sort((d,u)=>d[0]-u[0]).map(([d,u])=>({type:"tool_use",id:u.id,name:u.name,input:Y(u.args,t.onJsonError)}));return{blocks:[...o,...l],stop_reason:l.length?"tool_use":"end",truncated:n==="length",finish_reason:n,usage:s}}function I(i,e={}){let t=i?.choices?.[0],o=[];if(t?.message?.tool_calls?.length)t.message.tool_calls.forEach(r=>o.push({type:"tool_use",id:r.id,name:r.function?.name,input:Y(r.function?.arguments,e.onJsonError)}));else{let r=Do(t?.message?.content);r&&o.push({type:"text",text:r})}return{blocks:o,stop_reason:t?.finish_reason==="tool_calls"||o.some(r=>r.type==="tool_use")?"tool_use":"end",truncated:t?.finish_reason==="length",finish_reason:t?.finish_reason,usage:i?.usage}}var x=(i,e="chat-completions")=>i.length===0?[]:e==="responses"?i.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):i.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function M(i){if(!i.hasTools){let t=await i.runWithoutTools();await i.onCompleteResponse(t);return}let e=await i.runWithTools();if(i.onToolBlocks&&i.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=v.getFullText(e.blocks);await i.onCompleteResponse(t);return}throw new Error(i.toolErrorMessage)}var E=i=>{let e=i.model??i.defaultModel,t=i.visionModel??(i.supportsVisionForModel(e)?e:i.defaultVisionModel);if(i.validate==="explicit"&&i.visionModel&&!i.supportsVisionForModel(i.visionModel))throw new Error(`Model ${i.visionModel} does not support vision capabilities.`);if(i.validate==="resolved"&&!i.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var ji="https://openrouter.ai/api/v1/models",qi=2,Ji=12e3,Xi=1,Zi=10;function Ao(i){return i instanceof Error?i.message:String(i)}function $t(i,e){return typeof i!="number"||!Number.isFinite(i)?e:Math.max(1,Math.floor(i))}function Yi(i){let e=new Set,t=[];for(let o of i){let r=o.trim();!r||e.has(r)||(e.add(r),t.push(r))}return t}async function li(i,e,t){if(!(typeof AbortController<"u"))return fetch(i,e);let r=new AbortController,n=setTimeout(()=>r.abort(),t);try{return await fetch(i,{...e,signal:r.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?new Error(`Timeout after ${t}ms`):s}finally{clearTimeout(n)}}async function pi(i){let e=`HTTP ${i.status} ${i.statusText}`.trim(),t="";try{t=await i.text()}catch{return e}let o=t.replace(/\s+/g," ").trim().slice(0,200);return o?`${e}: ${o}`:e}function Qi(i){if(!i||typeof i!="object")throw new Error("Invalid models response shape");let e=i,t=Array.isArray(e.data)?e.data:Array.isArray(e.models)?e.models:[];if(t.length===0)return[];let o=t.map(r=>r.id).filter(r=>typeof r=="string");return Yi(o)}async function er({modelId:i,apiKey:e,endpoint:t,timeoutMs:o,appName:r,appUrl:n}){let s={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};r&&(s["X-Title"]=r),n&&(s["HTTP-Referer"]=n);try{let a=await li(t,{method:"POST",headers:s,body:JSON.stringify({model:i,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},o);if(!a.ok)return{id:i,ok:!1,reason:await pi(a)};try{await a.json()}catch(l){return{id:i,ok:!1,reason:`JSON parse failed: ${Ao(l)}`}}return{id:i,ok:!0}}catch(a){return{id:i,ok:!1,reason:Ao(a)}}}async function tr(i,e,t){if(i.length===0)return[];let o=new Array(i.length),r=0,n=Math.min(e,i.length);return await Promise.all(Array.from({length:n},async()=>{for(;r<i.length;){let s=r;r+=1,o[s]=await t(i[s])}})),o}async function or(i){let e=i.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=i.modelsEndpoint||ji,o=i.endpoint||Ge,r=$t(i.timeoutMs,Ji),n=$t(i.concurrency,qi),s=$t(i.maxCandidates,Xi),a=$t(i.maxWorking,Zi),l=await li(t,{method:"GET"},r);if(!l.ok)throw new Error(await pi(l));let c;try{c=await l.json()}catch(h){throw new Error(`JSON parse failed: ${Ao(h)}`)}let d=Qi(c).filter(h=>J(h)).slice(0,s),u=await tr(d,n,h=>er({modelId:h,apiKey:e,endpoint:o,timeoutMs:r,appName:i.appName,appUrl:i.appUrl})),m=u.filter(h=>h.ok).map(h=>h.id).slice(0,a),p=u.filter(h=>!h.ok).map(h=>({id:h.id,reason:h.reason||"Unknown error"}));return{working:m,failed:p,fetchedAt:Date.now()}}function ci(i){return i.map(e=>({role:zt(e.role),content:e.content}))}function ui(i){return i.map(e=>{if(typeof e.content=="string")return{role:zt(e.role),content:[{type:"text",text:e.content}]};if(Array.isArray(e.content)){let t=e.content.map(o=>{if(o.type==="image_url"){if(o.image_url.url.startsWith("data:")){let r=o.image_url.url.match(/^data:([^;]+);base64,(.+)$/);return r?{type:"image",source:{type:"base64",media_type:r[1],data:r[2]}}:null}return{type:"image",source:{type:"url",url:o.image_url.url,media_type:ir(o.image_url.url)}}}return o}).filter(o=>o);return{role:zt(e.role),content:t}}return{role:zt(e.role),content:[]}})}function zt(i){switch(i){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}function ir(i){switch(i.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 ue=class{constructor(e,t=R,o=R,r=[],n=[],s){this.provider="claude";if(this.apiKey=e,this.model=t||R,this.visionModel=o||R,this.tools=r,this.mcpServers=n,this.responseLength=s,!ke.includes(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`)}getModel(){return this.model}getVisionModel(){return this.visionModel}getMCPServers(){return this.mcpServers}addMCPServer(e){this.mcpServers.push(e)}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e)}hasMCPServers(){return this.mcpServers.length>0}async processChat(e,t,o){await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callClaude(e,this.model,!0);return this.parsePureStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callClaude(e,this.visionModel,!0);return this.parsePureStream(r,t)},runWithTools:()=>this.visionChatOnce(e),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async callClaude(e,t,o,r){let n=e.find(u=>u.role==="system")?.content??"",s=e.filter(u=>u.role!=="system"),a=s.some(u=>Array.isArray(u.content)&&u.content.some(m=>m.type==="image_url"||m.type==="image")),l={model:t,system:n,messages:a?ui(s):ci(s),stream:o,max_tokens:r!==void 0?r:O(this.responseLength)};this.tools.length&&(l.tools=this.tools.map(u=>({name:u.name,description:u.description,input_schema:u.parameters})),l.tool_choice={type:"auto"}),this.mcpServers.length>0&&(l.mcp_servers=this.mcpServers);let c={"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"};return this.mcpServers.length>0&&(c["anthropic-beta"]="mcp-client-2025-04-04"),await f.post(oo,l,c)}async parseStream(e,t){let o=e.body.getReader(),r=new TextDecoder,n=[],s=new Map,a="";for(;;){let{done:l,value:c}=await o.read();if(l)break;a+=r.decode(c,{stream:!0});let d;for(;(d=a.indexOf(`
|
|
12
|
+
`))!==-1;){let u=a.slice(0,d).trim();if(a=a.slice(d+1),!u.startsWith("data:"))continue;let m=u.slice(5).trim();if(m==="[DONE]")break;let p=JSON.parse(m);if(p.type==="content_block_delta"&&p.delta?.text&&(t(p.delta.text),n.push({type:"text",text:p.delta.text})),p.type==="content_block_start"&&p.content_block?.type==="tool_use"?s.set(p.index,{id:p.content_block.id,name:p.content_block.name,args:""}):p.type==="content_block_start"&&p.content_block?.type==="mcp_tool_use"?s.set(p.index,{id:p.content_block.id,name:p.content_block.name,args:"",server_name:p.content_block.server_name}):p.type==="content_block_start"&&p.content_block?.type==="tool_result"?n.push({type:"tool_result",tool_use_id:p.content_block.tool_use_id,content:p.content_block.content??""}):p.type==="content_block_start"&&p.content_block?.type==="mcp_tool_result"&&n.push({type:"mcp_tool_result",tool_use_id:p.content_block.tool_use_id,is_error:p.content_block.is_error??!1,content:p.content_block.content??[]}),p.type==="content_block_delta"&&p.delta?.type==="input_json_delta"){let h=s.get(p.index);h&&(h.args+=p.delta.partial_json||"")}if(p.type==="content_block_stop"&&s.has(p.index)){let{id:h,name:g,args:S,server_name:k}=s.get(p.index);k?n.push({type:"mcp_tool_use",id:h,name:g,server_name:k,input:JSON.parse(S||"{}")}):n.push({type:"tool_use",id:h,name:g,input:JSON.parse(S||"{}")}),s.delete(p.index)}}}return{blocks:n,stop_reason:n.some(l=>l.type==="tool_use"||l.type==="mcp_tool_use")?"tool_use":"end"}}async parsePureStream(e,t){let{blocks:o}=await this.parseStream(e,t);return o.filter(r=>r.type==="text").map(r=>r.text).join("")}parseOneShot(e){let t=[];return(e.content??[]).forEach(o=>{o.type==="text"?t.push({type:"text",text:o.text}):o.type==="tool_use"?t.push({type:"tool_use",id:o.id,name:o.name,input:o.input??{}}):o.type==="mcp_tool_use"?t.push({type:"mcp_tool_use",id:o.id,name:o.name,server_name:o.server_name,input:o.input??{}}):o.type==="tool_result"?t.push({type:"tool_result",tool_use_id:o.tool_use_id,content:o.content??""}):o.type==="mcp_tool_result"&&t.push({type:"mcp_tool_result",tool_use_id:o.tool_use_id,is_error:o.is_error??!1,content:o.content??[]})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use"||o.type==="mcp_tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callClaude(e,this.model,t,r),s=t?await this.parseStream(n,o):this.parseOneShot(await n.json());return this.convertToStandardCompletion(s)}async visionChatOnce(e,t=!1,o=()=>{},r){let n=await this.callClaude(e,this.visionModel,t,r),s=t?await this.parseStream(n,o):this.parseOneShot(await n.json());return this.convertToStandardCompletion(s)}convertToStandardCompletion(e){return{blocks:e.blocks.filter(o=>o.type==="text"||o.type==="tool_use"||o.type==="tool_result"),stop_reason:e.stop_reason}}};var he=class{createChatService(e){let t=E({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:o=>this.supportsVisionForModel(o),validate:"resolved"});return new ue(e.apiKey,e.model||this.getDefaultModel(),t,e.tools??[],e.mcpServers??[],e.responseLength)}getProviderName(){return"claude"}getSupportedModels(){return[ot,it,rt,R,nt,st,at,lt,pt,tt]}getDefaultModel(){return R}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ke.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};async function jt(i,e,t={}){let o=i.body.getReader(),r=new TextDecoder,n=[],s=new Map,a,l,c,d="";for(;;){let{done:m,value:p}=await o.read();if(m)break;d+=r.decode(p,{stream:!0});let h="",g="",S=d.split(`
|
|
13
|
+
`);d=S.pop()||"";for(let k=0;k<S.length;k++){let _=S[k].trim();if(_.startsWith("event:"))h=_.slice(6).trim();else if(_.startsWith("data:"))g=_.slice(5).trim();else if(_===""&&h&&g){try{let D=JSON.parse(g);rr(h,D,e,n,s,t,T=>{T.responseStatus!==void 0&&(a=T.responseStatus),T.incompleteDetails!==void 0&&(l=T.incompleteDetails),T.usage!==void 0&&(c=T.usage)})}catch(D){t.onJsonError?.(g,D),console.warn("Failed to parse SSE data:",g)}h="",g=""}}}let u=Array.from(s.values()).map(m=>({type:"tool_use",id:m.id,name:m.name,input:m.input||{}}));return{blocks:[...n,...u],stop_reason:u.length?"tool_use":"end",truncated:a==="incomplete",response_status:a,incomplete_details:l,usage:c}}function rr(i,e,t,o,r,n,s){switch(i){case"response.output_item.added":e.item?.type==="message"&&Array.isArray(e.item.content)?e.item.content.forEach(a=>{a.type==="output_text"&&a.text&&(t(a.text),v.append(o,a.text))}):e.item?.type==="function_call"&&r.set(e.item.id,{id:e.item.id,name:e.item.name,input:Y(e.item.arguments,n.onJsonError)});break;case"response.content_part.added":e.part?.type==="output_text"&&typeof e.part.text=="string"&&(t(e.part.text),v.append(o,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),v.append(o,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(hi(e,"completed"));break;case"response.incomplete":s(hi(e,"incomplete"));break;default:break}}function hi(i,e){let t=i?.response??i;return{responseStatus:t?.status??e,incompleteDetails:t?.incomplete_details??null,usage:t?.usage}}function mi(i,e={}){let t=[];return i.output&&Array.isArray(i.output)&&i.output.forEach(o=>{o.type==="message"&&o.content&&o.content.forEach(r=>{r.type==="output_text"&&r.text&&t.push({type:"text",text:r.text})}),o.type==="function_call"&&t.push({type:"tool_use",id:o.id,name:o.name,input:Y(o.arguments,e.onJsonError)})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use")?"tool_use":"end",truncated:i?.status==="incomplete",response_status:i?.status,incomplete_details:i?.incomplete_details??null,usage:i?.usage}}function di({tools:i,mcpServers:e,isResponsesAPI:t}){let o=[];return i.length>0&&o.push(...x(i,t?"responses":"chat-completions")),e.length>0&&t&&o.push(...nr(e)),o}function nr(i){return i.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 sr={[C.VERY_SHORT]:800,[C.SHORT]:1200,[C.MEDIUM]:2e3,[C.LONG]:3e3,[C.VERY_LONG]:8e3,[C.DEEP]:25e3},ar={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3},lr=new Set(["openai-compatible","deepseek","mistral"]);function gi({provider:i,endpoint:e,messages:t,model:o,stream:r,tools:n,mcpServers:s,responseLength:a,verbosity:l,reasoning_effort:c,enableReasoningSummary:d,maxTokens:u}){let m=e===A;cr(e,s);let p={model:o,stream:r},h=pr({provider:i,model:o,responseLength:a,reasoning_effort:c,maxTokens:u});m?h!==void 0&&(p.max_output_tokens=h):h!==void 0&&(_i(i)?p.max_tokens=h:p.max_completion_tokens=h),m?p.input=ur(t):p.messages=i==="mistral"?hr(t):t,j(o)&&(m?(c&&(p.reasoning={...p.reasoning,effort:c},d&&(p.reasoning.summary="auto")),l&&(p.text={...p.text,format:{type:"text"},verbosity:l})):(c&&(p.reasoning_effort=c),l&&(p.verbosity=l))),i==="mistral"&&ze(o)&&c&&To(c)&&(p.reasoning_effort=c);let g=di({tools:n,mcpServers:s,isResponsesAPI:m});return g.length>0&&(p.tools=g,m||(p.tool_choice="auto")),p}function pr({provider:i,model:e,responseLength:t,reasoning_effort:o,maxTokens:r}){if(r!==void 0)return r;let n=_i(i)?t!==void 0?O(t):void 0:O(t);if(i!=="openai"||!j(e)||t===void 0)return n;let s=o??we(e);return Math.max(n??0,sr[t],ar[s])}function cr(i,e){if(e.length>0&&i===U)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${i}. Please use OpenAI Responses API endpoint: ${A}. MCP tools are only available in the Responses API endpoint.`)}function ur(i){return i.map(e=>{let o={role:e.role==="tool"?"user":e.role};return typeof e.content=="string"?o.content=e.content:Array.isArray(e.content)?o.content=e.content.map(r=>r.type==="text"?{type:"input_text",text:r.text}:r.type==="image_url"?{type:"input_image",image_url:r.image_url.url}:r):o.content=e.content,o})}function hr(i){return i.map(e=>{let t={role:e.role};return Array.isArray(e.content)?(t.content=e.content.map(o=>o.type==="image_url"&&typeof o.image_url=="object"&&typeof o.image_url?.url=="string"?{type:"image_url",image_url:o.image_url.url}:o),t):(t.content=e.content,t)})}function _i(i){return lr.has(i)}var y=class{constructor(e,t=z,o=z,r,n=U,s=[],a,l,c,d=!1,u="openai",m=!0){if(this.provider=u,this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=n,this.mcpServers=s,this.responseLength=a,this.verbosity=l,this.reasoning_effort=c,this.enableReasoningSummary=d,m&&!Re.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenAI(e,this.model,!0),n=this.endpoint===A;try{if(n){let s=await jt(r,t);return v.getFullText(s.blocks)}return this.handleStream(r,t)}catch(s){throw console.error("[processChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){try{await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenAI(e,this.visionModel,!0),n=this.endpoint===A;try{if(n){let s=await jt(r,t);return v.getFullText(s.blocks)}return this.handleStream(r,t)}catch(s){throw console.error("[processVisionChat] Error in streaming/completion:",s),s}},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processVisionChat:",r),r}}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callOpenAI(e,this.model,t,r);return this.parseResponse(n,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){let n=await this.callOpenAI(e,this.visionModel,t,r);return this.parseResponse(n,t,o)}async parseResponse(e,t,o){return this.endpoint===A?t?jt(e,o):mi(await e.json()):t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callOpenAI(e,t,o=!1,r){let n=gi({provider:this.provider,endpoint:this.endpoint,messages:e,model:t,stream:o,tools:this.tools,mcpServers:this.mcpServers,responseLength:this.responseLength,verbosity:this.verbosity,reasoning_effort:this.reasoning_effort,enableReasoningSummary:this.enableReasoningSummary,maxTokens:r}),s={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(s.Authorization=`Bearer ${this.apiKey}`),await f.post(this.endpoint,n,s)}async handleStream(e,t){return L(e,t)}async parseStream(e,t){return P(e,t,{appendTextBlock:v.addTextBlock})}parseOneShot(e){return I(e)}};var me=class extends y{constructor(e,t=pe,o=t,r,n=Be,s){super(e,t,o,r,n,[],s,void 0,void 0,!1,"deepseek",!1)}};var de=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new me(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength)}getProviderName(){return"deepseek"}getSupportedModels(){return[...Mo]}getDefaultModel(){return pe}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("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 Be}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var fi=(i,e)=>({name:`mcp_${i.name}_search`,description:e==="schema-fetch-failed"?`Search using ${i.name} MCP server (schema fetch failed)`:`Search using ${i.name} MCP server`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}),qt=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 r=await(await f.post(`${e.url}/tools`,{},t)).json();return Array.isArray(r.tools)?{schemas:r.tools.map(n=>({name:`mcp_${e.name}_${n.name}`,description:n.description||`Tool from ${e.name} MCP server`,parameters:n.inputSchema||{type:"object",properties:{},required:[]}})),failures:[]}:{schemas:[fi(e)],failures:[]}}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),{schemas:[fi(e,"schema-fetch-failed")],failures:[{server:e,error:t}]}}}static async fetchAllToolSchemas(e){return(await this.fetchAllToolSchemasWithStatus(e)).schemas}static async fetchAllToolSchemasWithStatus(e){let t=[],o=[];for(let r of e)try{let n=await this.fetchToolSchemasWithStatus(r);t.push(...n.schemas),o.push(...n.failures)}catch(n){console.error(`Failed to fetch schemas from ${r.name}:`,n),o.push({server:r,error:n})}return{schemas:t,failures:o}}};function Mi(i){switch(i){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}function vi(i,e={}){let t=[],o=null,r=[],n=()=>{o&&r.length&&(t.push({role:o,parts:[...r]}),r=[])};for(let s of i){let a=Mi(s.role);if(s.tool_calls){n();for(let l of s.tool_calls)e.callIdMap?.set(l.id,l.function.name),t.push({role:"model",parts:[{functionCall:{name:l.function.name,args:JSON.parse(l.function.arguments||"{}")}}]});continue}if(s.role==="tool"){n();let l=s.name??e.callIdMap?.get(s.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:l,response:Si(Oi(s.content))}}]});continue}a!==o&&n(),o=a,r.push({text:s.content})}return n(),t}async function Ei(i,e={}){let t=e.imageFetcher??f.get,o=e.blobToBase64??mr,r=[],n=null,s=[];for(let a of i){let l=Mi(a.role);if(a.tool_calls){for(let c of a.tool_calls)r.push({role:"model",parts:[{functionCall:{name:c.function.name,args:JSON.parse(c.function.arguments||"{}")}}]});continue}if(a.role==="tool"){let c=a.name??e.callIdMap?.get(a.tool_call_id)??"result";r.push({role:"user",parts:[{functionResponse:{name:c,response:Si(Oi(a.content))}}]});continue}if(l!==n&&s.length>0&&(r.push({role:n,parts:[...s]}),s=[]),n=l,typeof a.content=="string")s.push({text:a.content});else if(Array.isArray(a.content)){for(let c of a.content)if(c.type==="text")s.push({text:c.text});else if(c.type==="image_url")try{let u=await(await t(c.image_url.url)).blob(),m=await o(u);s.push({inlineData:{mimeType:u.type||"image/jpeg",data:m.split(",")[1]}})}catch(d){throw console.error("Error processing image:",d),new Error(`Failed to process image: ${d.message}`)}}}return n&&s.length>0&&r.push({role:n,parts:[...s]}),r}function Oi(i){try{return JSON.parse(i)}catch{return i}}function Si(i){return i===null?{content:null}:typeof i=="object"?i:{content:i}}function mr(i){return new Promise((e,t)=>{let o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=t,o.readAsDataURL(i)})}function dr(i,e){return[...i,...e].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}function Ci(i,e){let t=dr(i,e);if(t.length!==0)return{tools:[{functionDeclarations:t}],toolConfig:{functionCallingConfig:{mode:"AUTO"}}}}function Ti(i){return i.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 ge=class{constructor(e,t=q,o=q,r=[],n=[],s){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=s,!Ve.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=r,this.mcpServers=n}isGemma4Model(e){return/^gemma-4-/.test(e)}shouldMinimizeThinking(e){return e===Qe||this.isGemma4Model(e)}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"};return Array.isArray(e)?e.map(o=>this.adaptKeysForApi(o)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([o,r])=>[t[o]??o,this.adaptKeysForApi(r)])):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((r,n)=>setTimeout(()=>n(new Error("MCP schema fetch timeout")),5e3)),t=qt.fetchAllToolSchemasWithStatus(this.mcpServers),o=await Promise.race([t,e]);this.mcpToolSchemas=o.schemas,this.mcpSchemasInitialized=!0,this.mcpSchemaInitializationError=o.failures[0]?.error}catch(e){console.warn("Failed to initialize MCP schemas, using fallback:",e),this.mcpSchemaInitializationError=e,this.mcpToolSchemas=Ti(this.mcpServers),this.mcpSchemasInitialized=!0}}async processChat(e,t,o){try{await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callGemini(e,this.model,!0),{blocks:n}=await this.parseStream(r,t,this.model);return v.getFullText(n)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use chatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processChat:",r),r}}async processVisionChat(e,t,o){try{await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callGemini(e,this.visionModel,!0),{blocks:n}=await this.parseStream(r,t,this.visionModel);return v.getFullText(n)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:r=>{r.filter(n=>n.type==="text").forEach(n=>t(n.text))},onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use visionChatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processVisionChat:",r),r}}async callGemini(e,t,o=!1,r){let a={contents:e.some(_=>Array.isArray(_.content)&&_.content.some(D=>D?.type==="image_url"||D?.inlineData))?await Ei(e,{callIdMap:this.callIdMap}):vi(e,{callIdMap:this.callIdMap}),generationConfig:{maxOutputTokens:r!==void 0?r:O(this.responseLength)}};this.shouldMinimizeThinking(t)&&(a.generationConfig.thinkingConfig={includeThoughts:!1,thinkingLevel:"MINIMAL"});let l=[];if(this.mcpServers.length>0)try{await this.initializeMCPSchemas(),l=this.mcpToolSchemas}catch(_){console.warn("MCP initialization failed, skipping MCP tools:",_)}let c=Ci(this.tools,l);c&&Object.assign(a,c);let d=async(_,D)=>{let T=o?"streamGenerateContent":"generateContent",Ro=o?"?alt=sse":"",Pi=`${to}/${_}/models/${t}:${T}${Ro}${Ro?"&":"?"}key=${this.apiKey}`;return f.post(Pi,D)},u=/flash[-_]lite/.test(t),m=this.isGemma4Model(t),p=/gemini-2\.5/.test(t),h=/^gemini-3(?:\.[0-9]+)?-/.test(t),g=u||m||p||h,S=g?"v1beta":"v1",k=async()=>{try{let _=S==="v1"?a:this.adaptKeysForApi(a);return await d(S,_)}catch(_){let D=/Unknown name|Cannot find field|404/.test(_?.message||"")||_?.status===404;if(!g&&D)try{return await d("v1beta",this.adaptKeysForApi(a))}catch(T){throw T instanceof Error&&(T.cause=_),T}throw _}};try{return await k()}catch(_){throw _.body&&(console.error("Gemini API Error Details:",_.body),console.error("Request Body:",JSON.stringify(a,null,2))),_}}async parseStream(e,t,o){let r=e.body.getReader(),n=new TextDecoder,s=[],a=[],l="",c=u=>{if(!u||u==="[DONE]")return;let m;try{m=JSON.parse(u)}catch{return}for(let p of m.candidates??[])for(let h of p.content?.parts??[])this.shouldExposeTextPart(h,o)&&(t(h.text),v.addTextBlock(s,h.text)),h.functionCall&&a.push({type:"tool_use",id:this.genUUID(),name:h.functionCall.name,input:h.functionCall.args??{}}),h.functionResponse&&a.push({type:"tool_result",tool_use_id:h.functionResponse.name,content:JSON.stringify(h.functionResponse.response)})};for(;;){let{done:u,value:m}=await r.read();if(u)break;l+=n.decode(m,{stream:!0});let p;for(;(p=l.indexOf(`
|
|
14
|
+
`))!==-1;){let h=l.slice(0,p);if(l=l.slice(p+1),h.endsWith("\r")&&(h=h.slice(0,-1)),!h.trim()){c("");continue}h.startsWith("data:")&&(h=h.slice(5).trim()),h&&c(h)}}return l&&c(l),{blocks:[...s,...a],stop_reason:a.some(u=>u.type==="tool_use")?"tool_use":"end"}}parseOneShot(e,t){let o=[],r=[];for(let s of e.candidates??[])for(let a of s.content?.parts??[])this.shouldExposeTextPart(a,t)&&o.push({type:"text",text:a.text}),a.functionCall&&r.push({type:"tool_use",id:this.genUUID(),name:a.functionCall.name,input:a.functionCall.args??{}}),a.functionResponse&&r.push({type:"tool_result",tool_use_id:a.functionResponse.name,content:JSON.stringify(a.functionResponse.response)});return{blocks:[...o,...r],stop_reason:r.some(s=>s.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callGemini(e,this.model,t,r);return t?this.parseStream(n,o,this.model):this.parseOneShot(await n.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},r){let n=await this.callGemini(e,this.visionModel,t,r);return t?this.parseStream(n,o,this.visionModel):this.parseOneShot(await n.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 _e=class{createChatService(e){let t=E({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:o=>this.supportsVisionForModel(o),validate:"resolved"});return new ge(e.apiKey,e.model||this.getDefaultModel(),t,e.tools||[],e.mcpServers||[],e.responseLength)}getProviderName(){return"gemini"}getSupportedModels(){return[...et]}getDefaultModel(){return q}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ve.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function gr(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var fe=class{constructor(e={}){this.provider="gemini-nano";this.expectedInputLanguages=e.expectedInputLanguages??["ja"],this.expectedOutputLanguages=e.expectedOutputLanguages??["ja"],this._responseLength=e.responseLength}getModel(){return Z}getVisionModel(){return Z}async processChat(e,t,o){let r=await this.generateResponse(e);t(r),await o(r)}async processVisionChat(e,t,o){throw new Error("Gemini Nano does not support vision capabilities.")}async chatOnce(e,t=!1,o=()=>{},r){let n=await this.generateResponse(e);return o(n),{blocks:[{type:"text",text:n}],stop_reason:"end"}}async visionChatOnce(e,t=!1,o=()=>{},r){throw new Error("Gemini Nano does not support vision capabilities.")}async generateResponse(e){let t=gr();if(!t)throw new Error("Gemini Nano is not available in this environment. Chrome 138+ with Prompt API enabled is required.");let o=await t.availability();if(o!=="available"&&o!=="downloadable")throw new Error(`Gemini Nano Prompt API is not ready in this environment. LanguageModel.availability() returned "${o}". Expected "available" or "downloadable".`);let n=e.filter(c=>c.role==="system").map(c=>c.content).join(`
|
|
15
15
|
`),s=e.filter(c=>c.role!=="system").slice(-20),a=[...s].reverse().find(c=>c.role==="user");if(!a)throw new Error("No user message found in the provided messages.");let l=await this.createSession(t,n,s);try{return await l.prompt(a.content)}finally{try{l.destroy()}catch{}}}async createSession(e,t,o){let r=this.buildSystemPrompt(t),n=o.slice(0,-1);if(n.length>0){let s=n.map(a=>`${a.role==="user"?"User":"Assistant"}: ${a.content}`).join(`
|
|
16
16
|
`);r+=`
|
|
17
17
|
|
|
18
18
|
The following is the prior conversation history. Use it as context for your response:
|
|
19
19
|
`+s}return e.create({systemPrompt:r,expectedInputs:[{type:"text",languages:this.expectedInputLanguages}],expectedOutputs:[{type:"text",languages:this.expectedOutputLanguages}]})}buildSystemPrompt(e){let t=[];e&&t.push(e);let o=this.getResponseLengthInstruction();return o&&t.push(o),t.join(`
|
|
20
20
|
|
|
21
|
-
`)}getResponseLengthInstruction(){if(!this._responseLength)return;let e=Ft[this._responseLength];if(e)return`Please keep your response concise, within approximately ${e} tokens.`}};var fe=class{createChatService(e){return new _e({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,responseLength:e.responseLength})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[Z]}getDefaultModel(){return Z}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var Me=class{constructor(e,t=w,o=w,r,n=se,s,a,l){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=n,this.responseLength=s,this.responseFormat=a,this.thinking=l??{type:"enabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callKimi(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!ae(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callKimi(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callKimi(e,this.model,t,r);return this.parseResponse(n,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!ae(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let n=await this.callKimi(e,this.visionModel,t,r);return this.parseResponse(n,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callKimi(e,t,o=!1,r){let n=this.buildRequestBody(e,t,o,r);return await f.post(this.endpoint,n,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let n={model:t,stream:o,messages:e},s=r!==void 0?r:O(this.responseLength);s!==void 0&&(n.max_tokens=s),this.responseFormat&&(n.response_format=this.responseFormat);let a=this.tools.length>0?{type:"disabled"}:this.thinking;a&&(this.isSelfHostedEndpoint()?a.type==="disabled"&&(n.chat_template_kwargs={thinking:!1}):n.thinking=a);let l=this.buildToolsDefinition();return l.length>0&&(n.tools=l,n.tool_choice="auto"),n}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(se)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}buildToolsDefinition(){return x(this.tools,"chat-completions")}async handleStream(e,t){return L(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var ve=class{createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),r=E({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:l=>this.supportsVisionForModel(l),validate:"explicit"}),n=e.tools,s=e.thinking??{type:"enabled"},a=n&&n.length>0?{type:"disabled"}:s;return new Me(e.apiKey,o,r,n,t,e.responseLength,e.responseFormat,a)}getProviderName(){return"kimi"}getSupportedModels(){return[w,kt]}getDefaultModel(){return w}getDefaultVisionModel(){return w}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ae(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 se}normalizeEndpoint(e){return e.replace(/\/+$/,"")}};var Ee=class extends y{constructor(e,t=V,o=t,r,n=Ue,s,a){super(e,t,o,r,n,[],s,void 0,a,!1,"mistral",!1)}};var Oe=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),r=e.tools,n=He(t)?e.reasoning_effort:void 0;return new Ee(e.apiKey,t,o,r,this.resolveEndpoint(e),e.responseLength,n)}getProviderName(){return"mistral"}getSupportedModels(){return[..._o]}getDefaultModel(){return V}getDefaultVisionModel(){return V}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Mo(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 Ue}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Se=class{createChatService(e){return this.validateRequiredOptions(e),new y(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)}getProviderName(){return"openai-compatible"}getSupportedModels(){return[]}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"unknown"}supportsVisionForModel(e){return!0}getVisionSupportLevelForModel(e){return"unknown"}getDefaultModel(){return"local-model"}validateRequiredOptions(e){if(e.mcpServers!==void 0)throw new Error("openai-compatible provider does not support mcpServers.");let t=e.endpoint?.trim();if(!t)throw new Error("openai-compatible provider requires endpoint (full URL).");let o;try{o=new URL(t)}catch{throw new Error("openai-compatible provider requires endpoint to be a full URL.")}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error("openai-compatible provider requires endpoint to be a full URL.");if(!e.model?.trim())throw new Error("openai-compatible provider requires model.")}};var Ce=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=E({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:c=>this.supportsVisionForModel(c),validate:"resolved"}),r=t.tools,n=t.mcpServers??[],s=t.model||this.getDefaultModel(),a=!1;n.length>0||qt(s)?a=!0:j(s)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let l=t.endpoint||(a?D:U);return new y(t.apiKey,s,o,r,l,n,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName())}getProviderName(){return"openai"}getSupportedModels(){return[H,Q,ee,te,K,W,B,$,G,We,Be,$e,z,ze,$t,zt,"o1"]}getDefaultModel(){return H}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return De.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!j(t))return e;let o={...e};if(e.gpt5Preset){let r=Eo[e.gpt5Preset];o.reasoning_effort=r.reasoning_effort,o.verbosity=r.verbosity}else e.reasoning_effort||(o.reasoning_effort=be(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!Re(e)||t==="minimal"&&!je(e)?t==="minimal"&&Re(e)?"none":t==="none"&&je(e)?"minimal":qe(e)?"low":"medium":t==="low"&&!qe(e)?"medium":t==="xhigh"&&!Jt(e)?"high":t}};var li=i=>i.trim()===b,Te=class{constructor(e,t=b,o=b,r,n=Ve,s,a,l,c,d,u){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=n,this.responseLength=s,this.appName=a,this.appUrl=l,this.reasoning_effort=c,this.includeReasoning=d,this.reasoningMaxTokens=u,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!J(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=ro){let o=6e4-t;o>0&&(console.log(`Rate limit reached for free tier. Waiting ${o}ms...`),await new Promise(r=>setTimeout(r,o)),this.requestCount=0)}this.lastRequestTime=e,this.requestCount++}async processChat(e,t,o){await this.applyRateLimiting(),await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenRouter(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!oe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processVisionChat:",r),r}}async chatOnce(e,t=!0,o=()=>{},r){await this.applyRateLimiting();let n=await this.callOpenRouter(e,this.model,t,r);return t?this.parseStream(n,o):this.parseOneShot(await n.json())}async visionChatOnce(e,t=!1,o=()=>{},r){if(!oe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let n=await this.callOpenRouter(e,this.visionModel,t,r);return t?this.parseStream(n,o):this.parseOneShot(await n.json())}async callOpenRouter(e,t,o=!1,r){let n=this.buildRequestBody(e,t,o,r),s={Authorization:`Bearer ${this.apiKey}`};return this.appUrl&&(s["HTTP-Referer"]=this.appUrl),this.appName&&(s["X-Title"]=this.appName),await f.post(this.endpoint,n,s)}buildRequestBody(e,t,o,r){let n={model:t,messages:e,stream:o},s=r!==void 0?r:O(this.responseLength);if(s&&li(t)?console.warn(`OpenRouter: Token limits are not supported for ${t} due to known issues. Using unlimited tokens instead.`):s&&(n.max_tokens=s),this.reasoning_effort!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens){if(n.reasoning={},this.reasoning_effort&&this.reasoning_effort!=="none"){let a=this.reasoning_effort==="minimal"?"low":this.reasoning_effort;n.reasoning.effort=a}(this.reasoning_effort==="none"||this.includeReasoning!==!0)&&(n.reasoning.exclude=!0),this.reasoningMaxTokens&&(n.reasoning.max_tokens=this.reasoningMaxTokens)}else n.reasoning={exclude:!0};return this.tools.length>0&&(n.tools=x(this.tools,"chat-completions"),n.tool_choice="auto"),n}async handleStream(e,t){return L(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var ye=class{createChatService(e){let t=E({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:e.model||this.getDefaultModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),o=e.tools,r=e.appName,n=e.appUrl;return new Te(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,r,n,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[Yt,b,At,lt,pt,ct,ut,ht,mt,dt,gt,_t,ft,Mt,vt,Et,Ot,St,Ct,Qt,Tt,yt,Lt,Pt,It,xt,eo,to,at,st]}getDefaultModel(){return b}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return oe(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return oo}isModelFree(e){return J(e)}};var Le=class{constructor(e,t=N,o=N,r,n=Ge,s){this.provider="xai";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=n,this.responseLength=s,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callXAI(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!ne(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callXAI(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callXAI(e,this.model,t,r);return this.parseResponse(n,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!ne(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let n=await this.callXAI(e,this.visionModel,t,r);return this.parseResponse(n,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callXAI(e,t,o=!1,r){let n=this.buildRequestBody(e,t,o,r);return await f.post(this.endpoint,n,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let n={model:t,stream:o,messages:e},s=r!==void 0?r:O(this.responseLength);s!==void 0&&(n.max_tokens=s);let a=this.buildToolsDefinition();return a.length>0&&(n.tools=a,n.tool_choice="auto"),n}buildToolsDefinition(){return x(this.tools,"chat-completions")}async handleStream(e,t){return L(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var Pe=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:n=>this.supportsVisionForModel(n),validate:"explicit"}),r=e.tools;return new Le(e.apiKey,t,o,r,e.endpoint||Ge,e.responseLength)}getProviderName(){return"xai"}getSupportedModels(){return[bt,Nt,wt,Vt,N]}getDefaultModel(){return N}getDefaultVisionModel(){return N}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ne(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Ie=class{constructor(e,t=re,o=X,r,n=ke,s,a,l){this.provider="zai";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=n,this.responseLength=s,this.responseFormat=a,this.thinking=l??{type:"disabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callZAI(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!ie(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callZAI(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callZAI(e,this.model,t,r);return this.parseResponse(n,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!ie(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let n=await this.callZAI(e,this.visionModel,t,r);return this.parseResponse(n,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callZAI(e,t,o=!1,r){let n=this.buildRequestBody(e,t,o,r);return await f.post(this.endpoint,n,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let n={model:t,stream:o,messages:e},s=r!==void 0?r:O(this.responseLength);s!==void 0&&(n.max_tokens=s),this.responseFormat&&(n.response_format=this.responseFormat),this.thinking&&(n.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(n.tools=a,n.tool_choice="auto",o&&po(t)&&(n.tool_stream=!0)),n}buildToolsDefinition(){return x(this.tools,"chat-completions")}async handleStream(e,t){return L(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var xe=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),r=e.tools,n=e.thinking??{type:"disabled"};return new Ie(e.apiKey,t,o,r,e.endpoint||ke,e.responseLength,e.responseFormat,n)}getProviderName(){return"zai"}getSupportedModels(){return[io,no,re,so,ao,lo,Dt,Rt,X]}getDefaultModel(){return re}getDefaultVisionModel(){return X}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ie(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var fr=[new Ce,new Se,new ge,new fe,new ue,new ye,new xe,new Pe,new ve,new me,new Oe];var Ae=class{static registerProvider(e){this.providers.set(e.getProviderName(),e)}static createChatService(e,t){let o=this.providers.get(e);if(!o)throw new Error(`Unknown chat provider: ${e}`);return o.createChatService(t)}static getProviders(){return this.providers}static getAvailableProviders(){return Array.from(this.providers.keys())}static getSupportedModels(e){let t=this.providers.get(e);return t?t.getSupportedModels():[]}static getVisionSupportLevel(e){let t=this.providers.get(e);return t?t.getVisionSupportLevel():"unsupported"}static getVisionSupportLevelForModel(e,t){let o=this.providers.get(e);return o?o.getVisionSupportLevelForModel?o.getVisionSupportLevelForModel(t):o.supportsVisionForModel?o.supportsVisionForModel(t)?"supported":"unsupported":o.getVisionSupportLevel():"unsupported"}};Ae.providers=new Map;fr.forEach(i=>Ae.registerProvider(i));function Mr(){f.setFetch(async(i,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,r={};if(Array.isArray(o))for(let[u,m]of o)r[u]=String(m);else if(o&&typeof o=="object")for(let[u,m]of Object.entries(o))r[u]=String(m);let n={method:t,headers:r,muteHttpExceptions:!0},s=e.body;typeof s=="string"?n.payload=s:s!=null&&(r["Content-Type"]||(r["Content-Type"]="application/json"),n.payload=JSON.stringify(s));let a=UrlFetchApp.fetch(i,n),l=a.getResponseCode(),c=a.getContentText();return{ok:l>=200&&l<300,status:l,statusText:String(l),text:async()=>c,json:async()=>c?JSON.parse(c):null}})}return yr(pi);})();
|
|
21
|
+
`)}getResponseLengthInstruction(){if(!this._responseLength)return;let e=Bt[this._responseLength];if(e)return`Please keep your response concise, within approximately ${e} tokens.`}};var Me=class{createChatService(e){return new fe({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,responseLength:e.responseLength})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[Z]}getDefaultModel(){return Z}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var ve=class{constructor(e,t=w,o=w,r,n=ae,s,a,l){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=n,this.responseLength=s,this.responseFormat=a,this.thinking=l??{type:"enabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callKimi(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!le(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callKimi(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callKimi(e,this.model,t,r);return this.parseResponse(n,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!le(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let n=await this.callKimi(e,this.visionModel,t,r);return this.parseResponse(n,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callKimi(e,t,o=!1,r){let n=this.buildRequestBody(e,t,o,r);return await f.post(this.endpoint,n,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let n={model:t,stream:o,messages:e},s=r!==void 0?r:O(this.responseLength);s!==void 0&&(n.max_tokens=s),this.responseFormat&&(n.response_format=this.responseFormat);let a=this.resolveEffectiveThinking(t);a&&(this.isSelfHostedEndpoint()?a.type==="disabled"&&(n.chat_template_kwargs={thinking:!1}):n.thinking=a);let l=this.buildToolsDefinition();return l.length>0&&(n.tools=l,n.tool_choice="auto"),n}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(ae)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveEffectiveThinking(e){if(We(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}buildToolsDefinition(){return x(this.tools,"chat-completions")}async handleStream(e,t){return L(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var Ee=class{constructor(){this.defaultThinking={type:"enabled"}}createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),r=E({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:a=>this.supportsVisionForModel(a),validate:"explicit"}),n=e.tools,s=this.resolveThinking(o,n,e.thinking);return new ve(e.apiKey,o,r,n,t,e.responseLength,e.responseFormat,s)}getProviderName(){return"kimi"}getSupportedModels(){return[He,Ke,w,Kt]}getDefaultModel(){return w}getDefaultVisionModel(){return w}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return le(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 ae}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveThinking(e,t,o){if(We(e)){if(o?.type==="disabled")throw new Error(`Model ${e} requires thinking mode and does not support thinking: disabled.`);return o??this.defaultThinking}return t&&t.length>0?{type:"disabled"}:o??this.defaultThinking}};var Oe=class extends y{constructor(e,t=V,o=t,r,n=$e,s,a){super(e,t,o,r,n,[],s,void 0,a,!1,"mistral",!1)}};var Se=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),r=e.tools,n=ze(t)?e.reasoning_effort:void 0;return new Oe(e.apiKey,t,o,r,this.resolveEndpoint(e),e.responseLength,n)}getProviderName(){return"mistral"}getSupportedModels(){return[...Co]}getDefaultModel(){return V}getDefaultVisionModel(){return V}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return yo(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 $e}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Ce=class{createChatService(e){return this.validateRequiredOptions(e),new y(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)}getProviderName(){return"openai-compatible"}getSupportedModels(){return[]}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"unknown"}supportsVisionForModel(e){return!0}getVisionSupportLevelForModel(e){return"unknown"}getDefaultModel(){return"local-model"}validateRequiredOptions(e){if(e.mcpServers!==void 0)throw new Error("openai-compatible provider does not support mcpServers.");let t=e.endpoint?.trim();if(!t)throw new Error("openai-compatible provider requires endpoint (full URL).");let o;try{o=new URL(t)}catch{throw new Error("openai-compatible provider requires endpoint to be a full URL.")}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error("openai-compatible provider requires endpoint to be a full URL.");if(!e.model?.trim())throw new Error("openai-compatible provider requires model.")}};var Te=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=E({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:c=>this.supportsVisionForModel(c),validate:"resolved"}),r=t.tools,n=t.mcpServers??[],s=t.model||this.getDefaultModel(),a=!1;n.length>0||Qt(s)?a=!0:j(s)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let l=t.endpoint||(a?A:U);return new y(t.apiKey,s,o,r,l,n,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName())}getProviderName(){return"openai"}getSupportedModels(){return[H,Q,ee,te,K,W,B,$,G,qe,Je,Xe,z,Ze,Xt,Zt,"o1"]}getDefaultModel(){return H}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Re.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!j(t))return e;let o={...e};if(e.gpt5Preset){let r=Po[e.gpt5Preset];o.reasoning_effort=r.reasoning_effort,o.verbosity=r.verbosity}else e.reasoning_effort||(o.reasoning_effort=we(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!be(e)||t==="minimal"&&!Ne(e)?t==="minimal"&&be(e)?"none":t==="none"&&Ne(e)?"minimal":Ye(e)?"low":"medium":t==="low"&&!Ye(e)?"medium":t==="xhigh"&&!eo(e)?"high":t}};var _r=i=>[b,oe].includes(i.trim()),fr=i=>i.trim()===oe?"none":void 0,ye=class{constructor(e,t=b,o=b,r,n=Ge,s,a,l,c,d,u){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=n,this.responseLength=s,this.appName=a,this.appUrl=l,this.reasoning_effort=c,this.includeReasoning=d,this.reasoningMaxTokens=u,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!J(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=po){let o=6e4-t;o>0&&(console.log(`Rate limit reached for free tier. Waiting ${o}ms...`),await new Promise(r=>setTimeout(r,o)),this.requestCount=0)}this.lastRequestTime=e,this.requestCount++}async processChat(e,t,o){await this.applyRateLimiting(),await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenRouter(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!ie(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processVisionChat:",r),r}}async chatOnce(e,t=!0,o=()=>{},r){await this.applyRateLimiting();let n=await this.callOpenRouter(e,this.model,t,r);return t?this.parseStream(n,o):this.parseOneShot(await n.json())}async visionChatOnce(e,t=!1,o=()=>{},r){if(!ie(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let n=await this.callOpenRouter(e,this.visionModel,t,r);return t?this.parseStream(n,o):this.parseOneShot(await n.json())}async callOpenRouter(e,t,o=!1,r){let n=this.buildRequestBody(e,t,o,r),s={Authorization:`Bearer ${this.apiKey}`};return this.appUrl&&(s["HTTP-Referer"]=this.appUrl),this.appName&&(s["X-Title"]=this.appName),await f.post(this.endpoint,n,s)}buildRequestBody(e,t,o,r){let n={model:t,messages:e,stream:o},s=r!==void 0?r:O(this.responseLength);s&&_r(t)?console.warn(`OpenRouter: Token limits are disabled for ${t} because this model can return empty content when a token limit is set.`):s&&(n.max_tokens=s);let a=fr(t);if(this.reasoning_effort!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens||a){if(n.reasoning={},this.reasoning_effort&&this.reasoning_effort!=="none"){let l=this.reasoning_effort==="minimal"?"low":this.reasoning_effort;n.reasoning.effort=l}else this.reasoning_effort===void 0&&a&&(n.reasoning.effort=a);(this.reasoning_effort==="none"||this.includeReasoning!==!0)&&(n.reasoning.exclude=!0),this.reasoningMaxTokens&&(n.reasoning.max_tokens=this.reasoningMaxTokens)}else n.reasoning={exclude:!0};return this.tools.length>0&&(n.tools=x(this.tools,"chat-completions"),n.tool_choice="auto"),n}async handleStream(e,t){return L(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var Le=class{createChatService(e){let t=E({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:e.model||this.getDefaultModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),o=e.tools,r=e.appName,n=e.appUrl;return new ye(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,r,n,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[io,ro,b,wt,mt,dt,gt,_t,ft,Mt,vt,Et,Ot,St,Ct,Tt,yt,Lt,Pt,It,no,xt,Dt,At,Rt,bt,Nt,oe,so,ao,ht,ct,ut]}getDefaultModel(){return b}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return ie(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return lo}isModelFree(e){return J(e)}};var Pe=class{constructor(e,t=N,o=N,r,n=Ue,s){this.provider="xai";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=n,this.responseLength=s,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callXAI(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!se(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callXAI(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callXAI(e,this.model,t,r);return this.parseResponse(n,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!se(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let n=await this.callXAI(e,this.visionModel,t,r);return this.parseResponse(n,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callXAI(e,t,o=!1,r){let n=this.buildRequestBody(e,t,o,r);return await f.post(this.endpoint,n,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let n={model:t,stream:o,messages:e},s=r!==void 0?r:O(this.responseLength);s!==void 0&&(n.max_tokens=s);let a=this.buildToolsDefinition();return a.length>0&&(n.tools=a,n.tool_choice="auto"),n}buildToolsDefinition(){return x(this.tools,"chat-completions")}async handleStream(e,t){return L(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var Ie=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:n=>this.supportsVisionForModel(n),validate:"explicit"}),r=e.tools;return new Pe(e.apiKey,t,o,r,e.endpoint||Ue,e.responseLength)}getProviderName(){return"xai"}getSupportedModels(){return[Gt,Ft,Ut,Ht,N]}getDefaultModel(){return N}getDefaultVisionModel(){return N}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return se(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var xe=class{constructor(e,t=re,o=X,r,n=Fe,s,a,l){this.provider="zai";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=n,this.responseLength=s,this.responseFormat=a,this.thinking=l??{type:"disabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callZAI(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!ne(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callZAI(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},r){let n=await this.callZAI(e,this.model,t,r);return this.parseResponse(n,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!ne(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let n=await this.callZAI(e,this.visionModel,t,r);return this.parseResponse(n,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callZAI(e,t,o=!1,r){let n=this.buildRequestBody(e,t,o,r);return await f.post(this.endpoint,n,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let n={model:t,stream:o,messages:e},s=r!==void 0?r:O(this.responseLength);s!==void 0&&(n.max_tokens=s),this.responseFormat&&(n.response_format=this.responseFormat),this.thinking&&(n.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(n.tools=a,n.tool_choice="auto",o&&fo(t)&&(n.tool_stream=!0)),n}buildToolsDefinition(){return x(this.tools,"chat-completions")}async handleStream(e,t){return L(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var De=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),r=e.tools,n=e.thinking??{type:"disabled"};return new xe(e.apiKey,t,o,r,e.endpoint||Fe,e.responseLength,e.responseFormat,n)}getProviderName(){return"zai"}getSupportedModels(){return[re,co,uo,ho,mo,go,_o,Vt,kt,X]}getDefaultModel(){return re}getDefaultVisionModel(){return X}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ne(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var yi=[new Te,new Ce,new _e,new Me,new he,new Le,new De,new Ie,new Ee,new de,new Se];var Ae=class{static registerProvider(e){this.providers.set(e.getProviderName(),e)}static createChatService(e,t){let o=this.providers.get(e);if(!o)throw new Error(`Unknown chat provider: ${e}`);return o.createChatService(t)}static getProviders(){return this.providers}static getAvailableProviders(){return Array.from(this.providers.keys())}static getSupportedModels(e){let t=this.providers.get(e);return t?t.getSupportedModels():[]}static getVisionSupportLevel(e){let t=this.providers.get(e);return t?t.getVisionSupportLevel():"unsupported"}static getVisionSupportLevelForModel(e,t){let o=this.providers.get(e);return o?o.getVisionSupportLevelForModel?o.getVisionSupportLevelForModel(t):o.supportsVisionForModel?o.supportsVisionForModel(t)?"supported":"unsupported":o.getVisionSupportLevel():"unsupported"}};Ae.providers=new Map;yi.forEach(i=>Ae.registerProvider(i));function Li(){f.setFetch(async(i,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,r={};if(Array.isArray(o))for(let[u,m]of o)r[u]=String(m);else if(o&&typeof o=="object")for(let[u,m]of Object.entries(o))r[u]=String(m);let n={method:t,headers:r,muteHttpExceptions:!0},s=e.body;typeof s=="string"?n.payload=s:s!=null&&(r["Content-Type"]||(r["Content-Type"]="application/json"),n.payload=JSON.stringify(s));let a=UrlFetchApp.fetch(i,n),l=a.getResponseCode(),c=a.getContentText();return{ok:l>=200&&l<300,status:l,statusText:String(l),text:async()=>c,json:async()=>c?JSON.parse(c):null}})}return bi(Mr);})();
|