@aituber-onair/chat 0.23.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/cjs/constants/geminiNano.d.ts +6 -0
  2. package/dist/cjs/constants/geminiNano.d.ts.map +1 -0
  3. package/dist/cjs/constants/geminiNano.js +9 -0
  4. package/dist/cjs/constants/geminiNano.js.map +1 -0
  5. package/dist/cjs/constants/index.d.ts +1 -0
  6. package/dist/cjs/constants/index.d.ts.map +1 -1
  7. package/dist/cjs/constants/index.js +1 -0
  8. package/dist/cjs/constants/index.js.map +1 -1
  9. package/dist/cjs/index.d.ts +3 -1
  10. package/dist/cjs/index.d.ts.map +1 -1
  11. package/dist/cjs/index.js +6 -1
  12. package/dist/cjs/index.js.map +1 -1
  13. package/dist/cjs/services/providers/ChatServiceProvider.d.ts +13 -0
  14. package/dist/cjs/services/providers/ChatServiceProvider.d.ts.map +1 -1
  15. package/dist/cjs/services/providers/geminiNano/GeminiNanoChatService.d.ts +37 -0
  16. package/dist/cjs/services/providers/geminiNano/GeminiNanoChatService.d.ts.map +1 -0
  17. package/dist/cjs/services/providers/geminiNano/GeminiNanoChatService.js +128 -0
  18. package/dist/cjs/services/providers/geminiNano/GeminiNanoChatService.js.map +1 -0
  19. package/dist/cjs/services/providers/geminiNano/GeminiNanoChatServiceProvider.d.ts +15 -0
  20. package/dist/cjs/services/providers/geminiNano/GeminiNanoChatServiceProvider.d.ts.map +1 -0
  21. package/dist/cjs/services/providers/geminiNano/GeminiNanoChatServiceProvider.js +35 -0
  22. package/dist/cjs/services/providers/geminiNano/GeminiNanoChatServiceProvider.js.map +1 -0
  23. package/dist/cjs/services/providers/index.d.ts +2 -1
  24. package/dist/cjs/services/providers/index.d.ts.map +1 -1
  25. package/dist/cjs/services/providers/index.js +2 -0
  26. package/dist/cjs/services/providers/index.js.map +1 -1
  27. package/dist/esm/constants/geminiNano.d.ts +6 -0
  28. package/dist/esm/constants/geminiNano.d.ts.map +1 -0
  29. package/dist/esm/constants/geminiNano.js +6 -0
  30. package/dist/esm/constants/geminiNano.js.map +1 -0
  31. package/dist/esm/constants/index.d.ts +1 -0
  32. package/dist/esm/constants/index.d.ts.map +1 -1
  33. package/dist/esm/constants/index.js +1 -0
  34. package/dist/esm/constants/index.js.map +1 -1
  35. package/dist/esm/index.d.ts +3 -1
  36. package/dist/esm/index.d.ts.map +1 -1
  37. package/dist/esm/index.js +3 -0
  38. package/dist/esm/index.js.map +1 -1
  39. package/dist/esm/services/providers/ChatServiceProvider.d.ts +13 -0
  40. package/dist/esm/services/providers/ChatServiceProvider.d.ts.map +1 -1
  41. package/dist/esm/services/providers/geminiNano/GeminiNanoChatService.d.ts +37 -0
  42. package/dist/esm/services/providers/geminiNano/GeminiNanoChatService.d.ts.map +1 -0
  43. package/dist/esm/services/providers/geminiNano/GeminiNanoChatService.js +124 -0
  44. package/dist/esm/services/providers/geminiNano/GeminiNanoChatService.js.map +1 -0
  45. package/dist/esm/services/providers/geminiNano/GeminiNanoChatServiceProvider.d.ts +15 -0
  46. package/dist/esm/services/providers/geminiNano/GeminiNanoChatServiceProvider.d.ts.map +1 -0
  47. package/dist/esm/services/providers/geminiNano/GeminiNanoChatServiceProvider.js +31 -0
  48. package/dist/esm/services/providers/geminiNano/GeminiNanoChatServiceProvider.js.map +1 -0
  49. package/dist/esm/services/providers/index.d.ts +2 -1
  50. package/dist/esm/services/providers/index.d.ts.map +1 -1
  51. package/dist/esm/services/providers/index.js +2 -0
  52. package/dist/esm/services/providers/index.js.map +1 -1
  53. package/dist/umd/aituber-onair-chat.js +142 -0
  54. package/dist/umd/aituber-onair-chat.min.js +11 -6
  55. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- "use strict";var AITuberOnAirChat=(()=>{var Et=Object.defineProperty;var lo=Object.getOwnPropertyDescriptor;var po=Object.getOwnPropertyNames;var co=Object.prototype.hasOwnProperty;var uo=(r,e)=>{for(var t in e)Et(r,t,{get:e[t],enumerable:!0})},ho=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of po(e))!co.call(r,s)&&s!==t&&Et(r,s,{get:()=>e[s],enumerable:!(o=lo(e,s))||o.enumerable});return r};var mo=r=>ho(Et({},"__esModule",{value:!0}),r);var Vo={};uo(Vo,{CHAT_RESPONSE_LENGTH:()=>C,CLAUDE_VISION_SUPPORTED_MODELS:()=>Se,ChatServiceFactory:()=>Me,ChatServiceHttpClient:()=>g,ClaudeChatService:()=>re,ClaudeChatServiceProvider:()=>ne,DEFAULT_MAX_TOKENS:()=>Bt,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>Mo,DEFAULT_VISION_PROMPT:()=>vo,EMOTION_TAG_CLEANUP_REGEX:()=>$t,EMOTION_TAG_REGEX:()=>Qt,ENDPOINT_CLAUDE_API:()=>bt,ENDPOINT_GEMINI_API:()=>Rt,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>oe,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>J,ENDPOINT_OPENAI_RESPONSES_API:()=>x,ENDPOINT_OPENROUTER_API:()=>Te,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>Pe,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>ye,EmotionParser:()=>ie,GEMINI_VISION_SUPPORTED_MODELS:()=>Ce,GPT5_PRESETS:()=>Kt,GPT_5_MODELS:()=>zt,GeminiChatService:()=>ae,GeminiChatServiceProvider:()=>le,HttpError:()=>G,KIMI_VISION_SUPPORTED_MODELS:()=>Zt,KimiChatService:()=>pe,KimiChatServiceProvider:()=>ce,MAX_TOKENS_BY_LENGTH:()=>Yt,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>Dt,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>lt,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>pt,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>nt,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>at,MODEL_CLAUDE_3_5_HAIKU:()=>We,MODEL_CLAUDE_3_5_SONNET:()=>Be,MODEL_CLAUDE_3_7_SONNET:()=>Ke,MODEL_CLAUDE_3_HAIKU:()=>I,MODEL_CLAUDE_4_5_HAIKU:()=>qe,MODEL_CLAUDE_4_5_OPUS:()=>Je,MODEL_CLAUDE_4_5_SONNET:()=>ze,MODEL_CLAUDE_4_6_OPUS:()=>Ze,MODEL_CLAUDE_4_6_SONNET:()=>Xe,MODEL_CLAUDE_4_OPUS:()=>je,MODEL_CLAUDE_4_SONNET:()=>$e,MODEL_GEMINI_2_0_FLASH:()=>He,MODEL_GEMINI_2_0_FLASH_LITE:()=>V,MODEL_GEMINI_2_5_FLASH:()=>Ge,MODEL_GEMINI_2_5_FLASH_LITE:()=>Fe,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>Ue,MODEL_GEMINI_2_5_PRO:()=>ke,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>Ne,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>Ae,MODEL_GEMINI_3_FLASH_PREVIEW:()=>Ve,MODEL_GEMINI_3_PRO_PREVIEW:()=>we,MODEL_GLM_4_6:()=>Ht,MODEL_GLM_4_6V:()=>mt,MODEL_GLM_4_6V_FLASH:()=>z,MODEL_GLM_4_6V_FLASHX:()=>_t,MODEL_GLM_4_7:()=>Q,MODEL_GLM_4_7_FLASH:()=>Ut,MODEL_GLM_4_7_FLASHX:()=>Ft,MODEL_GLM_5:()=>kt,MODEL_GLM_5_TURBO:()=>Gt,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>ut,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>ht,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>ct,MODEL_GPT_4O:()=>De,MODEL_GPT_4O_MINI:()=>K,MODEL_GPT_4_1:()=>Ie,MODEL_GPT_4_1_MINI:()=>Re,MODEL_GPT_4_1_NANO:()=>be,MODEL_GPT_5:()=>Z,MODEL_GPT_5_1:()=>H,MODEL_GPT_5_4:()=>N,MODEL_GPT_5_4_MINI:()=>W,MODEL_GPT_5_4_NANO:()=>B,MODEL_GPT_5_4_PRO:()=>w,MODEL_GPT_5_MINI:()=>X,MODEL_GPT_5_NANO:()=>U,MODEL_GPT_OSS_20B_FREE:()=>k,MODEL_GROK_4_1_FAST_NON_REASONING:()=>b,MODEL_GROK_4_1_FAST_REASONING:()=>vt,MODEL_GROK_4_20_NON_REASONING:()=>ft,MODEL_GROK_4_20_REASONING:()=>gt,MODEL_KIMI_K2_5:()=>D,MODEL_MOONSHOTAI_KIMI_K2_5:()=>Ye,MODEL_O1:()=>Tt,MODEL_O1_MINI:()=>St,MODEL_O3_MINI:()=>Ct,MODEL_OPENAI_GPT_4O:()=>st,MODEL_OPENAI_GPT_4_1_MINI:()=>it,MODEL_OPENAI_GPT_4_1_NANO:()=>rt,MODEL_OPENAI_GPT_5_1_CHAT:()=>Qe,MODEL_OPENAI_GPT_5_1_CODEX:()=>et,MODEL_OPENAI_GPT_5_MINI:()=>tt,MODEL_OPENAI_GPT_5_NANO:()=>ot,MODEL_ZAI_GLM_4_5_AIR:()=>Nt,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>dt,MODEL_ZAI_GLM_4_7_FLASH:()=>At,OPENROUTER_CREDITS_THRESHOLD:()=>fo,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>go,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>_o,OPENROUTER_FREE_MODELS:()=>wt,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>Vt,OPENROUTER_VISION_SUPPORTED_MODELS:()=>qt,OpenAIChatService:()=>F,OpenAIChatServiceProvider:()=>he,OpenAICompatibleChatServiceProvider:()=>ue,OpenRouterChatService:()=>de,OpenRouterChatServiceProvider:()=>me,StreamTextAccumulator:()=>v,VISION_SUPPORTED_MODELS:()=>Ee,XAIChatService:()=>_e,XAIChatServiceProvider:()=>ge,XAI_VISION_SUPPORTED_MODELS:()=>Xt,ZAIChatService:()=>fe,ZAIChatServiceProvider:()=>ve,ZAI_VISION_SUPPORTED_MODELS:()=>Jt,allowsReasoningLow:()=>It,allowsReasoningMinimal:()=>xt,allowsReasoningNone:()=>Lt,allowsReasoningXHigh:()=>Pt,buildOpenAICompatibleTools:()=>L,getDefaultReasoningEffortForGPT5Model:()=>R,getMaxTokensForResponseLength:()=>O,installGASFetch:()=>no,isGPT5Model:()=>$,isKimiVisionModel:()=>se,isOpenRouterFreeModel:()=>j,isOpenRouterVisionModel:()=>Y,isResponsesOnlyGPT5Model:()=>yt,isXaiVisionModel:()=>te,isZaiToolStreamModel:()=>Wt,isZaiVisionModel:()=>ee,parseOpenAICompatibleOneShot:()=>P,parseOpenAICompatibleTextStream:()=>T,parseOpenAICompatibleToolStream:()=>y,processChatWithOptionalTools:()=>f,refreshOpenRouterFreeModels:()=>Ao,resolveVisionModel:()=>E,runOnceText:()=>So,screenplayToText:()=>Co,textToScreenplay:()=>eo,textsToScreenplay:()=>Eo});var J="https://api.openai.com/v1/chat/completions",x="https://api.openai.com/v1/responses",U="gpt-5-nano",X="gpt-5-mini",Z="gpt-5",H="gpt-5.1",N="gpt-5.4",W="gpt-5.4-mini",B="gpt-5.4-nano",w="gpt-5.4-pro",Ie="gpt-4.1",Re="gpt-4.1-mini",be="gpt-4.1-nano",K="gpt-4o-mini",De="gpt-4o",Ct="o3-mini",St="o1-mini",Tt="o1",Ee=[U,X,Z,H,N,W,B,w,Ie,Re,be,K,De,"o1"],zt=[U,X,Z,H,N,W,B,w];function $(r){return zt.includes(r)}function yt(r){return r===w}function Pt(r){return r===N||r===W||r===B||r===w}function Lt(r){return r===H||r===N||r===W||r===B}function xt(r){return r===U||r===X||r===Z}function It(r){return r!==w}function R(r){return r===H||r===N?"none":"medium"}var Rt="https://generativelanguage.googleapis.com",Ae="gemini-3.1-pro-preview",Ne="gemini-3.1-flash-lite-preview",we="gemini-3-pro-preview",Ve="gemini-3-flash-preview",ke="gemini-2.5-pro",Ge="gemini-2.5-flash",Fe="gemini-2.5-flash-lite",Ue="gemini-2.5-flash-lite-preview-06-17",He="gemini-2.0-flash",V="gemini-2.0-flash-lite",Ce=[Ae,Ne,we,Ve,ke,Ge,Fe,Ue,He,V];var bt="https://api.anthropic.com/v1/messages",I="claude-3-haiku-20240307",We="claude-3-5-haiku-20241022",Be="claude-3-5-sonnet-20241022",Ke="claude-3-7-sonnet-20250219",$e="claude-4-sonnet-20250514",je="claude-4-opus-20250514",ze="claude-sonnet-4-5-20250929",qe="claude-haiku-4-5-20251001",Je="claude-opus-4-5-20251101",Xe="claude-sonnet-4-6",Ze="claude-opus-4-6",Se=[I,We,Be,Ke,$e,je,ze,qe,Je,Xe,Ze];var Te="https://openrouter.ai/api/v1/chat/completions",k="openai/gpt-oss-20b:free",Ye="moonshotai/kimi-k2.5",Qe="openai/gpt-5.1-chat",et="openai/gpt-5.1-codex",tt="openai/gpt-5-mini",ot="openai/gpt-5-nano",st="openai/gpt-4o",it="openai/gpt-4.1-mini",rt="openai/gpt-4.1-nano",nt="anthropic/claude-opus-4",at="anthropic/claude-sonnet-4",lt="anthropic/claude-3.7-sonnet",Dt="anthropic/claude-3.5-sonnet",pt="anthropic/claude-haiku-4.5",ct="google/gemini-2.5-pro",ut="google/gemini-2.5-flash",ht="google/gemini-2.5-flash-lite-preview-09-2025",At="z-ai/glm-4.7-flash",Nt="z-ai/glm-4.5-air",dt="z-ai/glm-4.5-air:free",wt=[k,dt],qt=[Qe,et,tt,ot,st,it,rt,nt,at,lt,pt,ct,ut,ht,Ye],Vt=20,_o=50,go=1e3,fo=10;function j(r){return r.trim().endsWith(":free")}function Y(r){return qt.some(e=>r.includes(e))}var ye="https://api.z.ai/api/paas/v4/chat/completions",kt="glm-5",Gt="glm-5-turbo",Q="glm-4.7",Ft="glm-4.7-FlashX",Ut="glm-4.7-Flash",Ht="glm-4.6",mt="glm-4.6V",_t="glm-4.6V-FlashX",z="glm-4.6V-Flash",Jt=[mt,_t,z];function ee(r){return Jt.includes(r)}function Wt(r){return r.toLowerCase().startsWith("glm-4.6")}var Pe="https://api.x.ai/v1/chat/completions",gt="grok-4.20-0309-reasoning",ft="grok-4.20-0309-non-reasoning",vt="grok-4-1-fast-reasoning",b="grok-4-1-fast-non-reasoning",Xt=[gt,ft,vt,b];function te(r){return Xt.includes(r)}var oe="https://api.moonshot.ai/v1/chat/completions",D="kimi-k2.5",Zt=[D];function se(r){return Zt.includes(r)}var C={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Yt={[C.VERY_SHORT]:40,[C.SHORT]:100,[C.MEDIUM]:200,[C.LONG]:300,[C.VERY_LONG]:1e3,[C.DEEP]:5e3},Bt=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 O(r){return r?Yt[r]??Bt:Bt}var vo="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",Mo=`You are a skilled summarizing assistant.
1
+ "use strict";var AITuberOnAirChat=(()=>{var yt=Object.defineProperty;var ho=Object.getOwnPropertyDescriptor;var mo=Object.getOwnPropertyNames;var go=Object.prototype.hasOwnProperty;var _o=(r,e)=>{for(var t in e)yt(r,t,{get:e[t],enumerable:!0})},fo=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of mo(e))!go.call(r,s)&&s!==t&&yt(r,s,{get:()=>e[s],enumerable:!(o=ho(e,s))||o.enumerable});return r};var vo=r=>fo(yt({},"__esModule",{value:!0}),r);var Ho={};_o(Ho,{CHAT_RESPONSE_LENGTH:()=>C,CLAUDE_VISION_SUPPORTED_MODELS:()=>Le,ChatServiceFactory:()=>Ce,ChatServiceHttpClient:()=>_,ClaudeChatService:()=>ne,ClaudeChatServiceProvider:()=>ae,DEFAULT_MAX_TOKENS:()=>jt,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>So,DEFAULT_VISION_PROMPT:()=>Co,EMOTION_TAG_CLEANUP_REGEX:()=>Xt,EMOTION_TAG_REGEX:()=>so,ENDPOINT_CLAUDE_API:()=>Nt,ENDPOINT_GEMINI_API:()=>Dt,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>se,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>J,ENDPOINT_OPENAI_RESPONSES_API:()=>x,ENDPOINT_OPENROUTER_API:()=>Pe,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>Ie,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>xe,EmotionParser:()=>re,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>zt,GEMINI_VISION_SUPPORTED_MODELS:()=>Te,GPT5_PRESETS:()=>qt,GPT_5_MODELS:()=>Zt,GeminiChatService:()=>le,GeminiChatServiceProvider:()=>pe,GeminiNanoChatService:()=>ce,GeminiNanoChatServiceProvider:()=>ue,HttpError:()=>G,KIMI_VISION_SUPPORTED_MODELS:()=>to,KimiChatService:()=>he,KimiChatServiceProvider:()=>de,MAX_TOKENS_BY_LENGTH:()=>oo,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>wt,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>ut,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>ht,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>pt,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>ct,MODEL_CLAUDE_3_5_HAIKU:()=>$e,MODEL_CLAUDE_3_5_SONNET:()=>je,MODEL_CLAUDE_3_7_SONNET:()=>qe,MODEL_CLAUDE_3_HAIKU:()=>I,MODEL_CLAUDE_4_5_HAIKU:()=>Ze,MODEL_CLAUDE_4_5_OPUS:()=>Ye,MODEL_CLAUDE_4_5_SONNET:()=>Je,MODEL_CLAUDE_4_6_OPUS:()=>et,MODEL_CLAUDE_4_6_SONNET:()=>Qe,MODEL_CLAUDE_4_OPUS:()=>Xe,MODEL_CLAUDE_4_SONNET:()=>ze,MODEL_GEMINI_2_0_FLASH:()=>Ke,MODEL_GEMINI_2_0_FLASH_LITE:()=>V,MODEL_GEMINI_2_5_FLASH:()=>He,MODEL_GEMINI_2_5_FLASH_LITE:()=>We,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>Be,MODEL_GEMINI_2_5_PRO:()=>Ue,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>ke,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>Ve,MODEL_GEMINI_3_FLASH_PREVIEW:()=>Fe,MODEL_GEMINI_3_PRO_PREVIEW:()=>Ge,MODEL_GEMINI_NANO:()=>z,MODEL_GLM_4_6:()=>Kt,MODEL_GLM_4_6V:()=>ft,MODEL_GLM_4_6V_FLASH:()=>q,MODEL_GLM_4_6V_FLASHX:()=>vt,MODEL_GLM_4_7:()=>ee,MODEL_GLM_4_7_FLASH:()=>Bt,MODEL_GLM_4_7_FLASHX:()=>Wt,MODEL_GLM_5:()=>Ut,MODEL_GLM_5_TURBO:()=>Ht,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>mt,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>gt,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>dt,MODEL_GPT_4O:()=>we,MODEL_GPT_4O_MINI:()=>K,MODEL_GPT_4_1:()=>Ae,MODEL_GPT_4_1_MINI:()=>De,MODEL_GPT_4_1_NANO:()=>Ne,MODEL_GPT_5:()=>Y,MODEL_GPT_5_1:()=>H,MODEL_GPT_5_4:()=>N,MODEL_GPT_5_4_MINI:()=>W,MODEL_GPT_5_4_NANO:()=>B,MODEL_GPT_5_4_PRO:()=>w,MODEL_GPT_5_MINI:()=>Z,MODEL_GPT_5_NANO:()=>U,MODEL_GPT_OSS_20B_FREE:()=>k,MODEL_GROK_4_1_FAST_NON_REASONING:()=>b,MODEL_GROK_4_1_FAST_REASONING:()=>Et,MODEL_GROK_4_20_NON_REASONING:()=>Ot,MODEL_GROK_4_20_REASONING:()=>Mt,MODEL_KIMI_K2_5:()=>A,MODEL_MOONSHOTAI_KIMI_K2_5:()=>tt,MODEL_O1:()=>Pt,MODEL_O1_MINI:()=>Lt,MODEL_O3_MINI:()=>Tt,MODEL_OPENAI_GPT_4O:()=>nt,MODEL_OPENAI_GPT_4_1_MINI:()=>at,MODEL_OPENAI_GPT_4_1_NANO:()=>lt,MODEL_OPENAI_GPT_5_1_CHAT:()=>ot,MODEL_OPENAI_GPT_5_1_CODEX:()=>st,MODEL_OPENAI_GPT_5_MINI:()=>it,MODEL_OPENAI_GPT_5_NANO:()=>rt,MODEL_ZAI_GLM_4_5_AIR:()=>kt,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>_t,MODEL_ZAI_GLM_4_7_FLASH:()=>Vt,OPENROUTER_CREDITS_THRESHOLD:()=>Eo,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>Oo,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>Mo,OPENROUTER_FREE_MODELS:()=>Gt,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>Ft,OPENROUTER_VISION_SUPPORTED_MODELS:()=>Yt,OpenAIChatService:()=>F,OpenAIChatServiceProvider:()=>ge,OpenAICompatibleChatServiceProvider:()=>me,OpenRouterChatService:()=>_e,OpenRouterChatServiceProvider:()=>fe,StreamTextAccumulator:()=>v,VISION_SUPPORTED_MODELS:()=>ye,XAIChatService:()=>ve,XAIChatServiceProvider:()=>Me,XAI_VISION_SUPPORTED_MODELS:()=>eo,ZAIChatService:()=>Oe,ZAIChatServiceProvider:()=>Ee,ZAI_VISION_SUPPORTED_MODELS:()=>Qt,allowsReasoningLow:()=>At,allowsReasoningMinimal:()=>bt,allowsReasoningNone:()=>Rt,allowsReasoningXHigh:()=>It,buildOpenAICompatibleTools:()=>P,getDefaultReasoningEffortForGPT5Model:()=>R,getMaxTokensForResponseLength:()=>O,installGASFetch:()=>co,isGPT5Model:()=>$,isKimiVisionModel:()=>ie,isOpenRouterFreeModel:()=>j,isOpenRouterVisionModel:()=>Q,isResponsesOnlyGPT5Model:()=>xt,isXaiVisionModel:()=>oe,isZaiToolStreamModel:()=>$t,isZaiVisionModel:()=>te,parseOpenAICompatibleOneShot:()=>L,parseOpenAICompatibleTextStream:()=>y,parseOpenAICompatibleToolStream:()=>T,processChatWithOptionalTools:()=>f,refreshOpenRouterFreeModels:()=>ko,resolveVisionModel:()=>E,runOnceText:()=>Po,screenplayToText:()=>Lo,textToScreenplay:()=>io,textsToScreenplay:()=>To});var J="https://api.openai.com/v1/chat/completions",x="https://api.openai.com/v1/responses",U="gpt-5-nano",Z="gpt-5-mini",Y="gpt-5",H="gpt-5.1",N="gpt-5.4",W="gpt-5.4-mini",B="gpt-5.4-nano",w="gpt-5.4-pro",Ae="gpt-4.1",De="gpt-4.1-mini",Ne="gpt-4.1-nano",K="gpt-4o-mini",we="gpt-4o",Tt="o3-mini",Lt="o1-mini",Pt="o1",ye=[U,Z,Y,H,N,W,B,w,Ae,De,Ne,K,we,"o1"],Zt=[U,Z,Y,H,N,W,B,w];function $(r){return Zt.includes(r)}function xt(r){return r===w}function It(r){return r===N||r===W||r===B||r===w}function Rt(r){return r===H||r===N||r===W||r===B}function bt(r){return r===U||r===Z||r===Y}function At(r){return r!==w}function R(r){return r===H||r===N?"none":"medium"}var Dt="https://generativelanguage.googleapis.com",Ve="gemini-3.1-pro-preview",ke="gemini-3.1-flash-lite-preview",Ge="gemini-3-pro-preview",Fe="gemini-3-flash-preview",Ue="gemini-2.5-pro",He="gemini-2.5-flash",We="gemini-2.5-flash-lite",Be="gemini-2.5-flash-lite-preview-06-17",Ke="gemini-2.0-flash",V="gemini-2.0-flash-lite",Te=[Ve,ke,Ge,Fe,Ue,He,We,Be,Ke,V];var Nt="https://api.anthropic.com/v1/messages",I="claude-3-haiku-20240307",$e="claude-3-5-haiku-20241022",je="claude-3-5-sonnet-20241022",qe="claude-3-7-sonnet-20250219",ze="claude-4-sonnet-20250514",Xe="claude-4-opus-20250514",Je="claude-sonnet-4-5-20250929",Ze="claude-haiku-4-5-20251001",Ye="claude-opus-4-5-20251101",Qe="claude-sonnet-4-6",et="claude-opus-4-6",Le=[I,$e,je,qe,ze,Xe,Je,Ze,Ye,Qe,et];var Pe="https://openrouter.ai/api/v1/chat/completions",k="openai/gpt-oss-20b:free",tt="moonshotai/kimi-k2.5",ot="openai/gpt-5.1-chat",st="openai/gpt-5.1-codex",it="openai/gpt-5-mini",rt="openai/gpt-5-nano",nt="openai/gpt-4o",at="openai/gpt-4.1-mini",lt="openai/gpt-4.1-nano",pt="anthropic/claude-opus-4",ct="anthropic/claude-sonnet-4",ut="anthropic/claude-3.7-sonnet",wt="anthropic/claude-3.5-sonnet",ht="anthropic/claude-haiku-4.5",dt="google/gemini-2.5-pro",mt="google/gemini-2.5-flash",gt="google/gemini-2.5-flash-lite-preview-09-2025",Vt="z-ai/glm-4.7-flash",kt="z-ai/glm-4.5-air",_t="z-ai/glm-4.5-air:free",Gt=[k,_t],Yt=[ot,st,it,rt,nt,at,lt,pt,ct,ut,ht,dt,mt,gt,tt],Ft=20,Mo=50,Oo=1e3,Eo=10;function j(r){return r.trim().endsWith(":free")}function Q(r){return Yt.some(e=>r.includes(e))}var xe="https://api.z.ai/api/paas/v4/chat/completions",Ut="glm-5",Ht="glm-5-turbo",ee="glm-4.7",Wt="glm-4.7-FlashX",Bt="glm-4.7-Flash",Kt="glm-4.6",ft="glm-4.6V",vt="glm-4.6V-FlashX",q="glm-4.6V-Flash",Qt=[ft,vt,q];function te(r){return Qt.includes(r)}function $t(r){return r.toLowerCase().startsWith("glm-4.6")}var Ie="https://api.x.ai/v1/chat/completions",Mt="grok-4.20-0309-reasoning",Ot="grok-4.20-0309-non-reasoning",Et="grok-4-1-fast-reasoning",b="grok-4-1-fast-non-reasoning",eo=[Mt,Ot,Et,b];function oe(r){return eo.includes(r)}var se="https://api.moonshot.ai/v1/chat/completions",A="kimi-k2.5",to=[A];function ie(r){return to.includes(r)}var C={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},oo={[C.VERY_SHORT]:40,[C.SHORT]:100,[C.MEDIUM]:200,[C.LONG]:300,[C.VERY_LONG]:1e3,[C.DEEP]:5e3},jt=5e3,qt={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(r){return r?oo[r]??jt:jt}var Co="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",So=`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,13 @@ Analyze the following conversation and produce a summary in the **same language*
7
7
  If the conversation is in Japanese, summarize in Japanese.
8
8
  If it's in English, summarize in English.
9
9
  If it's in another language, summarize in that language.
10
- `;var G=class extends Error{constructor(t,o,s){super(`HTTP ${t}: ${o}`);this.status=t;this.statusText=o;this.body=s;this.name="HttpError"}},Le=class Le{static setFetch(e){this.fetchImpl=e}static async post(e,t,o={},s={}){let{timeout:i=3e4,retries:n=0,retryDelay:a=1e3}=s,h={...{"Content-Type":"application/json"},...o},u=null;for(let c=0;c<=n;c++)try{let d=typeof AbortController<"u",l=d?new AbortController:void 0,_=d?setTimeout(()=>l.abort(),i):void 0,M=await Le.fetchImpl(e,{method:"POST",headers:h,body:typeof t=="string"?t:JSON.stringify(t),...l?{signal:l.signal}:{}});if(_&&clearTimeout(_),!M.ok){let m=await M.text();throw new G(M.status,M.statusText,m)}return M}catch(d){if(u=d,d instanceof G&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError")throw new Error(`Request timeout after ${i}ms`);c<n&&await new Promise(l=>setTimeout(l,a*(c+1)))}throw u||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:i=0,retryDelay:n=1e3}=o,a=null;for(let p=0;p<=i;p++)try{let h=typeof AbortController<"u",u=h?new AbortController:void 0,c=h?setTimeout(()=>u.abort(),s):void 0,d=await Le.fetchImpl(e,{method:"GET",headers:t,...u?{signal:u.signal}:{}});if(c&&clearTimeout(c),!d.ok){let l=await d.text();throw new G(d.status,d.statusText,l)}return d}catch(h){if(a=h,h instanceof G&&h.status>=400&&h.status<500)throw h;if(h instanceof Error&&h.name==="AbortError")throw new Error(`Request timeout after ${s}ms`);p<i&&await new Promise(u=>setTimeout(u,n*(p+1)))}throw a||new Error("Request failed")}};Le.fetchImpl=(e,t)=>fetch(e,t);var g=Le;var v=class{static append(e,t){if(!t)return;let o=e[e.length-1];o&&o.type==="text"?o.text+=t:e.push({type:"text",text:t})}static getFullText(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}static addTextBlock(e,t){t&&e.push({type:"text",text:t})}};var Oo=["happy","sad","angry","surprised","neutral"],Qt=/\[([a-z]+)\]/i,$t=/\[[a-z]+\]\s*/gi,ie=class{static extractEmotion(e){let t=e.match(Qt);if(t){let o=t[1].toLowerCase(),s=e.replace($t,"").trim();return{emotion:o,cleanText:s}}return{cleanText:e}}static isValidEmotion(e){return Oo.includes(e)}static cleanEmotionTags(e){return e.replace($t,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function eo(r){let{emotion:e,cleanText:t}=ie.extractEmotion(r);return e?{emotion:e,text:t}:{text:t}}function Eo(r){return r.map(e=>eo(e))}function Co(r){return r.emotion?ie.addEmotionTag(r.emotion,r.text):r.text}async function So(r,e){let{blocks:t}=await r.chatOnce(e,!1,()=>{});return v.getFullText(t)}var to=(r,e)=>{try{return JSON.parse(r)}catch(t){if(e){e(r,t);return}throw t}},oo=async(r,e)=>{let t=r.body?.getReader();if(!t)throw new Error("Response body is null.");let o=new TextDecoder,s="",i=!1;for(;!i;){let{done:n,value:a}=await t.read();if(n)break;s+=o.decode(a,{stream:!0});let p=s.split(`
11
- `);s=p.pop()||"";for(let h of p){let u=h.trim();if(!u||u.startsWith(":")||!u.startsWith("data:"))continue;let c=u.slice(5).trim();if(c==="[DONE]"){i=!0;break}e(c)}}};async function T(r,e,t={}){let o="";return await oo(r,s=>{let i=to(s,t.onJsonError);if(!i)return;let n=i.choices?.[0]?.delta?.content||"";n&&(e(n),o+=n)}),o}async function y(r,e,t={}){let o=[],s=new Map,i,n,a=t.appendTextBlock??v.append;await oo(r,u=>{let c=to(u,t.onJsonError);if(!c)return;let d=c.choices?.[0];typeof d?.finish_reason=="string"&&(i=d.finish_reason),c.usage&&(n=c.usage);let l=d?.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((u,c)=>u[0]-c[0]).map(([u,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:i==="length",finish_reason:i,usage:n}}function P(r){let e=r?.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:r?.usage}}var L=(r,e="chat-completions")=>r.length===0?[]:e==="responses"?r.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):r.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function f(r){if(!r.hasTools){let t=await r.runWithoutTools();await r.onCompleteResponse(t);return}let e=await r.runWithTools();if(r.onToolBlocks&&r.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=v.getFullText(e.blocks);await r.onCompleteResponse(t);return}throw new Error(r.toolErrorMessage)}var E=r=>{let e=r.model??r.defaultModel,t=r.visionModel??(r.supportsVisionForModel(e)?e:r.defaultVisionModel);if(r.validate==="explicit"&&r.visionModel&&!r.supportsVisionForModel(r.visionModel))throw new Error(`Model ${r.visionModel} does not support vision capabilities.`);if(r.validate==="resolved"&&!r.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var To="https://openrouter.ai/api/v1/models",yo=2,Po=12e3,Lo=1,xo=10;function jt(r){return r instanceof Error?r.message:String(r)}function Mt(r,e){return typeof r!="number"||!Number.isFinite(r)?e:Math.max(1,Math.floor(r))}function Io(r){let e=new Set,t=[];for(let o of r){let s=o.trim();!s||e.has(s)||(e.add(s),t.push(s))}return t}async function so(r,e,t){if(!(typeof AbortController<"u"))return fetch(r,e);let s=new AbortController,i=setTimeout(()=>s.abort(),t);try{return await fetch(r,{...e,signal:s.signal})}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Timeout after ${t}ms`):n}finally{clearTimeout(i)}}async function io(r){let e=`HTTP ${r.status} ${r.statusText}`.trim(),t="";try{t=await r.text()}catch{return e}let o=t.replace(/\s+/g," ").trim().slice(0,200);return o?`${e}: ${o}`:e}function Ro(r){if(!r||typeof r!="object")throw new Error("Invalid models response shape");let e=r,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 Io(o)}async function bo({modelId:r,apiKey:e,endpoint:t,timeoutMs:o,appName:s,appUrl:i}){let n={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};s&&(n["X-Title"]=s),i&&(n["HTTP-Referer"]=i);try{let a=await so(t,{method:"POST",headers:n,body:JSON.stringify({model:r,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},o);if(!a.ok)return{id:r,ok:!1,reason:await io(a)};try{await a.json()}catch(p){return{id:r,ok:!1,reason:`JSON parse failed: ${jt(p)}`}}return{id:r,ok:!0}}catch(a){return{id:r,ok:!1,reason:jt(a)}}}async function Do(r,e,t){if(r.length===0)return[];let o=new Array(r.length),s=0,i=Math.min(e,r.length);return await Promise.all(Array.from({length:i},async()=>{for(;s<r.length;){let n=s;s+=1,o[n]=await t(r[n])}})),o}async function Ao(r){let e=r.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=r.modelsEndpoint||To,o=r.endpoint||Te,s=Mt(r.timeoutMs,Po),i=Mt(r.concurrency,yo),n=Mt(r.maxCandidates,Lo),a=Mt(r.maxWorking,xo),p=await so(t,{method:"GET"},s);if(!p.ok)throw new Error(await io(p));let h;try{h=await p.json()}catch(_){throw new Error(`JSON parse failed: ${jt(_)}`)}let u=Ro(h).filter(_=>j(_)).slice(0,n),c=await Do(u,i,_=>bo({modelId:_,apiKey:e,endpoint:o,timeoutMs:s,appName:r.appName,appUrl:r.appUrl})),d=c.filter(_=>_.ok).map(_=>_.id).slice(0,a),l=c.filter(_=>!_.ok).map(_=>({id:_.id,reason:_.reason||"Unknown error"}));return{working:d,failed:l,fetchedAt:Date.now()}}var re=class{constructor(e,t=I,o=I,s=[],i=[],n){this.provider="claude";if(this.apiKey=e,this.model=t||I,this.visionModel=o||I,this.tools=s,this.mcpServers=i,this.responseLength=n,!Se.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 f({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 f({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 i=s.image_url.url.match(/^data:([^;]+);base64,(.+)$/);return i?{type:"image",source:{type:"base64",media_type:i[1],data:i[2]}}:null}return{type:"image",source:{type:"url",url: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 i=e.find(c=>c.role==="system")?.content??"",n=e.filter(c=>c.role!=="system"),a=n.some(c=>Array.isArray(c.content)&&c.content.some(d=>d.type==="image_url"||d.type==="image")),p={model:t,system:i,messages:a?this.convertVisionMessagesToClaudeFormat(n):this.convertMessagesToClaudeFormat(n),stream:o,max_tokens:s!==void 0?s:O(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 h={"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&&(h["anthropic-beta"]="mcp-client-2025-04-04"),await g.post(bt,p,h)}async parseStream(e,t){let o=e.body.getReader(),s=new TextDecoder,i=[],n=new Map,a="";for(;;){let{done:p,value:h}=await o.read();if(p)break;a+=s.decode(h,{stream:!0});let u;for(;(u=a.indexOf(`
12
- `))!==-1;){let c=a.slice(0,u).trim();if(a=a.slice(u+1),!c.startsWith("data:"))continue;let d=c.slice(5).trim();if(d==="[DONE]")break;let l=JSON.parse(d);if(l.type==="content_block_delta"&&l.delta?.text&&(t(l.delta.text),i.push({type:"text",text:l.delta.text})),l.type==="content_block_start"&&l.content_block?.type==="tool_use"?n.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"?n.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"?i.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"&&i.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 _=n.get(l.index);_&&(_.args+=l.delta.partial_json||"")}if(l.type==="content_block_stop"&&n.has(l.index)){let{id:_,name:M,args:m,server_name:S}=n.get(l.index);S?i.push({type:"mcp_tool_use",id:_,name:M,server_name:S,input:JSON.parse(m||"{}")}):i.push({type:"tool_use",id:_,name:M,input:JSON.parse(m||"{}")}),n.delete(l.index)}}}return{blocks:i,stop_reason:i.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 i=await this.callClaude(e,this.model,t,s),n=t?await this.parseStream(i,o):this.parseOneShot(await i.json());return this.convertToStandardCompletion(n)}async visionChatOnce(e,t=!1,o=()=>{},s){let i=await this.callClaude(e,this.visionModel,t,s),n=t?await this.parseStream(i,o):this.parseOneShot(await i.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 ne=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"claude"}getSupportedModels(){return[I,We,Be,Ke,$e,je,ze,qe,Je,Xe,Ze]}getDefaultModel(){return I}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Se.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Ot=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(i=>({name:`mcp_${e.name}_${i.name}`,description:i.description||`Tool from ${e.name} MCP server`,parameters:i.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 ae=class{constructor(e,t=V,o=V,s=[],i=[],n){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=n,!Ce.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=s,this.mcpServers=i}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=Ot.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 f({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callGemini(e,this.model,!0),{blocks:i}=await this.parseStream(s,t);return v.getFullText(i)},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 f({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callGemini(e,this.visionModel,!0),{blocks:i}=await this.parseStream(s,t);return v.getFullText(i)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:s=>{s.filter(i=>i.type==="text").forEach(i=>t(i.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=[],i=()=>{o&&s.length&&(t.push({role:o,parts:[...s]}),s=[])};for(let n of e){let a=this.mapRoleToGemini(n.role);if(n.tool_calls){i();for(let p of n.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(n.role==="tool"){i();let p=n.name??this.callIdMap.get(n.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:p,response:this.normalizeToolResult(this.safeJsonParse(n.content))}}]});continue}a!==o&&i(),o=a,s.push({text:n.content})}return i(),t}async callGemini(e,t,o=!1,s){let a={contents:e.some(m=>Array.isArray(m.content)&&m.content.some(S=>S?.type==="image_url"||S?.inlineData))?await this.convertVisionMessagesToGeminiFormat(e):this.convertMessagesToGeminiFormat(e),generationConfig:{maxOutputTokens:s!==void 0?s:O(this.responseLength)}},p=[];if(this.tools.length>0&&p.push(...this.tools.map(m=>({name:m.name,description:m.description,parameters:m.parameters}))),this.mcpServers.length>0)try{await this.initializeMCPSchemas(),p.push(...this.mcpToolSchemas.map(m=>({name:m.name,description:m.description,parameters:m.parameters})))}catch(m){console.warn("MCP initialization failed, skipping MCP tools:",m)}p.length>0&&(a.tools=[{functionDeclarations:p}],a.toolConfig={functionCallingConfig:{mode:"AUTO"}});let h=async(m,S)=>{let Oe=o?"streamGenerateContent":"generateContent",A=o?"?alt=sse":"",xe=`${Rt}/${m}/models/${t}:${Oe}${A}${A?"&":"?"}key=${this.apiKey}`;return g.post(xe,S)},u=/flash[-_]lite/.test(t),c=/gemini-2\.5/.test(t),d=/^gemini-3(?:\.[0-9]+)?-.*preview/.test(t),l=u||c||d,_=l?"v1beta":"v1",M=async()=>{try{let m=_==="v1"?a:this.adaptKeysForApi(a);return await h(_,m)}catch(m){let S=/Unknown name|Cannot find field|404/.test(m?.message||"")||m?.status===404;if(!l&&S)return await h("v1beta",this.adaptKeysForApi(a));throw m}};try{return await M()}catch(m){throw m.body&&(console.error("Gemini API Error Details:",m.body),console.error("Request Body:",JSON.stringify(a,null,2))),m}}async convertVisionMessagesToGeminiFormat(e){let t=[],o=null,s=[];for(let i of e){let n=this.mapRoleToGemini(i.role);if(i.tool_calls){for(let a of i.tool_calls)t.push({role:"model",parts:[{functionCall:{name:a.function.name,args:JSON.parse(a.function.arguments||"{}")}}]});continue}if(i.role==="tool"){let a=i.name??this.callIdMap.get(i.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:a,response:this.normalizeToolResult(this.safeJsonParse(i.content))}}]});continue}if(n!==o&&s.length>0&&(t.push({role:o,parts:[...s]}),s=[]),o=n,typeof i.content=="string")s.push({text:i.content});else if(Array.isArray(i.content)){for(let a of i.content)if(a.type==="text")s.push({text:a.text});else if(a.type==="image_url")try{let h=await(await g.get(a.image_url.url)).blob(),u=await this.blobToBase64(h);s.push({inlineData:{mimeType:h.type||"image/jpeg",data:u.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,i=[],n=[],a="",p=u=>{if(!u||u==="[DONE]")return;let c;try{c=JSON.parse(u)}catch{return}for(let d of c.candidates??[])for(let l of d.content?.parts??[])l.text&&(t(l.text),v.addTextBlock(i,l.text)),l.functionCall&&n.push({type:"tool_use",id:this.genUUID(),name:l.functionCall.name,input:l.functionCall.args??{}}),l.functionResponse&&n.push({type:"tool_result",tool_use_id:l.functionResponse.name,content:JSON.stringify(l.functionResponse.response)})};for(;;){let{done:u,value:c}=await o.read();if(u)break;a+=s.decode(c,{stream:!0});let d;for(;(d=a.indexOf(`
13
- `))!==-1;){let l=a.slice(0,d);if(a=a.slice(d+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:[...i,...n],stop_reason:n.some(u=>u.type==="tool_use")?"tool_use":"end"}}parseOneShot(e){let t=[],o=[];for(let i of e.candidates??[])for(let n of i.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(i=>i.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},s){let i=await this.callGemini(e,this.model,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.json())}async visionChatOnce(e,t=!1,o=()=>{},s){let i=await this.callGemini(e,this.visionModel,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.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 le=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 ae(e.apiKey,e.model||this.getDefaultModel(),t,e.tools||[],e.mcpServers||[],e.responseLength)}getProviderName(){return"gemini"}getSupportedModels(){return[Ae,Ne,we,Ve,ke,Ge,Fe,Ue,He,V]}getDefaultModel(){return V}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ce.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var pe=class{constructor(e,t=D,o=D,s,i=oe,n,a,p){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.responseLength=n,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 f({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(!se(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await f({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 i=await this.callKimi(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){if(!se(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let i=await this.callKimi(e,this.visionModel,t,s);return this.parseResponse(i,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 i=this.buildRequestBody(e,t,o,s);return await g.post(this.endpoint,i,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let i={model:t,stream:o,messages:e},n=s!==void 0?s:O(this.responseLength);n!==void 0&&(i.max_tokens=n),this.responseFormat&&(i.response_format=this.responseFormat);let a=this.tools.length>0?{type:"disabled"}:this.thinking;a&&(this.isSelfHostedEndpoint()?a.type==="disabled"&&(i.chat_template_kwargs={thinking:!1}):i.thinking=a);let p=this.buildToolsDefinition();return p.length>0&&(i.tools=p,i.tool_choice="auto"),i}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(oe)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}buildToolsDefinition(){return L(this.tools,"chat-completions")}async handleStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return P(e)}};var ce=class{createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),s=E({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:p=>this.supportsVisionForModel(p),validate:"explicit"}),i=e.tools,n=e.thinking??{type:"enabled"},a=i&&i.length>0?{type:"disabled"}:n;return new pe(e.apiKey,o,s,i,t,e.responseLength,e.responseFormat,a)}getProviderName(){return"kimi"}getSupportedModels(){return[D]}getDefaultModel(){return D}getDefaultVisionModel(){return D}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return se(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}resolveEndpoint(e){if(e.endpoint)return this.normalizeEndpoint(e.endpoint);if(e.baseUrl){let t=this.normalizeEndpoint(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return oe}normalizeEndpoint(e){return e.replace(/\/+$/,"")}};var No={[C.VERY_SHORT]:800,[C.SHORT]:1200,[C.MEDIUM]:2e3,[C.LONG]:3e3,[C.VERY_LONG]:8e3,[C.DEEP]:25e3},wo={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3},F=class{constructor(e,t=K,o=K,s,i=J,n=[],a,p,h,u=!1,c="openai",d=!0){if(this.provider=c,this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.mcpServers=n,this.responseLength=a,this.verbosity=p,this.reasoning_effort=h,this.enableReasoningSummary=u,d&&!Ee.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 f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenAI(e,this.model,!0),i=this.endpoint===x;try{if(i){let n=await this.parseResponsesStream(s,t);return v.getFullText(n.blocks)}return this.handleStream(s,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 f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenAI(e,this.visionModel,!0),i=this.endpoint===x;try{if(i){let n=await this.parseResponsesStream(s,t);return v.getFullText(n.blocks)}return this.handleStream(s,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(s){throw console.error("Error in processVisionChat:",s),s}}async chatOnce(e,t=!0,o=()=>{},s){let i=await this.callOpenAI(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){let i=await this.callOpenAI(e,this.visionModel,t,s);return this.parseResponse(i,t,o)}async parseResponse(e,t,o){return this.endpoint===x?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 i=this.buildRequestBody(e,t,o,s),n={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(n.Authorization=`Bearer ${this.apiKey}`),await g.post(this.endpoint,i,n)}buildRequestBody(e,t,o,s){let i=this.endpoint===x;this.validateMCPCompatibility();let n={model:t,stream:o},a=this.resolveTokenLimit(t,s);i?a!==void 0&&(n.max_output_tokens=a):a!==void 0&&(this.provider==="openai-compatible"?n.max_tokens=a:n.max_completion_tokens=a),i?n.input=this.cleanMessagesForResponsesAPI(e):n.messages=e,$(t)&&(i?(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 p=this.buildToolsDefinition();return p.length>0&&(n.tools=p,i||(n.tool_choice="auto")),n}resolveTokenLimit(e,t){if(t!==void 0)return t;let o=this.provider==="openai-compatible"?this.responseLength!==void 0?O(this.responseLength):void 0:O(this.responseLength);if(this.provider!=="openai"||!$(e)||this.responseLength===void 0)return o;let s=this.reasoning_effort??R(e);return Math.max(o??0,No[this.responseLength],wo[s])}validateMCPCompatibility(){if(this.mcpServers.length>0&&this.endpoint===J)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${this.endpoint}. Please use OpenAI Responses API endpoint: ${x}. 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(i=>i.type==="text"?{type:"input_text",text:i.text}:i.type==="image_url"?{type:"input_image",image_url:i.image_url.url}:i):s.content=t.content,s})}buildToolsDefinition(){let e=this.endpoint===x,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 T(e,t)}async parseStream(e,t){return y(e,t,{appendTextBlock:v.addTextBlock})}parseOneShot(e){return P(e)}async parseResponsesStream(e,t){let o=e.body.getReader(),s=new TextDecoder,i=[],n=new Map,a,p,h,u="";for(;;){let{done:l,value:_}=await o.read();if(l)break;u+=s.decode(_,{stream:!0});let M="",m="",S=u.split(`
14
- `);u=S.pop()||"";for(let Oe=0;Oe<S.length;Oe++){let A=S[Oe].trim();if(A.startsWith("event:"))M=A.slice(6).trim();else if(A.startsWith("data:"))m=A.slice(5).trim();else if(A===""&&M&&m){try{let xe=JSON.parse(m),ao=this.handleResponsesSSEEvent(M,xe,t,i,n,q=>{q.responseStatus!==void 0&&(a=q.responseStatus),q.incompleteDetails!==void 0&&(p=q.incompleteDetails),q.usage!==void 0&&(h=q.usage)})}catch{console.warn("Failed to parse SSE data:",m)}M="",m=""}}}let c=Array.from(n.values()).map(l=>({type:"tool_use",id:l.id,name:l.name,input:l.input||{}}));return{blocks:[...i,...c],stop_reason:c.length?"tool_use":"end",truncated:a==="incomplete",response_status:a,incomplete_details:p,usage:h}}handleResponsesSSEEvent(e,t,o,s,i,n){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),v.append(s,a.text))}):t.item?.type==="function_call"&&i.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),v.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),v.append(s,a))}break;case"response.output_text.done":case"response.content_part.done":break;case"response.completed":return n(this.extractResponsesMetadata(t,"completed")),"completed";case"response.incomplete":return n(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 ue=class{createChatService(e){return this.validateRequiredOptions(e),new F(e.apiKey?.trim()??"",e.model,e.visionModel??e.model,e.tools,e.endpoint,[],e.responseLength,e.verbosity,e.reasoning_effort,e.enableReasoningSummary,this.getProviderName(),!1)}getProviderName(){return"openai-compatible"}getSupportedModels(){return[]}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"unknown"}supportsVisionForModel(e){return!0}getVisionSupportLevelForModel(e){return"unknown"}getDefaultModel(){return"local-model"}validateRequiredOptions(e){if(e.mcpServers!==void 0)throw new Error("openai-compatible provider does not support mcpServers.");let t=e.endpoint?.trim();if(!t)throw new Error("openai-compatible provider requires endpoint (full URL).");let o;try{o=new URL(t)}catch{throw new Error("openai-compatible provider requires endpoint to be a full URL.")}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error("openai-compatible provider requires endpoint to be a full URL.");if(!e.model?.trim())throw new Error("openai-compatible provider requires model.")}};var he=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=E({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:h=>this.supportsVisionForModel(h),validate:"resolved"}),s=t.tools,i=t.mcpServers??[],n=t.model||this.getDefaultModel(),a=!1;i.length>0||yt(n)?a=!0:$(n)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let p=t.endpoint||(a?x:J);return new F(t.apiKey,n,o,s,p,i,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName())}getProviderName(){return"openai"}getSupportedModels(){return[U,X,Z,H,N,W,B,w,Ie,Re,be,K,De,Ct,St,"o1"]}getDefaultModel(){return U}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ee.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!$(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=R(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!Lt(e)?R(e):t==="minimal"&&!xt(e)?R(e):t==="low"&&!It(e)?R(e):t==="xhigh"&&!Pt(e)?R(e):t}};var de=class{constructor(e,t=k,o=k,s,i=Te,n,a,p,h,u,c){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.responseLength=n,this.appName=a,this.appUrl=p,this.reasoning_effort=h,this.includeReasoning=u,this.reasoningMaxTokens=c,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!j(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=Vt){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 f({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(!Y(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await f({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 i=await this.callOpenRouter(e,this.model,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.json())}async visionChatOnce(e,t=!1,o=()=>{},s){if(!Y(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let i=await this.callOpenRouter(e,this.visionModel,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.json())}async callOpenRouter(e,t,o=!1,s){let i=this.buildRequestBody(e,t,o,s),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,i,n)}buildRequestBody(e,t,o,s){let i={model:t,messages:e,stream:o};if((s!==void 0?s: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(i.reasoning={},this.reasoning_effort&&this.reasoning_effort!=="none"){let a=this.reasoning_effort==="minimal"?"low":this.reasoning_effort;i.reasoning.effort=a}(this.reasoning_effort==="none"||this.includeReasoning!==!0)&&(i.reasoning.exclude=!0),this.reasoningMaxTokens&&(i.reasoning.max_tokens=this.reasoningMaxTokens)}else i.reasoning={exclude:!0};return this.tools.length>0&&(i.tools=L(this.tools,"chat-completions"),i.tool_choice="auto"),i}async handleStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return P(e)}};var me=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,s=e.appName,i=e.appUrl;return new de(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,s,i,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[k,dt,Qe,et,tt,ot,st,it,rt,nt,at,lt,Dt,pt,ct,ut,ht,At,Nt,Ye]}getDefaultModel(){return k}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return Y(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return wt}isModelFree(e){return j(e)}};var _e=class{constructor(e,t=b,o=b,s,i=Pe,n){this.provider="xai";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.responseLength=n,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callXAI(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 f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callXAI(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 i=await this.callXAI(e,this.model,t,s);return this.parseResponse(i,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 i=await this.callXAI(e,this.visionModel,t,s);return this.parseResponse(i,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callXAI(e,t,o=!1,s){let i=this.buildRequestBody(e,t,o,s);return await g.post(this.endpoint,i,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let i={model:t,stream:o,messages:e},n=s!==void 0?s:O(this.responseLength);n!==void 0&&(i.max_tokens=n);let a=this.buildToolsDefinition();return a.length>0&&(i.tools=a,i.tool_choice="auto"),i}buildToolsDefinition(){return L(this.tools,"chat-completions")}async handleStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return P(e)}};var ge=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"explicit"}),s=e.tools;return new _e(e.apiKey,t,o,s,e.endpoint||Pe,e.responseLength)}getProviderName(){return"xai"}getSupportedModels(){return[gt,ft,vt,b]}getDefaultModel(){return b}getDefaultVisionModel(){return b}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return te(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var fe=class{constructor(e,t=Q,o=z,s,i=ye,n,a,p){this.provider="zai";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.responseLength=n,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 f({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(!ee(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await f({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 i=await this.callZAI(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){if(!ee(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let i=await this.callZAI(e,this.visionModel,t,s);return this.parseResponse(i,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 i=this.buildRequestBody(e,t,o,s);return await g.post(this.endpoint,i,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let i={model:t,stream:o,messages:e},n=s!==void 0?s:O(this.responseLength);n!==void 0&&(i.max_tokens=n),this.responseFormat&&(i.response_format=this.responseFormat),this.thinking&&(i.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(i.tools=a,i.tool_choice="auto",o&&Wt(t)&&(i.tool_stream=!0)),i}buildToolsDefinition(){return L(this.tools,"chat-completions")}async handleStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return P(e)}};var ve=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"}),s=e.tools,i=e.thinking??{type:"disabled"};return new fe(e.apiKey,t,o,s,e.endpoint||ye,e.responseLength,e.responseFormat,i)}getProviderName(){return"zai"}getSupportedModels(){return[kt,Gt,Q,Ft,Ut,Ht,mt,_t,z]}getDefaultModel(){return Q}getDefaultVisionModel(){return z}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ee(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var ro=[new he,new ue,new le,new ne,new me,new ve,new ge,new ce];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():[]}static getVisionSupportLevel(e){let t=this.providers.get(e);return t?t.getVisionSupportLevel():"unsupported"}static getVisionSupportLevelForModel(e,t){let o=this.providers.get(e);return o?o.getVisionSupportLevelForModel?o.getVisionSupportLevelForModel(t):o.supportsVisionForModel?o.supportsVisionForModel(t)?"supported":"unsupported":o.getVisionSupportLevel():"unsupported"}};Me.providers=new Map;ro.forEach(r=>Me.registerProvider(r));function no(){g.setFetch(async(r,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,s={};if(Array.isArray(o))for(let[c,d]of o)s[c]=String(d);else if(o&&typeof o=="object")for(let[c,d]of Object.entries(o))s[c]=String(d);let i={method:t,headers:s,muteHttpExceptions:!0},n=e.body;typeof n=="string"?i.payload=n:n!=null&&(s["Content-Type"]||(s["Content-Type"]="application/json"),i.payload=JSON.stringify(n));let a=UrlFetchApp.fetch(r,i),p=a.getResponseCode(),h=a.getContentText();return{ok:p>=200&&p<300,status:p,statusText:String(p),text:async()=>h,json:async()=>h?JSON.parse(h):null}})}return mo(Vo);})();
10
+ `;var z="gemini-nano",zt=20;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"}},Re=class Re{static setFetch(e){this.fetchImpl=e}static async post(e,t,o={},s={}){let{timeout:i=3e4,retries:n=0,retryDelay:a=1e3}=s,u={...{"Content-Type":"application/json"},...o},h=null;for(let c=0;c<=n;c++)try{let d=typeof AbortController<"u",p=d?new AbortController:void 0,g=d?setTimeout(()=>p.abort(),i):void 0,M=await Re.fetchImpl(e,{method:"POST",headers:u,body:typeof t=="string"?t:JSON.stringify(t),...p?{signal:p.signal}:{}});if(g&&clearTimeout(g),!M.ok){let m=await M.text();throw new G(M.status,M.statusText,m)}return M}catch(d){if(h=d,d instanceof G&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError")throw new Error(`Request timeout after ${i}ms`);c<n&&await new Promise(p=>setTimeout(p,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:i=0,retryDelay:n=1e3}=o,a=null;for(let l=0;l<=i;l++)try{let u=typeof AbortController<"u",h=u?new AbortController:void 0,c=u?setTimeout(()=>h.abort(),s):void 0,d=await Re.fetchImpl(e,{method:"GET",headers:t,...h?{signal:h.signal}:{}});if(c&&clearTimeout(c),!d.ok){let p=await d.text();throw new G(d.status,d.statusText,p)}return d}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`);l<i&&await new Promise(h=>setTimeout(h,n*(l+1)))}throw a||new Error("Request failed")}};Re.fetchImpl=(e,t)=>fetch(e,t);var _=Re;var v=class{static append(e,t){if(!t)return;let o=e[e.length-1];o&&o.type==="text"?o.text+=t:e.push({type:"text",text:t})}static getFullText(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}static addTextBlock(e,t){t&&e.push({type:"text",text:t})}};var yo=["happy","sad","angry","surprised","neutral"],so=/\[([a-z]+)\]/i,Xt=/\[[a-z]+\]\s*/gi,re=class{static extractEmotion(e){let t=e.match(so);if(t){let o=t[1].toLowerCase(),s=e.replace(Xt,"").trim();return{emotion:o,cleanText:s}}return{cleanText:e}}static isValidEmotion(e){return yo.includes(e)}static cleanEmotionTags(e){return e.replace(Xt,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function io(r){let{emotion:e,cleanText:t}=re.extractEmotion(r);return e?{emotion:e,text:t}:{text:t}}function To(r){return r.map(e=>io(e))}function Lo(r){return r.emotion?re.addEmotionTag(r.emotion,r.text):r.text}async function Po(r,e){let{blocks:t}=await r.chatOnce(e,!1,()=>{});return v.getFullText(t)}var ro=(r,e)=>{try{return JSON.parse(r)}catch(t){if(e){e(r,t);return}throw t}},no=async(r,e)=>{let t=r.body?.getReader();if(!t)throw new Error("Response body is null.");let o=new TextDecoder,s="",i=!1;for(;!i;){let{done:n,value:a}=await t.read();if(n)break;s+=o.decode(a,{stream:!0});let l=s.split(`
11
+ `);s=l.pop()||"";for(let u of l){let h=u.trim();if(!h||h.startsWith(":")||!h.startsWith("data:"))continue;let c=h.slice(5).trim();if(c==="[DONE]"){i=!0;break}e(c)}}};async function y(r,e,t={}){let o="";return await no(r,s=>{let i=ro(s,t.onJsonError);if(!i)return;let n=i.choices?.[0]?.delta?.content||"";n&&(e(n),o+=n)}),o}async function T(r,e,t={}){let o=[],s=new Map,i,n,a=t.appendTextBlock??v.append;await no(r,h=>{let c=ro(h,t.onJsonError);if(!c)return;let d=c.choices?.[0];typeof d?.finish_reason=="string"&&(i=d.finish_reason),c.usage&&(n=c.usage);let p=d?.delta;p?.content&&(e(p.content),a(o,p.content)),p?.tool_calls&&p.tool_calls.forEach(g=>{let M=s.get(g.index)??{id:g.id,name:g.function?.name,args:""};M.args+=g.function?.arguments||"",s.set(g.index,M)})});let l=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,...l],stop_reason:l.length?"tool_use":"end",truncated:i==="length",finish_reason:i,usage:n}}function L(r){let e=r?.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:r?.usage}}var P=(r,e="chat-completions")=>r.length===0?[]:e==="responses"?r.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):r.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function f(r){if(!r.hasTools){let t=await r.runWithoutTools();await r.onCompleteResponse(t);return}let e=await r.runWithTools();if(r.onToolBlocks&&r.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=v.getFullText(e.blocks);await r.onCompleteResponse(t);return}throw new Error(r.toolErrorMessage)}var E=r=>{let e=r.model??r.defaultModel,t=r.visionModel??(r.supportsVisionForModel(e)?e:r.defaultVisionModel);if(r.validate==="explicit"&&r.visionModel&&!r.supportsVisionForModel(r.visionModel))throw new Error(`Model ${r.visionModel} does not support vision capabilities.`);if(r.validate==="resolved"&&!r.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var xo="https://openrouter.ai/api/v1/models",Io=2,Ro=12e3,bo=1,Ao=10;function Jt(r){return r instanceof Error?r.message:String(r)}function Ct(r,e){return typeof r!="number"||!Number.isFinite(r)?e:Math.max(1,Math.floor(r))}function Do(r){let e=new Set,t=[];for(let o of r){let s=o.trim();!s||e.has(s)||(e.add(s),t.push(s))}return t}async function ao(r,e,t){if(!(typeof AbortController<"u"))return fetch(r,e);let s=new AbortController,i=setTimeout(()=>s.abort(),t);try{return await fetch(r,{...e,signal:s.signal})}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Timeout after ${t}ms`):n}finally{clearTimeout(i)}}async function lo(r){let e=`HTTP ${r.status} ${r.statusText}`.trim(),t="";try{t=await r.text()}catch{return e}let o=t.replace(/\s+/g," ").trim().slice(0,200);return o?`${e}: ${o}`:e}function No(r){if(!r||typeof r!="object")throw new Error("Invalid models response shape");let e=r,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 Do(o)}async function wo({modelId:r,apiKey:e,endpoint:t,timeoutMs:o,appName:s,appUrl:i}){let n={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};s&&(n["X-Title"]=s),i&&(n["HTTP-Referer"]=i);try{let a=await ao(t,{method:"POST",headers:n,body:JSON.stringify({model:r,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},o);if(!a.ok)return{id:r,ok:!1,reason:await lo(a)};try{await a.json()}catch(l){return{id:r,ok:!1,reason:`JSON parse failed: ${Jt(l)}`}}return{id:r,ok:!0}}catch(a){return{id:r,ok:!1,reason:Jt(a)}}}async function Vo(r,e,t){if(r.length===0)return[];let o=new Array(r.length),s=0,i=Math.min(e,r.length);return await Promise.all(Array.from({length:i},async()=>{for(;s<r.length;){let n=s;s+=1,o[n]=await t(r[n])}})),o}async function ko(r){let e=r.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=r.modelsEndpoint||xo,o=r.endpoint||Pe,s=Ct(r.timeoutMs,Ro),i=Ct(r.concurrency,Io),n=Ct(r.maxCandidates,bo),a=Ct(r.maxWorking,Ao),l=await ao(t,{method:"GET"},s);if(!l.ok)throw new Error(await lo(l));let u;try{u=await l.json()}catch(g){throw new Error(`JSON parse failed: ${Jt(g)}`)}let h=No(u).filter(g=>j(g)).slice(0,n),c=await Vo(h,i,g=>wo({modelId:g,apiKey:e,endpoint:o,timeoutMs:s,appName:r.appName,appUrl:r.appUrl})),d=c.filter(g=>g.ok).map(g=>g.id).slice(0,a),p=c.filter(g=>!g.ok).map(g=>({id:g.id,reason:g.reason||"Unknown error"}));return{working:d,failed:p,fetchedAt:Date.now()}}var ne=class{constructor(e,t=I,o=I,s=[],i=[],n){this.provider="claude";if(this.apiKey=e,this.model=t||I,this.visionModel=o||I,this.tools=s,this.mcpServers=i,this.responseLength=n,!Le.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 f({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 f({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 i=s.image_url.url.match(/^data:([^;]+);base64,(.+)$/);return i?{type:"image",source:{type:"base64",media_type:i[1],data:i[2]}}:null}return{type:"image",source:{type:"url",url: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 i=e.find(c=>c.role==="system")?.content??"",n=e.filter(c=>c.role!=="system"),a=n.some(c=>Array.isArray(c.content)&&c.content.some(d=>d.type==="image_url"||d.type==="image")),l={model:t,system:i,messages:a?this.convertVisionMessagesToClaudeFormat(n):this.convertMessagesToClaudeFormat(n),stream:o,max_tokens:s!==void 0?s:O(this.responseLength)};this.tools.length&&(l.tools=this.tools.map(c=>({name:c.name,description:c.description,input_schema:c.parameters})),l.tool_choice={type:"auto"}),this.mcpServers.length>0&&(l.mcp_servers=this.mcpServers);let 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 _.post(Nt,l,u)}async parseStream(e,t){let o=e.body.getReader(),s=new TextDecoder,i=[],n=new Map,a="";for(;;){let{done:l,value:u}=await o.read();if(l)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 d=c.slice(5).trim();if(d==="[DONE]")break;let p=JSON.parse(d);if(p.type==="content_block_delta"&&p.delta?.text&&(t(p.delta.text),i.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"?i.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"&&i.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 g=n.get(p.index);g&&(g.args+=p.delta.partial_json||"")}if(p.type==="content_block_stop"&&n.has(p.index)){let{id:g,name:M,args:m,server_name:S}=n.get(p.index);S?i.push({type:"mcp_tool_use",id:g,name:M,server_name:S,input:JSON.parse(m||"{}")}):i.push({type:"tool_use",id:g,name:M,input:JSON.parse(m||"{}")}),n.delete(p.index)}}}return{blocks:i,stop_reason:i.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(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 i=await this.callClaude(e,this.model,t,s),n=t?await this.parseStream(i,o):this.parseOneShot(await i.json());return this.convertToStandardCompletion(n)}async visionChatOnce(e,t=!1,o=()=>{},s){let i=await this.callClaude(e,this.visionModel,t,s),n=t?await this.parseStream(i,o):this.parseOneShot(await i.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 ae=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 ne(e.apiKey,e.model||this.getDefaultModel(),t,e.tools??[],e.mcpServers??[],e.responseLength)}getProviderName(){return"claude"}getSupportedModels(){return[I,$e,je,qe,ze,Xe,Je,Ze,Ye,Qe,et]}getDefaultModel(){return I}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Le.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var St=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 _.post(`${e.url}/tools`,{},t)).json();return Array.isArray(s.tools)?s.tools.map(i=>({name:`mcp_${e.name}_${i.name}`,description:i.description||`Tool from ${e.name} MCP server`,parameters:i.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 le=class{constructor(e,t=V,o=V,s=[],i=[],n){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=n,!Te.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=s,this.mcpServers=i}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=St.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 f({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callGemini(e,this.model,!0),{blocks:i}=await this.parseStream(s,t);return v.getFullText(i)},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 f({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callGemini(e,this.visionModel,!0),{blocks:i}=await this.parseStream(s,t);return v.getFullText(i)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:s=>{s.filter(i=>i.type==="text").forEach(i=>t(i.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=[],i=()=>{o&&s.length&&(t.push({role:o,parts:[...s]}),s=[])};for(let n of e){let a=this.mapRoleToGemini(n.role);if(n.tool_calls){i();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"){i();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&&i(),o=a,s.push({text:n.content})}return i(),t}async callGemini(e,t,o=!1,s){let a={contents:e.some(m=>Array.isArray(m.content)&&m.content.some(S=>S?.type==="image_url"||S?.inlineData))?await this.convertVisionMessagesToGeminiFormat(e):this.convertMessagesToGeminiFormat(e),generationConfig:{maxOutputTokens:s!==void 0?s:O(this.responseLength)}},l=[];if(this.tools.length>0&&l.push(...this.tools.map(m=>({name:m.name,description:m.description,parameters:m.parameters}))),this.mcpServers.length>0)try{await this.initializeMCPSchemas(),l.push(...this.mcpToolSchemas.map(m=>({name:m.name,description:m.description,parameters:m.parameters})))}catch(m){console.warn("MCP initialization failed, skipping MCP tools:",m)}l.length>0&&(a.tools=[{functionDeclarations:l}],a.toolConfig={functionCallingConfig:{mode:"AUTO"}});let u=async(m,S)=>{let Se=o?"streamGenerateContent":"generateContent",D=o?"?alt=sse":"",be=`${Dt}/${m}/models/${t}:${Se}${D}${D?"&":"?"}key=${this.apiKey}`;return _.post(be,S)},h=/flash[-_]lite/.test(t),c=/gemini-2\.5/.test(t),d=/^gemini-3(?:\.[0-9]+)?-.*preview/.test(t),p=h||c||d,g=p?"v1beta":"v1",M=async()=>{try{let m=g==="v1"?a:this.adaptKeysForApi(a);return await u(g,m)}catch(m){let S=/Unknown name|Cannot find field|404/.test(m?.message||"")||m?.status===404;if(!p&&S)return await u("v1beta",this.adaptKeysForApi(a));throw m}};try{return await M()}catch(m){throw m.body&&(console.error("Gemini API Error Details:",m.body),console.error("Request Body:",JSON.stringify(a,null,2))),m}}async convertVisionMessagesToGeminiFormat(e){let t=[],o=null,s=[];for(let i of e){let n=this.mapRoleToGemini(i.role);if(i.tool_calls){for(let a of i.tool_calls)t.push({role:"model",parts:[{functionCall:{name:a.function.name,args:JSON.parse(a.function.arguments||"{}")}}]});continue}if(i.role==="tool"){let a=i.name??this.callIdMap.get(i.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:a,response:this.normalizeToolResult(this.safeJsonParse(i.content))}}]});continue}if(n!==o&&s.length>0&&(t.push({role:o,parts:[...s]}),s=[]),o=n,typeof i.content=="string")s.push({text:i.content});else if(Array.isArray(i.content)){for(let a of i.content)if(a.type==="text")s.push({text:a.text});else if(a.type==="image_url")try{let u=await(await _.get(a.image_url.url)).blob(),h=await this.blobToBase64(u);s.push({inlineData:{mimeType:u.type||"image/jpeg",data:h.split(",")[1]}})}catch(l){throw console.error("Error processing image:",l),new Error(`Failed to process image: ${l.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,i=[],n=[],a="",l=h=>{if(!h||h==="[DONE]")return;let c;try{c=JSON.parse(h)}catch{return}for(let d of c.candidates??[])for(let p of d.content?.parts??[])p.text&&(t(p.text),v.addTextBlock(i,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:h,value:c}=await o.read();if(h)break;a+=s.decode(c,{stream:!0});let d;for(;(d=a.indexOf(`
13
+ `))!==-1;){let p=a.slice(0,d);if(a=a.slice(d+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:[...i,...n],stop_reason:n.some(h=>h.type==="tool_use")?"tool_use":"end"}}parseOneShot(e){let t=[],o=[];for(let i of e.candidates??[])for(let n of i.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(i=>i.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},s){let i=await this.callGemini(e,this.model,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.json())}async visionChatOnce(e,t=!1,o=()=>{},s){let i=await this.callGemini(e,this.visionModel,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.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 pe=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 le(e.apiKey,e.model||this.getDefaultModel(),t,e.tools||[],e.mcpServers||[],e.responseLength)}getProviderName(){return"gemini"}getSupportedModels(){return[Ve,ke,Ge,Fe,Ue,He,We,Be,Ke,V]}getDefaultModel(){return V}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Te.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function Go(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var ce=class{constructor(e={}){this.provider="gemini-nano";this.expectedInputLanguages=e.expectedInputLanguages??["ja"],this.expectedOutputLanguages=e.expectedOutputLanguages??["ja"],this._responseLength=e.responseLength,this._responseLength}getModel(){return z}getVisionModel(){return z}async processChat(e,t,o){let s=await this.generateResponse(e);t(s),await o(s)}async processVisionChat(e,t,o){throw new Error("Gemini Nano does not support vision capabilities.")}async chatOnce(e,t=!1,o=()=>{},s){let i=await this.generateResponse(e);return o(i),{blocks:[{type:"text",text:i}],stop_reason:"end"}}async visionChatOnce(e,t=!1,o=()=>{},s){throw new Error("Gemini Nano does not support vision capabilities.")}async generateResponse(e){let t=Go();if(!t)throw new Error("Gemini Nano is not available in this environment. Chrome 138+ with Prompt API enabled is required.");let o=await t.availability();if(o!=="available"&&o!=="downloadable")throw new Error(`Gemini Nano Prompt API is not ready in this environment. LanguageModel.availability() returned "${o}". Expected "available" or "downloadable".`);let i=e.filter(u=>u.role==="system").map(u=>u.content).join(`
14
+ `),n=e.filter(u=>u.role!=="system").slice(-20),a=[...n].reverse().find(u=>u.role==="user");if(!a)throw new Error("No user message found in the provided messages.");let l=await this.createSession(t,i,n);try{return await l.prompt(a.content)}finally{try{l.destroy()}catch{}}}async createSession(e,t,o){let s=t,i=o.slice(0,-1);if(i.length>0){let n=i.map(a=>`${a.role==="user"?"User":"Assistant"}: ${a.content}`).join(`
15
+ `);s+=`
16
+
17
+ \u4EE5\u4E0B\u306F\u3053\u308C\u307E\u3067\u306E\u4F1A\u8A71\u5C65\u6B74\u3067\u3059\u3002\u3053\u306E\u6587\u8108\u3092\u8E0F\u307E\u3048\u3066\u56DE\u7B54\u3057\u3066\u304F\u3060\u3055\u3044:
18
+ `+n}return e.create({systemPrompt:s,expectedInputs:[{type:"text",languages:this.expectedInputLanguages}],expectedOutputs:[{type:"text",languages:this.expectedOutputLanguages}]})}};var ue=class{createChatService(e){return new ce({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,responseLength:e.responseLength})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[z]}getDefaultModel(){return z}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var he=class{constructor(e,t=A,o=A,s,i=se,n,a,l){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,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 f({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(!ie(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await f({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 i=await this.callKimi(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){if(!ie(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let i=await this.callKimi(e,this.visionModel,t,s);return this.parseResponse(i,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 i=this.buildRequestBody(e,t,o,s);return await _.post(this.endpoint,i,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let i={model:t,stream:o,messages:e},n=s!==void 0?s:O(this.responseLength);n!==void 0&&(i.max_tokens=n),this.responseFormat&&(i.response_format=this.responseFormat);let a=this.tools.length>0?{type:"disabled"}:this.thinking;a&&(this.isSelfHostedEndpoint()?a.type==="disabled"&&(i.chat_template_kwargs={thinking:!1}):i.thinking=a);let l=this.buildToolsDefinition();return l.length>0&&(i.tools=l,i.tool_choice="auto"),i}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(se)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}buildToolsDefinition(){return P(this.tools,"chat-completions")}async handleStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var de=class{createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),s=E({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:l=>this.supportsVisionForModel(l),validate:"explicit"}),i=e.tools,n=e.thinking??{type:"enabled"},a=i&&i.length>0?{type:"disabled"}:n;return new he(e.apiKey,o,s,i,t,e.responseLength,e.responseFormat,a)}getProviderName(){return"kimi"}getSupportedModels(){return[A]}getDefaultModel(){return A}getDefaultVisionModel(){return A}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ie(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}resolveEndpoint(e){if(e.endpoint)return this.normalizeEndpoint(e.endpoint);if(e.baseUrl){let t=this.normalizeEndpoint(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return se}normalizeEndpoint(e){return e.replace(/\/+$/,"")}};var Fo={[C.VERY_SHORT]:800,[C.SHORT]:1200,[C.MEDIUM]:2e3,[C.LONG]:3e3,[C.VERY_LONG]:8e3,[C.DEEP]:25e3},Uo={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3},F=class{constructor(e,t=K,o=K,s,i=J,n=[],a,l,u,h=!1,c="openai",d=!0){if(this.provider=c,this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.mcpServers=n,this.responseLength=a,this.verbosity=l,this.reasoning_effort=u,this.enableReasoningSummary=h,d&&!ye.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 f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenAI(e,this.model,!0),i=this.endpoint===x;try{if(i){let n=await this.parseResponsesStream(s,t);return v.getFullText(n.blocks)}return this.handleStream(s,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 f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenAI(e,this.visionModel,!0),i=this.endpoint===x;try{if(i){let n=await this.parseResponsesStream(s,t);return v.getFullText(n.blocks)}return this.handleStream(s,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(s){throw console.error("Error in processVisionChat:",s),s}}async chatOnce(e,t=!0,o=()=>{},s){let i=await this.callOpenAI(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){let i=await this.callOpenAI(e,this.visionModel,t,s);return this.parseResponse(i,t,o)}async parseResponse(e,t,o){return this.endpoint===x?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 i=this.buildRequestBody(e,t,o,s),n={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(n.Authorization=`Bearer ${this.apiKey}`),await _.post(this.endpoint,i,n)}buildRequestBody(e,t,o,s){let i=this.endpoint===x;this.validateMCPCompatibility();let n={model:t,stream:o},a=this.resolveTokenLimit(t,s);i?a!==void 0&&(n.max_output_tokens=a):a!==void 0&&(this.provider==="openai-compatible"?n.max_tokens=a:n.max_completion_tokens=a),i?n.input=this.cleanMessagesForResponsesAPI(e):n.messages=e,$(t)&&(i?(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,i||(n.tool_choice="auto")),n}resolveTokenLimit(e,t){if(t!==void 0)return t;let o=this.provider==="openai-compatible"?this.responseLength!==void 0?O(this.responseLength):void 0:O(this.responseLength);if(this.provider!=="openai"||!$(e)||this.responseLength===void 0)return o;let s=this.reasoning_effort??R(e);return Math.max(o??0,Fo[this.responseLength],Uo[s])}validateMCPCompatibility(){if(this.mcpServers.length>0&&this.endpoint===J)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${this.endpoint}. Please use OpenAI Responses API endpoint: ${x}. 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(i=>i.type==="text"?{type:"input_text",text:i.text}:i.type==="image_url"?{type:"input_image",image_url:i.image_url.url}:i):s.content=t.content,s})}buildToolsDefinition(){let e=this.endpoint===x,t=[];return this.tools.length>0&&t.push(...P(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 y(e,t)}async parseStream(e,t){return T(e,t,{appendTextBlock:v.addTextBlock})}parseOneShot(e){return L(e)}async parseResponsesStream(e,t){let o=e.body.getReader(),s=new TextDecoder,i=[],n=new Map,a,l,u,h="";for(;;){let{done:p,value:g}=await o.read();if(p)break;h+=s.decode(g,{stream:!0});let M="",m="",S=h.split(`
19
+ `);h=S.pop()||"";for(let Se=0;Se<S.length;Se++){let D=S[Se].trim();if(D.startsWith("event:"))M=D.slice(6).trim();else if(D.startsWith("data:"))m=D.slice(5).trim();else if(D===""&&M&&m){try{let be=JSON.parse(m),uo=this.handleResponsesSSEEvent(M,be,t,i,n,X=>{X.responseStatus!==void 0&&(a=X.responseStatus),X.incompleteDetails!==void 0&&(l=X.incompleteDetails),X.usage!==void 0&&(u=X.usage)})}catch{console.warn("Failed to parse SSE data:",m)}M="",m=""}}}let c=Array.from(n.values()).map(p=>({type:"tool_use",id:p.id,name:p.name,input:p.input||{}}));return{blocks:[...i,...c],stop_reason:c.length?"tool_use":"end",truncated:a==="incomplete",response_status:a,incomplete_details:l,usage:u}}handleResponsesSSEEvent(e,t,o,s,i,n){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),v.append(s,a.text))}):t.item?.type==="function_call"&&i.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),v.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),v.append(s,a))}break;case"response.output_text.done":case"response.content_part.done":break;case"response.completed":return n(this.extractResponsesMetadata(t,"completed")),"completed";case"response.incomplete":return n(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 me=class{createChatService(e){return this.validateRequiredOptions(e),new F(e.apiKey?.trim()??"",e.model,e.visionModel??e.model,e.tools,e.endpoint,[],e.responseLength,e.verbosity,e.reasoning_effort,e.enableReasoningSummary,this.getProviderName(),!1)}getProviderName(){return"openai-compatible"}getSupportedModels(){return[]}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"unknown"}supportsVisionForModel(e){return!0}getVisionSupportLevelForModel(e){return"unknown"}getDefaultModel(){return"local-model"}validateRequiredOptions(e){if(e.mcpServers!==void 0)throw new Error("openai-compatible provider does not support mcpServers.");let t=e.endpoint?.trim();if(!t)throw new Error("openai-compatible provider requires endpoint (full URL).");let o;try{o=new URL(t)}catch{throw new Error("openai-compatible provider requires endpoint to be a full URL.")}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error("openai-compatible provider requires endpoint to be a full URL.");if(!e.model?.trim())throw new Error("openai-compatible provider requires model.")}};var ge=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=E({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:u=>this.supportsVisionForModel(u),validate:"resolved"}),s=t.tools,i=t.mcpServers??[],n=t.model||this.getDefaultModel(),a=!1;i.length>0||xt(n)?a=!0:$(n)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let l=t.endpoint||(a?x:J);return new F(t.apiKey,n,o,s,l,i,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName())}getProviderName(){return"openai"}getSupportedModels(){return[U,Z,Y,H,N,W,B,w,Ae,De,Ne,K,we,Tt,Lt,"o1"]}getDefaultModel(){return U}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ye.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!$(t))return e;let o={...e};if(e.gpt5Preset){let s=qt[e.gpt5Preset];o.reasoning_effort=s.reasoning_effort,o.verbosity=s.verbosity}else e.reasoning_effort||(o.reasoning_effort=R(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!Rt(e)?R(e):t==="minimal"&&!bt(e)?R(e):t==="low"&&!At(e)?R(e):t==="xhigh"&&!It(e)?R(e):t}};var _e=class{constructor(e,t=k,o=k,s,i=Pe,n,a,l,u,h,c){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.responseLength=n,this.appName=a,this.appUrl=l,this.reasoning_effort=u,this.includeReasoning=h,this.reasoningMaxTokens=c,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!j(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=Ft){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 f({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(!Q(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await f({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 i=await this.callOpenRouter(e,this.model,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.json())}async visionChatOnce(e,t=!1,o=()=>{},s){if(!Q(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let i=await this.callOpenRouter(e,this.visionModel,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.json())}async callOpenRouter(e,t,o=!1,s){let i=this.buildRequestBody(e,t,o,s),n={Authorization:`Bearer ${this.apiKey}`};return this.appUrl&&(n["HTTP-Referer"]=this.appUrl),this.appName&&(n["X-Title"]=this.appName),await _.post(this.endpoint,i,n)}buildRequestBody(e,t,o,s){let i={model:t,messages:e,stream:o};if((s!==void 0?s: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(i.reasoning={},this.reasoning_effort&&this.reasoning_effort!=="none"){let a=this.reasoning_effort==="minimal"?"low":this.reasoning_effort;i.reasoning.effort=a}(this.reasoning_effort==="none"||this.includeReasoning!==!0)&&(i.reasoning.exclude=!0),this.reasoningMaxTokens&&(i.reasoning.max_tokens=this.reasoningMaxTokens)}else i.reasoning={exclude:!0};return this.tools.length>0&&(i.tools=P(this.tools,"chat-completions"),i.tool_choice="auto"),i}async handleStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var fe=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,s=e.appName,i=e.appUrl;return new _e(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,s,i,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[k,_t,ot,st,it,rt,nt,at,lt,pt,ct,ut,wt,ht,dt,mt,gt,Vt,kt,tt]}getDefaultModel(){return k}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return Q(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return Gt}isModelFree(e){return j(e)}};var ve=class{constructor(e,t=b,o=b,s,i=Ie,n){this.provider="xai";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.responseLength=n,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callXAI(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(!oe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callXAI(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 i=await this.callXAI(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){if(!oe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let i=await this.callXAI(e,this.visionModel,t,s);return this.parseResponse(i,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callXAI(e,t,o=!1,s){let i=this.buildRequestBody(e,t,o,s);return await _.post(this.endpoint,i,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let i={model:t,stream:o,messages:e},n=s!==void 0?s:O(this.responseLength);n!==void 0&&(i.max_tokens=n);let a=this.buildToolsDefinition();return a.length>0&&(i.tools=a,i.tool_choice="auto"),i}buildToolsDefinition(){return P(this.tools,"chat-completions")}async handleStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var Me=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"explicit"}),s=e.tools;return new ve(e.apiKey,t,o,s,e.endpoint||Ie,e.responseLength)}getProviderName(){return"xai"}getSupportedModels(){return[Mt,Ot,Et,b]}getDefaultModel(){return b}getDefaultVisionModel(){return b}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return oe(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Oe=class{constructor(e,t=ee,o=q,s,i=xe,n,a,l){this.provider="zai";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,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 f({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(!te(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await f({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 i=await this.callZAI(e,this.model,t,s);return this.parseResponse(i,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 i=await this.callZAI(e,this.visionModel,t,s);return this.parseResponse(i,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 i=this.buildRequestBody(e,t,o,s);return await _.post(this.endpoint,i,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let i={model:t,stream:o,messages:e},n=s!==void 0?s:O(this.responseLength);n!==void 0&&(i.max_tokens=n),this.responseFormat&&(i.response_format=this.responseFormat),this.thinking&&(i.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(i.tools=a,i.tool_choice="auto",o&&$t(t)&&(i.tool_stream=!0)),i}buildToolsDefinition(){return P(this.tools,"chat-completions")}async handleStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var Ee=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"}),s=e.tools,i=e.thinking??{type:"disabled"};return new Oe(e.apiKey,t,o,s,e.endpoint||xe,e.responseLength,e.responseFormat,i)}getProviderName(){return"zai"}getSupportedModels(){return[Ut,Ht,ee,Wt,Bt,Kt,ft,vt,q]}getDefaultModel(){return ee}getDefaultVisionModel(){return q}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return te(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var po=[new ge,new me,new pe,new ue,new ae,new fe,new Ee,new Me,new de];var Ce=class{static registerProvider(e){this.providers.set(e.getProviderName(),e)}static createChatService(e,t){let o=this.providers.get(e);if(!o)throw new Error(`Unknown chat provider: ${e}`);return o.createChatService(t)}static getProviders(){return this.providers}static getAvailableProviders(){return Array.from(this.providers.keys())}static getSupportedModels(e){let t=this.providers.get(e);return t?t.getSupportedModels():[]}static getVisionSupportLevel(e){let t=this.providers.get(e);return t?t.getVisionSupportLevel():"unsupported"}static getVisionSupportLevelForModel(e,t){let o=this.providers.get(e);return o?o.getVisionSupportLevelForModel?o.getVisionSupportLevelForModel(t):o.supportsVisionForModel?o.supportsVisionForModel(t)?"supported":"unsupported":o.getVisionSupportLevel():"unsupported"}};Ce.providers=new Map;po.forEach(r=>Ce.registerProvider(r));function co(){_.setFetch(async(r,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,s={};if(Array.isArray(o))for(let[c,d]of o)s[c]=String(d);else if(o&&typeof o=="object")for(let[c,d]of Object.entries(o))s[c]=String(d);let i={method:t,headers:s,muteHttpExceptions:!0},n=e.body;typeof n=="string"?i.payload=n:n!=null&&(s["Content-Type"]||(s["Content-Type"]="application/json"),i.payload=JSON.stringify(n));let a=UrlFetchApp.fetch(r,i),l=a.getResponseCode(),u=a.getContentText();return{ok:l>=200&&l<300,status:l,statusText:String(l),text:async()=>u,json:async()=>u?JSON.parse(u):null}})}return vo(Ho);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aituber-onair/chat",
3
- "version": "0.23.0",
3
+ "version": "0.24.0",
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",