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