@aituber-onair/chat 0.21.0 → 0.21.2

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.
Files changed (31) hide show
  1. package/README.ja.md +19 -2
  2. package/README.md +17 -1
  3. package/dist/cjs/constants/openai.d.ts +1 -1
  4. package/dist/cjs/constants/openai.d.ts.map +1 -1
  5. package/dist/cjs/constants/openai.js +5 -2
  6. package/dist/cjs/constants/openai.js.map +1 -1
  7. package/dist/cjs/services/providers/openai/OpenAIChatService.d.ts +2 -0
  8. package/dist/cjs/services/providers/openai/OpenAIChatService.d.ts.map +1 -1
  9. package/dist/cjs/services/providers/openai/OpenAIChatService.js +69 -9
  10. package/dist/cjs/services/providers/openai/OpenAIChatService.js.map +1 -1
  11. package/dist/cjs/types/toolChat.d.ts +8 -0
  12. package/dist/cjs/types/toolChat.d.ts.map +1 -1
  13. package/dist/cjs/utils/openaiCompatibleSse.d.ts.map +1 -1
  14. package/dist/cjs/utils/openaiCompatibleSse.js +16 -1
  15. package/dist/cjs/utils/openaiCompatibleSse.js.map +1 -1
  16. package/dist/esm/constants/openai.d.ts +1 -1
  17. package/dist/esm/constants/openai.d.ts.map +1 -1
  18. package/dist/esm/constants/openai.js +5 -2
  19. package/dist/esm/constants/openai.js.map +1 -1
  20. package/dist/esm/services/providers/openai/OpenAIChatService.d.ts +2 -0
  21. package/dist/esm/services/providers/openai/OpenAIChatService.d.ts.map +1 -1
  22. package/dist/esm/services/providers/openai/OpenAIChatService.js +71 -11
  23. package/dist/esm/services/providers/openai/OpenAIChatService.js.map +1 -1
  24. package/dist/esm/types/toolChat.d.ts +8 -0
  25. package/dist/esm/types/toolChat.d.ts.map +1 -1
  26. package/dist/esm/utils/openaiCompatibleSse.d.ts.map +1 -1
  27. package/dist/esm/utils/openaiCompatibleSse.js +16 -1
  28. package/dist/esm/utils/openaiCompatibleSse.js.map +1 -1
  29. package/dist/umd/aituber-onair-chat.js +89 -9
  30. package/dist/umd/aituber-onair-chat.min.js +6 -6
  31. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- "use strict";var AITuberOnAirChat=(()=>{var ct=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var Qt=Object.prototype.hasOwnProperty;var eo=(i,e)=>{for(var t in e)ct(i,t,{get:e[t],enumerable:!0})},to=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Yt(e))!Qt.call(i,r)&&r!==t&&ct(i,r,{get:()=>e[r],enumerable:!(o=Xt(e,r))||o.enumerable});return i};var oo=i=>to(ct({},"__esModule",{value:!0}),i);var yo={};eo(yo,{CHAT_RESPONSE_LENGTH:()=>W,CLAUDE_VISION_SUPPORTED_MODELS:()=>ge,ChatServiceFactory:()=>me,ChatServiceHttpClient:()=>g,ClaudeChatService:()=>te,ClaudeChatServiceProvider:()=>oe,DEFAULT_MAX_TOKENS:()=>Dt,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>ao,DEFAULT_VISION_PROMPT:()=>no,EMOTION_TAG_CLEANUP_REGEX:()=>wt,EMOTION_TAG_REGEX:()=>Wt,ENDPOINT_CLAUDE_API:()=>Ot,ENDPOINT_GEMINI_API:()=>Mt,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>Y,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>B,ENDPOINT_OPENAI_RESPONSES_API:()=>y,ENDPOINT_OPENROUTER_API:()=>fe,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>ve,EmotionParser:()=>ee,GEMINI_VISION_SUPPORTED_MODELS:()=>_e,GPT5_PRESETS:()=>At,GPT_5_MODELS:()=>Vt,GeminiChatService:()=>re,GeminiChatServiceProvider:()=>se,HttpError:()=>w,KIMI_VISION_SUPPORTED_MODELS:()=>Ut,KimiChatService:()=>ie,KimiChatServiceProvider:()=>ne,MAX_TOKENS_BY_LENGTH:()=>Ht,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>Et,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>Qe,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>et,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>Xe,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>Ye,MODEL_CLAUDE_3_5_HAIKU:()=>Ae,MODEL_CLAUDE_3_5_SONNET:()=>we,MODEL_CLAUDE_3_7_SONNET:()=>Ne,MODEL_CLAUDE_3_HAIKU:()=>T,MODEL_CLAUDE_4_5_HAIKU:()=>Fe,MODEL_CLAUDE_4_5_OPUS:()=>Ue,MODEL_CLAUDE_4_5_SONNET:()=>Ge,MODEL_CLAUDE_4_6_OPUS:()=>We,MODEL_CLAUDE_4_6_SONNET:()=>He,MODEL_CLAUDE_4_OPUS:()=>Ve,MODEL_CLAUDE_4_SONNET:()=>ke,MODEL_GEMINI_2_0_FLASH:()=>De,MODEL_GEMINI_2_0_FLASH_LITE:()=>D,MODEL_GEMINI_2_5_FLASH:()=>Le,MODEL_GEMINI_2_5_FLASH_LITE:()=>be,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>Re,MODEL_GEMINI_2_5_PRO:()=>Ie,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>Se,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>Te,MODEL_GEMINI_3_FLASH_PREVIEW:()=>xe,MODEL_GEMINI_3_PRO_PREVIEW:()=>Pe,MODEL_GLM_4_6:()=>bt,MODEL_GLM_4_6V:()=>it,MODEL_GLM_4_6V_FLASH:()=>H,MODEL_GLM_4_6V_FLASHX:()=>nt,MODEL_GLM_4_7:()=>Z,MODEL_GLM_4_7_FLASH:()=>Lt,MODEL_GLM_4_7_FLASHX:()=>It,MODEL_GLM_5:()=>Pt,MODEL_GLM_5_TURBO:()=>xt,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>ot,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>rt,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>tt,MODEL_GPT_4O:()=>ye,MODEL_GPT_4O_MINI:()=>G,MODEL_GPT_4_1:()=>Oe,MODEL_GPT_4_1_MINI:()=>Ee,MODEL_GPT_4_1_NANO:()=>Ce,MODEL_GPT_5:()=>$,MODEL_GPT_5_1:()=>V,MODEL_GPT_5_4:()=>b,MODEL_GPT_5_4_MINI:()=>j,MODEL_GPT_5_4_NANO:()=>z,MODEL_GPT_5_4_PRO:()=>R,MODEL_GPT_5_MINI:()=>K,MODEL_GPT_5_NANO:()=>k,MODEL_GPT_OSS_20B_FREE:()=>A,MODEL_KIMI_K2_5:()=>S,MODEL_MOONSHOTAI_KIMI_K2_5:()=>Be,MODEL_O1:()=>mt,MODEL_O1_MINI:()=>ut,MODEL_O3_MINI:()=>ht,MODEL_OPENAI_GPT_4O:()=>qe,MODEL_OPENAI_GPT_4_1_MINI:()=>Je,MODEL_OPENAI_GPT_4_1_NANO:()=>Ze,MODEL_OPENAI_GPT_5_1_CHAT:()=>Ke,MODEL_OPENAI_GPT_5_1_CODEX:()=>$e,MODEL_OPENAI_GPT_5_MINI:()=>je,MODEL_OPENAI_GPT_5_NANO:()=>ze,MODEL_ZAI_GLM_4_5_AIR:()=>yt,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>st,MODEL_ZAI_GLM_4_7_FLASH:()=>Ct,OPENROUTER_CREDITS_THRESHOLD:()=>io,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>so,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>ro,OPENROUTER_FREE_MODELS:()=>Tt,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>St,OPENROUTER_VISION_SUPPORTED_MODELS:()=>Gt,OpenAIChatService:()=>N,OpenAIChatServiceProvider:()=>le,OpenAICompatibleChatServiceProvider:()=>ae,OpenRouterChatService:()=>pe,OpenRouterChatServiceProvider:()=>ce,StreamTextAccumulator:()=>f,VISION_SUPPORTED_MODELS:()=>de,ZAIChatService:()=>he,ZAIChatServiceProvider:()=>ue,ZAI_VISION_SUPPORTED_MODELS:()=>Ft,allowsReasoningLow:()=>vt,allowsReasoningMinimal:()=>ft,allowsReasoningNone:()=>gt,allowsReasoningXHigh:()=>_t,buildOpenAICompatibleTools:()=>L,getDefaultReasoningEffortForGPT5Model:()=>F,getMaxTokensForResponseLength:()=>O,installGASFetch:()=>Jt,isGPT5Model:()=>q,isKimiVisionModel:()=>Q,isOpenRouterFreeModel:()=>U,isOpenRouterVisionModel:()=>J,isResponsesOnlyGPT5Model:()=>dt,isZaiToolStreamModel:()=>Rt,isZaiVisionModel:()=>X,parseOpenAICompatibleOneShot:()=>I,parseOpenAICompatibleTextStream:()=>P,parseOpenAICompatibleToolStream:()=>x,processChatWithOptionalTools:()=>v,refreshOpenRouterFreeModels:()=>Co,resolveVisionModel:()=>E,runOnceText:()=>ho,screenplayToText:()=>co,textToScreenplay:()=>Bt,textsToScreenplay:()=>po});var B="https://api.openai.com/v1/chat/completions",y="https://api.openai.com/v1/responses",k="gpt-5-nano",K="gpt-5-mini",$="gpt-5",V="gpt-5.1",b="gpt-5.4",j="gpt-5.4-mini",z="gpt-5.4-nano",R="gpt-5.4-pro",Oe="gpt-4.1",Ee="gpt-4.1-mini",Ce="gpt-4.1-nano",G="gpt-4o-mini",ye="gpt-4o",ht="o3-mini",ut="o1-mini",mt="o1",de=[k,K,$,V,b,j,z,R,Oe,Ee,Ce,G,ye,"o1"],Vt=[k,K,$,V,b,j,z,R];function q(i){return Vt.includes(i)}function dt(i){return i===R}function _t(i){return i===b||i===j||i===z||i===R}function gt(i){return i===V||i===b}function ft(i){return i===k||i===K||i===$}function vt(i){return i!==R}function F(i){return i===V||i===b?"none":"medium"}var Mt="https://generativelanguage.googleapis.com",Te="gemini-3.1-pro-preview",Se="gemini-3.1-flash-lite-preview",Pe="gemini-3-pro-preview",xe="gemini-3-flash-preview",Ie="gemini-2.5-pro",Le="gemini-2.5-flash",be="gemini-2.5-flash-lite",Re="gemini-2.5-flash-lite-preview-06-17",De="gemini-2.0-flash",D="gemini-2.0-flash-lite",_e=[Te,Se,Pe,xe,Ie,Le,be,Re,De,D];var Ot="https://api.anthropic.com/v1/messages",T="claude-3-haiku-20240307",Ae="claude-3-5-haiku-20241022",we="claude-3-5-sonnet-20241022",Ne="claude-3-7-sonnet-20250219",ke="claude-4-sonnet-20250514",Ve="claude-4-opus-20250514",Ge="claude-sonnet-4-5-20250929",Fe="claude-haiku-4-5-20251001",Ue="claude-opus-4-5-20251101",He="claude-sonnet-4-6",We="claude-opus-4-6",ge=[T,Ae,we,Ne,ke,Ve,Ge,Fe,Ue,He,We];var fe="https://openrouter.ai/api/v1/chat/completions",A="openai/gpt-oss-20b:free",Be="moonshotai/kimi-k2.5",Ke="openai/gpt-5.1-chat",$e="openai/gpt-5.1-codex",je="openai/gpt-5-mini",ze="openai/gpt-5-nano",qe="openai/gpt-4o",Je="openai/gpt-4.1-mini",Ze="openai/gpt-4.1-nano",Xe="anthropic/claude-opus-4",Ye="anthropic/claude-sonnet-4",Qe="anthropic/claude-3.7-sonnet",Et="anthropic/claude-3.5-sonnet",et="anthropic/claude-haiku-4.5",tt="google/gemini-2.5-pro",ot="google/gemini-2.5-flash",rt="google/gemini-2.5-flash-lite-preview-09-2025",Ct="z-ai/glm-4.7-flash",yt="z-ai/glm-4.5-air",st="z-ai/glm-4.5-air:free",Tt=[A,st],Gt=[Ke,$e,je,ze,qe,Je,Ze,Xe,Ye,Qe,et,tt,ot,rt,Be],St=20,ro=50,so=1e3,io=10;function U(i){return i.trim().endsWith(":free")}function J(i){return Gt.some(e=>i.includes(e))}var ve="https://api.z.ai/api/paas/v4/chat/completions",Pt="glm-5",xt="glm-5-turbo",Z="glm-4.7",It="glm-4.7-FlashX",Lt="glm-4.7-Flash",bt="glm-4.6",it="glm-4.6V",nt="glm-4.6V-FlashX",H="glm-4.6V-Flash",Ft=[it,nt,H];function X(i){return Ft.includes(i)}function Rt(i){return i.toLowerCase().startsWith("glm-4.6")}var Y="https://api.moonshot.ai/v1/chat/completions",S="kimi-k2.5",Ut=[S];function Q(i){return Ut.includes(i)}var W={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Ht={[W.VERY_SHORT]:40,[W.SHORT]:100,[W.MEDIUM]:200,[W.LONG]:300,[W.VERY_LONG]:1e3,[W.DEEP]:5e3},Dt=5e3,At={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?Ht[i]??Dt:Dt}var no="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",ao=`You are a skilled summarizing assistant.
1
+ "use strict";var AITuberOnAirChat=(()=>{var mt=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var eo=Object.getOwnPropertyNames;var to=Object.prototype.hasOwnProperty;var oo=(n,e)=>{for(var t in e)mt(n,t,{get:e[t],enumerable:!0})},so=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of eo(e))!to.call(n,s)&&s!==t&&mt(n,s,{get:()=>e[s],enumerable:!(o=Qt(e,s))||o.enumerable});return n};var ro=n=>so(mt({},"__esModule",{value:!0}),n);var xo={};oo(xo,{CHAT_RESPONSE_LENGTH:()=>O,CLAUDE_VISION_SUPPORTED_MODELS:()=>Me,ChatServiceFactory:()=>_e,ChatServiceHttpClient:()=>g,ClaudeChatService:()=>se,ClaudeChatServiceProvider:()=>re,DEFAULT_MAX_TOKENS:()=>Nt,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>po,DEFAULT_VISION_PROMPT:()=>lo,EMOTION_TAG_CLEANUP_REGEX:()=>Gt,EMOTION_TAG_REGEX:()=>Kt,ENDPOINT_CLAUDE_API:()=>yt,ENDPOINT_GEMINI_API:()=>Ct,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>ee,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>q,ENDPOINT_OPENAI_RESPONSES_API:()=>T,ENDPOINT_OPENROUTER_API:()=>Oe,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>Ee,EmotionParser:()=>oe,GEMINI_VISION_SUPPORTED_MODELS:()=>ve,GPT5_PRESETS:()=>kt,GPT_5_MODELS:()=>Ft,GeminiChatService:()=>ne,GeminiChatServiceProvider:()=>ie,HttpError:()=>G,KIMI_VISION_SUPPORTED_MODELS:()=>Wt,KimiChatService:()=>ae,KimiChatServiceProvider:()=>le,MAX_TOKENS_BY_LENGTH:()=>Bt,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>Tt,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>st,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>rt,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>tt,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>ot,MODEL_CLAUDE_3_5_HAIKU:()=>Ge,MODEL_CLAUDE_3_5_SONNET:()=>Ve,MODEL_CLAUDE_3_7_SONNET:()=>Fe,MODEL_CLAUDE_3_HAIKU:()=>S,MODEL_CLAUDE_4_5_HAIKU:()=>Be,MODEL_CLAUDE_4_5_OPUS:()=>Ke,MODEL_CLAUDE_4_5_SONNET:()=>We,MODEL_CLAUDE_4_6_OPUS:()=>je,MODEL_CLAUDE_4_6_SONNET:()=>$e,MODEL_CLAUDE_4_OPUS:()=>He,MODEL_CLAUDE_4_SONNET:()=>Ue,MODEL_GEMINI_2_0_FLASH:()=>ke,MODEL_GEMINI_2_0_FLASH_LITE:()=>N,MODEL_GEMINI_2_5_FLASH:()=>Ae,MODEL_GEMINI_2_5_FLASH_LITE:()=>we,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>Ne,MODEL_GEMINI_2_5_PRO:()=>De,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>Re,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>Ie,MODEL_GEMINI_3_FLASH_PREVIEW:()=>be,MODEL_GEMINI_3_PRO_PREVIEW:()=>Le,MODEL_GLM_4_6:()=>At,MODEL_GLM_4_6V:()=>pt,MODEL_GLM_4_6V_FLASH:()=>j,MODEL_GLM_4_6V_FLASHX:()=>ct,MODEL_GLM_4_7:()=>Y,MODEL_GLM_4_7_FLASH:()=>Dt,MODEL_GLM_4_7_FLASHX:()=>bt,MODEL_GLM_5:()=>Rt,MODEL_GLM_5_TURBO:()=>Lt,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>it,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>at,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>nt,MODEL_GPT_4O:()=>xe,MODEL_GPT_4O_MINI:()=>B,MODEL_GPT_4_1:()=>Te,MODEL_GPT_4_1_MINI:()=>Se,MODEL_GPT_4_1_NANO:()=>Pe,MODEL_GPT_5:()=>Z,MODEL_GPT_5_1:()=>U,MODEL_GPT_5_4:()=>A,MODEL_GPT_5_4_MINI:()=>H,MODEL_GPT_5_4_NANO:()=>W,MODEL_GPT_5_4_PRO:()=>w,MODEL_GPT_5_MINI:()=>J,MODEL_GPT_5_NANO:()=>F,MODEL_GPT_OSS_20B_FREE:()=>k,MODEL_KIMI_K2_5:()=>x,MODEL_MOONSHOTAI_KIMI_K2_5:()=>ze,MODEL_O1:()=>gt,MODEL_O1_MINI:()=>_t,MODEL_O3_MINI:()=>dt,MODEL_OPENAI_GPT_4O:()=>Ye,MODEL_OPENAI_GPT_4_1_MINI:()=>Qe,MODEL_OPENAI_GPT_4_1_NANO:()=>et,MODEL_OPENAI_GPT_5_1_CHAT:()=>qe,MODEL_OPENAI_GPT_5_1_CODEX:()=>Je,MODEL_OPENAI_GPT_5_MINI:()=>Ze,MODEL_OPENAI_GPT_5_NANO:()=>Xe,MODEL_ZAI_GLM_4_5_AIR:()=>Pt,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>lt,MODEL_ZAI_GLM_4_7_FLASH:()=>St,OPENROUTER_CREDITS_THRESHOLD:()=>ao,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>io,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>no,OPENROUTER_FREE_MODELS:()=>xt,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>It,OPENROUTER_VISION_SUPPORTED_MODELS:()=>Ut,OpenAIChatService:()=>V,OpenAIChatServiceProvider:()=>ce,OpenAICompatibleChatServiceProvider:()=>pe,OpenRouterChatService:()=>he,OpenRouterChatServiceProvider:()=>ue,StreamTextAccumulator:()=>f,VISION_SUPPORTED_MODELS:()=>fe,ZAIChatService:()=>me,ZAIChatServiceProvider:()=>de,ZAI_VISION_SUPPORTED_MODELS:()=>Ht,allowsReasoningLow:()=>Et,allowsReasoningMinimal:()=>Ot,allowsReasoningNone:()=>Mt,allowsReasoningXHigh:()=>vt,buildOpenAICompatibleTools:()=>b,getDefaultReasoningEffortForGPT5Model:()=>P,getMaxTokensForResponseLength:()=>E,installGASFetch:()=>Xt,isGPT5Model:()=>K,isKimiVisionModel:()=>te,isOpenRouterFreeModel:()=>$,isOpenRouterVisionModel:()=>X,isResponsesOnlyGPT5Model:()=>ft,isZaiToolStreamModel:()=>wt,isZaiVisionModel:()=>Q,parseOpenAICompatibleOneShot:()=>L,parseOpenAICompatibleTextStream:()=>I,parseOpenAICompatibleToolStream:()=>R,processChatWithOptionalTools:()=>v,refreshOpenRouterFreeModels:()=>To,resolveVisionModel:()=>y,runOnceText:()=>mo,screenplayToText:()=>uo,textToScreenplay:()=>$t,textsToScreenplay:()=>ho});var q="https://api.openai.com/v1/chat/completions",T="https://api.openai.com/v1/responses",F="gpt-5-nano",J="gpt-5-mini",Z="gpt-5",U="gpt-5.1",A="gpt-5.4",H="gpt-5.4-mini",W="gpt-5.4-nano",w="gpt-5.4-pro",Te="gpt-4.1",Se="gpt-4.1-mini",Pe="gpt-4.1-nano",B="gpt-4o-mini",xe="gpt-4o",dt="o3-mini",_t="o1-mini",gt="o1",fe=[F,J,Z,U,A,H,W,w,Te,Se,Pe,B,xe,"o1"],Ft=[F,J,Z,U,A,H,W,w];function K(n){return Ft.includes(n)}function ft(n){return n===w}function vt(n){return n===A||n===H||n===W||n===w}function Mt(n){return n===U||n===A||n===H||n===W}function Ot(n){return n===F||n===J||n===Z}function Et(n){return n!==w}function P(n){return n===U||n===A?"none":"medium"}var Ct="https://generativelanguage.googleapis.com",Ie="gemini-3.1-pro-preview",Re="gemini-3.1-flash-lite-preview",Le="gemini-3-pro-preview",be="gemini-3-flash-preview",De="gemini-2.5-pro",Ae="gemini-2.5-flash",we="gemini-2.5-flash-lite",Ne="gemini-2.5-flash-lite-preview-06-17",ke="gemini-2.0-flash",N="gemini-2.0-flash-lite",ve=[Ie,Re,Le,be,De,Ae,we,Ne,ke,N];var yt="https://api.anthropic.com/v1/messages",S="claude-3-haiku-20240307",Ge="claude-3-5-haiku-20241022",Ve="claude-3-5-sonnet-20241022",Fe="claude-3-7-sonnet-20250219",Ue="claude-4-sonnet-20250514",He="claude-4-opus-20250514",We="claude-sonnet-4-5-20250929",Be="claude-haiku-4-5-20251001",Ke="claude-opus-4-5-20251101",$e="claude-sonnet-4-6",je="claude-opus-4-6",Me=[S,Ge,Ve,Fe,Ue,He,We,Be,Ke,$e,je];var Oe="https://openrouter.ai/api/v1/chat/completions",k="openai/gpt-oss-20b:free",ze="moonshotai/kimi-k2.5",qe="openai/gpt-5.1-chat",Je="openai/gpt-5.1-codex",Ze="openai/gpt-5-mini",Xe="openai/gpt-5-nano",Ye="openai/gpt-4o",Qe="openai/gpt-4.1-mini",et="openai/gpt-4.1-nano",tt="anthropic/claude-opus-4",ot="anthropic/claude-sonnet-4",st="anthropic/claude-3.7-sonnet",Tt="anthropic/claude-3.5-sonnet",rt="anthropic/claude-haiku-4.5",nt="google/gemini-2.5-pro",it="google/gemini-2.5-flash",at="google/gemini-2.5-flash-lite-preview-09-2025",St="z-ai/glm-4.7-flash",Pt="z-ai/glm-4.5-air",lt="z-ai/glm-4.5-air:free",xt=[k,lt],Ut=[qe,Je,Ze,Xe,Ye,Qe,et,tt,ot,st,rt,nt,it,at,ze],It=20,no=50,io=1e3,ao=10;function $(n){return n.trim().endsWith(":free")}function X(n){return Ut.some(e=>n.includes(e))}var Ee="https://api.z.ai/api/paas/v4/chat/completions",Rt="glm-5",Lt="glm-5-turbo",Y="glm-4.7",bt="glm-4.7-FlashX",Dt="glm-4.7-Flash",At="glm-4.6",pt="glm-4.6V",ct="glm-4.6V-FlashX",j="glm-4.6V-Flash",Ht=[pt,ct,j];function Q(n){return Ht.includes(n)}function wt(n){return n.toLowerCase().startsWith("glm-4.6")}var ee="https://api.moonshot.ai/v1/chat/completions",x="kimi-k2.5",Wt=[x];function te(n){return Wt.includes(n)}var O={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Bt={[O.VERY_SHORT]:40,[O.SHORT]:100,[O.MEDIUM]:200,[O.LONG]:300,[O.VERY_LONG]:1e3,[O.DEEP]:5e3},Nt=5e3,kt={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 E(n){return n?Bt[n]??Nt:Nt}var lo="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",po=`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,8 +7,8 @@ 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 w=class extends Error{constructor(t,o,r){super(`HTTP ${t}: ${o}`);this.status=t;this.statusText=o;this.body=r;this.name="HttpError"}},Me=class Me{static setFetch(e){this.fetchImpl=e}static async post(e,t,o={},r={}){let{timeout:s=3e4,retries:n=0,retryDelay:a=1e3}=r,c={...{"Content-Type":"application/json"},...o},u=null;for(let h=0;h<=n;h++)try{let m=typeof AbortController<"u",p=m?new AbortController:void 0,_=m?setTimeout(()=>p.abort(),s):void 0,M=await Me.fetchImpl(e,{method:"POST",headers:c,body:typeof t=="string"?t:JSON.stringify(t),...p?{signal:p.signal}:{}});if(_&&clearTimeout(_),!M.ok){let d=await M.text();throw new w(M.status,M.statusText,d)}return M}catch(m){if(u=m,m instanceof w&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError")throw new Error(`Request timeout after ${s}ms`);h<n&&await new Promise(p=>setTimeout(p,a*(h+1)))}throw u||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new w(e.status,e.statusText,t)}static async get(e,t={},o={}){let{timeout:r=3e4,retries:s=0,retryDelay:n=1e3}=o,a=null;for(let l=0;l<=s;l++)try{let c=typeof AbortController<"u",u=c?new AbortController:void 0,h=c?setTimeout(()=>u.abort(),r):void 0,m=await Me.fetchImpl(e,{method:"GET",headers:t,...u?{signal:u.signal}:{}});if(h&&clearTimeout(h),!m.ok){let p=await m.text();throw new w(m.status,m.statusText,p)}return m}catch(c){if(a=c,c instanceof w&&c.status>=400&&c.status<500)throw c;if(c instanceof Error&&c.name==="AbortError")throw new Error(`Request timeout after ${r}ms`);l<s&&await new Promise(u=>setTimeout(u,n*(l+1)))}throw a||new Error("Request failed")}};Me.fetchImpl=(e,t)=>fetch(e,t);var g=Me;var f=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 lo=["happy","sad","angry","surprised","neutral"],Wt=/\[([a-z]+)\]/i,wt=/\[[a-z]+\]\s*/gi,ee=class{static extractEmotion(e){let t=e.match(Wt);if(t){let o=t[1].toLowerCase(),r=e.replace(wt,"").trim();return{emotion:o,cleanText:r}}return{cleanText:e}}static isValidEmotion(e){return lo.includes(e)}static cleanEmotionTags(e){return e.replace(wt,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function Bt(i){let{emotion:e,cleanText:t}=ee.extractEmotion(i);return e?{emotion:e,text:t}:{text:t}}function po(i){return i.map(e=>Bt(e))}function co(i){return i.emotion?ee.addEmotionTag(i.emotion,i.text):i.text}async function ho(i,e){let{blocks:t}=await i.chatOnce(e,!1,()=>{});return f.getFullText(t)}var Kt=(i,e)=>{try{return JSON.parse(i)}catch(t){if(e){e(i,t);return}throw t}},$t=async(i,e)=>{let t=i.body?.getReader();if(!t)throw new Error("Response body is null.");let o=new TextDecoder,r="",s=!1;for(;!s;){let{done:n,value:a}=await t.read();if(n)break;r+=o.decode(a,{stream:!0});let l=r.split(`
11
- `);r=l.pop()||"";for(let c of l){let u=c.trim();if(!u||u.startsWith(":")||!u.startsWith("data:"))continue;let h=u.slice(5).trim();if(h==="[DONE]"){s=!0;break}e(h)}}};async function P(i,e,t={}){let o="";return await $t(i,r=>{let s=Kt(r,t.onJsonError);if(!s)return;let n=s.choices?.[0]?.delta?.content||"";n&&(e(n),o+=n)}),o}async function x(i,e,t={}){let o=[],r=new Map,s=t.appendTextBlock??f.append;await $t(i,l=>{let c=Kt(l,t.onJsonError);if(!c)return;let u=c.choices?.[0]?.delta;u?.content&&(e(u.content),s(o,u.content)),u?.tool_calls&&u.tool_calls.forEach(h=>{let m=r.get(h.index)??{id:h.id,name:h.function?.name,args:""};m.args+=h.function?.arguments||"",r.set(h.index,m)})});let n=Array.from(r.entries()).sort((l,c)=>l[0]-c[0]).map(([l,c])=>({type:"tool_use",id:c.id,name:c.name,input:JSON.parse(c.args||"{}")}));return{blocks:[...o,...n],stop_reason:n.length?"tool_use":"end"}}function I(i){let e=i?.choices?.[0],t=[];return e?.message?.tool_calls?.length?e.message.tool_calls.forEach(o=>t.push({type:"tool_use",id:o.id,name:o.function?.name,input:JSON.parse(o.function?.arguments||"{}")})):e?.message?.content&&t.push({type:"text",text:e.message.content}),{blocks:t,stop_reason:e?.finish_reason==="tool_calls"||t.some(o=>o.type==="tool_use")?"tool_use":"end"}}var L=(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 v(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=f.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 uo="https://openrouter.ai/api/v1/models",mo=2,_o=12e3,go=1,fo=10;function Nt(i){return i instanceof Error?i.message:String(i)}function at(i,e){return typeof i!="number"||!Number.isFinite(i)?e:Math.max(1,Math.floor(i))}function vo(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 jt(i,e,t){if(!(typeof AbortController<"u"))return fetch(i,e);let r=new AbortController,s=setTimeout(()=>r.abort(),t);try{return await fetch(i,{...e,signal:r.signal})}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Timeout after ${t}ms`):n}finally{clearTimeout(s)}}async function zt(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 Mo(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 vo(o)}async function Oo({modelId:i,apiKey:e,endpoint:t,timeoutMs:o,appName:r,appUrl:s}){let n={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};r&&(n["X-Title"]=r),s&&(n["HTTP-Referer"]=s);try{let a=await jt(t,{method:"POST",headers:n,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 zt(a)};try{await a.json()}catch(l){return{id:i,ok:!1,reason:`JSON parse failed: ${Nt(l)}`}}return{id:i,ok:!0}}catch(a){return{id:i,ok:!1,reason:Nt(a)}}}async function Eo(i,e,t){if(i.length===0)return[];let o=new Array(i.length),r=0,s=Math.min(e,i.length);return await Promise.all(Array.from({length:s},async()=>{for(;r<i.length;){let n=r;r+=1,o[n]=await t(i[n])}})),o}async function Co(i){let e=i.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=i.modelsEndpoint||uo,o=i.endpoint||fe,r=at(i.timeoutMs,_o),s=at(i.concurrency,mo),n=at(i.maxCandidates,go),a=at(i.maxWorking,fo),l=await jt(t,{method:"GET"},r);if(!l.ok)throw new Error(await zt(l));let c;try{c=await l.json()}catch(_){throw new Error(`JSON parse failed: ${Nt(_)}`)}let u=Mo(c).filter(_=>U(_)).slice(0,n),h=await Eo(u,s,_=>Oo({modelId:_,apiKey:e,endpoint:o,timeoutMs:r,appName:i.appName,appUrl:i.appUrl})),m=h.filter(_=>_.ok).map(_=>_.id).slice(0,a),p=h.filter(_=>!_.ok).map(_=>({id:_.id,reason:_.reason||"Unknown error"}));return{working:m,failed:p,fetchedAt:Date.now()}}var te=class{constructor(e,t=T,o=T,r=[],s=[],n){this.provider="claude";if(this.apiKey=e,this.model=t||T,this.visionModel=o||T,this.tools=r,this.mcpServers=s,this.responseLength=n,!ge.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 v({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 v({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."})}convertMessagesToClaudeFormat(e){return e.map(t=>({role:this.mapRoleToClaude(t.role),content:t.content}))}convertVisionMessagesToClaudeFormat(e){return e.map(t=>{if(typeof t.content=="string")return{role:this.mapRoleToClaude(t.role),content:[{type:"text",text:t.content}]};if(Array.isArray(t.content)){let o=t.content.map(r=>{if(r.type==="image_url"){if(r.image_url.url.startsWith("data:")){let s=r.image_url.url.match(/^data:([^;]+);base64,(.+)$/);return s?{type:"image",source:{type:"base64",media_type:s[1],data:s[2]}}:null}return{type:"image",source:{type:"url",url:r.image_url.url,media_type:this.getMimeTypeFromUrl(r.image_url.url)}}}return r}).filter(r=>r);return{role:this.mapRoleToClaude(t.role),content:o}}return{role:this.mapRoleToClaude(t.role),content:[]}})}mapRoleToClaude(e){switch(e){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}getMimeTypeFromUrl(e){switch(e.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"}}async callClaude(e,t,o,r){let s=e.find(h=>h.role==="system")?.content??"",n=e.filter(h=>h.role!=="system"),a=n.some(h=>Array.isArray(h.content)&&h.content.some(m=>m.type==="image_url"||m.type==="image")),l={model:t,system:s,messages:a?this.convertVisionMessagesToClaudeFormat(n):this.convertMessagesToClaudeFormat(n),stream:o,max_tokens:r!==void 0?r:O(this.responseLength)};this.tools.length&&(l.tools=this.tools.map(h=>({name:h.name,description:h.description,input_schema:h.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 g.post(Ot,l,c)}async parseStream(e,t){let o=e.body.getReader(),r=new TextDecoder,s=[],n=new Map,a="";for(;;){let{done:l,value:c}=await o.read();if(l)break;a+=r.decode(c,{stream:!0});let u;for(;(u=a.indexOf(`
12
- `))!==-1;){let h=a.slice(0,u).trim();if(a=a.slice(u+1),!h.startsWith("data:"))continue;let m=h.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),s.push({type:"text",text:p.delta.text})),p.type==="content_block_start"&&p.content_block?.type==="tool_use"?n.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"?n.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"?s.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"&&s.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 _=n.get(p.index);_&&(_.args+=p.delta.partial_json||"")}if(p.type==="content_block_stop"&&n.has(p.index)){let{id:_,name:M,args:d,server_name:C}=n.get(p.index);C?s.push({type:"mcp_tool_use",id:_,name:M,server_name:C,input:JSON.parse(d||"{}")}):s.push({type:"tool_use",id:_,name:M,input:JSON.parse(d||"{}")}),n.delete(p.index)}}}return{blocks:s,stop_reason:s.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 s=await this.callClaude(e,this.model,t,r),n=t?await this.parseStream(s,o):this.parseOneShot(await s.json());return this.convertToStandardCompletion(n)}async visionChatOnce(e,t=!1,o=()=>{},r){let s=await this.callClaude(e,this.visionModel,t,r),n=t?await this.parseStream(s,o):this.parseOneShot(await s.json());return this.convertToStandardCompletion(n)}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 oe=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 te(e.apiKey,e.model||this.getDefaultModel(),t,e.tools??[],e.mcpServers??[],e.responseLength)}getProviderName(){return"claude"}getSupportedModels(){return[T,Ae,we,Ne,ke,Ve,Ge,Fe,Ue,He,We]}getDefaultModel(){return T}supportsVision(){return!0}supportsVisionForModel(e){return ge.includes(e)}};var lt=class{static async fetchToolSchemas(e){try{let t={"Content-Type":"application/json"};e.authorization_token&&(t.Authorization=`Bearer ${e.authorization_token}`);let r=await(await g.post(`${e.url}/tools`,{},t)).json();return Array.isArray(r.tools)?r.tools.map(s=>({name:`mcp_${e.name}_${s.name}`,description:s.description||`Tool from ${e.name} MCP server`,parameters:s.inputSchema||{type:"object",properties:{},required:[]}})):[{name:`mcp_${e.name}_search`,description:`Search using ${e.name} MCP server`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}]}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),[{name:`mcp_${e.name}_search`,description:`Search using ${e.name} MCP server (schema fetch failed)`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}]}}static async fetchAllToolSchemas(e){let t=[];for(let o of e)try{let r=await this.fetchToolSchemas(o);t.push(...r)}catch(r){console.error(`Failed to fetch schemas from ${o.name}:`,r)}return t}};var re=class{constructor(e,t=D,o=D,r=[],s=[],n){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=n,!_e.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=r,this.mcpServers=s}safeJsonParse(e){try{return JSON.parse(e)}catch{return e}}normalizeToolResult(e){return e===null?{content:null}:typeof e=="object"?e:{content:e}}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}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e),this.mcpSchemasInitialized=!1}hasMCPServers(){return this.mcpServers.length>0}async initializeMCPSchemas(){if(!(this.mcpSchemasInitialized||this.mcpServers.length===0))try{let e=new Promise((o,r)=>setTimeout(()=>r(new Error("MCP schema fetch timeout")),5e3)),t=lt.fetchAllToolSchemas(this.mcpServers);this.mcpToolSchemas=await Promise.race([t,e]),this.mcpSchemasInitialized=!0}catch(e){console.warn("Failed to initialize MCP schemas, using fallback:",e),this.mcpToolSchemas=this.mcpServers.map(t=>({name:`mcp_${t.name}_search`,description:`Search using ${t.name} MCP server (fallback)`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}})),this.mcpSchemasInitialized=!0}}async processChat(e,t,o){try{await v({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callGemini(e,this.model,!0),{blocks:s}=await this.parseStream(r,t);return f.getFullText(s)},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 v({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callGemini(e,this.visionModel,!0),{blocks:s}=await this.parseStream(r,t);return f.getFullText(s)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:r=>{r.filter(s=>s.type==="text").forEach(s=>t(s.text))},onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use visionChatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processVisionChat:",r),r}}convertMessagesToGeminiFormat(e){let t=[],o=null,r=[],s=()=>{o&&r.length&&(t.push({role:o,parts:[...r]}),r=[])};for(let n of e){let a=this.mapRoleToGemini(n.role);if(n.tool_calls){s();for(let l of n.tool_calls)this.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(n.role==="tool"){s();let l=n.name??this.callIdMap.get(n.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:l,response:this.normalizeToolResult(this.safeJsonParse(n.content))}}]});continue}a!==o&&s(),o=a,r.push({text:n.content})}return s(),t}async callGemini(e,t,o=!1,r){let a={contents:e.some(d=>Array.isArray(d.content)&&d.content.some(C=>C?.type==="image_url"||C?.inlineData))?await this.convertVisionMessagesToGeminiFormat(e):this.convertMessagesToGeminiFormat(e),generationConfig:{maxOutputTokens:r!==void 0?r:O(this.responseLength)}},l=[];if(this.tools.length>0&&l.push(...this.tools.map(d=>({name:d.name,description:d.description,parameters:d.parameters}))),this.mcpServers.length>0)try{await this.initializeMCPSchemas(),l.push(...this.mcpToolSchemas.map(d=>({name:d.name,description:d.description,parameters:d.parameters})))}catch(d){console.warn("MCP initialization failed, skipping MCP tools:",d)}l.length>0&&(a.tools=[{functionDeclarations:l}],a.toolConfig={functionCallingConfig:{mode:"AUTO"}});let c=async(d,C)=>{let pt=o?"streamGenerateContent":"generateContent",kt=o?"?alt=sse":"",Zt=`${Mt}/${d}/models/${t}:${pt}${kt}${kt?"&":"?"}key=${this.apiKey}`;return g.post(Zt,C)},u=/flash[-_]lite/.test(t),h=/gemini-2\.5/.test(t),m=/^gemini-3(?:\.[0-9]+)?-.*preview/.test(t),p=u||h||m,_=p?"v1beta":"v1",M=async()=>{try{let d=_==="v1"?a:this.adaptKeysForApi(a);return await c(_,d)}catch(d){let C=/Unknown name|Cannot find field|404/.test(d?.message||"")||d?.status===404;if(!p&&C)return await c("v1beta",this.adaptKeysForApi(a));throw d}};try{return await M()}catch(d){throw d.body&&(console.error("Gemini API Error Details:",d.body),console.error("Request Body:",JSON.stringify(a,null,2))),d}}async convertVisionMessagesToGeminiFormat(e){let t=[],o=null,r=[];for(let s of e){let n=this.mapRoleToGemini(s.role);if(s.tool_calls){for(let a of s.tool_calls)t.push({role:"model",parts:[{functionCall:{name:a.function.name,args:JSON.parse(a.function.arguments||"{}")}}]});continue}if(s.role==="tool"){let a=s.name??this.callIdMap.get(s.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:a,response:this.normalizeToolResult(this.safeJsonParse(s.content))}}]});continue}if(n!==o&&r.length>0&&(t.push({role:o,parts:[...r]}),r=[]),o=n,typeof s.content=="string")r.push({text:s.content});else if(Array.isArray(s.content)){for(let a of s.content)if(a.type==="text")r.push({text:a.text});else if(a.type==="image_url")try{let c=await(await g.get(a.image_url.url)).blob(),u=await this.blobToBase64(c);r.push({inlineData:{mimeType:c.type||"image/jpeg",data:u.split(",")[1]}})}catch(l){throw console.error("Error processing image:",l),new Error(`Failed to process image: ${l.message}`)}}}return o&&r.length>0&&t.push({role:o,parts:[...r]}),t}blobToBase64(e){return new Promise((t,o)=>{let r=new FileReader;r.onloadend=()=>t(r.result),r.onerror=o,r.readAsDataURL(e)})}mapRoleToGemini(e){switch(e){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}async parseStream(e,t){let o=e.body.getReader(),r=new TextDecoder,s=[],n=[],a="",l=u=>{if(!u||u==="[DONE]")return;let h;try{h=JSON.parse(u)}catch{return}for(let m of h.candidates??[])for(let p of m.content?.parts??[])p.text&&(t(p.text),f.addTextBlock(s,p.text)),p.functionCall&&n.push({type:"tool_use",id:this.genUUID(),name:p.functionCall.name,input:p.functionCall.args??{}}),p.functionResponse&&n.push({type:"tool_result",tool_use_id:p.functionResponse.name,content:JSON.stringify(p.functionResponse.response)})};for(;;){let{done:u,value:h}=await o.read();if(u)break;a+=r.decode(h,{stream:!0});let m;for(;(m=a.indexOf(`
13
- `))!==-1;){let p=a.slice(0,m);if(a=a.slice(m+1),p.endsWith("\r")&&(p=p.slice(0,-1)),!p.trim()){l("");continue}p.startsWith("data:")&&(p=p.slice(5).trim()),p&&l(p)}}return a&&l(a),{blocks:[...s,...n],stop_reason:n.some(u=>u.type==="tool_use")?"tool_use":"end"}}parseOneShot(e){let t=[],o=[];for(let s of e.candidates??[])for(let n of s.content?.parts??[])n.text&&t.push({type:"text",text:n.text}),n.functionCall&&o.push({type:"tool_use",id:this.genUUID(),name:n.functionCall.name,input:n.functionCall.args??{}}),n.functionResponse&&o.push({type:"tool_result",tool_use_id:n.functionResponse.name,content:JSON.stringify(n.functionResponse.response)});return{blocks:[...t,...o],stop_reason:o.some(s=>s.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},r){let s=await this.callGemini(e,this.model,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}async visionChatOnce(e,t=!1,o=()=>{},r){let s=await this.callGemini(e,this.visionModel,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}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 se=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 re(e.apiKey,e.model||this.getDefaultModel(),t,e.tools||[],e.mcpServers||[],e.responseLength)}getProviderName(){return"gemini"}getSupportedModels(){return[Te,Se,Pe,xe,Ie,Le,be,Re,De,D]}getDefaultModel(){return D}supportsVision(){return!0}supportsVisionForModel(e){return _e.includes(e)}};var ie=class{constructor(e,t=S,o=S,r,s=Y,n,a,l){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=s,this.responseLength=n,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 v({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(!Q(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await v({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 s=await this.callKimi(e,this.model,t,r);return this.parseResponse(s,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!Q(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let s=await this.callKimi(e,this.visionModel,t,r);return this.parseResponse(s,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 s=this.buildRequestBody(e,t,o,r);return await g.post(this.endpoint,s,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let s={model:t,stream:o,messages:e},n=r!==void 0?r:O(this.responseLength);n!==void 0&&(s.max_tokens=n),this.responseFormat&&(s.response_format=this.responseFormat);let a=this.tools.length>0?{type:"disabled"}:this.thinking;a&&(this.isSelfHostedEndpoint()?a.type==="disabled"&&(s.chat_template_kwargs={thinking:!1}):s.thinking=a);let l=this.buildToolsDefinition();return l.length>0&&(s.tools=l,s.tool_choice="auto"),s}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(Y)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}buildToolsDefinition(){return L(this.tools,"chat-completions")}async handleStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var ne=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"}),s=e.tools,n=e.thinking??{type:"enabled"},a=s&&s.length>0?{type:"disabled"}:n;return new ie(e.apiKey,o,r,s,t,e.responseLength,e.responseFormat,a)}getProviderName(){return"kimi"}getSupportedModels(){return[S]}getDefaultModel(){return S}getDefaultVisionModel(){return S}supportsVision(){return!0}supportsVisionForModel(e){return Q(e)}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 Y}normalizeEndpoint(e){return e.replace(/\/+$/,"")}};var N=class{constructor(e,t=G,o=G,r,s=B,n=[],a,l,c,u=!1,h="openai",m=!0){if(this.provider=h,this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=s,this.mcpServers=n,this.responseLength=a,this.verbosity=l,this.reasoning_effort=c,this.enableReasoningSummary=u,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 v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenAI(e,this.model,!0),s=this.endpoint===y;try{if(s){let n=await this.parseResponsesStream(r,t);return f.getFullText(n.blocks)}return this.handleStream(r,t)}catch(n){throw console.error("[processChat] Error in streaming/completion:",n),n}},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 v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenAI(e,this.visionModel,!0),s=this.endpoint===y;try{if(s){let n=await this.parseResponsesStream(r,t);return f.getFullText(n.blocks)}return this.handleStream(r,t)}catch(n){throw console.error("[processVisionChat] Error in streaming/completion:",n),n}},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 s=await this.callOpenAI(e,this.model,t,r);return this.parseResponse(s,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){let s=await this.callOpenAI(e,this.visionModel,t,r);return this.parseResponse(s,t,o)}async parseResponse(e,t,o){return this.endpoint===y?t?this.parseResponsesStream(e,o):this.parseResponsesOneShot(await e.json()):t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callOpenAI(e,t,o=!1,r){let s=this.buildRequestBody(e,t,o,r),n={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(n.Authorization=`Bearer ${this.apiKey}`),await g.post(this.endpoint,s,n)}buildRequestBody(e,t,o,r){let s=this.endpoint===y;this.validateMCPCompatibility();let n={model:t,stream:o},a=r!==void 0?r:this.provider==="openai-compatible"?this.responseLength!==void 0?O(this.responseLength):void 0:O(this.responseLength);s?a!==void 0&&(n.max_output_tokens=a):a!==void 0&&(this.provider==="openai-compatible"?n.max_tokens=a:n.max_completion_tokens=a),s?n.input=this.cleanMessagesForResponsesAPI(e):n.messages=e,q(t)&&(s?(this.reasoning_effort&&(n.reasoning={...n.reasoning,effort:this.reasoning_effort},this.enableReasoningSummary&&(n.reasoning.summary="auto")),this.verbosity&&(n.text={...n.text,format:{type:"text"},verbosity:this.verbosity})):(this.reasoning_effort&&(n.reasoning_effort=this.reasoning_effort),this.verbosity&&(n.verbosity=this.verbosity)));let l=this.buildToolsDefinition();return l.length>0&&(n.tools=l,s||(n.tool_choice="auto")),n}validateMCPCompatibility(){if(this.mcpServers.length>0&&this.endpoint===B)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${this.endpoint}. Please use OpenAI Responses API endpoint: ${y}. MCP tools are only available in the Responses API endpoint.`)}cleanMessagesForResponsesAPI(e){return e.map(t=>{let r={role:t.role==="tool"?"user":t.role};return typeof t.content=="string"?r.content=t.content:Array.isArray(t.content)?r.content=t.content.map(s=>s.type==="text"?{type:"input_text",text:s.text}:s.type==="image_url"?{type:"input_image",image_url:s.image_url.url}:s):r.content=t.content,r})}buildToolsDefinition(){let e=this.endpoint===y,t=[];return this.tools.length>0&&t.push(...L(this.tools,e?"responses":"chat-completions")),this.mcpServers.length>0&&e&&t.push(...this.buildMCPToolsDefinition()),t}buildMCPToolsDefinition(){return this.mcpServers.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})}async handleStream(e,t){return P(e,t)}async parseStream(e,t){return x(e,t,{appendTextBlock:f.addTextBlock})}parseOneShot(e){return I(e)}async parseResponsesStream(e,t){let o=e.body.getReader(),r=new TextDecoder,s=[],n=new Map,a="";for(;;){let{done:u,value:h}=await o.read();if(u)break;a+=r.decode(h,{stream:!0});let m="",p="",_=a.split(`
14
- `);a=_.pop()||"";for(let M=0;M<_.length;M++){let d=_[M].trim();if(d.startsWith("event:"))m=d.slice(6).trim();else if(d.startsWith("data:"))p=d.slice(5).trim();else if(d===""&&m&&p){try{let C=JSON.parse(p),pt=this.handleResponsesSSEEvent(m,C,t,s,n)}catch{console.warn("Failed to parse SSE data:",p)}m="",p=""}}}let l=Array.from(n.values()).map(u=>({type:"tool_use",id:u.id,name:u.name,input:u.input||{}}));return{blocks:[...s,...l],stop_reason:l.length?"tool_use":"end"}}handleResponsesSSEEvent(e,t,o,r,s){switch(e){case"response.output_item.added":t.item?.type==="message"&&Array.isArray(t.item.content)?t.item.content.forEach(n=>{n.type==="output_text"&&n.text&&(o(n.text),f.append(r,n.text))}):t.item?.type==="function_call"&&s.set(t.item.id,{id:t.item.id,name:t.item.name,input:t.item.arguments?JSON.parse(t.item.arguments):{}});break;case"response.content_part.added":t.part?.type==="output_text"&&typeof t.part.text=="string"&&(o(t.part.text),f.append(r,t.part.text));break;case"response.output_text.delta":case"response.content_part.delta":{let n=typeof t.delta=="string"?t.delta:t.delta?.text??"";n&&(o(n),f.append(r,n))}break;case"response.output_text.done":case"response.content_part.done":break;case"response.completed":return"completed";case"response.reasoning.started":case"response.reasoning.delta":case"response.reasoning.done":break;default:break}}parseResponsesOneShot(e){let t=[];return e.output&&Array.isArray(e.output)&&e.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:o.arguments?JSON.parse(o.arguments):{}})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use")?"tool_use":"end"}}};var ae=class{createChatService(e){return this.validateRequiredOptions(e),new N(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!1}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 le=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,s=t.mcpServers??[],n=t.model||this.getDefaultModel(),a=!1;s.length>0||dt(n)?a=!0:q(n)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let l=t.endpoint||(a?y:B);return new N(t.apiKey,n,o,r,l,s,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName())}getProviderName(){return"openai"}getSupportedModels(){return[k,K,$,V,b,j,z,R,Oe,Ee,Ce,G,ye,ht,ut,"o1"]}getDefaultModel(){return k}supportsVision(){return!0}supportsVisionForModel(e){return de.includes(e)}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!q(t))return e;let o={...e};if(e.gpt5Preset){let r=At[e.gpt5Preset];o.reasoning_effort=r.reasoning_effort,o.verbosity=r.verbosity}else e.reasoning_effort||(o.reasoning_effort=F(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!gt(e)?F(e):t==="minimal"&&!ft(e)?F(e):t==="low"&&!vt(e)?F(e):t==="xhigh"&&!_t(e)?F(e):t}};var pe=class{constructor(e,t=A,o=A,r,s=fe,n,a,l,c,u,h){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=s,this.responseLength=n,this.appName=a,this.appUrl=l,this.reasoning_effort=c,this.includeReasoning=u,this.reasoningMaxTokens=h,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!U(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=St){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 v({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(!J(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await v({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 s=await this.callOpenRouter(e,this.model,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}async visionChatOnce(e,t=!1,o=()=>{},r){if(!J(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let s=await this.callOpenRouter(e,this.visionModel,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}async callOpenRouter(e,t,o=!1,r){let s=this.buildRequestBody(e,t,o,r),n={Authorization:`Bearer ${this.apiKey}`};return this.appUrl&&(n["HTTP-Referer"]=this.appUrl),this.appName&&(n["X-Title"]=this.appName),await g.post(this.endpoint,s,n)}buildRequestBody(e,t,o,r){let s={model:t,messages:e,stream:o};if((r!==void 0?r:O(this.responseLength))&&console.warn("OpenRouter: Token limits are not supported for gpt-oss-20b model due to known issues. Using unlimited tokens instead."),this.reasoning_effort!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens){if(s.reasoning={},this.reasoning_effort&&this.reasoning_effort!=="none"){let a=this.reasoning_effort==="minimal"?"low":this.reasoning_effort;s.reasoning.effort=a}(this.reasoning_effort==="none"||this.includeReasoning!==!0)&&(s.reasoning.exclude=!0),this.reasoningMaxTokens&&(s.reasoning.max_tokens=this.reasoningMaxTokens)}else s.reasoning={exclude:!0};return this.tools.length>0&&(s.tools=L(this.tools,"chat-completions"),s.tool_choice="auto"),s}async handleStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var ce=class{createChatService(e){let t=E({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:e.model||this.getDefaultModel(),supportsVisionForModel:n=>this.supportsVisionForModel(n),validate:"explicit"}),o=e.tools,r=e.appName,s=e.appUrl;return new pe(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,r,s,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[A,st,Ke,$e,je,ze,qe,Je,Ze,Xe,Ye,Qe,Et,et,tt,ot,rt,Ct,yt,Be]}getDefaultModel(){return A}supportsVision(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))}supportsVisionForModel(e){return J(e)}getFreeModels(){return Tt}isModelFree(e){return U(e)}};var he=class{constructor(e,t=Z,o=H,r,s=ve,n,a,l){this.provider="zai";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=s,this.responseLength=n,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 v({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(!X(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await v({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 s=await this.callZAI(e,this.model,t,r);return this.parseResponse(s,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!X(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let s=await this.callZAI(e,this.visionModel,t,r);return this.parseResponse(s,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 s=this.buildRequestBody(e,t,o,r);return await g.post(this.endpoint,s,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let s={model:t,stream:o,messages:e},n=r!==void 0?r:O(this.responseLength);n!==void 0&&(s.max_tokens=n),this.responseFormat&&(s.response_format=this.responseFormat),this.thinking&&(s.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(s.tools=a,s.tool_choice="auto",o&&Rt(t)&&(s.tool_stream=!0)),s}buildToolsDefinition(){return L(this.tools,"chat-completions")}async handleStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var ue=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,s=e.thinking??{type:"disabled"};return new he(e.apiKey,t,o,r,e.endpoint||ve,e.responseLength,e.responseFormat,s)}getProviderName(){return"zai"}getSupportedModels(){return[Pt,xt,Z,It,Lt,bt,it,nt,H]}getDefaultModel(){return Z}getDefaultVisionModel(){return H}supportsVision(){return!0}supportsVisionForModel(e){return X(e)}};var qt=[new le,new ae,new se,new oe,new ce,new ue,new ne];var me=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():[]}};me.providers=new Map;qt.forEach(i=>me.registerProvider(i));function Jt(){g.setFetch(async(i,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,r={};if(Array.isArray(o))for(let[h,m]of o)r[h]=String(m);else if(o&&typeof o=="object")for(let[h,m]of Object.entries(o))r[h]=String(m);let s={method:t,headers:r,muteHttpExceptions:!0},n=e.body;typeof n=="string"?s.payload=n:n!=null&&(r["Content-Type"]||(r["Content-Type"]="application/json"),s.payload=JSON.stringify(n));let a=UrlFetchApp.fetch(i,s),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 oo(yo);})();
10
+ `;var G=class extends Error{constructor(t,o,s){super(`HTTP ${t}: ${o}`);this.status=t;this.statusText=o;this.body=s;this.name="HttpError"}},Ce=class Ce{static setFetch(e){this.fetchImpl=e}static async post(e,t,o={},s={}){let{timeout:r=3e4,retries:i=0,retryDelay:a=1e3}=s,u={...{"Content-Type":"application/json"},...o},h=null;for(let c=0;c<=i;c++)try{let m=typeof AbortController<"u",l=m?new AbortController:void 0,_=m?setTimeout(()=>l.abort(),r):void 0,M=await Ce.fetchImpl(e,{method:"POST",headers:u,body:typeof t=="string"?t:JSON.stringify(t),...l?{signal:l.signal}:{}});if(_&&clearTimeout(_),!M.ok){let d=await M.text();throw new G(M.status,M.statusText,d)}return M}catch(m){if(h=m,m instanceof G&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError")throw new Error(`Request timeout after ${r}ms`);c<i&&await new Promise(l=>setTimeout(l,a*(c+1)))}throw h||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new G(e.status,e.statusText,t)}static async get(e,t={},o={}){let{timeout:s=3e4,retries:r=0,retryDelay:i=1e3}=o,a=null;for(let p=0;p<=r;p++)try{let u=typeof AbortController<"u",h=u?new AbortController:void 0,c=u?setTimeout(()=>h.abort(),s):void 0,m=await Ce.fetchImpl(e,{method:"GET",headers:t,...h?{signal:h.signal}:{}});if(c&&clearTimeout(c),!m.ok){let l=await m.text();throw new G(m.status,m.statusText,l)}return m}catch(u){if(a=u,u instanceof G&&u.status>=400&&u.status<500)throw u;if(u instanceof Error&&u.name==="AbortError")throw new Error(`Request timeout after ${s}ms`);p<r&&await new Promise(h=>setTimeout(h,i*(p+1)))}throw a||new Error("Request failed")}};Ce.fetchImpl=(e,t)=>fetch(e,t);var g=Ce;var f=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 co=["happy","sad","angry","surprised","neutral"],Kt=/\[([a-z]+)\]/i,Gt=/\[[a-z]+\]\s*/gi,oe=class{static extractEmotion(e){let t=e.match(Kt);if(t){let o=t[1].toLowerCase(),s=e.replace(Gt,"").trim();return{emotion:o,cleanText:s}}return{cleanText:e}}static isValidEmotion(e){return co.includes(e)}static cleanEmotionTags(e){return e.replace(Gt,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function $t(n){let{emotion:e,cleanText:t}=oe.extractEmotion(n);return e?{emotion:e,text:t}:{text:t}}function ho(n){return n.map(e=>$t(e))}function uo(n){return n.emotion?oe.addEmotionTag(n.emotion,n.text):n.text}async function mo(n,e){let{blocks:t}=await n.chatOnce(e,!1,()=>{});return f.getFullText(t)}var jt=(n,e)=>{try{return JSON.parse(n)}catch(t){if(e){e(n,t);return}throw t}},zt=async(n,e)=>{let t=n.body?.getReader();if(!t)throw new Error("Response body is null.");let o=new TextDecoder,s="",r=!1;for(;!r;){let{done:i,value:a}=await t.read();if(i)break;s+=o.decode(a,{stream:!0});let p=s.split(`
11
+ `);s=p.pop()||"";for(let u of p){let h=u.trim();if(!h||h.startsWith(":")||!h.startsWith("data:"))continue;let c=h.slice(5).trim();if(c==="[DONE]"){r=!0;break}e(c)}}};async function I(n,e,t={}){let o="";return await zt(n,s=>{let r=jt(s,t.onJsonError);if(!r)return;let i=r.choices?.[0]?.delta?.content||"";i&&(e(i),o+=i)}),o}async function R(n,e,t={}){let o=[],s=new Map,r,i,a=t.appendTextBlock??f.append;await zt(n,h=>{let c=jt(h,t.onJsonError);if(!c)return;let m=c.choices?.[0];typeof m?.finish_reason=="string"&&(r=m.finish_reason),c.usage&&(i=c.usage);let l=m?.delta;l?.content&&(e(l.content),a(o,l.content)),l?.tool_calls&&l.tool_calls.forEach(_=>{let M=s.get(_.index)??{id:_.id,name:_.function?.name,args:""};M.args+=_.function?.arguments||"",s.set(_.index,M)})});let p=Array.from(s.entries()).sort((h,c)=>h[0]-c[0]).map(([h,c])=>({type:"tool_use",id:c.id,name:c.name,input:JSON.parse(c.args||"{}")}));return{blocks:[...o,...p],stop_reason:p.length?"tool_use":"end",truncated:r==="length",finish_reason:r,usage:i}}function L(n){let e=n?.choices?.[0],t=[];return e?.message?.tool_calls?.length?e.message.tool_calls.forEach(o=>t.push({type:"tool_use",id:o.id,name:o.function?.name,input:JSON.parse(o.function?.arguments||"{}")})):e?.message?.content&&t.push({type:"text",text:e.message.content}),{blocks:t,stop_reason:e?.finish_reason==="tool_calls"||t.some(o=>o.type==="tool_use")?"tool_use":"end",truncated:e?.finish_reason==="length",finish_reason:e?.finish_reason,usage:n?.usage}}var b=(n,e="chat-completions")=>n.length===0?[]:e==="responses"?n.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):n.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function v(n){if(!n.hasTools){let t=await n.runWithoutTools();await n.onCompleteResponse(t);return}let e=await n.runWithTools();if(n.onToolBlocks&&n.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=f.getFullText(e.blocks);await n.onCompleteResponse(t);return}throw new Error(n.toolErrorMessage)}var y=n=>{let e=n.model??n.defaultModel,t=n.visionModel??(n.supportsVisionForModel(e)?e:n.defaultVisionModel);if(n.validate==="explicit"&&n.visionModel&&!n.supportsVisionForModel(n.visionModel))throw new Error(`Model ${n.visionModel} does not support vision capabilities.`);if(n.validate==="resolved"&&!n.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var _o="https://openrouter.ai/api/v1/models",go=2,fo=12e3,vo=1,Mo=10;function Vt(n){return n instanceof Error?n.message:String(n)}function ht(n,e){return typeof n!="number"||!Number.isFinite(n)?e:Math.max(1,Math.floor(n))}function Oo(n){let e=new Set,t=[];for(let o of n){let s=o.trim();!s||e.has(s)||(e.add(s),t.push(s))}return t}async function qt(n,e,t){if(!(typeof AbortController<"u"))return fetch(n,e);let s=new AbortController,r=setTimeout(()=>s.abort(),t);try{return await fetch(n,{...e,signal:s.signal})}catch(i){throw i instanceof Error&&i.name==="AbortError"?new Error(`Timeout after ${t}ms`):i}finally{clearTimeout(r)}}async function Jt(n){let e=`HTTP ${n.status} ${n.statusText}`.trim(),t="";try{t=await n.text()}catch{return e}let o=t.replace(/\s+/g," ").trim().slice(0,200);return o?`${e}: ${o}`:e}function Eo(n){if(!n||typeof n!="object")throw new Error("Invalid models response shape");let e=n,t=Array.isArray(e.data)?e.data:Array.isArray(e.models)?e.models:[];if(t.length===0)return[];let o=t.map(s=>s.id).filter(s=>typeof s=="string");return Oo(o)}async function Co({modelId:n,apiKey:e,endpoint:t,timeoutMs:o,appName:s,appUrl:r}){let i={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};s&&(i["X-Title"]=s),r&&(i["HTTP-Referer"]=r);try{let a=await qt(t,{method:"POST",headers:i,body:JSON.stringify({model:n,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},o);if(!a.ok)return{id:n,ok:!1,reason:await Jt(a)};try{await a.json()}catch(p){return{id:n,ok:!1,reason:`JSON parse failed: ${Vt(p)}`}}return{id:n,ok:!0}}catch(a){return{id:n,ok:!1,reason:Vt(a)}}}async function yo(n,e,t){if(n.length===0)return[];let o=new Array(n.length),s=0,r=Math.min(e,n.length);return await Promise.all(Array.from({length:r},async()=>{for(;s<n.length;){let i=s;s+=1,o[i]=await t(n[i])}})),o}async function To(n){let e=n.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=n.modelsEndpoint||_o,o=n.endpoint||Oe,s=ht(n.timeoutMs,fo),r=ht(n.concurrency,go),i=ht(n.maxCandidates,vo),a=ht(n.maxWorking,Mo),p=await qt(t,{method:"GET"},s);if(!p.ok)throw new Error(await Jt(p));let u;try{u=await p.json()}catch(_){throw new Error(`JSON parse failed: ${Vt(_)}`)}let h=Eo(u).filter(_=>$(_)).slice(0,i),c=await yo(h,r,_=>Co({modelId:_,apiKey:e,endpoint:o,timeoutMs:s,appName:n.appName,appUrl:n.appUrl})),m=c.filter(_=>_.ok).map(_=>_.id).slice(0,a),l=c.filter(_=>!_.ok).map(_=>({id:_.id,reason:_.reason||"Unknown error"}));return{working:m,failed:l,fetchedAt:Date.now()}}var se=class{constructor(e,t=S,o=S,s=[],r=[],i){this.provider="claude";if(this.apiKey=e,this.model=t||S,this.visionModel=o||S,this.tools=s,this.mcpServers=r,this.responseLength=i,!Me.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 v({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callClaude(e,this.model,!0);return this.parsePureStream(s,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 v({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callClaude(e,this.visionModel,!0);return this.parsePureStream(s,t)},runWithTools:()=>this.visionChatOnce(e),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}convertMessagesToClaudeFormat(e){return e.map(t=>({role:this.mapRoleToClaude(t.role),content:t.content}))}convertVisionMessagesToClaudeFormat(e){return e.map(t=>{if(typeof t.content=="string")return{role:this.mapRoleToClaude(t.role),content:[{type:"text",text:t.content}]};if(Array.isArray(t.content)){let o=t.content.map(s=>{if(s.type==="image_url"){if(s.image_url.url.startsWith("data:")){let r=s.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:s.image_url.url,media_type:this.getMimeTypeFromUrl(s.image_url.url)}}}return s}).filter(s=>s);return{role:this.mapRoleToClaude(t.role),content:o}}return{role:this.mapRoleToClaude(t.role),content:[]}})}mapRoleToClaude(e){switch(e){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}getMimeTypeFromUrl(e){switch(e.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"}}async callClaude(e,t,o,s){let r=e.find(c=>c.role==="system")?.content??"",i=e.filter(c=>c.role!=="system"),a=i.some(c=>Array.isArray(c.content)&&c.content.some(m=>m.type==="image_url"||m.type==="image")),p={model:t,system:r,messages:a?this.convertVisionMessagesToClaudeFormat(i):this.convertMessagesToClaudeFormat(i),stream:o,max_tokens:s!==void 0?s:E(this.responseLength)};this.tools.length&&(p.tools=this.tools.map(c=>({name:c.name,description:c.description,input_schema:c.parameters})),p.tool_choice={type:"auto"}),this.mcpServers.length>0&&(p.mcp_servers=this.mcpServers);let u={"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&&(u["anthropic-beta"]="mcp-client-2025-04-04"),await g.post(yt,p,u)}async parseStream(e,t){let o=e.body.getReader(),s=new TextDecoder,r=[],i=new Map,a="";for(;;){let{done:p,value:u}=await o.read();if(p)break;a+=s.decode(u,{stream:!0});let h;for(;(h=a.indexOf(`
12
+ `))!==-1;){let c=a.slice(0,h).trim();if(a=a.slice(h+1),!c.startsWith("data:"))continue;let m=c.slice(5).trim();if(m==="[DONE]")break;let l=JSON.parse(m);if(l.type==="content_block_delta"&&l.delta?.text&&(t(l.delta.text),r.push({type:"text",text:l.delta.text})),l.type==="content_block_start"&&l.content_block?.type==="tool_use"?i.set(l.index,{id:l.content_block.id,name:l.content_block.name,args:""}):l.type==="content_block_start"&&l.content_block?.type==="mcp_tool_use"?i.set(l.index,{id:l.content_block.id,name:l.content_block.name,args:"",server_name:l.content_block.server_name}):l.type==="content_block_start"&&l.content_block?.type==="tool_result"?r.push({type:"tool_result",tool_use_id:l.content_block.tool_use_id,content:l.content_block.content??""}):l.type==="content_block_start"&&l.content_block?.type==="mcp_tool_result"&&r.push({type:"mcp_tool_result",tool_use_id:l.content_block.tool_use_id,is_error:l.content_block.is_error??!1,content:l.content_block.content??[]}),l.type==="content_block_delta"&&l.delta?.type==="input_json_delta"){let _=i.get(l.index);_&&(_.args+=l.delta.partial_json||"")}if(l.type==="content_block_stop"&&i.has(l.index)){let{id:_,name:M,args:d,server_name:C}=i.get(l.index);C?r.push({type:"mcp_tool_use",id:_,name:M,server_name:C,input:JSON.parse(d||"{}")}):r.push({type:"tool_use",id:_,name:M,input:JSON.parse(d||"{}")}),i.delete(l.index)}}}return{blocks:r,stop_reason:r.some(p=>p.type==="tool_use"||p.type==="mcp_tool_use")?"tool_use":"end"}}async parsePureStream(e,t){let{blocks:o}=await this.parseStream(e,t);return o.filter(s=>s.type==="text").map(s=>s.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=()=>{},s){let r=await this.callClaude(e,this.model,t,s),i=t?await this.parseStream(r,o):this.parseOneShot(await r.json());return this.convertToStandardCompletion(i)}async visionChatOnce(e,t=!1,o=()=>{},s){let r=await this.callClaude(e,this.visionModel,t,s),i=t?await this.parseStream(r,o):this.parseOneShot(await r.json());return this.convertToStandardCompletion(i)}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 re=class{createChatService(e){let t=y({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:o=>this.supportsVisionForModel(o),validate:"resolved"});return new se(e.apiKey,e.model||this.getDefaultModel(),t,e.tools??[],e.mcpServers??[],e.responseLength)}getProviderName(){return"claude"}getSupportedModels(){return[S,Ge,Ve,Fe,Ue,He,We,Be,Ke,$e,je]}getDefaultModel(){return S}supportsVision(){return!0}supportsVisionForModel(e){return Me.includes(e)}};var ut=class{static async fetchToolSchemas(e){try{let t={"Content-Type":"application/json"};e.authorization_token&&(t.Authorization=`Bearer ${e.authorization_token}`);let s=await(await g.post(`${e.url}/tools`,{},t)).json();return Array.isArray(s.tools)?s.tools.map(r=>({name:`mcp_${e.name}_${r.name}`,description:r.description||`Tool from ${e.name} MCP server`,parameters:r.inputSchema||{type:"object",properties:{},required:[]}})):[{name:`mcp_${e.name}_search`,description:`Search using ${e.name} MCP server`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}]}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),[{name:`mcp_${e.name}_search`,description:`Search using ${e.name} MCP server (schema fetch failed)`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}]}}static async fetchAllToolSchemas(e){let t=[];for(let o of e)try{let s=await this.fetchToolSchemas(o);t.push(...s)}catch(s){console.error(`Failed to fetch schemas from ${o.name}:`,s)}return t}};var ne=class{constructor(e,t=N,o=N,s=[],r=[],i){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=i,!ve.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=s,this.mcpServers=r}safeJsonParse(e){try{return JSON.parse(e)}catch{return e}}normalizeToolResult(e){return e===null?{content:null}:typeof e=="object"?e:{content:e}}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,s])=>[t[o]??o,this.adaptKeysForApi(s)])):e}getModel(){return this.model}getVisionModel(){return this.visionModel}getMCPServers(){return this.mcpServers}addMCPServer(e){this.mcpServers.push(e),this.mcpSchemasInitialized=!1}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e),this.mcpSchemasInitialized=!1}hasMCPServers(){return this.mcpServers.length>0}async initializeMCPSchemas(){if(!(this.mcpSchemasInitialized||this.mcpServers.length===0))try{let e=new Promise((o,s)=>setTimeout(()=>s(new Error("MCP schema fetch timeout")),5e3)),t=ut.fetchAllToolSchemas(this.mcpServers);this.mcpToolSchemas=await Promise.race([t,e]),this.mcpSchemasInitialized=!0}catch(e){console.warn("Failed to initialize MCP schemas, using fallback:",e),this.mcpToolSchemas=this.mcpServers.map(t=>({name:`mcp_${t.name}_search`,description:`Search using ${t.name} MCP server (fallback)`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}})),this.mcpSchemasInitialized=!0}}async processChat(e,t,o){try{await v({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callGemini(e,this.model,!0),{blocks:r}=await this.parseStream(s,t);return f.getFullText(r)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use chatOnce() loop when tools are enabled."})}catch(s){throw console.error("Error in processChat:",s),s}}async processVisionChat(e,t,o){try{await v({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callGemini(e,this.visionModel,!0),{blocks:r}=await this.parseStream(s,t);return f.getFullText(r)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:s=>{s.filter(r=>r.type==="text").forEach(r=>t(r.text))},onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use visionChatOnce() loop when tools are enabled."})}catch(s){throw console.error("Error in processVisionChat:",s),s}}convertMessagesToGeminiFormat(e){let t=[],o=null,s=[],r=()=>{o&&s.length&&(t.push({role:o,parts:[...s]}),s=[])};for(let i of e){let a=this.mapRoleToGemini(i.role);if(i.tool_calls){r();for(let p of i.tool_calls)this.callIdMap.set(p.id,p.function.name),t.push({role:"model",parts:[{functionCall:{name:p.function.name,args:JSON.parse(p.function.arguments||"{}")}}]});continue}if(i.role==="tool"){r();let p=i.name??this.callIdMap.get(i.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:p,response:this.normalizeToolResult(this.safeJsonParse(i.content))}}]});continue}a!==o&&r(),o=a,s.push({text:i.content})}return r(),t}async callGemini(e,t,o=!1,s){let a={contents:e.some(d=>Array.isArray(d.content)&&d.content.some(C=>C?.type==="image_url"||C?.inlineData))?await this.convertVisionMessagesToGeminiFormat(e):this.convertMessagesToGeminiFormat(e),generationConfig:{maxOutputTokens:s!==void 0?s:E(this.responseLength)}},p=[];if(this.tools.length>0&&p.push(...this.tools.map(d=>({name:d.name,description:d.description,parameters:d.parameters}))),this.mcpServers.length>0)try{await this.initializeMCPSchemas(),p.push(...this.mcpToolSchemas.map(d=>({name:d.name,description:d.description,parameters:d.parameters})))}catch(d){console.warn("MCP initialization failed, skipping MCP tools:",d)}p.length>0&&(a.tools=[{functionDeclarations:p}],a.toolConfig={functionCallingConfig:{mode:"AUTO"}});let u=async(d,C)=>{let ge=o?"streamGenerateContent":"generateContent",D=o?"?alt=sse":"",ye=`${Ct}/${d}/models/${t}:${ge}${D}${D?"&":"?"}key=${this.apiKey}`;return g.post(ye,C)},h=/flash[-_]lite/.test(t),c=/gemini-2\.5/.test(t),m=/^gemini-3(?:\.[0-9]+)?-.*preview/.test(t),l=h||c||m,_=l?"v1beta":"v1",M=async()=>{try{let d=_==="v1"?a:this.adaptKeysForApi(a);return await u(_,d)}catch(d){let C=/Unknown name|Cannot find field|404/.test(d?.message||"")||d?.status===404;if(!l&&C)return await u("v1beta",this.adaptKeysForApi(a));throw d}};try{return await M()}catch(d){throw d.body&&(console.error("Gemini API Error Details:",d.body),console.error("Request Body:",JSON.stringify(a,null,2))),d}}async convertVisionMessagesToGeminiFormat(e){let t=[],o=null,s=[];for(let r of e){let i=this.mapRoleToGemini(r.role);if(r.tool_calls){for(let a of r.tool_calls)t.push({role:"model",parts:[{functionCall:{name:a.function.name,args:JSON.parse(a.function.arguments||"{}")}}]});continue}if(r.role==="tool"){let a=r.name??this.callIdMap.get(r.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:a,response:this.normalizeToolResult(this.safeJsonParse(r.content))}}]});continue}if(i!==o&&s.length>0&&(t.push({role:o,parts:[...s]}),s=[]),o=i,typeof r.content=="string")s.push({text:r.content});else if(Array.isArray(r.content)){for(let a of r.content)if(a.type==="text")s.push({text:a.text});else if(a.type==="image_url")try{let u=await(await g.get(a.image_url.url)).blob(),h=await this.blobToBase64(u);s.push({inlineData:{mimeType:u.type||"image/jpeg",data:h.split(",")[1]}})}catch(p){throw console.error("Error processing image:",p),new Error(`Failed to process image: ${p.message}`)}}}return o&&s.length>0&&t.push({role:o,parts:[...s]}),t}blobToBase64(e){return new Promise((t,o)=>{let s=new FileReader;s.onloadend=()=>t(s.result),s.onerror=o,s.readAsDataURL(e)})}mapRoleToGemini(e){switch(e){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}async parseStream(e,t){let o=e.body.getReader(),s=new TextDecoder,r=[],i=[],a="",p=h=>{if(!h||h==="[DONE]")return;let c;try{c=JSON.parse(h)}catch{return}for(let m of c.candidates??[])for(let l of m.content?.parts??[])l.text&&(t(l.text),f.addTextBlock(r,l.text)),l.functionCall&&i.push({type:"tool_use",id:this.genUUID(),name:l.functionCall.name,input:l.functionCall.args??{}}),l.functionResponse&&i.push({type:"tool_result",tool_use_id:l.functionResponse.name,content:JSON.stringify(l.functionResponse.response)})};for(;;){let{done:h,value:c}=await o.read();if(h)break;a+=s.decode(c,{stream:!0});let m;for(;(m=a.indexOf(`
13
+ `))!==-1;){let l=a.slice(0,m);if(a=a.slice(m+1),l.endsWith("\r")&&(l=l.slice(0,-1)),!l.trim()){p("");continue}l.startsWith("data:")&&(l=l.slice(5).trim()),l&&p(l)}}return a&&p(a),{blocks:[...r,...i],stop_reason:i.some(h=>h.type==="tool_use")?"tool_use":"end"}}parseOneShot(e){let t=[],o=[];for(let r of e.candidates??[])for(let i of r.content?.parts??[])i.text&&t.push({type:"text",text:i.text}),i.functionCall&&o.push({type:"tool_use",id:this.genUUID(),name:i.functionCall.name,input:i.functionCall.args??{}}),i.functionResponse&&o.push({type:"tool_result",tool_use_id:i.functionResponse.name,content:JSON.stringify(i.functionResponse.response)});return{blocks:[...t,...o],stop_reason:o.some(r=>r.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},s){let r=await this.callGemini(e,this.model,t,s);return t?this.parseStream(r,o):this.parseOneShot(await r.json())}async visionChatOnce(e,t=!1,o=()=>{},s){let r=await this.callGemini(e,this.visionModel,t,s);return t?this.parseStream(r,o):this.parseOneShot(await r.json())}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 ie=class{createChatService(e){let t=y({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:o=>this.supportsVisionForModel(o),validate:"resolved"});return new ne(e.apiKey,e.model||this.getDefaultModel(),t,e.tools||[],e.mcpServers||[],e.responseLength)}getProviderName(){return"gemini"}getSupportedModels(){return[Ie,Re,Le,be,De,Ae,we,Ne,ke,N]}getDefaultModel(){return N}supportsVision(){return!0}supportsVisionForModel(e){return ve.includes(e)}};var ae=class{constructor(e,t=x,o=x,s,r=ee,i,a,p){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=r,this.responseLength=i,this.responseFormat=a,this.thinking=p??{type:"enabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callKimi(e,this.model,!0);return this.handleStream(s,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(!te(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callKimi(e,this.visionModel,!0);return this.handleStream(s,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=()=>{},s){let r=await this.callKimi(e,this.model,t,s);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){if(!te(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callKimi(e,this.visionModel,t,s);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callKimi(e,t,o=!1,s){let r=this.buildRequestBody(e,t,o,s);return await g.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let r={model:t,stream:o,messages:e},i=s!==void 0?s:E(this.responseLength);i!==void 0&&(r.max_tokens=i),this.responseFormat&&(r.response_format=this.responseFormat);let a=this.tools.length>0?{type:"disabled"}:this.thinking;a&&(this.isSelfHostedEndpoint()?a.type==="disabled"&&(r.chat_template_kwargs={thinking:!1}):r.thinking=a);let p=this.buildToolsDefinition();return p.length>0&&(r.tools=p,r.tool_choice="auto"),r}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(ee)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}buildToolsDefinition(){return b(this.tools,"chat-completions")}async handleStream(e,t){return I(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return R(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var le=class{createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),s=y({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:p=>this.supportsVisionForModel(p),validate:"explicit"}),r=e.tools,i=e.thinking??{type:"enabled"},a=r&&r.length>0?{type:"disabled"}:i;return new ae(e.apiKey,o,s,r,t,e.responseLength,e.responseFormat,a)}getProviderName(){return"kimi"}getSupportedModels(){return[x]}getDefaultModel(){return x}getDefaultVisionModel(){return x}supportsVision(){return!0}supportsVisionForModel(e){return te(e)}resolveEndpoint(e){if(e.endpoint)return this.normalizeEndpoint(e.endpoint);if(e.baseUrl){let t=this.normalizeEndpoint(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return ee}normalizeEndpoint(e){return e.replace(/\/+$/,"")}};var So={[O.VERY_SHORT]:800,[O.SHORT]:1200,[O.MEDIUM]:2e3,[O.LONG]:3e3,[O.VERY_LONG]:8e3,[O.DEEP]:25e3},Po={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3},V=class{constructor(e,t=B,o=B,s,r=q,i=[],a,p,u,h=!1,c="openai",m=!0){if(this.provider=c,this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=r,this.mcpServers=i,this.responseLength=a,this.verbosity=p,this.reasoning_effort=u,this.enableReasoningSummary=h,m&&!fe.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 v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenAI(e,this.model,!0),r=this.endpoint===T;try{if(r){let i=await this.parseResponsesStream(s,t);return f.getFullText(i.blocks)}return this.handleStream(s,t)}catch(i){throw console.error("[processChat] Error in streaming/completion:",i),i}},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 v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenAI(e,this.visionModel,!0),r=this.endpoint===T;try{if(r){let i=await this.parseResponsesStream(s,t);return f.getFullText(i.blocks)}return this.handleStream(s,t)}catch(i){throw console.error("[processVisionChat] Error in streaming/completion:",i),i}},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(s){throw console.error("Error in processVisionChat:",s),s}}async chatOnce(e,t=!0,o=()=>{},s){let r=await this.callOpenAI(e,this.model,t,s);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){let r=await this.callOpenAI(e,this.visionModel,t,s);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return this.endpoint===T?t?this.parseResponsesStream(e,o):this.parseResponsesOneShot(await e.json()):t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callOpenAI(e,t,o=!1,s){let r=this.buildRequestBody(e,t,o,s),i={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(i.Authorization=`Bearer ${this.apiKey}`),await g.post(this.endpoint,r,i)}buildRequestBody(e,t,o,s){let r=this.endpoint===T;this.validateMCPCompatibility();let i={model:t,stream:o},a=this.resolveTokenLimit(t,s);r?a!==void 0&&(i.max_output_tokens=a):a!==void 0&&(this.provider==="openai-compatible"?i.max_tokens=a:i.max_completion_tokens=a),r?i.input=this.cleanMessagesForResponsesAPI(e):i.messages=e,K(t)&&(r?(this.reasoning_effort&&(i.reasoning={...i.reasoning,effort:this.reasoning_effort},this.enableReasoningSummary&&(i.reasoning.summary="auto")),this.verbosity&&(i.text={...i.text,format:{type:"text"},verbosity:this.verbosity})):(this.reasoning_effort&&(i.reasoning_effort=this.reasoning_effort),this.verbosity&&(i.verbosity=this.verbosity)));let p=this.buildToolsDefinition();return p.length>0&&(i.tools=p,r||(i.tool_choice="auto")),i}resolveTokenLimit(e,t){if(t!==void 0)return t;let o=this.provider==="openai-compatible"?this.responseLength!==void 0?E(this.responseLength):void 0:E(this.responseLength);if(this.provider!=="openai"||!K(e)||this.responseLength===void 0)return o;let s=this.reasoning_effort??P(e);return Math.max(o??0,So[this.responseLength],Po[s])}validateMCPCompatibility(){if(this.mcpServers.length>0&&this.endpoint===q)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${this.endpoint}. Please use OpenAI Responses API endpoint: ${T}. MCP tools are only available in the Responses API endpoint.`)}cleanMessagesForResponsesAPI(e){return e.map(t=>{let s={role:t.role==="tool"?"user":t.role};return typeof t.content=="string"?s.content=t.content:Array.isArray(t.content)?s.content=t.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):s.content=t.content,s})}buildToolsDefinition(){let e=this.endpoint===T,t=[];return this.tools.length>0&&t.push(...b(this.tools,e?"responses":"chat-completions")),this.mcpServers.length>0&&e&&t.push(...this.buildMCPToolsDefinition()),t}buildMCPToolsDefinition(){return this.mcpServers.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})}async handleStream(e,t){return I(e,t)}async parseStream(e,t){return R(e,t,{appendTextBlock:f.addTextBlock})}parseOneShot(e){return L(e)}async parseResponsesStream(e,t){let o=e.body.getReader(),s=new TextDecoder,r=[],i=new Map,a,p,u,h="";for(;;){let{done:l,value:_}=await o.read();if(l)break;h+=s.decode(_,{stream:!0});let M="",d="",C=h.split(`
14
+ `);h=C.pop()||"";for(let ge=0;ge<C.length;ge++){let D=C[ge].trim();if(D.startsWith("event:"))M=D.slice(6).trim();else if(D.startsWith("data:"))d=D.slice(5).trim();else if(D===""&&M&&d){try{let ye=JSON.parse(d),Yt=this.handleResponsesSSEEvent(M,ye,t,r,i,z=>{z.responseStatus!==void 0&&(a=z.responseStatus),z.incompleteDetails!==void 0&&(p=z.incompleteDetails),z.usage!==void 0&&(u=z.usage)})}catch{console.warn("Failed to parse SSE data:",d)}M="",d=""}}}let c=Array.from(i.values()).map(l=>({type:"tool_use",id:l.id,name:l.name,input:l.input||{}}));return{blocks:[...r,...c],stop_reason:c.length?"tool_use":"end",truncated:a==="incomplete",response_status:a,incomplete_details:p,usage:u}}handleResponsesSSEEvent(e,t,o,s,r,i){switch(e){case"response.output_item.added":t.item?.type==="message"&&Array.isArray(t.item.content)?t.item.content.forEach(a=>{a.type==="output_text"&&a.text&&(o(a.text),f.append(s,a.text))}):t.item?.type==="function_call"&&r.set(t.item.id,{id:t.item.id,name:t.item.name,input:t.item.arguments?JSON.parse(t.item.arguments):{}});break;case"response.content_part.added":t.part?.type==="output_text"&&typeof t.part.text=="string"&&(o(t.part.text),f.append(s,t.part.text));break;case"response.output_text.delta":case"response.content_part.delta":{let a=typeof t.delta=="string"?t.delta:t.delta?.text??"";a&&(o(a),f.append(s,a))}break;case"response.output_text.done":case"response.content_part.done":break;case"response.completed":return i(this.extractResponsesMetadata(t,"completed")),"completed";case"response.incomplete":return i(this.extractResponsesMetadata(t,"incomplete")),"completed";case"response.reasoning.started":case"response.reasoning.delta":case"response.reasoning.done":break;default:break}}extractResponsesMetadata(e,t){let o=e?.response??e;return{responseStatus:o?.status??t,incompleteDetails:o?.incomplete_details??null,usage:o?.usage}}parseResponsesOneShot(e){let t=[];return e.output&&Array.isArray(e.output)&&e.output.forEach(o=>{o.type==="message"&&o.content&&o.content.forEach(s=>{s.type==="output_text"&&s.text&&t.push({type:"text",text:s.text})}),o.type==="function_call"&&t.push({type:"tool_use",id:o.id,name:o.name,input:o.arguments?JSON.parse(o.arguments):{}})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use")?"tool_use":"end",truncated:e?.status==="incomplete",response_status:e?.status,incomplete_details:e?.incomplete_details??null,usage:e?.usage}}};var pe=class{createChatService(e){return this.validateRequiredOptions(e),new V(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!1}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=y({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:u=>this.supportsVisionForModel(u),validate:"resolved"}),s=t.tools,r=t.mcpServers??[],i=t.model||this.getDefaultModel(),a=!1;r.length>0||ft(i)?a=!0:K(i)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let p=t.endpoint||(a?T:q);return new V(t.apiKey,i,o,s,p,r,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName())}getProviderName(){return"openai"}getSupportedModels(){return[F,J,Z,U,A,H,W,w,Te,Se,Pe,B,xe,dt,_t,"o1"]}getDefaultModel(){return F}supportsVision(){return!0}supportsVisionForModel(e){return fe.includes(e)}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!K(t))return e;let o={...e};if(e.gpt5Preset){let s=kt[e.gpt5Preset];o.reasoning_effort=s.reasoning_effort,o.verbosity=s.verbosity}else e.reasoning_effort||(o.reasoning_effort=P(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!Mt(e)?P(e):t==="minimal"&&!Ot(e)?P(e):t==="low"&&!Et(e)?P(e):t==="xhigh"&&!vt(e)?P(e):t}};var he=class{constructor(e,t=k,o=k,s,r=Oe,i,a,p,u,h,c){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=r,this.responseLength=i,this.appName=a,this.appUrl=p,this.reasoning_effort=u,this.includeReasoning=h,this.reasoningMaxTokens=c,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!$(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=It){let o=6e4-t;o>0&&(console.log(`Rate limit reached for free tier. Waiting ${o}ms...`),await new Promise(s=>setTimeout(s,o)),this.requestCount=0)}this.lastRequestTime=e,this.requestCount++}async processChat(e,t,o){await this.applyRateLimiting(),await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenRouter(e,this.model,!0);return this.handleStream(s,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(!X(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(s,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(s){throw console.error("Error in processVisionChat:",s),s}}async chatOnce(e,t=!0,o=()=>{},s){await this.applyRateLimiting();let r=await this.callOpenRouter(e,this.model,t,s);return t?this.parseStream(r,o):this.parseOneShot(await r.json())}async visionChatOnce(e,t=!1,o=()=>{},s){if(!X(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let r=await this.callOpenRouter(e,this.visionModel,t,s);return t?this.parseStream(r,o):this.parseOneShot(await r.json())}async callOpenRouter(e,t,o=!1,s){let r=this.buildRequestBody(e,t,o,s),i={Authorization:`Bearer ${this.apiKey}`};return this.appUrl&&(i["HTTP-Referer"]=this.appUrl),this.appName&&(i["X-Title"]=this.appName),await g.post(this.endpoint,r,i)}buildRequestBody(e,t,o,s){let r={model:t,messages:e,stream:o};if((s!==void 0?s:E(this.responseLength))&&console.warn("OpenRouter: Token limits are not supported for gpt-oss-20b model due to known issues. Using unlimited tokens instead."),this.reasoning_effort!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens){if(r.reasoning={},this.reasoning_effort&&this.reasoning_effort!=="none"){let a=this.reasoning_effort==="minimal"?"low":this.reasoning_effort;r.reasoning.effort=a}(this.reasoning_effort==="none"||this.includeReasoning!==!0)&&(r.reasoning.exclude=!0),this.reasoningMaxTokens&&(r.reasoning.max_tokens=this.reasoningMaxTokens)}else r.reasoning={exclude:!0};return this.tools.length>0&&(r.tools=b(this.tools,"chat-completions"),r.tool_choice="auto"),r}async handleStream(e,t){return I(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return R(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var ue=class{createChatService(e){let t=y({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:e.model||this.getDefaultModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"explicit"}),o=e.tools,s=e.appName,r=e.appUrl;return new he(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,s,r,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[k,lt,qe,Je,Ze,Xe,Ye,Qe,et,tt,ot,st,Tt,rt,nt,it,at,St,Pt,ze]}getDefaultModel(){return k}supportsVision(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))}supportsVisionForModel(e){return X(e)}getFreeModels(){return xt}isModelFree(e){return $(e)}};var me=class{constructor(e,t=Y,o=j,s,r=Ee,i,a,p){this.provider="zai";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=r,this.responseLength=i,this.responseFormat=a,this.thinking=p??{type:"disabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callZAI(e,this.model,!0);return this.handleStream(s,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(!Q(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callZAI(e,this.visionModel,!0);return this.handleStream(s,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=()=>{},s){let r=await this.callZAI(e,this.model,t,s);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){if(!Q(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callZAI(e,this.visionModel,t,s);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callZAI(e,t,o=!1,s){let r=this.buildRequestBody(e,t,o,s);return await g.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let r={model:t,stream:o,messages:e},i=s!==void 0?s:E(this.responseLength);i!==void 0&&(r.max_tokens=i),this.responseFormat&&(r.response_format=this.responseFormat),this.thinking&&(r.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto",o&&wt(t)&&(r.tool_stream=!0)),r}buildToolsDefinition(){return b(this.tools,"chat-completions")}async handleStream(e,t){return I(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return R(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var de=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=y({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"explicit"}),s=e.tools,r=e.thinking??{type:"disabled"};return new me(e.apiKey,t,o,s,e.endpoint||Ee,e.responseLength,e.responseFormat,r)}getProviderName(){return"zai"}getSupportedModels(){return[Rt,Lt,Y,bt,Dt,At,pt,ct,j]}getDefaultModel(){return Y}getDefaultVisionModel(){return j}supportsVision(){return!0}supportsVisionForModel(e){return Q(e)}};var Zt=[new ce,new pe,new ie,new re,new ue,new de,new le];var _e=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():[]}};_e.providers=new Map;Zt.forEach(n=>_e.registerProvider(n));function Xt(){g.setFetch(async(n,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,s={};if(Array.isArray(o))for(let[c,m]of o)s[c]=String(m);else if(o&&typeof o=="object")for(let[c,m]of Object.entries(o))s[c]=String(m);let r={method:t,headers:s,muteHttpExceptions:!0},i=e.body;typeof i=="string"?r.payload=i:i!=null&&(s["Content-Type"]||(s["Content-Type"]="application/json"),r.payload=JSON.stringify(i));let a=UrlFetchApp.fetch(n,r),p=a.getResponseCode(),u=a.getContentText();return{ok:p>=200&&p<300,status:p,statusText:String(p),text:async()=>u,json:async()=>u?JSON.parse(u):null}})}return ro(xo);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aituber-onair/chat",
3
- "version": "0.21.0",
3
+ "version": "0.21.2",
4
4
  "description": "Chat and LLM API integration library for AITuber OnAir",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",